2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_PARENT(stmt) \
113 statement_t *const new_parent = (stmt); \
114 statement_t *const old_parent = current_parent; \
115 ((void)(current_parent = new_parent))
116 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
118 #define PUSH_SCOPE(scope) \
119 size_t const top = environment_top(); \
120 scope_t *const new_scope = (scope); \
121 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
122 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
123 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
125 #define PUSH_EXTENSION() \
127 bool const old_gcc_extension = in_gcc_extension; \
128 while (next_if(T___extension__)) { \
129 in_gcc_extension = true; \
132 #define POP_EXTENSION() \
133 ((void)(in_gcc_extension = old_gcc_extension))
135 /** special symbol used for anonymous entities. */
136 static symbol_t *sym_anonymous = NULL;
138 /** The token anchor set */
139 static unsigned short token_anchor_set[T_LAST_TOKEN];
141 /** The current source position. */
142 #define HERE (&token.base.source_position)
144 /** true if we are in GCC mode. */
145 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
147 static statement_t *parse_compound_statement(bool inside_expression_statement);
148 static statement_t *parse_statement(void);
150 static expression_t *parse_subexpression(precedence_t);
151 static expression_t *parse_expression(void);
152 static type_t *parse_typename(void);
153 static void parse_externals(void);
154 static void parse_external(void);
156 static void parse_compound_type_entries(compound_t *compound_declaration);
158 static void check_call_argument(type_t *expected_type,
159 call_argument_t *argument, unsigned pos);
161 typedef enum declarator_flags_t {
163 DECL_MAY_BE_ABSTRACT = 1U << 0,
164 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
165 DECL_IS_PARAMETER = 1U << 2
166 } declarator_flags_t;
168 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
169 declarator_flags_t flags);
171 static void semantic_comparison(binary_expression_t *expression);
173 #define STORAGE_CLASSES \
174 STORAGE_CLASSES_NO_EXTERN \
177 #define STORAGE_CLASSES_NO_EXTERN \
184 #define TYPE_QUALIFIERS \
189 case T__forceinline: \
190 case T___attribute__:
192 #define COMPLEX_SPECIFIERS \
194 #define IMAGINARY_SPECIFIERS \
197 #define TYPE_SPECIFIERS \
199 case T___builtin_va_list: \
224 #define DECLARATION_START \
229 #define DECLARATION_START_NO_EXTERN \
230 STORAGE_CLASSES_NO_EXTERN \
234 #define EXPRESSION_START \
243 case T_CHARACTER_CONSTANT: \
244 case T_FLOATINGPOINT: \
245 case T_FLOATINGPOINT_HEXADECIMAL: \
247 case T_INTEGER_HEXADECIMAL: \
248 case T_INTEGER_OCTAL: \
251 case T_STRING_LITERAL: \
252 case T_WIDE_CHARACTER_CONSTANT: \
253 case T_WIDE_STRING_LITERAL: \
254 case T___FUNCDNAME__: \
255 case T___FUNCSIG__: \
256 case T___FUNCTION__: \
257 case T___PRETTY_FUNCTION__: \
258 case T___alignof__: \
259 case T___builtin_classify_type: \
260 case T___builtin_constant_p: \
261 case T___builtin_isgreater: \
262 case T___builtin_isgreaterequal: \
263 case T___builtin_isless: \
264 case T___builtin_islessequal: \
265 case T___builtin_islessgreater: \
266 case T___builtin_isunordered: \
267 case T___builtin_offsetof: \
268 case T___builtin_va_arg: \
269 case T___builtin_va_copy: \
270 case T___builtin_va_start: \
281 * Returns the size of a statement node.
283 * @param kind the statement kind
285 static size_t get_statement_struct_size(statement_kind_t kind)
287 static const size_t sizes[] = {
288 [STATEMENT_ERROR] = sizeof(statement_base_t),
289 [STATEMENT_EMPTY] = sizeof(statement_base_t),
290 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
291 [STATEMENT_RETURN] = sizeof(return_statement_t),
292 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
293 [STATEMENT_IF] = sizeof(if_statement_t),
294 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
295 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
296 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
297 [STATEMENT_BREAK] = sizeof(statement_base_t),
298 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
299 [STATEMENT_GOTO] = sizeof(goto_statement_t),
300 [STATEMENT_LABEL] = sizeof(label_statement_t),
301 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
302 [STATEMENT_WHILE] = sizeof(while_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_INTEGER_OCTAL] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
329 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
333 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
335 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
336 [EXPR_CALL] = sizeof(call_expression_t),
337 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
338 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
339 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
340 [EXPR_SELECT] = sizeof(select_expression_t),
341 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
342 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
343 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
344 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
345 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
346 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
347 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
348 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
349 [EXPR_VA_START] = sizeof(va_start_expression_t),
350 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
351 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
352 [EXPR_STATEMENT] = sizeof(statement_expression_t),
353 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
355 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
356 return sizes[EXPR_UNARY_FIRST];
358 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
359 return sizes[EXPR_BINARY_FIRST];
361 assert((size_t)kind < lengthof(sizes));
362 assert(sizes[kind] != 0);
367 * Allocate a statement node of given kind and initialize all
368 * fields with zero. Sets its source position to the position
369 * of the current token.
371 static statement_t *allocate_statement_zero(statement_kind_t kind)
373 size_t size = get_statement_struct_size(kind);
374 statement_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.parent = current_parent;
378 res->base.source_position = token.base.source_position;
383 * Allocate an expression node of given kind and initialize all
386 * @param kind the kind of the expression to allocate
388 static expression_t *allocate_expression_zero(expression_kind_t kind)
390 size_t size = get_expression_struct_size(kind);
391 expression_t *res = allocate_ast_zero(size);
393 res->base.kind = kind;
394 res->base.type = type_error_type;
395 res->base.source_position = token.base.source_position;
400 * Creates a new invalid expression at the source position
401 * of the current token.
403 static expression_t *create_error_expression(void)
405 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
406 expression->base.type = type_error_type;
411 * Creates a new invalid statement.
413 static statement_t *create_error_statement(void)
415 return allocate_statement_zero(STATEMENT_ERROR);
419 * Allocate a new empty statement.
421 static statement_t *create_empty_statement(void)
423 return allocate_statement_zero(STATEMENT_EMPTY);
427 * Returns the size of an initializer node.
429 * @param kind the initializer kind
431 static size_t get_initializer_size(initializer_kind_t kind)
433 static const size_t sizes[] = {
434 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
435 [INITIALIZER_STRING] = sizeof(initializer_string_t),
436 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
437 [INITIALIZER_LIST] = sizeof(initializer_list_t),
438 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
440 assert((size_t)kind < lengthof(sizes));
441 assert(sizes[kind] != 0);
446 * Allocate an initializer node of given kind and initialize all
449 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
451 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
458 * Returns the index of the top element of the environment stack.
460 static size_t environment_top(void)
462 return ARR_LEN(environment_stack);
466 * Returns the index of the top element of the global label stack.
468 static size_t label_top(void)
470 return ARR_LEN(label_stack);
474 * Return the next token.
476 static inline void next_token(void)
478 token = lookahead_buffer[lookahead_bufpos];
479 lookahead_buffer[lookahead_bufpos] = lexer_token;
482 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
485 print_token(stderr, &token);
486 fprintf(stderr, "\n");
490 static inline bool next_if(int const type)
492 if (token.kind == type) {
501 * Return the next token with a given lookahead.
503 static inline const token_t *look_ahead(size_t num)
505 assert(0 < num && num <= MAX_LOOKAHEAD);
506 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
507 return &lookahead_buffer[pos];
511 * Adds a token type to the token type anchor set (a multi-set).
513 static void add_anchor_token(int token_kind)
515 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
516 ++token_anchor_set[token_kind];
520 * Remove a token type from the token type anchor set (a multi-set).
522 static void rem_anchor_token(int token_kind)
524 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
525 assert(token_anchor_set[token_kind] != 0);
526 --token_anchor_set[token_kind];
530 * Eat tokens until a matching token type is found.
532 static void eat_until_matching_token(int type)
536 case '(': end_token = ')'; break;
537 case '{': end_token = '}'; break;
538 case '[': end_token = ']'; break;
539 default: end_token = type; break;
542 unsigned parenthesis_count = 0;
543 unsigned brace_count = 0;
544 unsigned bracket_count = 0;
545 while (token.kind != end_token ||
546 parenthesis_count != 0 ||
548 bracket_count != 0) {
549 switch (token.kind) {
551 case '(': ++parenthesis_count; break;
552 case '{': ++brace_count; break;
553 case '[': ++bracket_count; break;
556 if (parenthesis_count > 0)
566 if (bracket_count > 0)
569 if (token.kind == end_token &&
570 parenthesis_count == 0 &&
584 * Eat input tokens until an anchor is found.
586 static void eat_until_anchor(void)
588 while (token_anchor_set[token.kind] == 0) {
589 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
590 eat_until_matching_token(token.kind);
596 * Eat a whole block from input tokens.
598 static void eat_block(void)
600 eat_until_matching_token('{');
604 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
607 * Report a parse error because an expected token was not found.
610 #if defined __GNUC__ && __GNUC__ >= 4
611 __attribute__((sentinel))
613 void parse_error_expected(const char *message, ...)
615 if (message != NULL) {
616 errorf(HERE, "%s", message);
619 va_start(ap, message);
620 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
625 * Report an incompatible type.
627 static void type_error_incompatible(const char *msg,
628 const source_position_t *source_position, type_t *type1, type_t *type2)
630 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
635 * Expect the current token is the expected token.
636 * If not, generate an error and skip until the next anchor.
638 static void expect(token_kind_t const expected)
640 if (UNLIKELY(token.kind != expected)) {
641 parse_error_expected(NULL, expected, NULL);
642 add_anchor_token(expected);
644 rem_anchor_token(expected);
645 if (token.kind != expected)
651 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
653 if (token.kind != T_IDENTIFIER) {
654 parse_error_expected(context, T_IDENTIFIER, NULL);
655 add_anchor_token(T_IDENTIFIER);
657 rem_anchor_token(T_IDENTIFIER);
658 if (token.kind != T_IDENTIFIER)
661 symbol_t *const sym = token.identifier.symbol;
669 * Push a given scope on the scope stack and make it the
672 static scope_t *scope_push(scope_t *new_scope)
674 if (current_scope != NULL) {
675 new_scope->depth = current_scope->depth + 1;
678 scope_t *old_scope = current_scope;
679 current_scope = new_scope;
684 * Pop the current scope from the scope stack.
686 static void scope_pop(scope_t *old_scope)
688 current_scope = old_scope;
692 * Search an entity by its symbol in a given namespace.
694 static entity_t *get_entity(const symbol_t *const symbol,
695 namespace_tag_t namespc)
697 entity_t *entity = symbol->entity;
698 for (; entity != NULL; entity = entity->base.symbol_next) {
699 if ((namespace_tag_t)entity->base.namespc == namespc)
706 /* §6.2.3:1 24) There is only one name space for tags even though three are
708 static entity_t *get_tag(symbol_t const *const symbol,
709 entity_kind_tag_t const kind)
711 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
712 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
714 "'%Y' defined as wrong kind of tag (previous definition %P)",
715 symbol, &entity->base.source_position);
722 * pushs an entity on the environment stack and links the corresponding symbol
725 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
727 symbol_t *symbol = entity->base.symbol;
728 entity_namespace_t namespc = entity->base.namespc;
729 assert(namespc != 0);
731 /* replace/add entity into entity list of the symbol */
734 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
739 /* replace an entry? */
740 if (iter->base.namespc == namespc) {
741 entity->base.symbol_next = iter->base.symbol_next;
747 /* remember old declaration */
749 entry.symbol = symbol;
750 entry.old_entity = iter;
751 entry.namespc = namespc;
752 ARR_APP1(stack_entry_t, *stack_ptr, entry);
756 * Push an entity on the environment stack.
758 static void environment_push(entity_t *entity)
760 assert(entity->base.source_position.input_name != NULL);
761 assert(entity->base.parent_scope != NULL);
762 stack_push(&environment_stack, entity);
766 * Push a declaration on the global label stack.
768 * @param declaration the declaration
770 static void label_push(entity_t *label)
772 /* we abuse the parameters scope as parent for the labels */
773 label->base.parent_scope = ¤t_function->parameters;
774 stack_push(&label_stack, label);
778 * pops symbols from the environment stack until @p new_top is the top element
780 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
782 stack_entry_t *stack = *stack_ptr;
783 size_t top = ARR_LEN(stack);
786 assert(new_top <= top);
790 for (i = top; i > new_top; --i) {
791 stack_entry_t *entry = &stack[i - 1];
793 entity_t *old_entity = entry->old_entity;
794 symbol_t *symbol = entry->symbol;
795 entity_namespace_t namespc = entry->namespc;
797 /* replace with old_entity/remove */
800 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
802 assert(iter != NULL);
803 /* replace an entry? */
804 if (iter->base.namespc == namespc)
808 /* restore definition from outer scopes (if there was one) */
809 if (old_entity != NULL) {
810 old_entity->base.symbol_next = iter->base.symbol_next;
811 *anchor = old_entity;
813 /* remove entry from list */
814 *anchor = iter->base.symbol_next;
818 ARR_SHRINKLEN(*stack_ptr, new_top);
822 * Pop all entries from the environment stack until the new_top
825 * @param new_top the new stack top
827 static void environment_pop_to(size_t new_top)
829 stack_pop_to(&environment_stack, new_top);
833 * Pop all entries from the global label stack until the new_top
836 * @param new_top the new stack top
838 static void label_pop_to(size_t new_top)
840 stack_pop_to(&label_stack, new_top);
843 static atomic_type_kind_t get_akind(const type_t *type)
845 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
846 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
847 return type->atomic.akind;
851 * §6.3.1.1:2 Do integer promotion for a given type.
853 * @param type the type to promote
854 * @return the promoted type
856 static type_t *promote_integer(type_t *type)
858 if (get_akind_rank(get_akind(type)) < 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 = expression->base.type;
899 if (source_type == dest_type)
902 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
903 cast->unary.value = expression;
904 cast->base.type = dest_type;
905 cast->base.implicit = true;
910 typedef enum assign_error_t {
912 ASSIGN_ERROR_INCOMPATIBLE,
913 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
914 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
915 ASSIGN_WARNING_POINTER_FROM_INT,
916 ASSIGN_WARNING_INT_FROM_POINTER
919 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
921 type_t *const orig_type_right = right->base.type;
922 type_t *const type_left = skip_typeref(orig_type_left);
923 type_t *const type_right = skip_typeref(orig_type_right);
928 case ASSIGN_ERROR_INCOMPATIBLE:
929 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
932 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
933 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
934 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
936 /* the left type has all qualifiers from the right type */
937 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
938 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);
942 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
943 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
946 case ASSIGN_WARNING_POINTER_FROM_INT:
947 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
950 case ASSIGN_WARNING_INT_FROM_POINTER:
951 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
955 panic("invalid error value");
959 /** Implements the rules from §6.5.16.1 */
960 static assign_error_t semantic_assign(type_t *orig_type_left,
961 const expression_t *const right)
963 type_t *const orig_type_right = right->base.type;
964 type_t *const type_left = skip_typeref(orig_type_left);
965 type_t *const type_right = skip_typeref(orig_type_right);
967 if (is_type_pointer(type_left)) {
968 if (is_null_pointer_constant(right)) {
969 return ASSIGN_SUCCESS;
970 } else if (is_type_pointer(type_right)) {
971 type_t *points_to_left
972 = skip_typeref(type_left->pointer.points_to);
973 type_t *points_to_right
974 = skip_typeref(type_right->pointer.points_to);
975 assign_error_t res = ASSIGN_SUCCESS;
977 /* the left type has all qualifiers from the right type */
978 unsigned missing_qualifiers
979 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
980 if (missing_qualifiers != 0) {
981 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
984 points_to_left = get_unqualified_type(points_to_left);
985 points_to_right = get_unqualified_type(points_to_right);
987 if (is_type_void(points_to_left))
990 if (is_type_void(points_to_right)) {
991 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
992 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
995 if (!types_compatible(points_to_left, points_to_right)) {
996 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1000 } else if (is_type_integer(type_right)) {
1001 return ASSIGN_WARNING_POINTER_FROM_INT;
1003 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1004 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1005 && is_type_pointer(type_right))) {
1006 return ASSIGN_SUCCESS;
1007 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1008 type_t *const unqual_type_left = get_unqualified_type(type_left);
1009 type_t *const unqual_type_right = get_unqualified_type(type_right);
1010 if (types_compatible(unqual_type_left, unqual_type_right)) {
1011 return ASSIGN_SUCCESS;
1013 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1014 return ASSIGN_WARNING_INT_FROM_POINTER;
1017 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1018 return ASSIGN_SUCCESS;
1020 return ASSIGN_ERROR_INCOMPATIBLE;
1023 static expression_t *parse_constant_expression(void)
1025 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1027 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1028 errorf(&result->base.source_position,
1029 "expression '%E' is not constant", result);
1035 static expression_t *parse_assignment_expression(void)
1037 return parse_subexpression(PREC_ASSIGNMENT);
1040 static void warn_string_concat(const source_position_t *pos)
1042 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1045 static string_t parse_string_literals(void)
1047 assert(token.kind == T_STRING_LITERAL);
1048 string_t result = token.string.string;
1052 while (token.kind == T_STRING_LITERAL) {
1053 warn_string_concat(&token.base.source_position);
1054 result = concat_strings(&result, &token.string.string);
1061 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1063 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1064 attribute->kind = kind;
1065 attribute->source_position = *HERE;
1070 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1073 * __attribute__ ( ( attribute-list ) )
1077 * attribute_list , attrib
1082 * any-word ( identifier )
1083 * any-word ( identifier , nonempty-expr-list )
1084 * any-word ( expr-list )
1086 * where the "identifier" must not be declared as a type, and
1087 * "any-word" may be any identifier (including one declared as a
1088 * type), a reserved word storage class specifier, type specifier or
1089 * type qualifier. ??? This still leaves out most reserved keywords
1090 * (following the old parser), shouldn't we include them, and why not
1091 * allow identifiers declared as types to start the arguments?
1093 * Matze: this all looks confusing and little systematic, so we're even less
1094 * strict and parse any list of things which are identifiers or
1095 * (assignment-)expressions.
1097 static attribute_argument_t *parse_attribute_arguments(void)
1099 attribute_argument_t *first = NULL;
1100 attribute_argument_t **anchor = &first;
1101 if (token.kind != ')') do {
1102 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1104 /* is it an identifier */
1105 if (token.kind == T_IDENTIFIER
1106 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1107 symbol_t *symbol = token.identifier.symbol;
1108 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1109 argument->v.symbol = symbol;
1112 /* must be an expression */
1113 expression_t *expression = parse_assignment_expression();
1115 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1116 argument->v.expression = expression;
1119 /* append argument */
1121 anchor = &argument->next;
1122 } while (next_if(','));
1127 static attribute_t *parse_attribute_asm(void)
1129 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1132 attribute->a.arguments = parse_attribute_arguments();
1136 static symbol_t *get_symbol_from_token(void)
1138 switch(token.kind) {
1140 return token.identifier.symbol;
1169 /* maybe we need more tokens ... add them on demand */
1170 return get_token_kind_symbol(token.kind);
1176 static attribute_t *parse_attribute_gnu_single(void)
1178 /* parse "any-word" */
1179 symbol_t *symbol = get_symbol_from_token();
1180 if (symbol == NULL) {
1181 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1185 attribute_kind_t kind;
1186 char const *const name = symbol->string;
1187 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1188 if (kind > ATTRIBUTE_GNU_LAST) {
1189 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1190 /* TODO: we should still save the attribute in the list... */
1191 kind = ATTRIBUTE_UNKNOWN;
1195 const char *attribute_name = get_attribute_name(kind);
1196 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1200 attribute_t *attribute = allocate_attribute_zero(kind);
1203 /* parse arguments */
1205 attribute->a.arguments = parse_attribute_arguments();
1210 static attribute_t *parse_attribute_gnu(void)
1212 attribute_t *first = NULL;
1213 attribute_t **anchor = &first;
1215 eat(T___attribute__);
1219 add_anchor_token(')');
1220 add_anchor_token(',');
1221 if (token.kind != ')') do {
1222 attribute_t *attribute = parse_attribute_gnu_single();
1224 *anchor = attribute;
1225 anchor = &attribute->next;
1227 } while (next_if(','));
1228 rem_anchor_token(',');
1229 rem_anchor_token(')');
1236 /** Parse attributes. */
1237 static attribute_t *parse_attributes(attribute_t *first)
1239 attribute_t **anchor = &first;
1241 while (*anchor != NULL)
1242 anchor = &(*anchor)->next;
1244 attribute_t *attribute;
1245 switch (token.kind) {
1246 case T___attribute__:
1247 attribute = parse_attribute_gnu();
1248 if (attribute == NULL)
1253 attribute = parse_attribute_asm();
1257 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1262 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1266 case T__forceinline:
1267 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1268 eat(T__forceinline);
1272 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1277 /* TODO record modifier */
1278 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1279 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1287 *anchor = attribute;
1288 anchor = &attribute->next;
1292 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1294 static entity_t *determine_lhs_ent(expression_t *const expr,
1297 switch (expr->kind) {
1298 case EXPR_REFERENCE: {
1299 entity_t *const entity = expr->reference.entity;
1300 /* we should only find variables as lvalues... */
1301 if (entity->base.kind != ENTITY_VARIABLE
1302 && entity->base.kind != ENTITY_PARAMETER)
1308 case EXPR_ARRAY_ACCESS: {
1309 expression_t *const ref = expr->array_access.array_ref;
1310 entity_t * ent = NULL;
1311 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1312 ent = determine_lhs_ent(ref, lhs_ent);
1315 mark_vars_read(ref, lhs_ent);
1317 mark_vars_read(expr->array_access.index, lhs_ent);
1322 mark_vars_read(expr->select.compound, lhs_ent);
1323 if (is_type_compound(skip_typeref(expr->base.type)))
1324 return determine_lhs_ent(expr->select.compound, lhs_ent);
1328 case EXPR_UNARY_DEREFERENCE: {
1329 expression_t *const val = expr->unary.value;
1330 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1332 return determine_lhs_ent(val->unary.value, lhs_ent);
1334 mark_vars_read(val, NULL);
1340 mark_vars_read(expr, NULL);
1345 #define ENT_ANY ((entity_t*)-1)
1348 * Mark declarations, which are read. This is used to detect variables, which
1352 * x is not marked as "read", because it is only read to calculate its own new
1356 * x and y are not detected as "not read", because multiple variables are
1359 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1361 switch (expr->kind) {
1362 case EXPR_REFERENCE: {
1363 entity_t *const entity = expr->reference.entity;
1364 if (entity->kind != ENTITY_VARIABLE
1365 && entity->kind != ENTITY_PARAMETER)
1368 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1369 if (entity->kind == ENTITY_VARIABLE) {
1370 entity->variable.read = true;
1372 entity->parameter.read = true;
1379 // TODO respect pure/const
1380 mark_vars_read(expr->call.function, NULL);
1381 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1382 mark_vars_read(arg->expression, NULL);
1386 case EXPR_CONDITIONAL:
1387 // TODO lhs_decl should depend on whether true/false have an effect
1388 mark_vars_read(expr->conditional.condition, NULL);
1389 if (expr->conditional.true_expression != NULL)
1390 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1391 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1395 if (lhs_ent == ENT_ANY
1396 && !is_type_compound(skip_typeref(expr->base.type)))
1398 mark_vars_read(expr->select.compound, lhs_ent);
1401 case EXPR_ARRAY_ACCESS: {
1402 mark_vars_read(expr->array_access.index, lhs_ent);
1403 expression_t *const ref = expr->array_access.array_ref;
1404 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1405 if (lhs_ent == ENT_ANY)
1408 mark_vars_read(ref, lhs_ent);
1413 mark_vars_read(expr->va_arge.ap, lhs_ent);
1417 mark_vars_read(expr->va_copye.src, lhs_ent);
1420 case EXPR_UNARY_CAST:
1421 /* Special case: Use void cast to mark a variable as "read" */
1422 if (is_type_void(skip_typeref(expr->base.type)))
1427 case EXPR_UNARY_THROW:
1428 if (expr->unary.value == NULL)
1431 case EXPR_UNARY_DEREFERENCE:
1432 case EXPR_UNARY_DELETE:
1433 case EXPR_UNARY_DELETE_ARRAY:
1434 if (lhs_ent == ENT_ANY)
1438 case EXPR_UNARY_NEGATE:
1439 case EXPR_UNARY_PLUS:
1440 case EXPR_UNARY_BITWISE_NEGATE:
1441 case EXPR_UNARY_NOT:
1442 case EXPR_UNARY_TAKE_ADDRESS:
1443 case EXPR_UNARY_POSTFIX_INCREMENT:
1444 case EXPR_UNARY_POSTFIX_DECREMENT:
1445 case EXPR_UNARY_PREFIX_INCREMENT:
1446 case EXPR_UNARY_PREFIX_DECREMENT:
1447 case EXPR_UNARY_ASSUME:
1449 mark_vars_read(expr->unary.value, lhs_ent);
1452 case EXPR_BINARY_ADD:
1453 case EXPR_BINARY_SUB:
1454 case EXPR_BINARY_MUL:
1455 case EXPR_BINARY_DIV:
1456 case EXPR_BINARY_MOD:
1457 case EXPR_BINARY_EQUAL:
1458 case EXPR_BINARY_NOTEQUAL:
1459 case EXPR_BINARY_LESS:
1460 case EXPR_BINARY_LESSEQUAL:
1461 case EXPR_BINARY_GREATER:
1462 case EXPR_BINARY_GREATEREQUAL:
1463 case EXPR_BINARY_BITWISE_AND:
1464 case EXPR_BINARY_BITWISE_OR:
1465 case EXPR_BINARY_BITWISE_XOR:
1466 case EXPR_BINARY_LOGICAL_AND:
1467 case EXPR_BINARY_LOGICAL_OR:
1468 case EXPR_BINARY_SHIFTLEFT:
1469 case EXPR_BINARY_SHIFTRIGHT:
1470 case EXPR_BINARY_COMMA:
1471 case EXPR_BINARY_ISGREATER:
1472 case EXPR_BINARY_ISGREATEREQUAL:
1473 case EXPR_BINARY_ISLESS:
1474 case EXPR_BINARY_ISLESSEQUAL:
1475 case EXPR_BINARY_ISLESSGREATER:
1476 case EXPR_BINARY_ISUNORDERED:
1477 mark_vars_read(expr->binary.left, lhs_ent);
1478 mark_vars_read(expr->binary.right, lhs_ent);
1481 case EXPR_BINARY_ASSIGN:
1482 case EXPR_BINARY_MUL_ASSIGN:
1483 case EXPR_BINARY_DIV_ASSIGN:
1484 case EXPR_BINARY_MOD_ASSIGN:
1485 case EXPR_BINARY_ADD_ASSIGN:
1486 case EXPR_BINARY_SUB_ASSIGN:
1487 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1488 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1489 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1490 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1491 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1492 if (lhs_ent == ENT_ANY)
1494 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1495 mark_vars_read(expr->binary.right, lhs_ent);
1500 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1503 case EXPR_LITERAL_CASES:
1505 case EXPR_STRING_LITERAL:
1506 case EXPR_WIDE_STRING_LITERAL:
1507 case EXPR_COMPOUND_LITERAL: // TODO init?
1509 case EXPR_CLASSIFY_TYPE:
1512 case EXPR_BUILTIN_CONSTANT_P:
1513 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1515 case EXPR_STATEMENT: // TODO
1516 case EXPR_LABEL_ADDRESS:
1517 case EXPR_ENUM_CONSTANT:
1521 panic("unhandled expression");
1524 static designator_t *parse_designation(void)
1526 designator_t *result = NULL;
1527 designator_t **anchor = &result;
1530 designator_t *designator;
1531 switch (token.kind) {
1533 designator = allocate_ast_zero(sizeof(designator[0]));
1534 designator->source_position = token.base.source_position;
1536 add_anchor_token(']');
1537 designator->array_index = parse_constant_expression();
1538 rem_anchor_token(']');
1542 designator = allocate_ast_zero(sizeof(designator[0]));
1543 designator->source_position = token.base.source_position;
1545 designator->symbol = expect_identifier("while parsing designator", NULL);
1546 if (!designator->symbol)
1554 assert(designator != NULL);
1555 *anchor = designator;
1556 anchor = &designator->next;
1560 static initializer_t *initializer_from_string(array_type_t *const type,
1561 const string_t *const string)
1563 /* TODO: check len vs. size of array type */
1566 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1567 initializer->string.string = *string;
1572 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1573 const string_t *const string)
1575 /* TODO: check len vs. size of array type */
1578 initializer_t *const initializer =
1579 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1580 initializer->wide_string.string = *string;
1586 * Build an initializer from a given expression.
1588 static initializer_t *initializer_from_expression(type_t *orig_type,
1589 expression_t *expression)
1591 /* TODO check that expression is a constant expression */
1593 /* §6.7.8.14/15 char array may be initialized by string literals */
1594 type_t *type = skip_typeref(orig_type);
1595 type_t *expr_type_orig = expression->base.type;
1596 type_t *expr_type = skip_typeref(expr_type_orig);
1598 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1599 array_type_t *const array_type = &type->array;
1600 type_t *const element_type = skip_typeref(array_type->element_type);
1602 if (element_type->kind == TYPE_ATOMIC) {
1603 atomic_type_kind_t akind = element_type->atomic.akind;
1604 switch (expression->kind) {
1605 case EXPR_STRING_LITERAL:
1606 if (akind == ATOMIC_TYPE_CHAR
1607 || akind == ATOMIC_TYPE_SCHAR
1608 || akind == ATOMIC_TYPE_UCHAR) {
1609 return initializer_from_string(array_type,
1610 &expression->string_literal.value);
1614 case EXPR_WIDE_STRING_LITERAL: {
1615 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1616 if (get_unqualified_type(element_type) == bare_wchar_type) {
1617 return initializer_from_wide_string(array_type,
1618 &expression->string_literal.value);
1629 assign_error_t error = semantic_assign(type, expression);
1630 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1632 report_assign_error(error, type, expression, "initializer",
1633 &expression->base.source_position);
1635 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1636 result->value.value = create_implicit_cast(expression, type);
1642 * Parses an scalar initializer.
1644 * §6.7.8.11; eat {} without warning
1646 static initializer_t *parse_scalar_initializer(type_t *type,
1647 bool must_be_constant)
1649 /* there might be extra {} hierarchies */
1651 if (token.kind == '{') {
1652 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1656 } while (token.kind == '{');
1659 expression_t *expression = parse_assignment_expression();
1660 mark_vars_read(expression, NULL);
1661 if (must_be_constant && !is_linker_constant(expression)) {
1662 errorf(&expression->base.source_position,
1663 "initialisation expression '%E' is not constant",
1667 initializer_t *initializer = initializer_from_expression(type, expression);
1669 if (initializer == NULL) {
1670 errorf(&expression->base.source_position,
1671 "expression '%E' (type '%T') doesn't match expected type '%T'",
1672 expression, expression->base.type, type);
1677 bool additional_warning_displayed = false;
1678 while (braces > 0) {
1680 if (token.kind != '}') {
1681 if (!additional_warning_displayed) {
1682 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1683 additional_warning_displayed = true;
1694 * An entry in the type path.
1696 typedef struct type_path_entry_t type_path_entry_t;
1697 struct type_path_entry_t {
1698 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1700 size_t index; /**< For array types: the current index. */
1701 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1706 * A type path expression a position inside compound or array types.
1708 typedef struct type_path_t type_path_t;
1709 struct type_path_t {
1710 type_path_entry_t *path; /**< An flexible array containing the current path. */
1711 type_t *top_type; /**< type of the element the path points */
1712 size_t max_index; /**< largest index in outermost array */
1716 * Prints a type path for debugging.
1718 static __attribute__((unused)) void debug_print_type_path(
1719 const type_path_t *path)
1721 size_t len = ARR_LEN(path->path);
1723 for (size_t i = 0; i < len; ++i) {
1724 const type_path_entry_t *entry = & path->path[i];
1726 type_t *type = skip_typeref(entry->type);
1727 if (is_type_compound(type)) {
1728 /* in gcc mode structs can have no members */
1729 if (entry->v.compound_entry == NULL) {
1733 fprintf(stderr, ".%s",
1734 entry->v.compound_entry->base.symbol->string);
1735 } else if (is_type_array(type)) {
1736 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1738 fprintf(stderr, "-INVALID-");
1741 if (path->top_type != NULL) {
1742 fprintf(stderr, " (");
1743 print_type(path->top_type);
1744 fprintf(stderr, ")");
1749 * Return the top type path entry, ie. in a path
1750 * (type).a.b returns the b.
1752 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1754 size_t len = ARR_LEN(path->path);
1756 return &path->path[len-1];
1760 * Enlarge the type path by an (empty) element.
1762 static type_path_entry_t *append_to_type_path(type_path_t *path)
1764 size_t len = ARR_LEN(path->path);
1765 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1767 type_path_entry_t *result = & path->path[len];
1768 memset(result, 0, sizeof(result[0]));
1773 * Descending into a sub-type. Enter the scope of the current top_type.
1775 static void descend_into_subtype(type_path_t *path)
1777 type_t *orig_top_type = path->top_type;
1778 type_t *top_type = skip_typeref(orig_top_type);
1780 type_path_entry_t *top = append_to_type_path(path);
1781 top->type = top_type;
1783 if (is_type_compound(top_type)) {
1784 compound_t *const compound = top_type->compound.compound;
1785 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1787 if (entry != NULL) {
1788 top->v.compound_entry = &entry->declaration;
1789 path->top_type = entry->declaration.type;
1791 path->top_type = NULL;
1793 } else if (is_type_array(top_type)) {
1795 path->top_type = top_type->array.element_type;
1797 assert(!is_type_valid(top_type));
1802 * Pop an entry from the given type path, ie. returning from
1803 * (type).a.b to (type).a
1805 static void ascend_from_subtype(type_path_t *path)
1807 type_path_entry_t *top = get_type_path_top(path);
1809 path->top_type = top->type;
1811 size_t len = ARR_LEN(path->path);
1812 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1816 * Pop entries from the given type path until the given
1817 * path level is reached.
1819 static void ascend_to(type_path_t *path, size_t top_path_level)
1821 size_t len = ARR_LEN(path->path);
1823 while (len > top_path_level) {
1824 ascend_from_subtype(path);
1825 len = ARR_LEN(path->path);
1829 static bool walk_designator(type_path_t *path, const designator_t *designator,
1830 bool used_in_offsetof)
1832 for (; designator != NULL; designator = designator->next) {
1833 type_path_entry_t *top = get_type_path_top(path);
1834 type_t *orig_type = top->type;
1836 type_t *type = skip_typeref(orig_type);
1838 if (designator->symbol != NULL) {
1839 symbol_t *symbol = designator->symbol;
1840 if (!is_type_compound(type)) {
1841 if (is_type_valid(type)) {
1842 errorf(&designator->source_position,
1843 "'.%Y' designator used for non-compound type '%T'",
1847 top->type = type_error_type;
1848 top->v.compound_entry = NULL;
1849 orig_type = type_error_type;
1851 compound_t *compound = type->compound.compound;
1852 entity_t *iter = compound->members.entities;
1853 for (; iter != NULL; iter = iter->base.next) {
1854 if (iter->base.symbol == symbol) {
1859 errorf(&designator->source_position,
1860 "'%T' has no member named '%Y'", orig_type, symbol);
1863 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1864 if (used_in_offsetof && iter->compound_member.bitfield) {
1865 errorf(&designator->source_position,
1866 "offsetof designator '%Y' must not specify bitfield",
1871 top->type = orig_type;
1872 top->v.compound_entry = &iter->declaration;
1873 orig_type = iter->declaration.type;
1876 expression_t *array_index = designator->array_index;
1877 assert(designator->array_index != NULL);
1879 if (!is_type_array(type)) {
1880 if (is_type_valid(type)) {
1881 errorf(&designator->source_position,
1882 "[%E] designator used for non-array type '%T'",
1883 array_index, orig_type);
1888 long index = fold_constant_to_int(array_index);
1889 if (!used_in_offsetof) {
1891 errorf(&designator->source_position,
1892 "array index [%E] must be positive", array_index);
1893 } else if (type->array.size_constant) {
1894 long array_size = type->array.size;
1895 if (index >= array_size) {
1896 errorf(&designator->source_position,
1897 "designator [%E] (%d) exceeds array size %d",
1898 array_index, index, array_size);
1903 top->type = orig_type;
1904 top->v.index = (size_t) index;
1905 orig_type = type->array.element_type;
1907 path->top_type = orig_type;
1909 if (designator->next != NULL) {
1910 descend_into_subtype(path);
1916 static void advance_current_object(type_path_t *path, size_t top_path_level)
1918 type_path_entry_t *top = get_type_path_top(path);
1920 type_t *type = skip_typeref(top->type);
1921 if (is_type_union(type)) {
1922 /* in unions only the first element is initialized */
1923 top->v.compound_entry = NULL;
1924 } else if (is_type_struct(type)) {
1925 declaration_t *entry = top->v.compound_entry;
1927 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1928 if (next_entity != NULL) {
1929 assert(is_declaration(next_entity));
1930 entry = &next_entity->declaration;
1935 top->v.compound_entry = entry;
1936 if (entry != NULL) {
1937 path->top_type = entry->type;
1940 } else if (is_type_array(type)) {
1941 assert(is_type_array(type));
1945 if (!type->array.size_constant || top->v.index < type->array.size) {
1949 assert(!is_type_valid(type));
1953 /* we're past the last member of the current sub-aggregate, try if we
1954 * can ascend in the type hierarchy and continue with another subobject */
1955 size_t len = ARR_LEN(path->path);
1957 if (len > top_path_level) {
1958 ascend_from_subtype(path);
1959 advance_current_object(path, top_path_level);
1961 path->top_type = NULL;
1966 * skip any {...} blocks until a closing bracket is reached.
1968 static void skip_initializers(void)
1972 while (token.kind != '}') {
1973 if (token.kind == T_EOF)
1975 if (token.kind == '{') {
1983 static initializer_t *create_empty_initializer(void)
1985 static initializer_t empty_initializer
1986 = { .list = { { INITIALIZER_LIST }, 0 } };
1987 return &empty_initializer;
1991 * Parse a part of an initialiser for a struct or union,
1993 static initializer_t *parse_sub_initializer(type_path_t *path,
1994 type_t *outer_type, size_t top_path_level,
1995 parse_initializer_env_t *env)
1997 if (token.kind == '}') {
1998 /* empty initializer */
1999 return create_empty_initializer();
2002 type_t *orig_type = path->top_type;
2003 type_t *type = NULL;
2005 if (orig_type == NULL) {
2006 /* We are initializing an empty compound. */
2008 type = skip_typeref(orig_type);
2011 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2014 designator_t *designator = NULL;
2015 if (token.kind == '.' || token.kind == '[') {
2016 designator = parse_designation();
2017 goto finish_designator;
2018 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2019 /* GNU-style designator ("identifier: value") */
2020 designator = allocate_ast_zero(sizeof(designator[0]));
2021 designator->source_position = token.base.source_position;
2022 designator->symbol = token.identifier.symbol;
2027 /* reset path to toplevel, evaluate designator from there */
2028 ascend_to(path, top_path_level);
2029 if (!walk_designator(path, designator, false)) {
2030 /* can't continue after designation error */
2034 initializer_t *designator_initializer
2035 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2036 designator_initializer->designator.designator = designator;
2037 ARR_APP1(initializer_t*, initializers, designator_initializer);
2039 orig_type = path->top_type;
2040 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2045 if (token.kind == '{') {
2046 if (type != NULL && is_type_scalar(type)) {
2047 sub = parse_scalar_initializer(type, env->must_be_constant);
2050 if (env->entity != NULL) {
2052 "extra brace group at end of initializer for '%Y'",
2053 env->entity->base.symbol);
2055 errorf(HERE, "extra brace group at end of initializer");
2060 descend_into_subtype(path);
2063 add_anchor_token('}');
2064 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2066 rem_anchor_token('}');
2071 goto error_parse_next;
2073 ascend_from_subtype(path);
2076 /* must be an expression */
2077 expression_t *expression = parse_assignment_expression();
2078 mark_vars_read(expression, NULL);
2080 if (env->must_be_constant && !is_linker_constant(expression)) {
2081 errorf(&expression->base.source_position,
2082 "Initialisation expression '%E' is not constant",
2087 /* we are already outside, ... */
2088 if (outer_type == NULL)
2089 goto error_parse_next;
2090 type_t *const outer_type_skip = skip_typeref(outer_type);
2091 if (is_type_compound(outer_type_skip) &&
2092 !outer_type_skip->compound.compound->complete) {
2093 goto error_parse_next;
2096 source_position_t const* const pos = &expression->base.source_position;
2097 if (env->entity != NULL) {
2098 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2100 warningf(WARN_OTHER, pos, "excess elements in initializer");
2102 goto error_parse_next;
2105 /* handle { "string" } special case */
2106 if ((expression->kind == EXPR_STRING_LITERAL
2107 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2108 && outer_type != NULL) {
2109 sub = initializer_from_expression(outer_type, expression);
2112 if (token.kind != '}') {
2113 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2115 /* TODO: eat , ... */
2120 /* descend into subtypes until expression matches type */
2122 orig_type = path->top_type;
2123 type = skip_typeref(orig_type);
2125 sub = initializer_from_expression(orig_type, expression);
2129 if (!is_type_valid(type)) {
2132 if (is_type_scalar(type)) {
2133 errorf(&expression->base.source_position,
2134 "expression '%E' doesn't match expected type '%T'",
2135 expression, orig_type);
2139 descend_into_subtype(path);
2143 /* update largest index of top array */
2144 const type_path_entry_t *first = &path->path[0];
2145 type_t *first_type = first->type;
2146 first_type = skip_typeref(first_type);
2147 if (is_type_array(first_type)) {
2148 size_t index = first->v.index;
2149 if (index > path->max_index)
2150 path->max_index = index;
2153 /* append to initializers list */
2154 ARR_APP1(initializer_t*, initializers, sub);
2157 if (token.kind == '}') {
2160 add_anchor_token('}');
2162 rem_anchor_token('}');
2163 if (token.kind == '}') {
2168 /* advance to the next declaration if we are not at the end */
2169 advance_current_object(path, top_path_level);
2170 orig_type = path->top_type;
2171 if (orig_type != NULL)
2172 type = skip_typeref(orig_type);
2178 size_t len = ARR_LEN(initializers);
2179 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2180 initializer_t *result = allocate_ast_zero(size);
2181 result->kind = INITIALIZER_LIST;
2182 result->list.len = len;
2183 memcpy(&result->list.initializers, initializers,
2184 len * sizeof(initializers[0]));
2186 DEL_ARR_F(initializers);
2187 ascend_to(path, top_path_level+1);
2192 skip_initializers();
2193 DEL_ARR_F(initializers);
2194 ascend_to(path, top_path_level+1);
2198 static expression_t *make_size_literal(size_t value)
2200 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2201 literal->base.type = type_size_t;
2204 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2205 literal->literal.value = make_string(buf);
2211 * Parses an initializer. Parsers either a compound literal
2212 * (env->declaration == NULL) or an initializer of a declaration.
2214 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2216 type_t *type = skip_typeref(env->type);
2217 size_t max_index = 0;
2218 initializer_t *result;
2220 if (is_type_scalar(type)) {
2221 result = parse_scalar_initializer(type, env->must_be_constant);
2222 } else if (token.kind == '{') {
2226 memset(&path, 0, sizeof(path));
2227 path.top_type = env->type;
2228 path.path = NEW_ARR_F(type_path_entry_t, 0);
2230 descend_into_subtype(&path);
2232 add_anchor_token('}');
2233 result = parse_sub_initializer(&path, env->type, 1, env);
2234 rem_anchor_token('}');
2236 max_index = path.max_index;
2237 DEL_ARR_F(path.path);
2241 /* parse_scalar_initializer() also works in this case: we simply
2242 * have an expression without {} around it */
2243 result = parse_scalar_initializer(type, env->must_be_constant);
2246 /* §6.7.8:22 array initializers for arrays with unknown size determine
2247 * the array type size */
2248 if (is_type_array(type) && type->array.size_expression == NULL
2249 && result != NULL) {
2251 switch (result->kind) {
2252 case INITIALIZER_LIST:
2253 assert(max_index != 0xdeadbeaf);
2254 size = max_index + 1;
2257 case INITIALIZER_STRING:
2258 size = result->string.string.size;
2261 case INITIALIZER_WIDE_STRING:
2262 size = result->wide_string.string.size;
2265 case INITIALIZER_DESIGNATOR:
2266 case INITIALIZER_VALUE:
2267 /* can happen for parse errors */
2272 internal_errorf(HERE, "invalid initializer type");
2275 type_t *new_type = duplicate_type(type);
2277 new_type->array.size_expression = make_size_literal(size);
2278 new_type->array.size_constant = true;
2279 new_type->array.has_implicit_size = true;
2280 new_type->array.size = size;
2281 env->type = new_type;
2287 static void append_entity(scope_t *scope, entity_t *entity)
2289 if (scope->last_entity != NULL) {
2290 scope->last_entity->base.next = entity;
2292 scope->entities = entity;
2294 entity->base.parent_entity = current_entity;
2295 scope->last_entity = entity;
2299 static compound_t *parse_compound_type_specifier(bool is_struct)
2301 source_position_t const pos = *HERE;
2302 eat(is_struct ? T_struct : T_union);
2304 symbol_t *symbol = NULL;
2305 entity_t *entity = NULL;
2306 attribute_t *attributes = NULL;
2308 if (token.kind == T___attribute__) {
2309 attributes = parse_attributes(NULL);
2312 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2313 if (token.kind == T_IDENTIFIER) {
2314 /* the compound has a name, check if we have seen it already */
2315 symbol = token.identifier.symbol;
2316 entity = get_tag(symbol, kind);
2319 if (entity != NULL) {
2320 if (entity->base.parent_scope != current_scope &&
2321 (token.kind == '{' || token.kind == ';')) {
2322 /* we're in an inner scope and have a definition. Shadow
2323 * existing definition in outer scope */
2325 } else if (entity->compound.complete && token.kind == '{') {
2326 source_position_t const *const ppos = &entity->base.source_position;
2327 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2328 /* clear members in the hope to avoid further errors */
2329 entity->compound.members.entities = NULL;
2332 } else if (token.kind != '{') {
2333 char const *const msg =
2334 is_struct ? "while parsing struct type specifier" :
2335 "while parsing union type specifier";
2336 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2341 if (entity == NULL) {
2342 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2343 entity->compound.alignment = 1;
2344 entity->base.parent_scope = current_scope;
2345 if (symbol != NULL) {
2346 environment_push(entity);
2348 append_entity(current_scope, entity);
2351 if (token.kind == '{') {
2352 parse_compound_type_entries(&entity->compound);
2354 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2355 if (symbol == NULL) {
2356 assert(anonymous_entity == NULL);
2357 anonymous_entity = entity;
2361 if (attributes != NULL) {
2362 handle_entity_attributes(attributes, entity);
2365 return &entity->compound;
2368 static void parse_enum_entries(type_t *const enum_type)
2372 if (token.kind == '}') {
2373 errorf(HERE, "empty enum not allowed");
2378 add_anchor_token('}');
2379 add_anchor_token(',');
2381 add_anchor_token('=');
2382 source_position_t pos;
2383 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2384 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2385 entity->enum_value.enum_type = enum_type;
2386 rem_anchor_token('=');
2389 expression_t *value = parse_constant_expression();
2391 value = create_implicit_cast(value, enum_type);
2392 entity->enum_value.value = value;
2397 record_entity(entity, false);
2398 } while (next_if(',') && token.kind != '}');
2399 rem_anchor_token(',');
2400 rem_anchor_token('}');
2405 static type_t *parse_enum_specifier(void)
2407 source_position_t const pos = *HERE;
2412 switch (token.kind) {
2414 symbol = token.identifier.symbol;
2415 entity = get_tag(symbol, ENTITY_ENUM);
2418 if (entity != NULL) {
2419 if (entity->base.parent_scope != current_scope &&
2420 (token.kind == '{' || token.kind == ';')) {
2421 /* we're in an inner scope and have a definition. Shadow
2422 * existing definition in outer scope */
2424 } else if (entity->enume.complete && token.kind == '{') {
2425 source_position_t const *const ppos = &entity->base.source_position;
2426 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2437 parse_error_expected("while parsing enum type specifier",
2438 T_IDENTIFIER, '{', NULL);
2442 if (entity == NULL) {
2443 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2444 entity->base.parent_scope = current_scope;
2447 type_t *const type = allocate_type_zero(TYPE_ENUM);
2448 type->enumt.enume = &entity->enume;
2449 type->enumt.base.akind = ATOMIC_TYPE_INT;
2451 if (token.kind == '{') {
2452 if (symbol != NULL) {
2453 environment_push(entity);
2455 append_entity(current_scope, entity);
2456 entity->enume.complete = true;
2458 parse_enum_entries(type);
2459 parse_attributes(NULL);
2461 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2462 if (symbol == NULL) {
2463 assert(anonymous_entity == NULL);
2464 anonymous_entity = entity;
2466 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2467 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2474 * if a symbol is a typedef to another type, return true
2476 static bool is_typedef_symbol(symbol_t *symbol)
2478 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2479 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2482 static type_t *parse_typeof(void)
2489 add_anchor_token(')');
2491 expression_t *expression = NULL;
2493 switch (token.kind) {
2495 if (is_typedef_symbol(token.identifier.symbol)) {
2497 type = parse_typename();
2500 expression = parse_expression();
2501 type = revert_automatic_type_conversion(expression);
2506 rem_anchor_token(')');
2509 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2510 typeof_type->typeoft.expression = expression;
2511 typeof_type->typeoft.typeof_type = type;
2516 typedef enum specifiers_t {
2517 SPECIFIER_SIGNED = 1 << 0,
2518 SPECIFIER_UNSIGNED = 1 << 1,
2519 SPECIFIER_LONG = 1 << 2,
2520 SPECIFIER_INT = 1 << 3,
2521 SPECIFIER_DOUBLE = 1 << 4,
2522 SPECIFIER_CHAR = 1 << 5,
2523 SPECIFIER_WCHAR_T = 1 << 6,
2524 SPECIFIER_SHORT = 1 << 7,
2525 SPECIFIER_LONG_LONG = 1 << 8,
2526 SPECIFIER_FLOAT = 1 << 9,
2527 SPECIFIER_BOOL = 1 << 10,
2528 SPECIFIER_VOID = 1 << 11,
2529 SPECIFIER_INT8 = 1 << 12,
2530 SPECIFIER_INT16 = 1 << 13,
2531 SPECIFIER_INT32 = 1 << 14,
2532 SPECIFIER_INT64 = 1 << 15,
2533 SPECIFIER_INT128 = 1 << 16,
2534 SPECIFIER_COMPLEX = 1 << 17,
2535 SPECIFIER_IMAGINARY = 1 << 18,
2538 static type_t *get_typedef_type(symbol_t *symbol)
2540 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2541 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2544 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2545 type->typedeft.typedefe = &entity->typedefe;
2550 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2552 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2556 add_anchor_token(')');
2557 add_anchor_token(',');
2559 add_anchor_token('=');
2560 source_position_t pos;
2561 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2562 rem_anchor_token('=');
2564 symbol_t **prop = NULL;
2566 if (streq(prop_sym->string, "put")) {
2567 prop = &property->put_symbol;
2568 } else if (streq(prop_sym->string, "get")) {
2569 prop = &property->get_symbol;
2571 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2575 add_anchor_token(T_IDENTIFIER);
2577 rem_anchor_token(T_IDENTIFIER);
2579 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2581 *prop = sym ? sym : sym_anonymous;
2582 } while (next_if(','));
2583 rem_anchor_token(',');
2584 rem_anchor_token(')');
2586 attribute->a.property = property;
2592 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2594 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2595 if (next_if(T_restrict)) {
2596 kind = ATTRIBUTE_MS_RESTRICT;
2597 } else if (token.kind == T_IDENTIFIER) {
2598 const char *name = token.identifier.symbol->string;
2599 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2601 const char *attribute_name = get_attribute_name(k);
2602 if (attribute_name != NULL && streq(attribute_name, name)) {
2608 if (kind == ATTRIBUTE_UNKNOWN) {
2609 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2612 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2616 attribute_t *attribute = allocate_attribute_zero(kind);
2619 if (kind == ATTRIBUTE_MS_PROPERTY) {
2620 return parse_attribute_ms_property(attribute);
2623 /* parse arguments */
2625 attribute->a.arguments = parse_attribute_arguments();
2630 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2635 if (token.kind != ')') {
2636 add_anchor_token(')');
2638 attribute_t **anchor = &first;
2640 while (*anchor != NULL)
2641 anchor = &(*anchor)->next;
2643 attribute_t *attribute
2644 = parse_microsoft_extended_decl_modifier_single();
2645 if (attribute == NULL)
2648 *anchor = attribute;
2649 anchor = &attribute->next;
2650 } while (next_if(','));
2652 rem_anchor_token(')');
2658 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2660 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2661 if (is_declaration(entity)) {
2662 entity->declaration.type = type_error_type;
2663 entity->declaration.implicit = true;
2664 } else if (kind == ENTITY_TYPEDEF) {
2665 entity->typedefe.type = type_error_type;
2666 entity->typedefe.builtin = true;
2668 if (kind != ENTITY_COMPOUND_MEMBER)
2669 record_entity(entity, false);
2673 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2675 type_t *type = NULL;
2676 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2677 unsigned type_specifiers = 0;
2678 bool newtype = false;
2679 bool saw_error = false;
2681 memset(specifiers, 0, sizeof(*specifiers));
2682 specifiers->source_position = token.base.source_position;
2685 specifiers->attributes = parse_attributes(specifiers->attributes);
2687 switch (token.kind) {
2689 #define MATCH_STORAGE_CLASS(token, class) \
2691 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2692 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2694 specifiers->storage_class = class; \
2695 if (specifiers->thread_local) \
2696 goto check_thread_storage_class; \
2700 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2701 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2702 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2703 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2704 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2707 specifiers->attributes
2708 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2712 if (specifiers->thread_local) {
2713 errorf(HERE, "duplicate '__thread'");
2715 specifiers->thread_local = true;
2716 check_thread_storage_class:
2717 switch (specifiers->storage_class) {
2718 case STORAGE_CLASS_EXTERN:
2719 case STORAGE_CLASS_NONE:
2720 case STORAGE_CLASS_STATIC:
2724 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2725 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2726 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2727 wrong_thread_storage_class:
2728 errorf(HERE, "'__thread' used with '%s'", wrong);
2735 /* type qualifiers */
2736 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2738 qualifiers |= qualifier; \
2742 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2743 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2744 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2745 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2746 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2747 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2748 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2749 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2751 /* type specifiers */
2752 #define MATCH_SPECIFIER(token, specifier, name) \
2754 if (type_specifiers & specifier) { \
2755 errorf(HERE, "multiple " name " type specifiers given"); \
2757 type_specifiers |= specifier; \
2762 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2763 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2764 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2765 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2766 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2767 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2768 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2769 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2770 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2771 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2772 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2773 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2774 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2775 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2776 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2777 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2778 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2779 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2783 specifiers->is_inline = true;
2787 case T__forceinline:
2789 specifiers->modifiers |= DM_FORCEINLINE;
2794 if (type_specifiers & SPECIFIER_LONG_LONG) {
2795 errorf(HERE, "too many long type specifiers given");
2796 } else if (type_specifiers & SPECIFIER_LONG) {
2797 type_specifiers |= SPECIFIER_LONG_LONG;
2799 type_specifiers |= SPECIFIER_LONG;
2804 #define CHECK_DOUBLE_TYPE() \
2805 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2808 CHECK_DOUBLE_TYPE();
2809 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2811 type->compound.compound = parse_compound_type_specifier(true);
2814 CHECK_DOUBLE_TYPE();
2815 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2816 type->compound.compound = parse_compound_type_specifier(false);
2819 CHECK_DOUBLE_TYPE();
2820 type = parse_enum_specifier();
2823 CHECK_DOUBLE_TYPE();
2824 type = parse_typeof();
2826 case T___builtin_va_list:
2827 CHECK_DOUBLE_TYPE();
2828 type = duplicate_type(type_valist);
2832 case T_IDENTIFIER: {
2833 /* only parse identifier if we haven't found a type yet */
2834 if (type != NULL || type_specifiers != 0) {
2835 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2836 * declaration, so it doesn't generate errors about expecting '(' or
2838 switch (look_ahead(1)->kind) {
2845 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2849 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2854 goto finish_specifiers;
2858 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2859 if (typedef_type == NULL) {
2860 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2861 * declaration, so it doesn't generate 'implicit int' followed by more
2862 * errors later on. */
2863 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2869 errorf(HERE, "%K does not name a type", &token);
2871 symbol_t *symbol = token.identifier.symbol;
2873 = create_error_entity(symbol, ENTITY_TYPEDEF);
2875 type = allocate_type_zero(TYPE_TYPEDEF);
2876 type->typedeft.typedefe = &entity->typedefe;
2884 goto finish_specifiers;
2889 type = typedef_type;
2893 /* function specifier */
2895 goto finish_specifiers;
2900 specifiers->attributes = parse_attributes(specifiers->attributes);
2902 if (type == NULL || (saw_error && type_specifiers != 0)) {
2903 atomic_type_kind_t atomic_type;
2905 /* match valid basic types */
2906 switch (type_specifiers) {
2907 case SPECIFIER_VOID:
2908 atomic_type = ATOMIC_TYPE_VOID;
2910 case SPECIFIER_WCHAR_T:
2911 atomic_type = ATOMIC_TYPE_WCHAR_T;
2913 case SPECIFIER_CHAR:
2914 atomic_type = ATOMIC_TYPE_CHAR;
2916 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2917 atomic_type = ATOMIC_TYPE_SCHAR;
2919 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2920 atomic_type = ATOMIC_TYPE_UCHAR;
2922 case SPECIFIER_SHORT:
2923 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2924 case SPECIFIER_SHORT | SPECIFIER_INT:
2925 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2926 atomic_type = ATOMIC_TYPE_SHORT;
2928 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2929 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2930 atomic_type = ATOMIC_TYPE_USHORT;
2933 case SPECIFIER_SIGNED:
2934 case SPECIFIER_SIGNED | SPECIFIER_INT:
2935 atomic_type = ATOMIC_TYPE_INT;
2937 case SPECIFIER_UNSIGNED:
2938 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2939 atomic_type = ATOMIC_TYPE_UINT;
2941 case SPECIFIER_LONG:
2942 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2943 case SPECIFIER_LONG | SPECIFIER_INT:
2944 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2945 atomic_type = ATOMIC_TYPE_LONG;
2947 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2948 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2949 atomic_type = ATOMIC_TYPE_ULONG;
2952 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2953 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2954 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2955 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2957 atomic_type = ATOMIC_TYPE_LONGLONG;
2958 goto warn_about_long_long;
2960 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2961 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2963 atomic_type = ATOMIC_TYPE_ULONGLONG;
2964 warn_about_long_long:
2965 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2968 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2969 atomic_type = unsigned_int8_type_kind;
2972 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2973 atomic_type = unsigned_int16_type_kind;
2976 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2977 atomic_type = unsigned_int32_type_kind;
2980 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2981 atomic_type = unsigned_int64_type_kind;
2984 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2985 atomic_type = unsigned_int128_type_kind;
2988 case SPECIFIER_INT8:
2989 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2990 atomic_type = int8_type_kind;
2993 case SPECIFIER_INT16:
2994 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2995 atomic_type = int16_type_kind;
2998 case SPECIFIER_INT32:
2999 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3000 atomic_type = int32_type_kind;
3003 case SPECIFIER_INT64:
3004 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3005 atomic_type = int64_type_kind;
3008 case SPECIFIER_INT128:
3009 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3010 atomic_type = int128_type_kind;
3013 case SPECIFIER_FLOAT:
3014 atomic_type = ATOMIC_TYPE_FLOAT;
3016 case SPECIFIER_DOUBLE:
3017 atomic_type = ATOMIC_TYPE_DOUBLE;
3019 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3020 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3022 case SPECIFIER_BOOL:
3023 atomic_type = ATOMIC_TYPE_BOOL;
3025 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3026 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3027 atomic_type = ATOMIC_TYPE_FLOAT;
3029 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3030 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3031 atomic_type = ATOMIC_TYPE_DOUBLE;
3033 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3034 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3035 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3038 /* invalid specifier combination, give an error message */
3039 source_position_t const* const pos = &specifiers->source_position;
3040 if (type_specifiers == 0) {
3042 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3043 if (!(c_mode & _CXX) && !strict_mode) {
3044 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3045 atomic_type = ATOMIC_TYPE_INT;
3048 errorf(pos, "no type specifiers given in declaration");
3051 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3052 (type_specifiers & SPECIFIER_UNSIGNED)) {
3053 errorf(pos, "signed and unsigned specifiers given");
3054 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3055 errorf(pos, "only integer types can be signed or unsigned");
3057 errorf(pos, "multiple datatypes in declaration");
3063 if (type_specifiers & SPECIFIER_COMPLEX) {
3064 type = allocate_type_zero(TYPE_COMPLEX);
3065 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3066 type = allocate_type_zero(TYPE_IMAGINARY);
3068 type = allocate_type_zero(TYPE_ATOMIC);
3070 type->atomic.akind = atomic_type;
3072 } else if (type_specifiers != 0) {
3073 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3076 /* FIXME: check type qualifiers here */
3077 type->base.qualifiers = qualifiers;
3080 type = identify_new_type(type);
3082 type = typehash_insert(type);
3085 if (specifiers->attributes != NULL)
3086 type = handle_type_attributes(specifiers->attributes, type);
3087 specifiers->type = type;
3091 specifiers->type = type_error_type;
3094 static type_qualifiers_t parse_type_qualifiers(void)
3096 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3099 switch (token.kind) {
3100 /* type qualifiers */
3101 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3102 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3103 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3104 /* microsoft extended type modifiers */
3105 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3106 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3107 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3108 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3109 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3118 * Parses an K&R identifier list
3120 static void parse_identifier_list(scope_t *scope)
3122 assert(token.kind == T_IDENTIFIER);
3124 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3125 /* a K&R parameter has no type, yet */
3129 append_entity(scope, entity);
3130 } while (next_if(',') && token.kind == T_IDENTIFIER);
3133 static entity_t *parse_parameter(void)
3135 declaration_specifiers_t specifiers;
3136 parse_declaration_specifiers(&specifiers);
3138 entity_t *entity = parse_declarator(&specifiers,
3139 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3140 anonymous_entity = NULL;
3144 static void semantic_parameter_incomplete(const entity_t *entity)
3146 assert(entity->kind == ENTITY_PARAMETER);
3148 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3149 * list in a function declarator that is part of a
3150 * definition of that function shall not have
3151 * incomplete type. */
3152 type_t *type = skip_typeref(entity->declaration.type);
3153 if (is_type_incomplete(type)) {
3154 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3158 static bool has_parameters(void)
3160 /* func(void) is not a parameter */
3161 if (look_ahead(1)->kind != ')')
3163 if (token.kind == T_IDENTIFIER) {
3164 entity_t const *const entity
3165 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3168 if (entity->kind != ENTITY_TYPEDEF)
3170 type_t const *const type = skip_typeref(entity->typedefe.type);
3171 if (!is_type_void(type))
3173 if (c_mode & _CXX) {
3174 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3175 * is not allowed. */
3176 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3177 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3178 /* §6.7.5.3:10 Qualification is not allowed here. */
3179 errorf(HERE, "'void' as parameter must not have type qualifiers");
3181 } else if (token.kind != T_void) {
3189 * Parses function type parameters (and optionally creates variable_t entities
3190 * for them in a scope)
3192 static void parse_parameters(function_type_t *type, scope_t *scope)
3195 add_anchor_token(')');
3197 if (token.kind == T_IDENTIFIER &&
3198 !is_typedef_symbol(token.identifier.symbol) &&
3199 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3200 type->kr_style_parameters = true;
3201 parse_identifier_list(scope);
3202 } else if (token.kind == ')') {
3203 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3204 if (!(c_mode & _CXX))
3205 type->unspecified_parameters = true;
3206 } else if (has_parameters()) {
3207 function_parameter_t **anchor = &type->parameters;
3208 add_anchor_token(',');
3210 switch (token.kind) {
3213 type->variadic = true;
3214 goto parameters_finished;
3219 entity_t *entity = parse_parameter();
3220 if (entity->kind == ENTITY_TYPEDEF) {
3221 errorf(&entity->base.source_position,
3222 "typedef not allowed as function parameter");
3225 assert(is_declaration(entity));
3227 semantic_parameter_incomplete(entity);
3229 function_parameter_t *const parameter =
3230 allocate_parameter(entity->declaration.type);
3232 if (scope != NULL) {
3233 append_entity(scope, entity);
3236 *anchor = parameter;
3237 anchor = ¶meter->next;
3242 goto parameters_finished;
3244 } while (next_if(','));
3245 parameters_finished:
3246 rem_anchor_token(',');
3249 rem_anchor_token(')');
3253 typedef enum construct_type_kind_t {
3254 CONSTRUCT_POINTER = 1,
3255 CONSTRUCT_REFERENCE,
3258 } construct_type_kind_t;
3260 typedef union construct_type_t construct_type_t;
3262 typedef struct construct_type_base_t {
3263 construct_type_kind_t kind;
3264 source_position_t pos;
3265 construct_type_t *next;
3266 } construct_type_base_t;
3268 typedef struct parsed_pointer_t {
3269 construct_type_base_t base;
3270 type_qualifiers_t type_qualifiers;
3271 variable_t *base_variable; /**< MS __based extension. */
3274 typedef struct parsed_reference_t {
3275 construct_type_base_t base;
3276 } parsed_reference_t;
3278 typedef struct construct_function_type_t {
3279 construct_type_base_t base;
3280 type_t *function_type;
3281 } construct_function_type_t;
3283 typedef struct parsed_array_t {
3284 construct_type_base_t base;
3285 type_qualifiers_t type_qualifiers;
3291 union construct_type_t {
3292 construct_type_kind_t kind;
3293 construct_type_base_t base;
3294 parsed_pointer_t pointer;
3295 parsed_reference_t reference;
3296 construct_function_type_t function;
3297 parsed_array_t array;
3300 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3302 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3303 memset(cons, 0, size);
3305 cons->base.pos = *HERE;
3310 static construct_type_t *parse_pointer_declarator(void)
3312 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3314 cons->pointer.type_qualifiers = parse_type_qualifiers();
3315 //cons->pointer.base_variable = base_variable;
3320 /* ISO/IEC 14882:1998(E) §8.3.2 */
3321 static construct_type_t *parse_reference_declarator(void)
3323 if (!(c_mode & _CXX))
3324 errorf(HERE, "references are only available for C++");
3326 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3333 static construct_type_t *parse_array_declarator(void)
3335 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3336 parsed_array_t *const array = &cons->array;
3339 add_anchor_token(']');
3341 bool is_static = next_if(T_static);
3343 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3346 is_static = next_if(T_static);
3348 array->type_qualifiers = type_qualifiers;
3349 array->is_static = is_static;
3351 expression_t *size = NULL;
3352 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3353 array->is_variable = true;
3355 } else if (token.kind != ']') {
3356 size = parse_assignment_expression();
3358 /* §6.7.5.2:1 Array size must have integer type */
3359 type_t *const orig_type = size->base.type;
3360 type_t *const type = skip_typeref(orig_type);
3361 if (!is_type_integer(type) && is_type_valid(type)) {
3362 errorf(&size->base.source_position,
3363 "array size '%E' must have integer type but has type '%T'",
3368 mark_vars_read(size, NULL);
3371 if (is_static && size == NULL)
3372 errorf(&array->base.pos, "static array parameters require a size");
3374 rem_anchor_token(']');
3380 static construct_type_t *parse_function_declarator(scope_t *scope)
3382 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3384 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3385 function_type_t *ftype = &type->function;
3387 ftype->linkage = current_linkage;
3388 ftype->calling_convention = CC_DEFAULT;
3390 parse_parameters(ftype, scope);
3392 cons->function.function_type = type;
3397 typedef struct parse_declarator_env_t {
3398 bool may_be_abstract : 1;
3399 bool must_be_abstract : 1;
3400 decl_modifiers_t modifiers;
3402 source_position_t source_position;
3404 attribute_t *attributes;
3405 } parse_declarator_env_t;
3408 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3410 /* construct a single linked list of construct_type_t's which describe
3411 * how to construct the final declarator type */
3412 construct_type_t *first = NULL;
3413 construct_type_t **anchor = &first;
3415 env->attributes = parse_attributes(env->attributes);
3418 construct_type_t *type;
3419 //variable_t *based = NULL; /* MS __based extension */
3420 switch (token.kind) {
3422 type = parse_reference_declarator();
3426 panic("based not supported anymore");
3431 type = parse_pointer_declarator();
3435 goto ptr_operator_end;
3439 anchor = &type->base.next;
3441 /* TODO: find out if this is correct */
3442 env->attributes = parse_attributes(env->attributes);
3446 construct_type_t *inner_types = NULL;
3448 switch (token.kind) {
3450 if (env->must_be_abstract) {
3451 errorf(HERE, "no identifier expected in typename");
3453 env->symbol = token.identifier.symbol;
3454 env->source_position = token.base.source_position;
3460 /* Parenthesized declarator or function declarator? */
3461 token_t const *const la1 = look_ahead(1);
3462 switch (la1->kind) {
3464 if (is_typedef_symbol(la1->identifier.symbol)) {
3466 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3467 * interpreted as ``function with no parameter specification'', rather
3468 * than redundant parentheses around the omitted identifier. */
3470 /* Function declarator. */
3471 if (!env->may_be_abstract) {
3472 errorf(HERE, "function declarator must have a name");
3479 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3480 /* Paranthesized declarator. */
3482 add_anchor_token(')');
3483 inner_types = parse_inner_declarator(env);
3484 if (inner_types != NULL) {
3485 /* All later declarators only modify the return type */
3486 env->must_be_abstract = true;
3488 rem_anchor_token(')');
3497 if (env->may_be_abstract)
3499 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3504 construct_type_t **const p = anchor;
3507 construct_type_t *type;
3508 switch (token.kind) {
3510 scope_t *scope = NULL;
3511 if (!env->must_be_abstract) {
3512 scope = &env->parameters;
3515 type = parse_function_declarator(scope);
3519 type = parse_array_declarator();
3522 goto declarator_finished;
3525 /* insert in the middle of the list (at p) */
3526 type->base.next = *p;
3529 anchor = &type->base.next;
3532 declarator_finished:
3533 /* append inner_types at the end of the list, we don't to set anchor anymore
3534 * as it's not needed anymore */
3535 *anchor = inner_types;
3540 static type_t *construct_declarator_type(construct_type_t *construct_list,
3543 construct_type_t *iter = construct_list;
3544 for (; iter != NULL; iter = iter->base.next) {
3545 source_position_t const* const pos = &iter->base.pos;
3546 switch (iter->kind) {
3547 case CONSTRUCT_FUNCTION: {
3548 construct_function_type_t *function = &iter->function;
3549 type_t *function_type = function->function_type;
3551 function_type->function.return_type = type;
3553 type_t *skipped_return_type = skip_typeref(type);
3555 if (is_type_function(skipped_return_type)) {
3556 errorf(pos, "function returning function is not allowed");
3557 } else if (is_type_array(skipped_return_type)) {
3558 errorf(pos, "function returning array is not allowed");
3560 if (skipped_return_type->base.qualifiers != 0) {
3561 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3565 /* The function type was constructed earlier. Freeing it here will
3566 * destroy other types. */
3567 type = typehash_insert(function_type);
3571 case CONSTRUCT_POINTER: {
3572 if (is_type_reference(skip_typeref(type)))
3573 errorf(pos, "cannot declare a pointer to reference");
3575 parsed_pointer_t *pointer = &iter->pointer;
3576 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3580 case CONSTRUCT_REFERENCE:
3581 if (is_type_reference(skip_typeref(type)))
3582 errorf(pos, "cannot declare a reference to reference");
3584 type = make_reference_type(type);
3587 case CONSTRUCT_ARRAY: {
3588 if (is_type_reference(skip_typeref(type)))
3589 errorf(pos, "cannot declare an array of references");
3591 parsed_array_t *array = &iter->array;
3592 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3594 expression_t *size_expression = array->size;
3595 if (size_expression != NULL) {
3597 = create_implicit_cast(size_expression, type_size_t);
3600 array_type->base.qualifiers = array->type_qualifiers;
3601 array_type->array.element_type = type;
3602 array_type->array.is_static = array->is_static;
3603 array_type->array.is_variable = array->is_variable;
3604 array_type->array.size_expression = size_expression;
3606 if (size_expression != NULL) {
3607 switch (is_constant_expression(size_expression)) {
3608 case EXPR_CLASS_CONSTANT: {
3609 long const size = fold_constant_to_int(size_expression);
3610 array_type->array.size = size;
3611 array_type->array.size_constant = true;
3612 /* §6.7.5.2:1 If the expression is a constant expression,
3613 * it shall have a value greater than zero. */
3615 errorf(&size_expression->base.source_position,
3616 "size of array must be greater than zero");
3617 } else if (size == 0 && !GNU_MODE) {
3618 errorf(&size_expression->base.source_position,
3619 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3624 case EXPR_CLASS_VARIABLE:
3625 array_type->array.is_vla = true;
3628 case EXPR_CLASS_ERROR:
3633 type_t *skipped_type = skip_typeref(type);
3635 if (is_type_incomplete(skipped_type)) {
3636 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3637 } else if (is_type_function(skipped_type)) {
3638 errorf(pos, "array of functions is not allowed");
3640 type = identify_new_type(array_type);
3644 internal_errorf(pos, "invalid type construction found");
3650 static type_t *automatic_type_conversion(type_t *orig_type);
3652 static type_t *semantic_parameter(const source_position_t *pos,
3654 const declaration_specifiers_t *specifiers,
3655 entity_t const *const param)
3657 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3658 * shall be adjusted to ``qualified pointer to type'',
3660 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3661 * type'' shall be adjusted to ``pointer to function
3662 * returning type'', as in 6.3.2.1. */
3663 type = automatic_type_conversion(type);
3665 if (specifiers->is_inline && is_type_valid(type)) {
3666 errorf(pos, "'%N' declared 'inline'", param);
3669 /* §6.9.1:6 The declarations in the declaration list shall contain
3670 * no storage-class specifier other than register and no
3671 * initializations. */
3672 if (specifiers->thread_local || (
3673 specifiers->storage_class != STORAGE_CLASS_NONE &&
3674 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3676 errorf(pos, "invalid storage class for '%N'", param);
3679 /* delay test for incomplete type, because we might have (void)
3680 * which is legal but incomplete... */
3685 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3686 declarator_flags_t flags)
3688 parse_declarator_env_t env;
3689 memset(&env, 0, sizeof(env));
3690 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3692 construct_type_t *construct_type = parse_inner_declarator(&env);
3694 construct_declarator_type(construct_type, specifiers->type);
3695 type_t *type = skip_typeref(orig_type);
3697 if (construct_type != NULL) {
3698 obstack_free(&temp_obst, construct_type);
3701 attribute_t *attributes = parse_attributes(env.attributes);
3702 /* append (shared) specifier attribute behind attributes of this
3704 attribute_t **anchor = &attributes;
3705 while (*anchor != NULL)
3706 anchor = &(*anchor)->next;
3707 *anchor = specifiers->attributes;
3710 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3711 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3712 entity->typedefe.type = orig_type;
3714 if (anonymous_entity != NULL) {
3715 if (is_type_compound(type)) {
3716 assert(anonymous_entity->compound.alias == NULL);
3717 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3718 anonymous_entity->kind == ENTITY_UNION);
3719 anonymous_entity->compound.alias = entity;
3720 anonymous_entity = NULL;
3721 } else if (is_type_enum(type)) {
3722 assert(anonymous_entity->enume.alias == NULL);
3723 assert(anonymous_entity->kind == ENTITY_ENUM);
3724 anonymous_entity->enume.alias = entity;
3725 anonymous_entity = NULL;
3729 /* create a declaration type entity */
3730 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3731 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3732 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3734 if (env.symbol != NULL) {
3735 if (specifiers->is_inline && is_type_valid(type)) {
3736 errorf(&env.source_position,
3737 "compound member '%Y' declared 'inline'", env.symbol);
3740 if (specifiers->thread_local ||
3741 specifiers->storage_class != STORAGE_CLASS_NONE) {
3742 errorf(&env.source_position,
3743 "compound member '%Y' must have no storage class",
3747 } else if (flags & DECL_IS_PARAMETER) {
3748 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3749 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3750 } else if (is_type_function(type)) {
3751 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3752 entity->function.is_inline = specifiers->is_inline;
3753 entity->function.elf_visibility = default_visibility;
3754 entity->function.parameters = env.parameters;
3756 if (env.symbol != NULL) {
3757 /* this needs fixes for C++ */
3758 bool in_function_scope = current_function != NULL;
3760 if (specifiers->thread_local || (
3761 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3762 specifiers->storage_class != STORAGE_CLASS_NONE &&
3763 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3765 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3769 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3770 entity->variable.elf_visibility = default_visibility;
3771 entity->variable.thread_local = specifiers->thread_local;
3773 if (env.symbol != NULL) {
3774 if (specifiers->is_inline && is_type_valid(type)) {
3775 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3778 bool invalid_storage_class = false;
3779 if (current_scope == file_scope) {
3780 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3781 specifiers->storage_class != STORAGE_CLASS_NONE &&
3782 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3783 invalid_storage_class = true;
3786 if (specifiers->thread_local &&
3787 specifiers->storage_class == STORAGE_CLASS_NONE) {
3788 invalid_storage_class = true;
3791 if (invalid_storage_class) {
3792 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3797 entity->declaration.type = orig_type;
3798 entity->declaration.alignment = get_type_alignment(orig_type);
3799 entity->declaration.modifiers = env.modifiers;
3800 entity->declaration.attributes = attributes;
3802 storage_class_t storage_class = specifiers->storage_class;
3803 entity->declaration.declared_storage_class = storage_class;
3805 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3806 storage_class = STORAGE_CLASS_AUTO;
3807 entity->declaration.storage_class = storage_class;
3810 if (attributes != NULL) {
3811 handle_entity_attributes(attributes, entity);
3814 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3815 adapt_special_functions(&entity->function);
3821 static type_t *parse_abstract_declarator(type_t *base_type)
3823 parse_declarator_env_t env;
3824 memset(&env, 0, sizeof(env));
3825 env.may_be_abstract = true;
3826 env.must_be_abstract = true;
3828 construct_type_t *construct_type = parse_inner_declarator(&env);
3830 type_t *result = construct_declarator_type(construct_type, base_type);
3831 if (construct_type != NULL) {
3832 obstack_free(&temp_obst, construct_type);
3834 result = handle_type_attributes(env.attributes, result);
3840 * Check if the declaration of main is suspicious. main should be a
3841 * function with external linkage, returning int, taking either zero
3842 * arguments, two, or three arguments of appropriate types, ie.
3844 * int main([ int argc, char **argv [, char **env ] ]).
3846 * @param decl the declaration to check
3847 * @param type the function type of the declaration
3849 static void check_main(const entity_t *entity)
3851 const source_position_t *pos = &entity->base.source_position;
3852 if (entity->kind != ENTITY_FUNCTION) {
3853 warningf(WARN_MAIN, pos, "'main' is not a function");
3857 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3858 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3861 type_t *type = skip_typeref(entity->declaration.type);
3862 assert(is_type_function(type));
3864 function_type_t const *const func_type = &type->function;
3865 type_t *const ret_type = func_type->return_type;
3866 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3867 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3869 const function_parameter_t *parm = func_type->parameters;
3871 type_t *const first_type = skip_typeref(parm->type);
3872 type_t *const first_type_unqual = get_unqualified_type(first_type);
3873 if (!types_compatible(first_type_unqual, type_int)) {
3874 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3878 type_t *const second_type = skip_typeref(parm->type);
3879 type_t *const second_type_unqual
3880 = get_unqualified_type(second_type);
3881 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3882 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3886 type_t *const third_type = skip_typeref(parm->type);
3887 type_t *const third_type_unqual
3888 = get_unqualified_type(third_type);
3889 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3890 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3894 goto warn_arg_count;
3898 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3904 * Check if a symbol is the equal to "main".
3906 static bool is_sym_main(const symbol_t *const sym)
3908 return streq(sym->string, "main");
3911 static void error_redefined_as_different_kind(const source_position_t *pos,
3912 const entity_t *old, entity_kind_t new_kind)
3914 char const *const what = get_entity_kind_name(new_kind);
3915 source_position_t const *const ppos = &old->base.source_position;
3916 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3919 static bool is_entity_valid(entity_t *const ent)
3921 if (is_declaration(ent)) {
3922 return is_type_valid(skip_typeref(ent->declaration.type));
3923 } else if (ent->kind == ENTITY_TYPEDEF) {
3924 return is_type_valid(skip_typeref(ent->typedefe.type));
3929 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3931 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3932 if (attributes_equal(tattr, attr))
3939 * test wether new_list contains any attributes not included in old_list
3941 static bool has_new_attributes(const attribute_t *old_list,
3942 const attribute_t *new_list)
3944 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3945 if (!contains_attribute(old_list, attr))
3952 * Merge in attributes from an attribute list (probably from a previous
3953 * declaration with the same name). Warning: destroys the old structure
3954 * of the attribute list - don't reuse attributes after this call.
3956 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3959 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3961 if (contains_attribute(decl->attributes, attr))
3964 /* move attribute to new declarations attributes list */
3965 attr->next = decl->attributes;
3966 decl->attributes = attr;
3971 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3972 * for various problems that occur for multiple definitions
3974 entity_t *record_entity(entity_t *entity, const bool is_definition)
3976 const symbol_t *const symbol = entity->base.symbol;
3977 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3978 const source_position_t *pos = &entity->base.source_position;
3980 /* can happen in error cases */
3984 entity_t *const previous_entity = get_entity(symbol, namespc);
3985 /* pushing the same entity twice will break the stack structure */
3986 assert(previous_entity != entity);
3988 if (entity->kind == ENTITY_FUNCTION) {
3989 type_t *const orig_type = entity->declaration.type;
3990 type_t *const type = skip_typeref(orig_type);
3992 assert(is_type_function(type));
3993 if (type->function.unspecified_parameters &&
3994 previous_entity == NULL &&
3995 !entity->declaration.implicit) {
3996 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3999 if (current_scope == file_scope && is_sym_main(symbol)) {
4004 if (is_declaration(entity) &&
4005 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4006 current_scope != file_scope &&
4007 !entity->declaration.implicit) {
4008 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4011 if (previous_entity != NULL) {
4012 source_position_t const *const ppos = &previous_entity->base.source_position;
4014 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4015 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4016 assert(previous_entity->kind == ENTITY_PARAMETER);
4017 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4021 if (previous_entity->base.parent_scope == current_scope) {
4022 if (previous_entity->kind != entity->kind) {
4023 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4024 error_redefined_as_different_kind(pos, previous_entity,
4029 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4030 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4033 if (previous_entity->kind == ENTITY_TYPEDEF) {
4034 type_t *const type = skip_typeref(entity->typedefe.type);
4035 type_t *const prev_type
4036 = skip_typeref(previous_entity->typedefe.type);
4037 if (c_mode & _CXX) {
4038 /* C++ allows double typedef if they are identical
4039 * (after skipping typedefs) */
4040 if (type == prev_type)
4043 /* GCC extension: redef in system headers is allowed */
4044 if ((pos->is_system_header || ppos->is_system_header) &&
4045 types_compatible(type, prev_type))
4048 errorf(pos, "redefinition of '%N' (declared %P)",
4053 /* at this point we should have only VARIABLES or FUNCTIONS */
4054 assert(is_declaration(previous_entity) && is_declaration(entity));
4056 declaration_t *const prev_decl = &previous_entity->declaration;
4057 declaration_t *const decl = &entity->declaration;
4059 /* can happen for K&R style declarations */
4060 if (prev_decl->type == NULL &&
4061 previous_entity->kind == ENTITY_PARAMETER &&
4062 entity->kind == ENTITY_PARAMETER) {
4063 prev_decl->type = decl->type;
4064 prev_decl->storage_class = decl->storage_class;
4065 prev_decl->declared_storage_class = decl->declared_storage_class;
4066 prev_decl->modifiers = decl->modifiers;
4067 return previous_entity;
4070 type_t *const type = skip_typeref(decl->type);
4071 type_t *const prev_type = skip_typeref(prev_decl->type);
4073 if (!types_compatible(type, prev_type)) {
4074 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4076 unsigned old_storage_class = prev_decl->storage_class;
4078 if (is_definition &&
4080 !(prev_decl->modifiers & DM_USED) &&
4081 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4082 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4085 storage_class_t new_storage_class = decl->storage_class;
4087 /* pretend no storage class means extern for function
4088 * declarations (except if the previous declaration is neither
4089 * none nor extern) */
4090 if (entity->kind == ENTITY_FUNCTION) {
4091 /* the previous declaration could have unspecified parameters or
4092 * be a typedef, so use the new type */
4093 if (prev_type->function.unspecified_parameters || is_definition)
4094 prev_decl->type = type;
4096 switch (old_storage_class) {
4097 case STORAGE_CLASS_NONE:
4098 old_storage_class = STORAGE_CLASS_EXTERN;
4101 case STORAGE_CLASS_EXTERN:
4102 if (is_definition) {
4103 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4104 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4106 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4107 new_storage_class = STORAGE_CLASS_EXTERN;
4114 } else if (is_type_incomplete(prev_type)) {
4115 prev_decl->type = type;
4118 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4119 new_storage_class == STORAGE_CLASS_EXTERN) {
4121 warn_redundant_declaration: ;
4123 = has_new_attributes(prev_decl->attributes,
4125 if (has_new_attrs) {
4126 merge_in_attributes(decl, prev_decl->attributes);
4127 } else if (!is_definition &&
4128 is_type_valid(prev_type) &&
4129 !pos->is_system_header) {
4130 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4132 } else if (current_function == NULL) {
4133 if (old_storage_class != STORAGE_CLASS_STATIC &&
4134 new_storage_class == STORAGE_CLASS_STATIC) {
4135 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4136 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4137 prev_decl->storage_class = STORAGE_CLASS_NONE;
4138 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4140 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4142 goto error_redeclaration;
4143 goto warn_redundant_declaration;
4145 } else if (is_type_valid(prev_type)) {
4146 if (old_storage_class == new_storage_class) {
4147 error_redeclaration:
4148 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4150 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4155 prev_decl->modifiers |= decl->modifiers;
4156 if (entity->kind == ENTITY_FUNCTION) {
4157 previous_entity->function.is_inline |= entity->function.is_inline;
4159 return previous_entity;
4163 if (is_warn_on(why = WARN_SHADOW) ||
4164 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4165 char const *const what = get_entity_kind_name(previous_entity->kind);
4166 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4170 if (entity->kind == ENTITY_FUNCTION) {
4171 if (is_definition &&
4172 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4173 !is_sym_main(symbol)) {
4174 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4175 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4177 goto warn_missing_declaration;
4180 } else if (entity->kind == ENTITY_VARIABLE) {
4181 if (current_scope == file_scope &&
4182 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4183 !entity->declaration.implicit) {
4184 warn_missing_declaration:
4185 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4190 assert(entity->base.parent_scope == NULL);
4191 assert(current_scope != NULL);
4193 entity->base.parent_scope = current_scope;
4194 environment_push(entity);
4195 append_entity(current_scope, entity);
4200 static void parser_error_multiple_definition(entity_t *entity,
4201 const source_position_t *source_position)
4203 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4204 entity->base.symbol, &entity->base.source_position);
4207 static bool is_declaration_specifier(const token_t *token)
4209 switch (token->kind) {
4213 return is_typedef_symbol(token->identifier.symbol);
4220 static void parse_init_declarator_rest(entity_t *entity)
4222 type_t *orig_type = type_error_type;
4224 if (entity->base.kind == ENTITY_TYPEDEF) {
4225 source_position_t const *const pos = &entity->base.source_position;
4226 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4228 assert(is_declaration(entity));
4229 orig_type = entity->declaration.type;
4232 type_t *type = skip_typeref(orig_type);
4234 if (entity->kind == ENTITY_VARIABLE
4235 && entity->variable.initializer != NULL) {
4236 parser_error_multiple_definition(entity, HERE);
4240 declaration_t *const declaration = &entity->declaration;
4241 bool must_be_constant = false;
4242 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4243 entity->base.parent_scope == file_scope) {
4244 must_be_constant = true;
4247 if (is_type_function(type)) {
4248 source_position_t const *const pos = &entity->base.source_position;
4249 errorf(pos, "'%N' is initialized like a variable", entity);
4250 orig_type = type_error_type;
4253 parse_initializer_env_t env;
4254 env.type = orig_type;
4255 env.must_be_constant = must_be_constant;
4256 env.entity = entity;
4258 initializer_t *initializer = parse_initializer(&env);
4260 if (entity->kind == ENTITY_VARIABLE) {
4261 /* §6.7.5:22 array initializers for arrays with unknown size
4262 * determine the array type size */
4263 declaration->type = env.type;
4264 entity->variable.initializer = initializer;
4268 /* parse rest of a declaration without any declarator */
4269 static void parse_anonymous_declaration_rest(
4270 const declaration_specifiers_t *specifiers)
4273 anonymous_entity = NULL;
4275 source_position_t const *const pos = &specifiers->source_position;
4276 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4277 specifiers->thread_local) {
4278 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4281 type_t *type = specifiers->type;
4282 switch (type->kind) {
4283 case TYPE_COMPOUND_STRUCT:
4284 case TYPE_COMPOUND_UNION: {
4285 if (type->compound.compound->base.symbol == NULL) {
4286 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4295 warningf(WARN_OTHER, pos, "empty declaration");
4300 static void check_variable_type_complete(entity_t *ent)
4302 if (ent->kind != ENTITY_VARIABLE)
4305 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4306 * type for the object shall be complete [...] */
4307 declaration_t *decl = &ent->declaration;
4308 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4309 decl->storage_class == STORAGE_CLASS_STATIC)
4312 type_t *const type = skip_typeref(decl->type);
4313 if (!is_type_incomplete(type))
4316 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4317 * are given length one. */
4318 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4319 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4323 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4327 static void parse_declaration_rest(entity_t *ndeclaration,
4328 const declaration_specifiers_t *specifiers,
4329 parsed_declaration_func finished_declaration,
4330 declarator_flags_t flags)
4332 add_anchor_token(';');
4333 add_anchor_token(',');
4335 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4337 if (token.kind == '=') {
4338 parse_init_declarator_rest(entity);
4339 } else if (entity->kind == ENTITY_VARIABLE) {
4340 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4341 * [...] where the extern specifier is explicitly used. */
4342 declaration_t *decl = &entity->declaration;
4343 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4344 is_type_reference(skip_typeref(decl->type))) {
4345 source_position_t const *const pos = &entity->base.source_position;
4346 errorf(pos, "reference '%#N' must be initialized", entity);
4350 check_variable_type_complete(entity);
4355 add_anchor_token('=');
4356 ndeclaration = parse_declarator(specifiers, flags);
4357 rem_anchor_token('=');
4359 rem_anchor_token(',');
4360 rem_anchor_token(';');
4363 anonymous_entity = NULL;
4366 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4368 symbol_t *symbol = entity->base.symbol;
4372 assert(entity->base.namespc == NAMESPACE_NORMAL);
4373 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4374 if (previous_entity == NULL
4375 || previous_entity->base.parent_scope != current_scope) {
4376 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4381 if (is_definition) {
4382 errorf(HERE, "'%N' is initialised", entity);
4385 return record_entity(entity, false);
4388 static void parse_declaration(parsed_declaration_func finished_declaration,
4389 declarator_flags_t flags)
4391 add_anchor_token(';');
4392 declaration_specifiers_t specifiers;
4393 parse_declaration_specifiers(&specifiers);
4394 rem_anchor_token(';');
4396 if (token.kind == ';') {
4397 parse_anonymous_declaration_rest(&specifiers);
4399 entity_t *entity = parse_declarator(&specifiers, flags);
4400 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4405 static type_t *get_default_promoted_type(type_t *orig_type)
4407 type_t *result = orig_type;
4409 type_t *type = skip_typeref(orig_type);
4410 if (is_type_integer(type)) {
4411 result = promote_integer(type);
4412 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4413 result = type_double;
4419 static void parse_kr_declaration_list(entity_t *entity)
4421 if (entity->kind != ENTITY_FUNCTION)
4424 type_t *type = skip_typeref(entity->declaration.type);
4425 assert(is_type_function(type));
4426 if (!type->function.kr_style_parameters)
4429 add_anchor_token('{');
4431 PUSH_SCOPE(&entity->function.parameters);
4433 entity_t *parameter = entity->function.parameters.entities;
4434 for ( ; parameter != NULL; parameter = parameter->base.next) {
4435 assert(parameter->base.parent_scope == NULL);
4436 parameter->base.parent_scope = current_scope;
4437 environment_push(parameter);
4440 /* parse declaration list */
4442 switch (token.kind) {
4444 /* This covers symbols, which are no type, too, and results in
4445 * better error messages. The typical cases are misspelled type
4446 * names and missing includes. */
4448 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4458 /* update function type */
4459 type_t *new_type = duplicate_type(type);
4461 function_parameter_t *parameters = NULL;
4462 function_parameter_t **anchor = ¶meters;
4464 /* did we have an earlier prototype? */
4465 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4466 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4469 function_parameter_t *proto_parameter = NULL;
4470 if (proto_type != NULL) {
4471 type_t *proto_type_type = proto_type->declaration.type;
4472 proto_parameter = proto_type_type->function.parameters;
4473 /* If a K&R function definition has a variadic prototype earlier, then
4474 * make the function definition variadic, too. This should conform to
4475 * §6.7.5.3:15 and §6.9.1:8. */
4476 new_type->function.variadic = proto_type_type->function.variadic;
4478 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4480 new_type->function.unspecified_parameters = true;
4483 bool need_incompatible_warning = false;
4484 parameter = entity->function.parameters.entities;
4485 for (; parameter != NULL; parameter = parameter->base.next,
4487 proto_parameter == NULL ? NULL : proto_parameter->next) {
4488 if (parameter->kind != ENTITY_PARAMETER)
4491 type_t *parameter_type = parameter->declaration.type;
4492 if (parameter_type == NULL) {
4493 source_position_t const* const pos = ¶meter->base.source_position;
4495 errorf(pos, "no type specified for function '%N'", parameter);
4496 parameter_type = type_error_type;
4498 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4499 parameter_type = type_int;
4501 parameter->declaration.type = parameter_type;
4504 semantic_parameter_incomplete(parameter);
4506 /* we need the default promoted types for the function type */
4507 type_t *not_promoted = parameter_type;
4508 parameter_type = get_default_promoted_type(parameter_type);
4510 /* gcc special: if the type of the prototype matches the unpromoted
4511 * type don't promote */
4512 if (!strict_mode && proto_parameter != NULL) {
4513 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4514 type_t *promo_skip = skip_typeref(parameter_type);
4515 type_t *param_skip = skip_typeref(not_promoted);
4516 if (!types_compatible(proto_p_type, promo_skip)
4517 && types_compatible(proto_p_type, param_skip)) {
4519 need_incompatible_warning = true;
4520 parameter_type = not_promoted;
4523 function_parameter_t *const function_parameter
4524 = allocate_parameter(parameter_type);
4526 *anchor = function_parameter;
4527 anchor = &function_parameter->next;
4530 new_type->function.parameters = parameters;
4531 new_type = identify_new_type(new_type);
4533 if (need_incompatible_warning) {
4534 symbol_t const *const sym = entity->base.symbol;
4535 source_position_t const *const pos = &entity->base.source_position;
4536 source_position_t const *const ppos = &proto_type->base.source_position;
4537 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4539 entity->declaration.type = new_type;
4541 rem_anchor_token('{');
4544 static bool first_err = true;
4547 * When called with first_err set, prints the name of the current function,
4550 static void print_in_function(void)
4554 char const *const file = current_function->base.base.source_position.input_name;
4555 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4560 * Check if all labels are defined in the current function.
4561 * Check if all labels are used in the current function.
4563 static void check_labels(void)
4565 for (const goto_statement_t *goto_statement = goto_first;
4566 goto_statement != NULL;
4567 goto_statement = goto_statement->next) {
4568 label_t *label = goto_statement->label;
4569 if (label->base.source_position.input_name == NULL) {
4570 print_in_function();
4571 source_position_t const *const pos = &goto_statement->base.source_position;
4572 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4576 if (is_warn_on(WARN_UNUSED_LABEL)) {
4577 for (const label_statement_t *label_statement = label_first;
4578 label_statement != NULL;
4579 label_statement = label_statement->next) {
4580 label_t *label = label_statement->label;
4582 if (! label->used) {
4583 print_in_function();
4584 source_position_t const *const pos = &label_statement->base.source_position;
4585 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4591 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4593 entity_t const *const end = last != NULL ? last->base.next : NULL;
4594 for (; entity != end; entity = entity->base.next) {
4595 if (!is_declaration(entity))
4598 declaration_t *declaration = &entity->declaration;
4599 if (declaration->implicit)
4602 if (!declaration->used) {
4603 print_in_function();
4604 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4605 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4606 print_in_function();
4607 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4612 static void check_unused_variables(statement_t *const stmt, void *const env)
4616 switch (stmt->kind) {
4617 case STATEMENT_DECLARATION: {
4618 declaration_statement_t const *const decls = &stmt->declaration;
4619 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4624 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4633 * Check declarations of current_function for unused entities.
4635 static void check_declarations(void)
4637 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4638 const scope_t *scope = ¤t_function->parameters;
4640 /* do not issue unused warnings for main */
4641 if (!is_sym_main(current_function->base.base.symbol)) {
4642 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4645 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4646 walk_statements(current_function->statement, check_unused_variables,
4651 static int determine_truth(expression_t const* const cond)
4654 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4655 fold_constant_to_bool(cond) ? 1 :
4659 static void check_reachable(statement_t *);
4660 static bool reaches_end;
4662 static bool expression_returns(expression_t const *const expr)
4664 switch (expr->kind) {
4666 expression_t const *const func = expr->call.function;
4667 type_t const *const type = skip_typeref(func->base.type);
4668 if (type->kind == TYPE_POINTER) {
4669 type_t const *const points_to
4670 = skip_typeref(type->pointer.points_to);
4671 if (points_to->kind == TYPE_FUNCTION
4672 && points_to->function.modifiers & DM_NORETURN)
4676 if (!expression_returns(func))
4679 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4680 if (!expression_returns(arg->expression))
4687 case EXPR_REFERENCE:
4688 case EXPR_ENUM_CONSTANT:
4689 case EXPR_LITERAL_CASES:
4690 case EXPR_STRING_LITERAL:
4691 case EXPR_WIDE_STRING_LITERAL:
4692 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4693 case EXPR_LABEL_ADDRESS:
4694 case EXPR_CLASSIFY_TYPE:
4695 case EXPR_SIZEOF: // TODO handle obscure VLA case
4698 case EXPR_BUILTIN_CONSTANT_P:
4699 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4704 case EXPR_STATEMENT: {
4705 bool old_reaches_end = reaches_end;
4706 reaches_end = false;
4707 check_reachable(expr->statement.statement);
4708 bool returns = reaches_end;
4709 reaches_end = old_reaches_end;
4713 case EXPR_CONDITIONAL:
4714 // TODO handle constant expression
4716 if (!expression_returns(expr->conditional.condition))
4719 if (expr->conditional.true_expression != NULL
4720 && expression_returns(expr->conditional.true_expression))
4723 return expression_returns(expr->conditional.false_expression);
4726 return expression_returns(expr->select.compound);
4728 case EXPR_ARRAY_ACCESS:
4730 expression_returns(expr->array_access.array_ref) &&
4731 expression_returns(expr->array_access.index);
4734 return expression_returns(expr->va_starte.ap);
4737 return expression_returns(expr->va_arge.ap);
4740 return expression_returns(expr->va_copye.src);
4742 case EXPR_UNARY_CASES_MANDATORY:
4743 return expression_returns(expr->unary.value);
4745 case EXPR_UNARY_THROW:
4748 case EXPR_BINARY_CASES:
4749 // TODO handle constant lhs of && and ||
4751 expression_returns(expr->binary.left) &&
4752 expression_returns(expr->binary.right);
4755 panic("unhandled expression");
4758 static bool initializer_returns(initializer_t const *const init)
4760 switch (init->kind) {
4761 case INITIALIZER_VALUE:
4762 return expression_returns(init->value.value);
4764 case INITIALIZER_LIST: {
4765 initializer_t * const* i = init->list.initializers;
4766 initializer_t * const* const end = i + init->list.len;
4767 bool returns = true;
4768 for (; i != end; ++i) {
4769 if (!initializer_returns(*i))
4775 case INITIALIZER_STRING:
4776 case INITIALIZER_WIDE_STRING:
4777 case INITIALIZER_DESIGNATOR: // designators have no payload
4780 panic("unhandled initializer");
4783 static bool noreturn_candidate;
4785 static void check_reachable(statement_t *const stmt)
4787 if (stmt->base.reachable)
4789 if (stmt->kind != STATEMENT_DO_WHILE)
4790 stmt->base.reachable = true;
4792 statement_t *last = stmt;
4794 switch (stmt->kind) {
4795 case STATEMENT_ERROR:
4796 case STATEMENT_EMPTY:
4798 next = stmt->base.next;
4801 case STATEMENT_DECLARATION: {
4802 declaration_statement_t const *const decl = &stmt->declaration;
4803 entity_t const * ent = decl->declarations_begin;
4804 entity_t const *const last_decl = decl->declarations_end;
4806 for (;; ent = ent->base.next) {
4807 if (ent->kind == ENTITY_VARIABLE &&
4808 ent->variable.initializer != NULL &&
4809 !initializer_returns(ent->variable.initializer)) {
4812 if (ent == last_decl)
4816 next = stmt->base.next;
4820 case STATEMENT_COMPOUND:
4821 next = stmt->compound.statements;
4823 next = stmt->base.next;
4826 case STATEMENT_RETURN: {
4827 expression_t const *const val = stmt->returns.value;
4828 if (val == NULL || expression_returns(val))
4829 noreturn_candidate = false;
4833 case STATEMENT_IF: {
4834 if_statement_t const *const ifs = &stmt->ifs;
4835 expression_t const *const cond = ifs->condition;
4837 if (!expression_returns(cond))
4840 int const val = determine_truth(cond);
4843 check_reachable(ifs->true_statement);
4848 if (ifs->false_statement != NULL) {
4849 check_reachable(ifs->false_statement);
4853 next = stmt->base.next;
4857 case STATEMENT_SWITCH: {
4858 switch_statement_t const *const switchs = &stmt->switchs;
4859 expression_t const *const expr = switchs->expression;
4861 if (!expression_returns(expr))
4864 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4865 long const val = fold_constant_to_int(expr);
4866 case_label_statement_t * defaults = NULL;
4867 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4868 if (i->expression == NULL) {
4873 if (i->first_case <= val && val <= i->last_case) {
4874 check_reachable((statement_t*)i);
4879 if (defaults != NULL) {
4880 check_reachable((statement_t*)defaults);
4884 bool has_default = false;
4885 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4886 if (i->expression == NULL)
4889 check_reachable((statement_t*)i);
4896 next = stmt->base.next;
4900 case STATEMENT_EXPRESSION: {
4901 /* Check for noreturn function call */
4902 expression_t const *const expr = stmt->expression.expression;
4903 if (!expression_returns(expr))
4906 next = stmt->base.next;
4910 case STATEMENT_CONTINUE:
4911 for (statement_t *parent = stmt;;) {
4912 parent = parent->base.parent;
4913 if (parent == NULL) /* continue not within loop */
4917 switch (parent->kind) {
4918 case STATEMENT_WHILE: goto continue_while;
4919 case STATEMENT_DO_WHILE: goto continue_do_while;
4920 case STATEMENT_FOR: goto continue_for;
4926 case STATEMENT_BREAK:
4927 for (statement_t *parent = stmt;;) {
4928 parent = parent->base.parent;
4929 if (parent == NULL) /* break not within loop/switch */
4932 switch (parent->kind) {
4933 case STATEMENT_SWITCH:
4934 case STATEMENT_WHILE:
4935 case STATEMENT_DO_WHILE:
4938 next = parent->base.next;
4939 goto found_break_parent;
4947 case STATEMENT_COMPUTED_GOTO: {
4948 if (!expression_returns(stmt->computed_goto.expression))
4951 statement_t *parent = stmt->base.parent;
4952 if (parent == NULL) /* top level goto */
4958 case STATEMENT_GOTO:
4959 next = stmt->gotos.label->statement;
4960 if (next == NULL) /* missing label */
4964 case STATEMENT_LABEL:
4965 next = stmt->label.statement;
4968 case STATEMENT_CASE_LABEL:
4969 next = stmt->case_label.statement;
4972 case STATEMENT_WHILE: {
4973 while_statement_t const *const whiles = &stmt->whiles;
4974 expression_t const *const cond = whiles->condition;
4976 if (!expression_returns(cond))
4979 int const val = determine_truth(cond);
4982 check_reachable(whiles->body);
4987 next = stmt->base.next;
4991 case STATEMENT_DO_WHILE:
4992 next = stmt->do_while.body;
4995 case STATEMENT_FOR: {
4996 for_statement_t *const fors = &stmt->fors;
4998 if (fors->condition_reachable)
5000 fors->condition_reachable = true;
5002 expression_t const *const cond = fors->condition;
5007 } else if (expression_returns(cond)) {
5008 val = determine_truth(cond);
5014 check_reachable(fors->body);
5019 next = stmt->base.next;
5023 case STATEMENT_MS_TRY: {
5024 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5025 check_reachable(ms_try->try_statement);
5026 next = ms_try->final_statement;
5030 case STATEMENT_LEAVE: {
5031 statement_t *parent = stmt;
5033 parent = parent->base.parent;
5034 if (parent == NULL) /* __leave not within __try */
5037 if (parent->kind == STATEMENT_MS_TRY) {
5039 next = parent->ms_try.final_statement;
5047 panic("invalid statement kind");
5050 while (next == NULL) {
5051 next = last->base.parent;
5053 noreturn_candidate = false;
5055 type_t *const type = skip_typeref(current_function->base.type);
5056 assert(is_type_function(type));
5057 type_t *const ret = skip_typeref(type->function.return_type);
5058 if (!is_type_void(ret) &&
5059 is_type_valid(ret) &&
5060 !is_sym_main(current_function->base.base.symbol)) {
5061 source_position_t const *const pos = &stmt->base.source_position;
5062 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5067 switch (next->kind) {
5068 case STATEMENT_ERROR:
5069 case STATEMENT_EMPTY:
5070 case STATEMENT_DECLARATION:
5071 case STATEMENT_EXPRESSION:
5073 case STATEMENT_RETURN:
5074 case STATEMENT_CONTINUE:
5075 case STATEMENT_BREAK:
5076 case STATEMENT_COMPUTED_GOTO:
5077 case STATEMENT_GOTO:
5078 case STATEMENT_LEAVE:
5079 panic("invalid control flow in function");
5081 case STATEMENT_COMPOUND:
5082 if (next->compound.stmt_expr) {
5088 case STATEMENT_SWITCH:
5089 case STATEMENT_LABEL:
5090 case STATEMENT_CASE_LABEL:
5092 next = next->base.next;
5095 case STATEMENT_WHILE: {
5097 if (next->base.reachable)
5099 next->base.reachable = true;
5101 while_statement_t const *const whiles = &next->whiles;
5102 expression_t const *const cond = whiles->condition;
5104 if (!expression_returns(cond))
5107 int const val = determine_truth(cond);
5110 check_reachable(whiles->body);
5116 next = next->base.next;
5120 case STATEMENT_DO_WHILE: {
5122 if (next->base.reachable)
5124 next->base.reachable = true;
5126 do_while_statement_t const *const dw = &next->do_while;
5127 expression_t const *const cond = dw->condition;
5129 if (!expression_returns(cond))
5132 int const val = determine_truth(cond);
5135 check_reachable(dw->body);
5141 next = next->base.next;
5145 case STATEMENT_FOR: {
5147 for_statement_t *const fors = &next->fors;
5149 fors->step_reachable = true;
5151 if (fors->condition_reachable)
5153 fors->condition_reachable = true;
5155 expression_t const *const cond = fors->condition;
5160 } else if (expression_returns(cond)) {
5161 val = determine_truth(cond);
5167 check_reachable(fors->body);
5173 next = next->base.next;
5177 case STATEMENT_MS_TRY:
5179 next = next->ms_try.final_statement;
5184 check_reachable(next);
5187 static void check_unreachable(statement_t* const stmt, void *const env)
5191 switch (stmt->kind) {
5192 case STATEMENT_DO_WHILE:
5193 if (!stmt->base.reachable) {
5194 expression_t const *const cond = stmt->do_while.condition;
5195 if (determine_truth(cond) >= 0) {
5196 source_position_t const *const pos = &cond->base.source_position;
5197 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5202 case STATEMENT_FOR: {
5203 for_statement_t const* const fors = &stmt->fors;
5205 // if init and step are unreachable, cond is unreachable, too
5206 if (!stmt->base.reachable && !fors->step_reachable) {
5207 goto warn_unreachable;
5209 if (!stmt->base.reachable && fors->initialisation != NULL) {
5210 source_position_t const *const pos = &fors->initialisation->base.source_position;
5211 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5214 if (!fors->condition_reachable && fors->condition != NULL) {
5215 source_position_t const *const pos = &fors->condition->base.source_position;
5216 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5219 if (!fors->step_reachable && fors->step != NULL) {
5220 source_position_t const *const pos = &fors->step->base.source_position;
5221 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5227 case STATEMENT_COMPOUND:
5228 if (stmt->compound.statements != NULL)
5230 goto warn_unreachable;
5232 case STATEMENT_DECLARATION: {
5233 /* Only warn if there is at least one declarator with an initializer.
5234 * This typically occurs in switch statements. */
5235 declaration_statement_t const *const decl = &stmt->declaration;
5236 entity_t const * ent = decl->declarations_begin;
5237 entity_t const *const last = decl->declarations_end;
5239 for (;; ent = ent->base.next) {
5240 if (ent->kind == ENTITY_VARIABLE &&
5241 ent->variable.initializer != NULL) {
5242 goto warn_unreachable;
5252 if (!stmt->base.reachable) {
5253 source_position_t const *const pos = &stmt->base.source_position;
5254 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5260 static bool is_main(entity_t *entity)
5262 static symbol_t *sym_main = NULL;
5263 if (sym_main == NULL) {
5264 sym_main = symbol_table_insert("main");
5267 if (entity->base.symbol != sym_main)
5269 /* must be in outermost scope */
5270 if (entity->base.parent_scope != file_scope)
5276 static void parse_external_declaration(void)
5278 /* function-definitions and declarations both start with declaration
5280 add_anchor_token(';');
5281 declaration_specifiers_t specifiers;
5282 parse_declaration_specifiers(&specifiers);
5283 rem_anchor_token(';');
5285 /* must be a declaration */
5286 if (token.kind == ';') {
5287 parse_anonymous_declaration_rest(&specifiers);
5291 add_anchor_token(',');
5292 add_anchor_token('=');
5293 add_anchor_token(';');
5294 add_anchor_token('{');
5296 /* declarator is common to both function-definitions and declarations */
5297 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5299 rem_anchor_token('{');
5300 rem_anchor_token(';');
5301 rem_anchor_token('=');
5302 rem_anchor_token(',');
5304 /* must be a declaration */
5305 switch (token.kind) {
5309 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5314 /* must be a function definition */
5315 parse_kr_declaration_list(ndeclaration);
5317 if (token.kind != '{') {
5318 parse_error_expected("while parsing function definition", '{', NULL);
5319 eat_until_matching_token(';');
5323 assert(is_declaration(ndeclaration));
5324 type_t *const orig_type = ndeclaration->declaration.type;
5325 type_t * type = skip_typeref(orig_type);
5327 if (!is_type_function(type)) {
5328 if (is_type_valid(type)) {
5329 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5335 source_position_t const *const pos = &ndeclaration->base.source_position;
5336 if (is_typeref(orig_type)) {
5338 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5341 if (is_type_compound(skip_typeref(type->function.return_type))) {
5342 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5344 if (type->function.unspecified_parameters) {
5345 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5347 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5350 /* §6.7.5.3:14 a function definition with () means no
5351 * parameters (and not unspecified parameters) */
5352 if (type->function.unspecified_parameters &&
5353 type->function.parameters == NULL) {
5354 type_t *copy = duplicate_type(type);
5355 copy->function.unspecified_parameters = false;
5356 type = identify_new_type(copy);
5358 ndeclaration->declaration.type = type;
5361 entity_t *const entity = record_entity(ndeclaration, true);
5362 assert(entity->kind == ENTITY_FUNCTION);
5363 assert(ndeclaration->kind == ENTITY_FUNCTION);
5365 function_t *const function = &entity->function;
5366 if (ndeclaration != entity) {
5367 function->parameters = ndeclaration->function.parameters;
5369 assert(is_declaration(entity));
5370 type = skip_typeref(entity->declaration.type);
5372 PUSH_SCOPE(&function->parameters);
5374 entity_t *parameter = function->parameters.entities;
5375 for (; parameter != NULL; parameter = parameter->base.next) {
5376 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5377 parameter->base.parent_scope = current_scope;
5379 assert(parameter->base.parent_scope == NULL
5380 || parameter->base.parent_scope == current_scope);
5381 parameter->base.parent_scope = current_scope;
5382 if (parameter->base.symbol == NULL) {
5383 errorf(¶meter->base.source_position, "parameter name omitted");
5386 environment_push(parameter);
5389 if (function->statement != NULL) {
5390 parser_error_multiple_definition(entity, HERE);
5393 /* parse function body */
5394 int label_stack_top = label_top();
5395 function_t *old_current_function = current_function;
5396 entity_t *old_current_entity = current_entity;
5397 current_function = function;
5398 current_entity = entity;
5402 goto_anchor = &goto_first;
5404 label_anchor = &label_first;
5406 statement_t *const body = parse_compound_statement(false);
5407 function->statement = body;
5410 check_declarations();
5411 if (is_warn_on(WARN_RETURN_TYPE) ||
5412 is_warn_on(WARN_UNREACHABLE_CODE) ||
5413 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5414 noreturn_candidate = true;
5415 check_reachable(body);
5416 if (is_warn_on(WARN_UNREACHABLE_CODE))
5417 walk_statements(body, check_unreachable, NULL);
5418 if (noreturn_candidate &&
5419 !(function->base.modifiers & DM_NORETURN)) {
5420 source_position_t const *const pos = &body->base.source_position;
5421 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5425 if (is_main(entity) && enable_main_collect2_hack)
5426 prepare_main_collect2(entity);
5429 assert(current_function == function);
5430 assert(current_entity == entity);
5431 current_entity = old_current_entity;
5432 current_function = old_current_function;
5433 label_pop_to(label_stack_top);
5439 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5441 entity_t *iter = compound->members.entities;
5442 for (; iter != NULL; iter = iter->base.next) {
5443 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5446 if (iter->base.symbol == symbol) {
5448 } else if (iter->base.symbol == NULL) {
5449 /* search in anonymous structs and unions */
5450 type_t *type = skip_typeref(iter->declaration.type);
5451 if (is_type_compound(type)) {
5452 if (find_compound_entry(type->compound.compound, symbol)
5463 static void check_deprecated(const source_position_t *source_position,
5464 const entity_t *entity)
5466 if (!is_declaration(entity))
5468 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5471 source_position_t const *const epos = &entity->base.source_position;
5472 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5474 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5476 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5481 static expression_t *create_select(const source_position_t *pos,
5483 type_qualifiers_t qualifiers,
5486 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5488 check_deprecated(pos, entry);
5490 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5491 select->select.compound = addr;
5492 select->select.compound_entry = entry;
5494 type_t *entry_type = entry->declaration.type;
5495 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5497 /* bitfields need special treatment */
5498 if (entry->compound_member.bitfield) {
5499 unsigned bit_size = entry->compound_member.bit_size;
5500 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5501 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5502 res_type = type_int;
5506 /* we always do the auto-type conversions; the & and sizeof parser contains
5507 * code to revert this! */
5508 select->base.type = automatic_type_conversion(res_type);
5515 * Find entry with symbol in compound. Search anonymous structs and unions and
5516 * creates implicit select expressions for them.
5517 * Returns the adress for the innermost compound.
5519 static expression_t *find_create_select(const source_position_t *pos,
5521 type_qualifiers_t qualifiers,
5522 compound_t *compound, symbol_t *symbol)
5524 entity_t *iter = compound->members.entities;
5525 for (; iter != NULL; iter = iter->base.next) {
5526 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5529 symbol_t *iter_symbol = iter->base.symbol;
5530 if (iter_symbol == NULL) {
5531 type_t *type = iter->declaration.type;
5532 if (type->kind != TYPE_COMPOUND_STRUCT
5533 && type->kind != TYPE_COMPOUND_UNION)
5536 compound_t *sub_compound = type->compound.compound;
5538 if (find_compound_entry(sub_compound, symbol) == NULL)
5541 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5542 sub_addr->base.source_position = *pos;
5543 sub_addr->base.implicit = true;
5544 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5548 if (iter_symbol == symbol) {
5549 return create_select(pos, addr, qualifiers, iter);
5556 static void parse_bitfield_member(entity_t *entity)
5560 expression_t *size = parse_constant_expression();
5563 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5564 type_t *type = entity->declaration.type;
5565 if (!is_type_integer(skip_typeref(type))) {
5566 errorf(HERE, "bitfield base type '%T' is not an integer type",
5570 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5571 /* error already reported by parse_constant_expression */
5572 size_long = get_type_size(type) * 8;
5574 size_long = fold_constant_to_int(size);
5576 const symbol_t *symbol = entity->base.symbol;
5577 const symbol_t *user_symbol
5578 = symbol == NULL ? sym_anonymous : symbol;
5579 unsigned bit_size = get_type_size(type) * 8;
5580 if (size_long < 0) {
5581 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5582 } else if (size_long == 0 && symbol != NULL) {
5583 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5584 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5585 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5588 /* hope that people don't invent crazy types with more bits
5589 * than our struct can hold */
5591 (1 << sizeof(entity->compound_member.bit_size)*8));
5595 entity->compound_member.bitfield = true;
5596 entity->compound_member.bit_size = (unsigned char)size_long;
5599 static void parse_compound_declarators(compound_t *compound,
5600 const declaration_specifiers_t *specifiers)
5602 add_anchor_token(';');
5603 add_anchor_token(',');
5607 if (token.kind == ':') {
5608 /* anonymous bitfield */
5609 type_t *type = specifiers->type;
5610 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5611 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5612 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5613 entity->declaration.type = type;
5615 parse_bitfield_member(entity);
5617 attribute_t *attributes = parse_attributes(NULL);
5618 attribute_t **anchor = &attributes;
5619 while (*anchor != NULL)
5620 anchor = &(*anchor)->next;
5621 *anchor = specifiers->attributes;
5622 if (attributes != NULL) {
5623 handle_entity_attributes(attributes, entity);
5625 entity->declaration.attributes = attributes;
5627 append_entity(&compound->members, entity);
5629 entity = parse_declarator(specifiers,
5630 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5631 source_position_t const *const pos = &entity->base.source_position;
5632 if (entity->kind == ENTITY_TYPEDEF) {
5633 errorf(pos, "typedef not allowed as compound member");
5635 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5637 /* make sure we don't define a symbol multiple times */
5638 symbol_t *symbol = entity->base.symbol;
5639 if (symbol != NULL) {
5640 entity_t *prev = find_compound_entry(compound, symbol);
5642 source_position_t const *const ppos = &prev->base.source_position;
5643 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5647 if (token.kind == ':') {
5648 parse_bitfield_member(entity);
5650 attribute_t *attributes = parse_attributes(NULL);
5651 handle_entity_attributes(attributes, entity);
5653 type_t *orig_type = entity->declaration.type;
5654 type_t *type = skip_typeref(orig_type);
5655 if (is_type_function(type)) {
5656 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5657 } else if (is_type_incomplete(type)) {
5658 /* §6.7.2.1:16 flexible array member */
5659 if (!is_type_array(type) ||
5660 token.kind != ';' ||
5661 look_ahead(1)->kind != '}') {
5662 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5663 } else if (compound->members.entities == NULL) {
5664 errorf(pos, "flexible array member in otherwise empty struct");
5669 append_entity(&compound->members, entity);
5672 } while (next_if(','));
5673 rem_anchor_token(',');
5674 rem_anchor_token(';');
5677 anonymous_entity = NULL;
5680 static void parse_compound_type_entries(compound_t *compound)
5683 add_anchor_token('}');
5686 switch (token.kind) {
5688 case T___extension__:
5689 case T_IDENTIFIER: {
5691 declaration_specifiers_t specifiers;
5692 parse_declaration_specifiers(&specifiers);
5693 parse_compound_declarators(compound, &specifiers);
5699 rem_anchor_token('}');
5702 compound->complete = true;
5708 static type_t *parse_typename(void)
5710 declaration_specifiers_t specifiers;
5711 parse_declaration_specifiers(&specifiers);
5712 if (specifiers.storage_class != STORAGE_CLASS_NONE
5713 || specifiers.thread_local) {
5714 /* TODO: improve error message, user does probably not know what a
5715 * storage class is...
5717 errorf(&specifiers.source_position, "typename must not have a storage class");
5720 type_t *result = parse_abstract_declarator(specifiers.type);
5728 typedef expression_t* (*parse_expression_function)(void);
5729 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5731 typedef struct expression_parser_function_t expression_parser_function_t;
5732 struct expression_parser_function_t {
5733 parse_expression_function parser;
5734 precedence_t infix_precedence;
5735 parse_expression_infix_function infix_parser;
5738 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5741 * Prints an error message if an expression was expected but not read
5743 static expression_t *expected_expression_error(void)
5745 /* skip the error message if the error token was read */
5746 if (token.kind != T_ERROR) {
5747 errorf(HERE, "expected expression, got token %K", &token);
5751 return create_error_expression();
5754 static type_t *get_string_type(void)
5756 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5759 static type_t *get_wide_string_type(void)
5761 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5765 * Parse a string constant.
5767 static expression_t *parse_string_literal(void)
5769 source_position_t begin = token.base.source_position;
5770 string_t res = token.string.string;
5771 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5774 while (token.kind == T_STRING_LITERAL
5775 || token.kind == T_WIDE_STRING_LITERAL) {
5776 warn_string_concat(&token.base.source_position);
5777 res = concat_strings(&res, &token.string.string);
5779 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5782 expression_t *literal;
5784 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5785 literal->base.type = get_wide_string_type();
5787 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5788 literal->base.type = get_string_type();
5790 literal->base.source_position = begin;
5791 literal->literal.value = res;
5797 * Parse a boolean constant.
5799 static expression_t *parse_boolean_literal(bool value)
5801 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5802 literal->base.type = type_bool;
5803 literal->literal.value.begin = value ? "true" : "false";
5804 literal->literal.value.size = value ? 4 : 5;
5810 static void warn_traditional_suffix(void)
5812 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5813 &token.number.suffix);
5816 static void check_integer_suffix(void)
5818 const string_t *suffix = &token.number.suffix;
5819 if (suffix->size == 0)
5822 bool not_traditional = false;
5823 const char *c = suffix->begin;
5824 if (*c == 'l' || *c == 'L') {
5827 not_traditional = true;
5829 if (*c == 'u' || *c == 'U') {
5832 } else if (*c == 'u' || *c == 'U') {
5833 not_traditional = true;
5836 } else if (*c == 'u' || *c == 'U') {
5837 not_traditional = true;
5839 if (*c == 'l' || *c == 'L') {
5847 errorf(&token.base.source_position,
5848 "invalid suffix '%S' on integer constant", suffix);
5849 } else if (not_traditional) {
5850 warn_traditional_suffix();
5854 static type_t *check_floatingpoint_suffix(void)
5856 const string_t *suffix = &token.number.suffix;
5857 type_t *type = type_double;
5858 if (suffix->size == 0)
5861 bool not_traditional = false;
5862 const char *c = suffix->begin;
5863 if (*c == 'f' || *c == 'F') {
5866 } else if (*c == 'l' || *c == 'L') {
5868 type = type_long_double;
5871 errorf(&token.base.source_position,
5872 "invalid suffix '%S' on floatingpoint constant", suffix);
5873 } else if (not_traditional) {
5874 warn_traditional_suffix();
5881 * Parse an integer constant.
5883 static expression_t *parse_number_literal(void)
5885 expression_kind_t kind;
5888 switch (token.kind) {
5890 kind = EXPR_LITERAL_INTEGER;
5891 check_integer_suffix();
5894 case T_INTEGER_OCTAL:
5895 kind = EXPR_LITERAL_INTEGER_OCTAL;
5896 check_integer_suffix();
5899 case T_INTEGER_HEXADECIMAL:
5900 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5901 check_integer_suffix();
5904 case T_FLOATINGPOINT:
5905 kind = EXPR_LITERAL_FLOATINGPOINT;
5906 type = check_floatingpoint_suffix();
5908 case T_FLOATINGPOINT_HEXADECIMAL:
5909 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5910 type = check_floatingpoint_suffix();
5913 panic("unexpected token type in parse_number_literal");
5916 expression_t *literal = allocate_expression_zero(kind);
5917 literal->base.type = type;
5918 literal->literal.value = token.number.number;
5919 literal->literal.suffix = token.number.suffix;
5922 /* integer type depends on the size of the number and the size
5923 * representable by the types. The backend/codegeneration has to determine
5926 determine_literal_type(&literal->literal);
5931 * Parse a character constant.
5933 static expression_t *parse_character_constant(void)
5935 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5936 literal->base.type = c_mode & _CXX ? type_char : type_int;
5937 literal->literal.value = token.string.string;
5939 size_t len = literal->literal.value.size;
5941 if (!GNU_MODE && !(c_mode & _C99)) {
5942 errorf(HERE, "more than 1 character in character constant");
5944 literal->base.type = type_int;
5945 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5954 * Parse a wide character constant.
5956 static expression_t *parse_wide_character_constant(void)
5958 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5959 literal->base.type = type_int;
5960 literal->literal.value = token.string.string;
5962 size_t len = wstrlen(&literal->literal.value);
5964 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5971 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5973 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5974 ntype->function.return_type = type_int;
5975 ntype->function.unspecified_parameters = true;
5976 ntype->function.linkage = LINKAGE_C;
5977 type_t *type = identify_new_type(ntype);
5979 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5980 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5981 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5982 entity->declaration.type = type;
5983 entity->declaration.implicit = true;
5985 if (current_scope != NULL)
5986 record_entity(entity, false);
5992 * Performs automatic type cast as described in §6.3.2.1.
5994 * @param orig_type the original type
5996 static type_t *automatic_type_conversion(type_t *orig_type)
5998 type_t *type = skip_typeref(orig_type);
5999 if (is_type_array(type)) {
6000 array_type_t *array_type = &type->array;
6001 type_t *element_type = array_type->element_type;
6002 unsigned qualifiers = array_type->base.qualifiers;
6004 return make_pointer_type(element_type, qualifiers);
6007 if (is_type_function(type)) {
6008 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6015 * reverts the automatic casts of array to pointer types and function
6016 * to function-pointer types as defined §6.3.2.1
6018 type_t *revert_automatic_type_conversion(const expression_t *expression)
6020 switch (expression->kind) {
6021 case EXPR_REFERENCE: {
6022 entity_t *entity = expression->reference.entity;
6023 if (is_declaration(entity)) {
6024 return entity->declaration.type;
6025 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6026 return entity->enum_value.enum_type;
6028 panic("no declaration or enum in reference");
6033 entity_t *entity = expression->select.compound_entry;
6034 assert(is_declaration(entity));
6035 type_t *type = entity->declaration.type;
6036 return get_qualified_type(type, expression->base.type->base.qualifiers);
6039 case EXPR_UNARY_DEREFERENCE: {
6040 const expression_t *const value = expression->unary.value;
6041 type_t *const type = skip_typeref(value->base.type);
6042 if (!is_type_pointer(type))
6043 return type_error_type;
6044 return type->pointer.points_to;
6047 case EXPR_ARRAY_ACCESS: {
6048 const expression_t *array_ref = expression->array_access.array_ref;
6049 type_t *type_left = skip_typeref(array_ref->base.type);
6050 if (!is_type_pointer(type_left))
6051 return type_error_type;
6052 return type_left->pointer.points_to;
6055 case EXPR_STRING_LITERAL: {
6056 size_t size = expression->string_literal.value.size;
6057 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6060 case EXPR_WIDE_STRING_LITERAL: {
6061 size_t size = wstrlen(&expression->string_literal.value);
6062 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6065 case EXPR_COMPOUND_LITERAL:
6066 return expression->compound_literal.type;
6071 return expression->base.type;
6075 * Find an entity matching a symbol in a scope.
6076 * Uses current scope if scope is NULL
6078 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6079 namespace_tag_t namespc)
6081 if (scope == NULL) {
6082 return get_entity(symbol, namespc);
6085 /* we should optimize here, if scope grows above a certain size we should
6086 construct a hashmap here... */
6087 entity_t *entity = scope->entities;
6088 for ( ; entity != NULL; entity = entity->base.next) {
6089 if (entity->base.symbol == symbol
6090 && (namespace_tag_t)entity->base.namespc == namespc)
6097 static entity_t *parse_qualified_identifier(void)
6099 /* namespace containing the symbol */
6101 source_position_t pos;
6102 const scope_t *lookup_scope = NULL;
6104 if (next_if(T_COLONCOLON))
6105 lookup_scope = &unit->scope;
6109 symbol = expect_identifier("while parsing identifier", &pos);
6111 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6114 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6116 if (!next_if(T_COLONCOLON))
6119 switch (entity->kind) {
6120 case ENTITY_NAMESPACE:
6121 lookup_scope = &entity->namespacee.members;
6126 lookup_scope = &entity->compound.members;
6129 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6130 symbol, get_entity_kind_name(entity->kind));
6132 /* skip further qualifications */
6133 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6135 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6139 if (entity == NULL) {
6140 if (!strict_mode && token.kind == '(') {
6141 /* an implicitly declared function */
6142 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6143 "implicit declaration of function '%Y'", symbol);
6144 entity = create_implicit_function(symbol, &pos);
6146 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6147 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6154 static expression_t *parse_reference(void)
6156 source_position_t const pos = token.base.source_position;
6157 entity_t *const entity = parse_qualified_identifier();
6160 if (is_declaration(entity)) {
6161 orig_type = entity->declaration.type;
6162 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6163 orig_type = entity->enum_value.enum_type;
6165 panic("expected declaration or enum value in reference");
6168 /* we always do the auto-type conversions; the & and sizeof parser contains
6169 * code to revert this! */
6170 type_t *type = automatic_type_conversion(orig_type);
6172 expression_kind_t kind = EXPR_REFERENCE;
6173 if (entity->kind == ENTITY_ENUM_VALUE)
6174 kind = EXPR_ENUM_CONSTANT;
6176 expression_t *expression = allocate_expression_zero(kind);
6177 expression->base.source_position = pos;
6178 expression->base.type = type;
6179 expression->reference.entity = entity;
6181 /* this declaration is used */
6182 if (is_declaration(entity)) {
6183 entity->declaration.used = true;
6186 if (entity->base.parent_scope != file_scope
6187 && (current_function != NULL
6188 && entity->base.parent_scope->depth < current_function->parameters.depth)
6189 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6190 if (entity->kind == ENTITY_VARIABLE) {
6191 /* access of a variable from an outer function */
6192 entity->variable.address_taken = true;
6193 } else if (entity->kind == ENTITY_PARAMETER) {
6194 entity->parameter.address_taken = true;
6196 current_function->need_closure = true;
6199 check_deprecated(&pos, entity);
6204 static bool semantic_cast(expression_t *cast)
6206 expression_t *expression = cast->unary.value;
6207 type_t *orig_dest_type = cast->base.type;
6208 type_t *orig_type_right = expression->base.type;
6209 type_t const *dst_type = skip_typeref(orig_dest_type);
6210 type_t const *src_type = skip_typeref(orig_type_right);
6211 source_position_t const *pos = &cast->base.source_position;
6213 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6214 if (is_type_void(dst_type))
6217 /* only integer and pointer can be casted to pointer */
6218 if (is_type_pointer(dst_type) &&
6219 !is_type_pointer(src_type) &&
6220 !is_type_integer(src_type) &&
6221 is_type_valid(src_type)) {
6222 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6226 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6227 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6231 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6232 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6236 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6237 type_t *src = skip_typeref(src_type->pointer.points_to);
6238 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6239 unsigned missing_qualifiers =
6240 src->base.qualifiers & ~dst->base.qualifiers;
6241 if (missing_qualifiers != 0) {
6242 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6248 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6250 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6251 expression->base.source_position = *pos;
6253 parse_initializer_env_t env;
6256 env.must_be_constant = false;
6257 initializer_t *initializer = parse_initializer(&env);
6260 expression->compound_literal.initializer = initializer;
6261 expression->compound_literal.type = type;
6262 expression->base.type = automatic_type_conversion(type);
6268 * Parse a cast expression.
6270 static expression_t *parse_cast(void)
6272 source_position_t const pos = *HERE;
6275 add_anchor_token(')');
6277 type_t *type = parse_typename();
6279 rem_anchor_token(')');
6282 if (token.kind == '{') {
6283 return parse_compound_literal(&pos, type);
6286 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6287 cast->base.source_position = pos;
6289 expression_t *value = parse_subexpression(PREC_CAST);
6290 cast->base.type = type;
6291 cast->unary.value = value;
6293 if (! semantic_cast(cast)) {
6294 /* TODO: record the error in the AST. else it is impossible to detect it */
6301 * Parse a statement expression.
6303 static expression_t *parse_statement_expression(void)
6305 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6308 add_anchor_token(')');
6310 statement_t *statement = parse_compound_statement(true);
6311 statement->compound.stmt_expr = true;
6312 expression->statement.statement = statement;
6314 /* find last statement and use its type */
6315 type_t *type = type_void;
6316 const statement_t *stmt = statement->compound.statements;
6318 while (stmt->base.next != NULL)
6319 stmt = stmt->base.next;
6321 if (stmt->kind == STATEMENT_EXPRESSION) {
6322 type = stmt->expression.expression->base.type;
6325 source_position_t const *const pos = &expression->base.source_position;
6326 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6328 expression->base.type = type;
6330 rem_anchor_token(')');
6336 * Parse a parenthesized expression.
6338 static expression_t *parse_parenthesized_expression(void)
6340 token_t const* const la1 = look_ahead(1);
6341 switch (la1->kind) {
6343 /* gcc extension: a statement expression */
6344 return parse_statement_expression();
6347 if (is_typedef_symbol(la1->identifier.symbol)) {
6349 return parse_cast();
6354 add_anchor_token(')');
6355 expression_t *result = parse_expression();
6356 result->base.parenthesized = true;
6357 rem_anchor_token(')');
6363 static expression_t *parse_function_keyword(void)
6367 if (current_function == NULL) {
6368 errorf(HERE, "'__func__' used outside of a function");
6371 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6372 expression->base.type = type_char_ptr;
6373 expression->funcname.kind = FUNCNAME_FUNCTION;
6380 static expression_t *parse_pretty_function_keyword(void)
6382 if (current_function == NULL) {
6383 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6386 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6387 expression->base.type = type_char_ptr;
6388 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6390 eat(T___PRETTY_FUNCTION__);
6395 static expression_t *parse_funcsig_keyword(void)
6397 if (current_function == NULL) {
6398 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6401 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6402 expression->base.type = type_char_ptr;
6403 expression->funcname.kind = FUNCNAME_FUNCSIG;
6410 static expression_t *parse_funcdname_keyword(void)
6412 if (current_function == NULL) {
6413 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6416 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6417 expression->base.type = type_char_ptr;
6418 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6420 eat(T___FUNCDNAME__);
6425 static designator_t *parse_designator(void)
6427 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6428 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6429 if (!result->symbol)
6432 designator_t *last_designator = result;
6435 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6436 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6437 if (!designator->symbol)
6440 last_designator->next = designator;
6441 last_designator = designator;
6445 add_anchor_token(']');
6446 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6447 designator->source_position = *HERE;
6448 designator->array_index = parse_expression();
6449 rem_anchor_token(']');
6451 if (designator->array_index == NULL) {
6455 last_designator->next = designator;
6456 last_designator = designator;
6466 * Parse the __builtin_offsetof() expression.
6468 static expression_t *parse_offsetof(void)
6470 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6471 expression->base.type = type_size_t;
6473 eat(T___builtin_offsetof);
6476 add_anchor_token(')');
6477 add_anchor_token(',');
6478 type_t *type = parse_typename();
6479 rem_anchor_token(',');
6481 designator_t *designator = parse_designator();
6482 rem_anchor_token(')');
6485 expression->offsetofe.type = type;
6486 expression->offsetofe.designator = designator;
6489 memset(&path, 0, sizeof(path));
6490 path.top_type = type;
6491 path.path = NEW_ARR_F(type_path_entry_t, 0);
6493 descend_into_subtype(&path);
6495 if (!walk_designator(&path, designator, true)) {
6496 return create_error_expression();
6499 DEL_ARR_F(path.path);
6505 * Parses a _builtin_va_start() expression.
6507 static expression_t *parse_va_start(void)
6509 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6511 eat(T___builtin_va_start);
6514 add_anchor_token(')');
6515 add_anchor_token(',');
6516 expression->va_starte.ap = parse_assignment_expression();
6517 rem_anchor_token(',');
6519 expression_t *const expr = parse_assignment_expression();
6520 if (expr->kind == EXPR_REFERENCE) {
6521 entity_t *const entity = expr->reference.entity;
6522 if (!current_function->base.type->function.variadic) {
6523 errorf(&expr->base.source_position,
6524 "'va_start' used in non-variadic function");
6525 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6526 entity->base.next != NULL ||
6527 entity->kind != ENTITY_PARAMETER) {
6528 errorf(&expr->base.source_position,
6529 "second argument of 'va_start' must be last parameter of the current function");
6531 expression->va_starte.parameter = &entity->variable;
6534 expression = create_error_expression();
6536 rem_anchor_token(')');
6542 * Parses a __builtin_va_arg() expression.
6544 static expression_t *parse_va_arg(void)
6546 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6548 eat(T___builtin_va_arg);
6551 add_anchor_token(')');
6552 add_anchor_token(',');
6554 ap.expression = parse_assignment_expression();
6555 expression->va_arge.ap = ap.expression;
6556 check_call_argument(type_valist, &ap, 1);
6558 rem_anchor_token(',');
6560 expression->base.type = parse_typename();
6561 rem_anchor_token(')');
6568 * Parses a __builtin_va_copy() expression.
6570 static expression_t *parse_va_copy(void)
6572 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6574 eat(T___builtin_va_copy);
6577 add_anchor_token(')');
6578 add_anchor_token(',');
6579 expression_t *dst = parse_assignment_expression();
6580 assign_error_t error = semantic_assign(type_valist, dst);
6581 report_assign_error(error, type_valist, dst, "call argument 1",
6582 &dst->base.source_position);
6583 expression->va_copye.dst = dst;
6585 rem_anchor_token(',');
6588 call_argument_t src;
6589 src.expression = parse_assignment_expression();
6590 check_call_argument(type_valist, &src, 2);
6591 expression->va_copye.src = src.expression;
6592 rem_anchor_token(')');
6599 * Parses a __builtin_constant_p() expression.
6601 static expression_t *parse_builtin_constant(void)
6603 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6605 eat(T___builtin_constant_p);
6608 add_anchor_token(')');
6609 expression->builtin_constant.value = parse_assignment_expression();
6610 rem_anchor_token(')');
6612 expression->base.type = type_int;
6618 * Parses a __builtin_types_compatible_p() expression.
6620 static expression_t *parse_builtin_types_compatible(void)
6622 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6624 eat(T___builtin_types_compatible_p);
6627 add_anchor_token(')');
6628 add_anchor_token(',');
6629 expression->builtin_types_compatible.left = parse_typename();
6630 rem_anchor_token(',');
6632 expression->builtin_types_compatible.right = parse_typename();
6633 rem_anchor_token(')');
6635 expression->base.type = type_int;
6641 * Parses a __builtin_is_*() compare expression.
6643 static expression_t *parse_compare_builtin(void)
6645 expression_t *expression;
6647 switch (token.kind) {
6648 case T___builtin_isgreater:
6649 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6651 case T___builtin_isgreaterequal:
6652 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6654 case T___builtin_isless:
6655 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6657 case T___builtin_islessequal:
6658 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6660 case T___builtin_islessgreater:
6661 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6663 case T___builtin_isunordered:
6664 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6667 internal_errorf(HERE, "invalid compare builtin found");
6669 expression->base.source_position = *HERE;
6673 add_anchor_token(')');
6674 add_anchor_token(',');
6675 expression->binary.left = parse_assignment_expression();
6676 rem_anchor_token(',');
6678 expression->binary.right = parse_assignment_expression();
6679 rem_anchor_token(')');
6682 type_t *const orig_type_left = expression->binary.left->base.type;
6683 type_t *const orig_type_right = expression->binary.right->base.type;
6685 type_t *const type_left = skip_typeref(orig_type_left);
6686 type_t *const type_right = skip_typeref(orig_type_right);
6687 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6688 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6689 type_error_incompatible("invalid operands in comparison",
6690 &expression->base.source_position, orig_type_left, orig_type_right);
6693 semantic_comparison(&expression->binary);
6700 * Parses a MS assume() expression.
6702 static expression_t *parse_assume(void)
6704 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6709 add_anchor_token(')');
6710 expression->unary.value = parse_assignment_expression();
6711 rem_anchor_token(')');
6714 expression->base.type = type_void;
6719 * Return the label for the current symbol or create a new one.
6721 static label_t *get_label(void)
6723 assert(token.kind == T_IDENTIFIER);
6724 assert(current_function != NULL);
6726 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6727 /* If we find a local label, we already created the declaration. */
6728 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6729 if (label->base.parent_scope != current_scope) {
6730 assert(label->base.parent_scope->depth < current_scope->depth);
6731 current_function->goto_to_outer = true;
6733 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6734 /* There is no matching label in the same function, so create a new one. */
6735 source_position_t const nowhere = { NULL, 0, 0, false };
6736 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6741 return &label->label;
6745 * Parses a GNU && label address expression.
6747 static expression_t *parse_label_address(void)
6749 source_position_t source_position = token.base.source_position;
6751 if (token.kind != T_IDENTIFIER) {
6752 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6753 return create_error_expression();
6756 label_t *const label = get_label();
6758 label->address_taken = true;
6760 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6761 expression->base.source_position = source_position;
6763 /* label address is treated as a void pointer */
6764 expression->base.type = type_void_ptr;
6765 expression->label_address.label = label;
6770 * Parse a microsoft __noop expression.
6772 static expression_t *parse_noop_expression(void)
6774 /* the result is a (int)0 */
6775 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6776 literal->base.type = type_int;
6777 literal->literal.value.begin = "__noop";
6778 literal->literal.value.size = 6;
6782 if (token.kind == '(') {
6783 /* parse arguments */
6785 add_anchor_token(')');
6786 add_anchor_token(',');
6788 if (token.kind != ')') do {
6789 (void)parse_assignment_expression();
6790 } while (next_if(','));
6792 rem_anchor_token(',');
6793 rem_anchor_token(')');
6801 * Parses a primary expression.
6803 static expression_t *parse_primary_expression(void)
6805 switch (token.kind) {
6806 case T_false: return parse_boolean_literal(false);
6807 case T_true: return parse_boolean_literal(true);
6809 case T_INTEGER_OCTAL:
6810 case T_INTEGER_HEXADECIMAL:
6811 case T_FLOATINGPOINT:
6812 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6813 case T_CHARACTER_CONSTANT: return parse_character_constant();
6814 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6815 case T_STRING_LITERAL:
6816 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6817 case T___FUNCTION__:
6818 case T___func__: return parse_function_keyword();
6819 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6820 case T___FUNCSIG__: return parse_funcsig_keyword();
6821 case T___FUNCDNAME__: return parse_funcdname_keyword();
6822 case T___builtin_offsetof: return parse_offsetof();
6823 case T___builtin_va_start: return parse_va_start();
6824 case T___builtin_va_arg: return parse_va_arg();
6825 case T___builtin_va_copy: return parse_va_copy();
6826 case T___builtin_isgreater:
6827 case T___builtin_isgreaterequal:
6828 case T___builtin_isless:
6829 case T___builtin_islessequal:
6830 case T___builtin_islessgreater:
6831 case T___builtin_isunordered: return parse_compare_builtin();
6832 case T___builtin_constant_p: return parse_builtin_constant();
6833 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6834 case T__assume: return parse_assume();
6837 return parse_label_address();
6840 case '(': return parse_parenthesized_expression();
6841 case T___noop: return parse_noop_expression();
6843 /* Gracefully handle type names while parsing expressions. */
6845 return parse_reference();
6847 if (!is_typedef_symbol(token.identifier.symbol)) {
6848 return parse_reference();
6852 source_position_t const pos = *HERE;
6853 declaration_specifiers_t specifiers;
6854 parse_declaration_specifiers(&specifiers);
6855 type_t const *const type = parse_abstract_declarator(specifiers.type);
6856 errorf(&pos, "encountered type '%T' while parsing expression", type);
6857 return create_error_expression();
6861 errorf(HERE, "unexpected token %K, expected an expression", &token);
6863 return create_error_expression();
6866 static expression_t *parse_array_expression(expression_t *left)
6868 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6869 array_access_expression_t *const arr = &expr->array_access;
6872 add_anchor_token(']');
6874 expression_t *const inside = parse_expression();
6876 type_t *const orig_type_left = left->base.type;
6877 type_t *const orig_type_inside = inside->base.type;
6879 type_t *const type_left = skip_typeref(orig_type_left);
6880 type_t *const type_inside = skip_typeref(orig_type_inside);
6886 if (is_type_pointer(type_left)) {
6889 idx_type = type_inside;
6890 res_type = type_left->pointer.points_to;
6892 } else if (is_type_pointer(type_inside)) {
6893 arr->flipped = true;
6896 idx_type = type_left;
6897 res_type = type_inside->pointer.points_to;
6899 res_type = automatic_type_conversion(res_type);
6900 if (!is_type_integer(idx_type)) {
6901 errorf(&idx->base.source_position, "array subscript must have integer type");
6902 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6903 source_position_t const *const pos = &idx->base.source_position;
6904 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6907 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6908 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6910 res_type = type_error_type;
6915 arr->array_ref = ref;
6917 arr->base.type = res_type;
6919 rem_anchor_token(']');
6924 static bool is_bitfield(const expression_t *expression)
6926 return expression->kind == EXPR_SELECT
6927 && expression->select.compound_entry->compound_member.bitfield;
6930 static expression_t *parse_typeprop(expression_kind_t const kind)
6932 expression_t *tp_expression = allocate_expression_zero(kind);
6933 tp_expression->base.type = type_size_t;
6935 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6938 expression_t *expression;
6939 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6940 source_position_t const pos = *HERE;
6942 add_anchor_token(')');
6943 orig_type = parse_typename();
6944 rem_anchor_token(')');
6947 if (token.kind == '{') {
6948 /* It was not sizeof(type) after all. It is sizeof of an expression
6949 * starting with a compound literal */
6950 expression = parse_compound_literal(&pos, orig_type);
6951 goto typeprop_expression;
6954 expression = parse_subexpression(PREC_UNARY);
6956 typeprop_expression:
6957 if (is_bitfield(expression)) {
6958 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6959 errorf(&tp_expression->base.source_position,
6960 "operand of %s expression must not be a bitfield", what);
6963 tp_expression->typeprop.tp_expression = expression;
6965 orig_type = revert_automatic_type_conversion(expression);
6966 expression->base.type = orig_type;
6969 tp_expression->typeprop.type = orig_type;
6970 type_t const* const type = skip_typeref(orig_type);
6971 char const* wrong_type = NULL;
6972 if (is_type_incomplete(type)) {
6973 if (!is_type_void(type) || !GNU_MODE)
6974 wrong_type = "incomplete";
6975 } else if (type->kind == TYPE_FUNCTION) {
6977 /* function types are allowed (and return 1) */
6978 source_position_t const *const pos = &tp_expression->base.source_position;
6979 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6980 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6982 wrong_type = "function";
6986 if (wrong_type != NULL) {
6987 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6988 errorf(&tp_expression->base.source_position,
6989 "operand of %s expression must not be of %s type '%T'",
6990 what, wrong_type, orig_type);
6993 return tp_expression;
6996 static expression_t *parse_sizeof(void)
6998 return parse_typeprop(EXPR_SIZEOF);
7001 static expression_t *parse_alignof(void)
7003 return parse_typeprop(EXPR_ALIGNOF);
7006 static expression_t *parse_select_expression(expression_t *addr)
7008 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7009 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7010 source_position_t const pos = *HERE;
7013 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
7015 return create_error_expression();
7017 type_t *const orig_type = addr->base.type;
7018 type_t *const type = skip_typeref(orig_type);
7021 bool saw_error = false;
7022 if (is_type_pointer(type)) {
7023 if (!select_left_arrow) {
7025 "request for member '%Y' in something not a struct or union, but '%T'",
7029 type_left = skip_typeref(type->pointer.points_to);
7031 if (select_left_arrow && is_type_valid(type)) {
7032 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7038 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7039 type_left->kind != TYPE_COMPOUND_UNION) {
7041 if (is_type_valid(type_left) && !saw_error) {
7043 "request for member '%Y' in something not a struct or union, but '%T'",
7046 return create_error_expression();
7049 compound_t *compound = type_left->compound.compound;
7050 if (!compound->complete) {
7051 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7053 return create_error_expression();
7056 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7057 expression_t *result =
7058 find_create_select(&pos, addr, qualifiers, compound, symbol);
7060 if (result == NULL) {
7061 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7062 return create_error_expression();
7068 static void check_call_argument(type_t *expected_type,
7069 call_argument_t *argument, unsigned pos)
7071 type_t *expected_type_skip = skip_typeref(expected_type);
7072 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7073 expression_t *arg_expr = argument->expression;
7074 type_t *arg_type = skip_typeref(arg_expr->base.type);
7076 /* handle transparent union gnu extension */
7077 if (is_type_union(expected_type_skip)
7078 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7079 compound_t *union_decl = expected_type_skip->compound.compound;
7080 type_t *best_type = NULL;
7081 entity_t *entry = union_decl->members.entities;
7082 for ( ; entry != NULL; entry = entry->base.next) {
7083 assert(is_declaration(entry));
7084 type_t *decl_type = entry->declaration.type;
7085 error = semantic_assign(decl_type, arg_expr);
7086 if (error == ASSIGN_ERROR_INCOMPATIBLE
7087 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7090 if (error == ASSIGN_SUCCESS) {
7091 best_type = decl_type;
7092 } else if (best_type == NULL) {
7093 best_type = decl_type;
7097 if (best_type != NULL) {
7098 expected_type = best_type;
7102 error = semantic_assign(expected_type, arg_expr);
7103 argument->expression = create_implicit_cast(arg_expr, expected_type);
7105 if (error != ASSIGN_SUCCESS) {
7106 /* report exact scope in error messages (like "in argument 3") */
7108 snprintf(buf, sizeof(buf), "call argument %u", pos);
7109 report_assign_error(error, expected_type, arg_expr, buf,
7110 &arg_expr->base.source_position);
7112 type_t *const promoted_type = get_default_promoted_type(arg_type);
7113 if (!types_compatible(expected_type_skip, promoted_type) &&
7114 !types_compatible(expected_type_skip, type_void_ptr) &&
7115 !types_compatible(type_void_ptr, promoted_type)) {
7116 /* Deliberately show the skipped types in this warning */
7117 source_position_t const *const apos = &arg_expr->base.source_position;
7118 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7124 * Handle the semantic restrictions of builtin calls
7126 static void handle_builtin_argument_restrictions(call_expression_t *call)
7128 entity_t *entity = call->function->reference.entity;
7129 switch (entity->function.btk) {
7131 switch (entity->function.b.firm_builtin_kind) {
7132 case ir_bk_return_address:
7133 case ir_bk_frame_address: {
7134 /* argument must be constant */
7135 call_argument_t *argument = call->arguments;
7137 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7138 errorf(&call->base.source_position,
7139 "argument of '%Y' must be a constant expression",
7140 call->function->reference.entity->base.symbol);
7144 case ir_bk_prefetch:
7145 /* second and third argument must be constant if existent */
7146 if (call->arguments == NULL)
7148 call_argument_t *rw = call->arguments->next;
7149 call_argument_t *locality = NULL;
7152 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7153 errorf(&call->base.source_position,
7154 "second argument of '%Y' must be a constant expression",
7155 call->function->reference.entity->base.symbol);
7157 locality = rw->next;
7159 if (locality != NULL) {
7160 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7161 errorf(&call->base.source_position,
7162 "third argument of '%Y' must be a constant expression",
7163 call->function->reference.entity->base.symbol);
7165 locality = rw->next;
7172 case BUILTIN_OBJECT_SIZE:
7173 if (call->arguments == NULL)
7176 call_argument_t *arg = call->arguments->next;
7177 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7178 errorf(&call->base.source_position,
7179 "second argument of '%Y' must be a constant expression",
7180 call->function->reference.entity->base.symbol);
7189 * Parse a call expression, ie. expression '( ... )'.
7191 * @param expression the function address
7193 static expression_t *parse_call_expression(expression_t *expression)
7195 expression_t *result = allocate_expression_zero(EXPR_CALL);
7196 call_expression_t *call = &result->call;
7197 call->function = expression;
7199 type_t *const orig_type = expression->base.type;
7200 type_t *const type = skip_typeref(orig_type);
7202 function_type_t *function_type = NULL;
7203 if (is_type_pointer(type)) {
7204 type_t *const to_type = skip_typeref(type->pointer.points_to);
7206 if (is_type_function(to_type)) {
7207 function_type = &to_type->function;
7208 call->base.type = function_type->return_type;
7212 if (function_type == NULL && is_type_valid(type)) {
7214 "called object '%E' (type '%T') is not a pointer to a function",
7215 expression, orig_type);
7218 /* parse arguments */
7220 add_anchor_token(')');
7221 add_anchor_token(',');
7223 if (token.kind != ')') {
7224 call_argument_t **anchor = &call->arguments;
7226 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7227 argument->expression = parse_assignment_expression();
7230 anchor = &argument->next;
7231 } while (next_if(','));
7233 rem_anchor_token(',');
7234 rem_anchor_token(')');
7237 if (function_type == NULL)
7240 /* check type and count of call arguments */
7241 function_parameter_t *parameter = function_type->parameters;
7242 call_argument_t *argument = call->arguments;
7243 if (!function_type->unspecified_parameters) {
7244 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7245 parameter = parameter->next, argument = argument->next) {
7246 check_call_argument(parameter->type, argument, ++pos);
7249 if (parameter != NULL) {
7250 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7251 } else if (argument != NULL && !function_type->variadic) {
7252 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7256 /* do default promotion for other arguments */
7257 for (; argument != NULL; argument = argument->next) {
7258 type_t *argument_type = argument->expression->base.type;
7259 if (!is_type_object(skip_typeref(argument_type))) {
7260 errorf(&argument->expression->base.source_position,
7261 "call argument '%E' must not be void", argument->expression);
7264 argument_type = get_default_promoted_type(argument_type);
7266 argument->expression
7267 = create_implicit_cast(argument->expression, argument_type);
7272 if (is_type_compound(skip_typeref(function_type->return_type))) {
7273 source_position_t const *const pos = &expression->base.source_position;
7274 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7277 if (expression->kind == EXPR_REFERENCE) {
7278 reference_expression_t *reference = &expression->reference;
7279 if (reference->entity->kind == ENTITY_FUNCTION &&
7280 reference->entity->function.btk != BUILTIN_NONE)
7281 handle_builtin_argument_restrictions(call);
7287 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7289 static bool same_compound_type(const type_t *type1, const type_t *type2)
7292 is_type_compound(type1) &&
7293 type1->kind == type2->kind &&
7294 type1->compound.compound == type2->compound.compound;
7297 static expression_t const *get_reference_address(expression_t const *expr)
7299 bool regular_take_address = true;
7301 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7302 expr = expr->unary.value;
7304 regular_take_address = false;
7307 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7310 expr = expr->unary.value;
7313 if (expr->kind != EXPR_REFERENCE)
7316 /* special case for functions which are automatically converted to a
7317 * pointer to function without an extra TAKE_ADDRESS operation */
7318 if (!regular_take_address &&
7319 expr->reference.entity->kind != ENTITY_FUNCTION) {
7326 static void warn_reference_address_as_bool(expression_t const* expr)
7328 expr = get_reference_address(expr);
7330 source_position_t const *const pos = &expr->base.source_position;
7331 entity_t const *const ent = expr->reference.entity;
7332 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7336 static void warn_assignment_in_condition(const expression_t *const expr)
7338 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7340 if (expr->base.parenthesized)
7342 source_position_t const *const pos = &expr->base.source_position;
7343 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7346 static void semantic_condition(expression_t const *const expr,
7347 char const *const context)
7349 type_t *const type = skip_typeref(expr->base.type);
7350 if (is_type_scalar(type)) {
7351 warn_reference_address_as_bool(expr);
7352 warn_assignment_in_condition(expr);
7353 } else if (is_type_valid(type)) {
7354 errorf(&expr->base.source_position,
7355 "%s must have scalar type", context);
7360 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7362 * @param expression the conditional expression
7364 static expression_t *parse_conditional_expression(expression_t *expression)
7366 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7368 conditional_expression_t *conditional = &result->conditional;
7369 conditional->condition = expression;
7372 add_anchor_token(':');
7374 /* §6.5.15:2 The first operand shall have scalar type. */
7375 semantic_condition(expression, "condition of conditional operator");
7377 expression_t *true_expression = expression;
7378 bool gnu_cond = false;
7379 if (GNU_MODE && token.kind == ':') {
7382 true_expression = parse_expression();
7384 rem_anchor_token(':');
7386 expression_t *false_expression =
7387 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7389 type_t *const orig_true_type = true_expression->base.type;
7390 type_t *const orig_false_type = false_expression->base.type;
7391 type_t *const true_type = skip_typeref(orig_true_type);
7392 type_t *const false_type = skip_typeref(orig_false_type);
7395 source_position_t const *const pos = &conditional->base.source_position;
7396 type_t *result_type;
7397 if (is_type_void(true_type) || is_type_void(false_type)) {
7398 /* ISO/IEC 14882:1998(E) §5.16:2 */
7399 if (true_expression->kind == EXPR_UNARY_THROW) {
7400 result_type = false_type;
7401 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7402 result_type = true_type;
7404 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7405 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7407 result_type = type_void;
7409 } else if (is_type_arithmetic(true_type)
7410 && is_type_arithmetic(false_type)) {
7411 result_type = semantic_arithmetic(true_type, false_type);
7412 } else if (same_compound_type(true_type, false_type)) {
7413 /* just take 1 of the 2 types */
7414 result_type = true_type;
7415 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7416 type_t *pointer_type;
7418 expression_t *other_expression;
7419 if (is_type_pointer(true_type) &&
7420 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7421 pointer_type = true_type;
7422 other_type = false_type;
7423 other_expression = false_expression;
7425 pointer_type = false_type;
7426 other_type = true_type;
7427 other_expression = true_expression;
7430 if (is_null_pointer_constant(other_expression)) {
7431 result_type = pointer_type;
7432 } else if (is_type_pointer(other_type)) {
7433 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7434 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7437 if (is_type_void(to1) || is_type_void(to2)) {
7439 } else if (types_compatible(get_unqualified_type(to1),
7440 get_unqualified_type(to2))) {
7443 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7447 type_t *const type =
7448 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7449 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7450 } else if (is_type_integer(other_type)) {
7451 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7452 result_type = pointer_type;
7454 goto types_incompatible;
7458 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7459 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7461 result_type = type_error_type;
7464 conditional->true_expression
7465 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7466 conditional->false_expression
7467 = create_implicit_cast(false_expression, result_type);
7468 conditional->base.type = result_type;
7473 * Parse an extension expression.
7475 static expression_t *parse_extension(void)
7478 expression_t *expression = parse_subexpression(PREC_UNARY);
7484 * Parse a __builtin_classify_type() expression.
7486 static expression_t *parse_builtin_classify_type(void)
7488 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7489 result->base.type = type_int;
7491 eat(T___builtin_classify_type);
7494 add_anchor_token(')');
7495 expression_t *expression = parse_expression();
7496 rem_anchor_token(')');
7498 result->classify_type.type_expression = expression;
7504 * Parse a delete expression
7505 * ISO/IEC 14882:1998(E) §5.3.5
7507 static expression_t *parse_delete(void)
7509 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7510 result->base.type = type_void;
7515 result->kind = EXPR_UNARY_DELETE_ARRAY;
7519 expression_t *const value = parse_subexpression(PREC_CAST);
7520 result->unary.value = value;
7522 type_t *const type = skip_typeref(value->base.type);
7523 if (!is_type_pointer(type)) {
7524 if (is_type_valid(type)) {
7525 errorf(&value->base.source_position,
7526 "operand of delete must have pointer type");
7528 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7529 source_position_t const *const pos = &value->base.source_position;
7530 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7537 * Parse a throw expression
7538 * ISO/IEC 14882:1998(E) §15:1
7540 static expression_t *parse_throw(void)
7542 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7543 result->base.type = type_void;
7547 expression_t *value = NULL;
7548 switch (token.kind) {
7550 value = parse_assignment_expression();
7551 /* ISO/IEC 14882:1998(E) §15.1:3 */
7552 type_t *const orig_type = value->base.type;
7553 type_t *const type = skip_typeref(orig_type);
7554 if (is_type_incomplete(type)) {
7555 errorf(&value->base.source_position,
7556 "cannot throw object of incomplete type '%T'", orig_type);
7557 } else if (is_type_pointer(type)) {
7558 type_t *const points_to = skip_typeref(type->pointer.points_to);
7559 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7560 errorf(&value->base.source_position,
7561 "cannot throw pointer to incomplete type '%T'", orig_type);
7569 result->unary.value = value;
7574 static bool check_pointer_arithmetic(const source_position_t *source_position,
7575 type_t *pointer_type,
7576 type_t *orig_pointer_type)
7578 type_t *points_to = pointer_type->pointer.points_to;
7579 points_to = skip_typeref(points_to);
7581 if (is_type_incomplete(points_to)) {
7582 if (!GNU_MODE || !is_type_void(points_to)) {
7583 errorf(source_position,
7584 "arithmetic with pointer to incomplete type '%T' not allowed",
7588 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7590 } else if (is_type_function(points_to)) {
7592 errorf(source_position,
7593 "arithmetic with pointer to function type '%T' not allowed",
7597 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7603 static bool is_lvalue(const expression_t *expression)
7605 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7606 switch (expression->kind) {
7607 case EXPR_ARRAY_ACCESS:
7608 case EXPR_COMPOUND_LITERAL:
7609 case EXPR_REFERENCE:
7611 case EXPR_UNARY_DEREFERENCE:
7615 type_t *type = skip_typeref(expression->base.type);
7617 /* ISO/IEC 14882:1998(E) §3.10:3 */
7618 is_type_reference(type) ||
7619 /* Claim it is an lvalue, if the type is invalid. There was a parse
7620 * error before, which maybe prevented properly recognizing it as
7622 !is_type_valid(type);
7627 static void semantic_incdec(unary_expression_t *expression)
7629 type_t *const orig_type = expression->value->base.type;
7630 type_t *const type = skip_typeref(orig_type);
7631 if (is_type_pointer(type)) {
7632 if (!check_pointer_arithmetic(&expression->base.source_position,
7636 } else if (!is_type_real(type) && is_type_valid(type)) {
7637 /* TODO: improve error message */
7638 errorf(&expression->base.source_position,
7639 "operation needs an arithmetic or pointer type");
7642 if (!is_lvalue(expression->value)) {
7643 /* TODO: improve error message */
7644 errorf(&expression->base.source_position, "lvalue required as operand");
7646 expression->base.type = orig_type;
7649 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7651 type_t *const res_type = promote_integer(type);
7652 expr->base.type = res_type;
7653 expr->value = create_implicit_cast(expr->value, res_type);
7656 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7658 type_t *const orig_type = expression->value->base.type;
7659 type_t *const type = skip_typeref(orig_type);
7660 if (!is_type_arithmetic(type)) {
7661 if (is_type_valid(type)) {
7662 /* TODO: improve error message */
7663 errorf(&expression->base.source_position,
7664 "operation needs an arithmetic type");
7667 } else if (is_type_integer(type)) {
7668 promote_unary_int_expr(expression, type);
7670 expression->base.type = orig_type;
7674 static void semantic_unexpr_plus(unary_expression_t *expression)
7676 semantic_unexpr_arithmetic(expression);
7677 source_position_t const *const pos = &expression->base.source_position;
7678 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7681 static void semantic_not(unary_expression_t *expression)
7683 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7684 semantic_condition(expression->value, "operand of !");
7685 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7688 static void semantic_unexpr_integer(unary_expression_t *expression)
7690 type_t *const orig_type = expression->value->base.type;
7691 type_t *const type = skip_typeref(orig_type);
7692 if (!is_type_integer(type)) {
7693 if (is_type_valid(type)) {
7694 errorf(&expression->base.source_position,
7695 "operand of ~ must be of integer type");
7700 promote_unary_int_expr(expression, type);
7703 static void semantic_dereference(unary_expression_t *expression)
7705 type_t *const orig_type = expression->value->base.type;
7706 type_t *const type = skip_typeref(orig_type);
7707 if (!is_type_pointer(type)) {
7708 if (is_type_valid(type)) {
7709 errorf(&expression->base.source_position,
7710 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7715 type_t *result_type = type->pointer.points_to;
7716 result_type = automatic_type_conversion(result_type);
7717 expression->base.type = result_type;
7721 * Record that an address is taken (expression represents an lvalue).
7723 * @param expression the expression
7724 * @param may_be_register if true, the expression might be an register
7726 static void set_address_taken(expression_t *expression, bool may_be_register)
7728 if (expression->kind != EXPR_REFERENCE)
7731 entity_t *const entity = expression->reference.entity;
7733 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7736 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7737 && !may_be_register) {
7738 source_position_t const *const pos = &expression->base.source_position;
7739 errorf(pos, "address of register '%N' requested", entity);
7742 if (entity->kind == ENTITY_VARIABLE) {
7743 entity->variable.address_taken = true;
7745 assert(entity->kind == ENTITY_PARAMETER);
7746 entity->parameter.address_taken = true;
7751 * Check the semantic of the address taken expression.
7753 static void semantic_take_addr(unary_expression_t *expression)
7755 expression_t *value = expression->value;
7756 value->base.type = revert_automatic_type_conversion(value);
7758 type_t *orig_type = value->base.type;
7759 type_t *type = skip_typeref(orig_type);
7760 if (!is_type_valid(type))
7764 if (!is_lvalue(value)) {
7765 errorf(&expression->base.source_position, "'&' requires an lvalue");
7767 if (is_bitfield(value)) {
7768 errorf(&expression->base.source_position,
7769 "'&' not allowed on bitfield");
7772 set_address_taken(value, false);
7774 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7777 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7778 static expression_t *parse_##unexpression_type(void) \
7780 expression_t *unary_expression \
7781 = allocate_expression_zero(unexpression_type); \
7783 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7785 sfunc(&unary_expression->unary); \
7787 return unary_expression; \
7790 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7791 semantic_unexpr_arithmetic)
7792 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7793 semantic_unexpr_plus)
7794 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7796 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7797 semantic_dereference)
7798 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7800 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7801 semantic_unexpr_integer)
7802 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7804 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7807 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7809 static expression_t *parse_##unexpression_type(expression_t *left) \
7811 expression_t *unary_expression \
7812 = allocate_expression_zero(unexpression_type); \
7814 unary_expression->unary.value = left; \
7816 sfunc(&unary_expression->unary); \
7818 return unary_expression; \
7821 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7822 EXPR_UNARY_POSTFIX_INCREMENT,
7824 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7825 EXPR_UNARY_POSTFIX_DECREMENT,
7828 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7830 /* TODO: handle complex + imaginary types */
7832 type_left = get_unqualified_type(type_left);
7833 type_right = get_unqualified_type(type_right);
7835 /* §6.3.1.8 Usual arithmetic conversions */
7836 if (type_left == type_long_double || type_right == type_long_double) {
7837 return type_long_double;
7838 } else if (type_left == type_double || type_right == type_double) {
7840 } else if (type_left == type_float || type_right == type_float) {
7844 type_left = promote_integer(type_left);
7845 type_right = promote_integer(type_right);
7847 if (type_left == type_right)
7850 bool const signed_left = is_type_signed(type_left);
7851 bool const signed_right = is_type_signed(type_right);
7852 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7853 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7855 if (signed_left == signed_right)
7856 return rank_left >= rank_right ? type_left : type_right;
7860 atomic_type_kind_t s_akind;
7861 atomic_type_kind_t u_akind;
7866 u_type = type_right;
7868 s_type = type_right;
7871 s_akind = get_akind(s_type);
7872 u_akind = get_akind(u_type);
7873 s_rank = get_akind_rank(s_akind);
7874 u_rank = get_akind_rank(u_akind);
7876 if (u_rank >= s_rank)
7879 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7883 case ATOMIC_TYPE_INT: return type_unsigned_int;
7884 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7885 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7887 default: panic("invalid atomic type");
7892 * Check the semantic restrictions for a binary expression.
7894 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7896 expression_t *const left = expression->left;
7897 expression_t *const right = expression->right;
7898 type_t *const orig_type_left = left->base.type;
7899 type_t *const orig_type_right = right->base.type;
7900 type_t *const type_left = skip_typeref(orig_type_left);
7901 type_t *const type_right = skip_typeref(orig_type_right);
7903 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7904 /* TODO: improve error message */
7905 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7906 errorf(&expression->base.source_position,
7907 "operation needs arithmetic types");
7912 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7913 expression->left = create_implicit_cast(left, arithmetic_type);
7914 expression->right = create_implicit_cast(right, arithmetic_type);
7915 expression->base.type = arithmetic_type;
7918 static void semantic_binexpr_integer(binary_expression_t *const expression)
7920 expression_t *const left = expression->left;
7921 expression_t *const right = expression->right;
7922 type_t *const orig_type_left = left->base.type;
7923 type_t *const orig_type_right = right->base.type;
7924 type_t *const type_left = skip_typeref(orig_type_left);
7925 type_t *const type_right = skip_typeref(orig_type_right);
7927 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7928 /* TODO: improve error message */
7929 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7930 errorf(&expression->base.source_position,
7931 "operation needs integer types");
7936 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7937 expression->left = create_implicit_cast(left, result_type);
7938 expression->right = create_implicit_cast(right, result_type);
7939 expression->base.type = result_type;
7942 static void warn_div_by_zero(binary_expression_t const *const expression)
7944 if (!is_type_integer(expression->base.type))
7947 expression_t const *const right = expression->right;
7948 /* The type of the right operand can be different for /= */
7949 if (is_type_integer(right->base.type) &&
7950 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7951 !fold_constant_to_bool(right)) {
7952 source_position_t const *const pos = &expression->base.source_position;
7953 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7958 * Check the semantic restrictions for a div/mod expression.
7960 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7962 semantic_binexpr_arithmetic(expression);
7963 warn_div_by_zero(expression);
7966 static void warn_addsub_in_shift(const expression_t *const expr)
7968 if (expr->base.parenthesized)
7972 switch (expr->kind) {
7973 case EXPR_BINARY_ADD: op = '+'; break;
7974 case EXPR_BINARY_SUB: op = '-'; break;
7978 source_position_t const *const pos = &expr->base.source_position;
7979 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7982 static bool semantic_shift(binary_expression_t *expression)
7984 expression_t *const left = expression->left;
7985 expression_t *const right = expression->right;
7986 type_t *const orig_type_left = left->base.type;
7987 type_t *const orig_type_right = right->base.type;
7988 type_t * type_left = skip_typeref(orig_type_left);
7989 type_t * type_right = skip_typeref(orig_type_right);
7991 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7992 /* TODO: improve error message */
7993 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7994 errorf(&expression->base.source_position,
7995 "operands of shift operation must have integer types");
8000 type_left = promote_integer(type_left);
8002 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8003 source_position_t const *const pos = &right->base.source_position;
8004 long const count = fold_constant_to_int(right);
8006 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8007 } else if ((unsigned long)count >=
8008 get_atomic_type_size(type_left->atomic.akind) * 8) {
8009 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8013 type_right = promote_integer(type_right);
8014 expression->right = create_implicit_cast(right, type_right);
8019 static void semantic_shift_op(binary_expression_t *expression)
8021 expression_t *const left = expression->left;
8022 expression_t *const right = expression->right;
8024 if (!semantic_shift(expression))
8027 warn_addsub_in_shift(left);
8028 warn_addsub_in_shift(right);
8030 type_t *const orig_type_left = left->base.type;
8031 type_t * type_left = skip_typeref(orig_type_left);
8033 type_left = promote_integer(type_left);
8034 expression->left = create_implicit_cast(left, type_left);
8035 expression->base.type = type_left;
8038 static void semantic_add(binary_expression_t *expression)
8040 expression_t *const left = expression->left;
8041 expression_t *const right = expression->right;
8042 type_t *const orig_type_left = left->base.type;
8043 type_t *const orig_type_right = right->base.type;
8044 type_t *const type_left = skip_typeref(orig_type_left);
8045 type_t *const type_right = skip_typeref(orig_type_right);
8048 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8049 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8050 expression->left = create_implicit_cast(left, arithmetic_type);
8051 expression->right = create_implicit_cast(right, arithmetic_type);
8052 expression->base.type = arithmetic_type;
8053 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8054 check_pointer_arithmetic(&expression->base.source_position,
8055 type_left, orig_type_left);
8056 expression->base.type = type_left;
8057 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8058 check_pointer_arithmetic(&expression->base.source_position,
8059 type_right, orig_type_right);
8060 expression->base.type = type_right;
8061 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8062 errorf(&expression->base.source_position,
8063 "invalid operands to binary + ('%T', '%T')",
8064 orig_type_left, orig_type_right);
8068 static void semantic_sub(binary_expression_t *expression)
8070 expression_t *const left = expression->left;
8071 expression_t *const right = expression->right;
8072 type_t *const orig_type_left = left->base.type;
8073 type_t *const orig_type_right = right->base.type;
8074 type_t *const type_left = skip_typeref(orig_type_left);
8075 type_t *const type_right = skip_typeref(orig_type_right);
8076 source_position_t const *const pos = &expression->base.source_position;
8079 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8080 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8081 expression->left = create_implicit_cast(left, arithmetic_type);
8082 expression->right = create_implicit_cast(right, arithmetic_type);
8083 expression->base.type = arithmetic_type;
8084 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8085 check_pointer_arithmetic(&expression->base.source_position,
8086 type_left, orig_type_left);
8087 expression->base.type = type_left;
8088 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8089 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8090 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8091 if (!types_compatible(unqual_left, unqual_right)) {
8093 "subtracting pointers to incompatible types '%T' and '%T'",
8094 orig_type_left, orig_type_right);
8095 } else if (!is_type_object(unqual_left)) {
8096 if (!is_type_void(unqual_left)) {
8097 errorf(pos, "subtracting pointers to non-object types '%T'",
8100 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8103 expression->base.type = type_ptrdiff_t;
8104 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8105 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8106 orig_type_left, orig_type_right);
8110 static void warn_string_literal_address(expression_t const* expr)
8112 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8113 expr = expr->unary.value;
8114 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8116 expr = expr->unary.value;
8119 if (expr->kind == EXPR_STRING_LITERAL
8120 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8121 source_position_t const *const pos = &expr->base.source_position;
8122 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8126 static bool maybe_negative(expression_t const *const expr)
8128 switch (is_constant_expression(expr)) {
8129 case EXPR_CLASS_ERROR: return false;
8130 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8131 default: return true;
8135 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8137 warn_string_literal_address(expr);
8139 expression_t const* const ref = get_reference_address(expr);
8140 if (ref != NULL && is_null_pointer_constant(other)) {
8141 entity_t const *const ent = ref->reference.entity;
8142 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8145 if (!expr->base.parenthesized) {
8146 switch (expr->base.kind) {
8147 case EXPR_BINARY_LESS:
8148 case EXPR_BINARY_GREATER:
8149 case EXPR_BINARY_LESSEQUAL:
8150 case EXPR_BINARY_GREATEREQUAL:
8151 case EXPR_BINARY_NOTEQUAL:
8152 case EXPR_BINARY_EQUAL:
8153 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8162 * Check the semantics of comparison expressions.
8164 * @param expression The expression to check.
8166 static void semantic_comparison(binary_expression_t *expression)
8168 source_position_t const *const pos = &expression->base.source_position;
8169 expression_t *const left = expression->left;
8170 expression_t *const right = expression->right;
8172 warn_comparison(pos, left, right);
8173 warn_comparison(pos, right, left);
8175 type_t *orig_type_left = left->base.type;
8176 type_t *orig_type_right = right->base.type;
8177 type_t *type_left = skip_typeref(orig_type_left);
8178 type_t *type_right = skip_typeref(orig_type_right);
8180 /* TODO non-arithmetic types */
8181 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8182 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8184 /* test for signed vs unsigned compares */
8185 if (is_type_integer(arithmetic_type)) {
8186 bool const signed_left = is_type_signed(type_left);
8187 bool const signed_right = is_type_signed(type_right);
8188 if (signed_left != signed_right) {
8189 /* FIXME long long needs better const folding magic */
8190 /* TODO check whether constant value can be represented by other type */
8191 if ((signed_left && maybe_negative(left)) ||
8192 (signed_right && maybe_negative(right))) {
8193 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8198 expression->left = create_implicit_cast(left, arithmetic_type);
8199 expression->right = create_implicit_cast(right, arithmetic_type);
8200 expression->base.type = arithmetic_type;
8201 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8202 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8203 is_type_float(arithmetic_type)) {
8204 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8206 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8207 /* TODO check compatibility */
8208 } else if (is_type_pointer(type_left)) {
8209 expression->right = create_implicit_cast(right, type_left);
8210 } else if (is_type_pointer(type_right)) {
8211 expression->left = create_implicit_cast(left, type_right);
8212 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8213 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8215 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8219 * Checks if a compound type has constant fields.
8221 static bool has_const_fields(const compound_type_t *type)
8223 compound_t *compound = type->compound;
8224 entity_t *entry = compound->members.entities;
8226 for (; entry != NULL; entry = entry->base.next) {
8227 if (!is_declaration(entry))
8230 const type_t *decl_type = skip_typeref(entry->declaration.type);
8231 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8238 static bool is_valid_assignment_lhs(expression_t const* const left)
8240 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8241 type_t *const type_left = skip_typeref(orig_type_left);
8243 if (!is_lvalue(left)) {
8244 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8249 if (left->kind == EXPR_REFERENCE
8250 && left->reference.entity->kind == ENTITY_FUNCTION) {
8251 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8255 if (is_type_array(type_left)) {
8256 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8259 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8260 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8264 if (is_type_incomplete(type_left)) {
8265 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8266 left, orig_type_left);
8269 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8270 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8271 left, orig_type_left);
8278 static void semantic_arithmetic_assign(binary_expression_t *expression)
8280 expression_t *left = expression->left;
8281 expression_t *right = expression->right;
8282 type_t *orig_type_left = left->base.type;
8283 type_t *orig_type_right = right->base.type;
8285 if (!is_valid_assignment_lhs(left))
8288 type_t *type_left = skip_typeref(orig_type_left);
8289 type_t *type_right = skip_typeref(orig_type_right);
8291 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8292 /* TODO: improve error message */
8293 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8294 errorf(&expression->base.source_position,
8295 "operation needs arithmetic types");
8300 /* combined instructions are tricky. We can't create an implicit cast on
8301 * the left side, because we need the uncasted form for the store.
8302 * The ast2firm pass has to know that left_type must be right_type
8303 * for the arithmetic operation and create a cast by itself */
8304 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8305 expression->right = create_implicit_cast(right, arithmetic_type);
8306 expression->base.type = type_left;
8309 static void semantic_divmod_assign(binary_expression_t *expression)
8311 semantic_arithmetic_assign(expression);
8312 warn_div_by_zero(expression);
8315 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8317 expression_t *const left = expression->left;
8318 expression_t *const right = expression->right;
8319 type_t *const orig_type_left = left->base.type;
8320 type_t *const orig_type_right = right->base.type;
8321 type_t *const type_left = skip_typeref(orig_type_left);
8322 type_t *const type_right = skip_typeref(orig_type_right);
8324 if (!is_valid_assignment_lhs(left))
8327 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8328 /* combined instructions are tricky. We can't create an implicit cast on
8329 * the left side, because we need the uncasted form for the store.
8330 * The ast2firm pass has to know that left_type must be right_type
8331 * for the arithmetic operation and create a cast by itself */
8332 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8333 expression->right = create_implicit_cast(right, arithmetic_type);
8334 expression->base.type = type_left;
8335 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8336 check_pointer_arithmetic(&expression->base.source_position,
8337 type_left, orig_type_left);
8338 expression->base.type = type_left;
8339 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8340 errorf(&expression->base.source_position,
8341 "incompatible types '%T' and '%T' in assignment",
8342 orig_type_left, orig_type_right);
8346 static void semantic_integer_assign(binary_expression_t *expression)
8348 expression_t *left = expression->left;
8349 expression_t *right = expression->right;
8350 type_t *orig_type_left = left->base.type;
8351 type_t *orig_type_right = right->base.type;
8353 if (!is_valid_assignment_lhs(left))
8356 type_t *type_left = skip_typeref(orig_type_left);
8357 type_t *type_right = skip_typeref(orig_type_right);
8359 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8360 /* TODO: improve error message */
8361 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8362 errorf(&expression->base.source_position,
8363 "operation needs integer types");
8368 /* combined instructions are tricky. We can't create an implicit cast on
8369 * the left side, because we need the uncasted form for the store.
8370 * The ast2firm pass has to know that left_type must be right_type
8371 * for the arithmetic operation and create a cast by itself */
8372 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8373 expression->right = create_implicit_cast(right, arithmetic_type);
8374 expression->base.type = type_left;
8377 static void semantic_shift_assign(binary_expression_t *expression)
8379 expression_t *left = expression->left;
8381 if (!is_valid_assignment_lhs(left))
8384 if (!semantic_shift(expression))
8387 expression->base.type = skip_typeref(left->base.type);
8390 static void warn_logical_and_within_or(const expression_t *const expr)
8392 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8394 if (expr->base.parenthesized)
8396 source_position_t const *const pos = &expr->base.source_position;
8397 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8401 * Check the semantic restrictions of a logical expression.
8403 static void semantic_logical_op(binary_expression_t *expression)
8405 /* §6.5.13:2 Each of the operands shall have scalar type.
8406 * §6.5.14:2 Each of the operands shall have scalar type. */
8407 semantic_condition(expression->left, "left operand of logical operator");
8408 semantic_condition(expression->right, "right operand of logical operator");
8409 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8410 warn_logical_and_within_or(expression->left);
8411 warn_logical_and_within_or(expression->right);
8413 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8417 * Check the semantic restrictions of a binary assign expression.
8419 static void semantic_binexpr_assign(binary_expression_t *expression)
8421 expression_t *left = expression->left;
8422 type_t *orig_type_left = left->base.type;
8424 if (!is_valid_assignment_lhs(left))
8427 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8428 report_assign_error(error, orig_type_left, expression->right,
8429 "assignment", &left->base.source_position);
8430 expression->right = create_implicit_cast(expression->right, orig_type_left);
8431 expression->base.type = orig_type_left;
8435 * Determine if the outermost operation (or parts thereof) of the given
8436 * expression has no effect in order to generate a warning about this fact.
8437 * Therefore in some cases this only examines some of the operands of the
8438 * expression (see comments in the function and examples below).
8440 * f() + 23; // warning, because + has no effect
8441 * x || f(); // no warning, because x controls execution of f()
8442 * x ? y : f(); // warning, because y has no effect
8443 * (void)x; // no warning to be able to suppress the warning
8444 * This function can NOT be used for an "expression has definitely no effect"-
8446 static bool expression_has_effect(const expression_t *const expr)
8448 switch (expr->kind) {
8449 case EXPR_ERROR: return true; /* do NOT warn */
8450 case EXPR_REFERENCE: return false;
8451 case EXPR_ENUM_CONSTANT: return false;
8452 case EXPR_LABEL_ADDRESS: return false;
8454 /* suppress the warning for microsoft __noop operations */
8455 case EXPR_LITERAL_MS_NOOP: return true;
8456 case EXPR_LITERAL_BOOLEAN:
8457 case EXPR_LITERAL_CHARACTER:
8458 case EXPR_LITERAL_WIDE_CHARACTER:
8459 case EXPR_LITERAL_INTEGER:
8460 case EXPR_LITERAL_INTEGER_OCTAL:
8461 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8462 case EXPR_LITERAL_FLOATINGPOINT:
8463 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8464 case EXPR_STRING_LITERAL: return false;
8465 case EXPR_WIDE_STRING_LITERAL: return false;
8468 const call_expression_t *const call = &expr->call;
8469 if (call->function->kind != EXPR_REFERENCE)
8472 switch (call->function->reference.entity->function.btk) {
8473 /* FIXME: which builtins have no effect? */
8474 default: return true;
8478 /* Generate the warning if either the left or right hand side of a
8479 * conditional expression has no effect */
8480 case EXPR_CONDITIONAL: {
8481 conditional_expression_t const *const cond = &expr->conditional;
8482 expression_t const *const t = cond->true_expression;
8484 (t == NULL || expression_has_effect(t)) &&
8485 expression_has_effect(cond->false_expression);
8488 case EXPR_SELECT: return false;
8489 case EXPR_ARRAY_ACCESS: return false;
8490 case EXPR_SIZEOF: return false;
8491 case EXPR_CLASSIFY_TYPE: return false;
8492 case EXPR_ALIGNOF: return false;
8494 case EXPR_FUNCNAME: return false;
8495 case EXPR_BUILTIN_CONSTANT_P: return false;
8496 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8497 case EXPR_OFFSETOF: return false;
8498 case EXPR_VA_START: return true;
8499 case EXPR_VA_ARG: return true;
8500 case EXPR_VA_COPY: return true;
8501 case EXPR_STATEMENT: return true; // TODO
8502 case EXPR_COMPOUND_LITERAL: return false;
8504 case EXPR_UNARY_NEGATE: return false;
8505 case EXPR_UNARY_PLUS: return false;
8506 case EXPR_UNARY_BITWISE_NEGATE: return false;
8507 case EXPR_UNARY_NOT: return false;
8508 case EXPR_UNARY_DEREFERENCE: return false;
8509 case EXPR_UNARY_TAKE_ADDRESS: return false;
8510 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8511 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8512 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8513 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8515 /* Treat void casts as if they have an effect in order to being able to
8516 * suppress the warning */
8517 case EXPR_UNARY_CAST: {
8518 type_t *const type = skip_typeref(expr->base.type);
8519 return is_type_void(type);
8522 case EXPR_UNARY_ASSUME: return true;
8523 case EXPR_UNARY_DELETE: return true;
8524 case EXPR_UNARY_DELETE_ARRAY: return true;
8525 case EXPR_UNARY_THROW: return true;
8527 case EXPR_BINARY_ADD: return false;
8528 case EXPR_BINARY_SUB: return false;
8529 case EXPR_BINARY_MUL: return false;
8530 case EXPR_BINARY_DIV: return false;
8531 case EXPR_BINARY_MOD: return false;
8532 case EXPR_BINARY_EQUAL: return false;
8533 case EXPR_BINARY_NOTEQUAL: return false;
8534 case EXPR_BINARY_LESS: return false;
8535 case EXPR_BINARY_LESSEQUAL: return false;
8536 case EXPR_BINARY_GREATER: return false;
8537 case EXPR_BINARY_GREATEREQUAL: return false;
8538 case EXPR_BINARY_BITWISE_AND: return false;
8539 case EXPR_BINARY_BITWISE_OR: return false;
8540 case EXPR_BINARY_BITWISE_XOR: return false;
8541 case EXPR_BINARY_SHIFTLEFT: return false;
8542 case EXPR_BINARY_SHIFTRIGHT: return false;
8543 case EXPR_BINARY_ASSIGN: return true;
8544 case EXPR_BINARY_MUL_ASSIGN: return true;
8545 case EXPR_BINARY_DIV_ASSIGN: return true;
8546 case EXPR_BINARY_MOD_ASSIGN: return true;
8547 case EXPR_BINARY_ADD_ASSIGN: return true;
8548 case EXPR_BINARY_SUB_ASSIGN: return true;
8549 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8550 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8551 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8552 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8553 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8555 /* Only examine the right hand side of && and ||, because the left hand
8556 * side already has the effect of controlling the execution of the right
8558 case EXPR_BINARY_LOGICAL_AND:
8559 case EXPR_BINARY_LOGICAL_OR:
8560 /* Only examine the right hand side of a comma expression, because the left
8561 * hand side has a separate warning */
8562 case EXPR_BINARY_COMMA:
8563 return expression_has_effect(expr->binary.right);
8565 case EXPR_BINARY_ISGREATER: return false;
8566 case EXPR_BINARY_ISGREATEREQUAL: return false;
8567 case EXPR_BINARY_ISLESS: return false;
8568 case EXPR_BINARY_ISLESSEQUAL: return false;
8569 case EXPR_BINARY_ISLESSGREATER: return false;
8570 case EXPR_BINARY_ISUNORDERED: return false;
8573 internal_errorf(HERE, "unexpected expression");
8576 static void semantic_comma(binary_expression_t *expression)
8578 const expression_t *const left = expression->left;
8579 if (!expression_has_effect(left)) {
8580 source_position_t const *const pos = &left->base.source_position;
8581 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8583 expression->base.type = expression->right->base.type;
8587 * @param prec_r precedence of the right operand
8589 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8590 static expression_t *parse_##binexpression_type(expression_t *left) \
8592 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8593 binexpr->binary.left = left; \
8596 expression_t *right = parse_subexpression(prec_r); \
8598 binexpr->binary.right = right; \
8599 sfunc(&binexpr->binary); \
8604 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8605 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8606 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8607 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8608 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8609 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8610 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8611 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8612 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8613 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8614 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8615 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8616 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8617 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8618 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8619 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8620 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8621 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8622 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8623 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8624 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8625 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8626 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8627 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8628 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8629 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8630 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8631 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8632 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8633 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8636 static expression_t *parse_subexpression(precedence_t precedence)
8638 if (token.kind < 0) {
8639 return expected_expression_error();
8642 expression_parser_function_t *parser
8643 = &expression_parsers[token.kind];
8646 if (parser->parser != NULL) {
8647 left = parser->parser();
8649 left = parse_primary_expression();
8651 assert(left != NULL);
8654 if (token.kind < 0) {
8655 return expected_expression_error();
8658 parser = &expression_parsers[token.kind];
8659 if (parser->infix_parser == NULL)
8661 if (parser->infix_precedence < precedence)
8664 left = parser->infix_parser(left);
8666 assert(left != NULL);
8673 * Parse an expression.
8675 static expression_t *parse_expression(void)
8677 return parse_subexpression(PREC_EXPRESSION);
8681 * Register a parser for a prefix-like operator.
8683 * @param parser the parser function
8684 * @param token_kind the token type of the prefix token
8686 static void register_expression_parser(parse_expression_function parser,
8689 expression_parser_function_t *entry = &expression_parsers[token_kind];
8691 if (entry->parser != NULL) {
8692 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8693 panic("trying to register multiple expression parsers for a token");
8695 entry->parser = parser;
8699 * Register a parser for an infix operator with given precedence.
8701 * @param parser the parser function
8702 * @param token_kind the token type of the infix operator
8703 * @param precedence the precedence of the operator
8705 static void register_infix_parser(parse_expression_infix_function parser,
8706 int token_kind, precedence_t precedence)
8708 expression_parser_function_t *entry = &expression_parsers[token_kind];
8710 if (entry->infix_parser != NULL) {
8711 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8712 panic("trying to register multiple infix expression parsers for a "
8715 entry->infix_parser = parser;
8716 entry->infix_precedence = precedence;
8720 * Initialize the expression parsers.
8722 static void init_expression_parsers(void)
8724 memset(&expression_parsers, 0, sizeof(expression_parsers));
8726 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8727 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8728 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8729 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8730 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8731 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8732 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8733 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8734 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8735 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8736 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8737 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8738 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8739 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8740 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8741 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8742 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8743 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8744 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8745 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8746 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8747 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8748 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8749 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8750 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8751 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8752 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8753 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8754 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8755 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8756 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8757 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8758 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8759 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8760 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8761 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8762 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8764 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8765 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8766 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8767 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8768 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8769 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8770 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8771 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8772 register_expression_parser(parse_sizeof, T_sizeof);
8773 register_expression_parser(parse_alignof, T___alignof__);
8774 register_expression_parser(parse_extension, T___extension__);
8775 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8776 register_expression_parser(parse_delete, T_delete);
8777 register_expression_parser(parse_throw, T_throw);
8781 * Parse a asm statement arguments specification.
8783 static asm_argument_t *parse_asm_arguments(bool is_out)
8785 asm_argument_t *result = NULL;
8786 asm_argument_t **anchor = &result;
8788 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8789 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8792 add_anchor_token(']');
8793 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8794 rem_anchor_token(']');
8796 if (!argument->symbol)
8800 argument->constraints = parse_string_literals();
8802 add_anchor_token(')');
8803 expression_t *expression = parse_expression();
8804 rem_anchor_token(')');
8806 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8807 * change size or type representation (e.g. int -> long is ok, but
8808 * int -> float is not) */
8809 if (expression->kind == EXPR_UNARY_CAST) {
8810 type_t *const type = expression->base.type;
8811 type_kind_t const kind = type->kind;
8812 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8815 if (kind == TYPE_ATOMIC) {
8816 atomic_type_kind_t const akind = type->atomic.akind;
8817 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8818 size = get_atomic_type_size(akind);
8820 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8821 size = get_type_size(type_void_ptr);
8825 expression_t *const value = expression->unary.value;
8826 type_t *const value_type = value->base.type;
8827 type_kind_t const value_kind = value_type->kind;
8829 unsigned value_flags;
8830 unsigned value_size;
8831 if (value_kind == TYPE_ATOMIC) {
8832 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8833 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8834 value_size = get_atomic_type_size(value_akind);
8835 } else if (value_kind == TYPE_POINTER) {
8836 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8837 value_size = get_type_size(type_void_ptr);
8842 if (value_flags != flags || value_size != size)
8846 } while (expression->kind == EXPR_UNARY_CAST);
8850 if (!is_lvalue(expression)) {
8851 errorf(&expression->base.source_position,
8852 "asm output argument is not an lvalue");
8855 if (argument->constraints.begin[0] == '=')
8856 determine_lhs_ent(expression, NULL);
8858 mark_vars_read(expression, NULL);
8860 mark_vars_read(expression, NULL);
8862 argument->expression = expression;
8865 set_address_taken(expression, true);
8868 anchor = &argument->next;
8878 * Parse a asm statement clobber specification.
8880 static asm_clobber_t *parse_asm_clobbers(void)
8882 asm_clobber_t *result = NULL;
8883 asm_clobber_t **anchor = &result;
8885 while (token.kind == T_STRING_LITERAL) {
8886 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8887 clobber->clobber = parse_string_literals();
8890 anchor = &clobber->next;
8900 * Parse an asm statement.
8902 static statement_t *parse_asm_statement(void)
8904 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8905 asm_statement_t *asm_statement = &statement->asms;
8909 if (next_if(T_volatile))
8910 asm_statement->is_volatile = true;
8913 add_anchor_token(')');
8914 if (token.kind != T_STRING_LITERAL) {
8915 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8918 asm_statement->asm_text = parse_string_literals();
8920 add_anchor_token(':');
8921 if (!next_if(':')) {
8922 rem_anchor_token(':');
8926 asm_statement->outputs = parse_asm_arguments(true);
8927 if (!next_if(':')) {
8928 rem_anchor_token(':');
8932 asm_statement->inputs = parse_asm_arguments(false);
8933 if (!next_if(':')) {
8934 rem_anchor_token(':');
8937 rem_anchor_token(':');
8939 asm_statement->clobbers = parse_asm_clobbers();
8942 rem_anchor_token(')');
8946 if (asm_statement->outputs == NULL) {
8947 /* GCC: An 'asm' instruction without any output operands will be treated
8948 * identically to a volatile 'asm' instruction. */
8949 asm_statement->is_volatile = true;
8955 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8957 statement_t *inner_stmt;
8958 switch (token.kind) {
8960 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8961 inner_stmt = create_error_statement();
8965 if (label->kind == STATEMENT_LABEL) {
8966 /* Eat an empty statement here, to avoid the warning about an empty
8967 * statement after a label. label:; is commonly used to have a label
8968 * before a closing brace. */
8969 inner_stmt = create_empty_statement();
8976 inner_stmt = parse_statement();
8977 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8978 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8979 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8980 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8988 * Parse a case statement.
8990 static statement_t *parse_case_statement(void)
8992 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8993 source_position_t *const pos = &statement->base.source_position;
8996 add_anchor_token(':');
8998 expression_t *expression = parse_expression();
8999 type_t *expression_type = expression->base.type;
9000 type_t *skipped = skip_typeref(expression_type);
9001 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9002 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9003 expression, expression_type);
9006 type_t *type = expression_type;
9007 if (current_switch != NULL) {
9008 type_t *switch_type = current_switch->expression->base.type;
9009 if (is_type_valid(switch_type)) {
9010 expression = create_implicit_cast(expression, switch_type);
9014 statement->case_label.expression = expression;
9015 expression_classification_t const expr_class = is_constant_expression(expression);
9016 if (expr_class != EXPR_CLASS_CONSTANT) {
9017 if (expr_class != EXPR_CLASS_ERROR) {
9018 errorf(pos, "case label does not reduce to an integer constant");
9020 statement->case_label.is_bad = true;
9022 long const val = fold_constant_to_int(expression);
9023 statement->case_label.first_case = val;
9024 statement->case_label.last_case = val;
9028 if (next_if(T_DOTDOTDOT)) {
9029 expression_t *end_range = parse_expression();
9030 expression_type = expression->base.type;
9031 skipped = skip_typeref(expression_type);
9032 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9033 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9034 expression, expression_type);
9037 end_range = create_implicit_cast(end_range, type);
9038 statement->case_label.end_range = end_range;
9039 expression_classification_t const end_class = is_constant_expression(end_range);
9040 if (end_class != EXPR_CLASS_CONSTANT) {
9041 if (end_class != EXPR_CLASS_ERROR) {
9042 errorf(pos, "case range does not reduce to an integer constant");
9044 statement->case_label.is_bad = true;
9046 long const val = fold_constant_to_int(end_range);
9047 statement->case_label.last_case = val;
9049 if (val < statement->case_label.first_case) {
9050 statement->case_label.is_empty_range = true;
9051 warningf(WARN_OTHER, pos, "empty range specified");
9057 PUSH_PARENT(statement);
9059 rem_anchor_token(':');
9062 if (current_switch != NULL) {
9063 if (! statement->case_label.is_bad) {
9064 /* Check for duplicate case values */
9065 case_label_statement_t *c = &statement->case_label;
9066 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9067 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9070 if (c->last_case < l->first_case || c->first_case > l->last_case)
9073 errorf(pos, "duplicate case value (previously used %P)",
9074 &l->base.source_position);
9078 /* link all cases into the switch statement */
9079 if (current_switch->last_case == NULL) {
9080 current_switch->first_case = &statement->case_label;
9082 current_switch->last_case->next = &statement->case_label;
9084 current_switch->last_case = &statement->case_label;
9086 errorf(pos, "case label not within a switch statement");
9089 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9096 * Parse a default statement.
9098 static statement_t *parse_default_statement(void)
9100 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9104 PUSH_PARENT(statement);
9108 if (current_switch != NULL) {
9109 const case_label_statement_t *def_label = current_switch->default_label;
9110 if (def_label != NULL) {
9111 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9113 current_switch->default_label = &statement->case_label;
9115 /* link all cases into the switch statement */
9116 if (current_switch->last_case == NULL) {
9117 current_switch->first_case = &statement->case_label;
9119 current_switch->last_case->next = &statement->case_label;
9121 current_switch->last_case = &statement->case_label;
9124 errorf(&statement->base.source_position,
9125 "'default' label not within a switch statement");
9128 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9135 * Parse a label statement.
9137 static statement_t *parse_label_statement(void)
9139 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9140 label_t *const label = get_label();
9141 statement->label.label = label;
9143 PUSH_PARENT(statement);
9145 /* if statement is already set then the label is defined twice,
9146 * otherwise it was just mentioned in a goto/local label declaration so far
9148 source_position_t const* const pos = &statement->base.source_position;
9149 if (label->statement != NULL) {
9150 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9152 label->base.source_position = *pos;
9153 label->statement = statement;
9158 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9159 parse_attributes(NULL); // TODO process attributes
9162 statement->label.statement = parse_label_inner_statement(statement, "label");
9164 /* remember the labels in a list for later checking */
9165 *label_anchor = &statement->label;
9166 label_anchor = &statement->label.next;
9172 static statement_t *parse_inner_statement(void)
9174 statement_t *const stmt = parse_statement();
9175 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9176 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9177 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9178 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9184 * Parse an expression in parentheses and mark its variables as read.
9186 static expression_t *parse_condition(void)
9189 add_anchor_token(')');
9190 expression_t *const expr = parse_expression();
9191 mark_vars_read(expr, NULL);
9192 rem_anchor_token(')');
9198 * Parse an if statement.
9200 static statement_t *parse_if(void)
9202 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9206 PUSH_PARENT(statement);
9207 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9209 add_anchor_token(T_else);
9211 expression_t *const expr = parse_condition();
9212 statement->ifs.condition = expr;
9213 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9215 semantic_condition(expr, "condition of 'if'-statment");
9217 statement_t *const true_stmt = parse_inner_statement();
9218 statement->ifs.true_statement = true_stmt;
9219 rem_anchor_token(T_else);
9221 if (true_stmt->kind == STATEMENT_EMPTY) {
9222 warningf(WARN_EMPTY_BODY, HERE,
9223 "suggest braces around empty body in an ‘if’ statement");
9226 if (next_if(T_else)) {
9227 statement->ifs.false_statement = parse_inner_statement();
9229 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9230 warningf(WARN_EMPTY_BODY, HERE,
9231 "suggest braces around empty body in an ‘if’ statement");
9233 } else if (true_stmt->kind == STATEMENT_IF &&
9234 true_stmt->ifs.false_statement != NULL) {
9235 source_position_t const *const pos = &true_stmt->base.source_position;
9236 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9245 * Check that all enums are handled in a switch.
9247 * @param statement the switch statement to check
9249 static void check_enum_cases(const switch_statement_t *statement)
9251 if (!is_warn_on(WARN_SWITCH_ENUM))
9253 const type_t *type = skip_typeref(statement->expression->base.type);
9254 if (! is_type_enum(type))
9256 const enum_type_t *enumt = &type->enumt;
9258 /* if we have a default, no warnings */
9259 if (statement->default_label != NULL)
9262 /* FIXME: calculation of value should be done while parsing */
9263 /* TODO: quadratic algorithm here. Change to an n log n one */
9264 long last_value = -1;
9265 const entity_t *entry = enumt->enume->base.next;
9266 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9267 entry = entry->base.next) {
9268 const expression_t *expression = entry->enum_value.value;
9269 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9271 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9272 if (l->expression == NULL)
9274 if (l->first_case <= value && value <= l->last_case) {
9280 source_position_t const *const pos = &statement->base.source_position;
9281 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9288 * Parse a switch statement.
9290 static statement_t *parse_switch(void)
9292 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9296 PUSH_PARENT(statement);
9297 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9299 expression_t *const expr = parse_condition();
9300 type_t * type = skip_typeref(expr->base.type);
9301 if (is_type_integer(type)) {
9302 type = promote_integer(type);
9303 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9304 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9306 } else if (is_type_valid(type)) {
9307 errorf(&expr->base.source_position,
9308 "switch quantity is not an integer, but '%T'", type);
9309 type = type_error_type;
9311 statement->switchs.expression = create_implicit_cast(expr, type);
9313 switch_statement_t *rem = current_switch;
9314 current_switch = &statement->switchs;
9315 statement->switchs.body = parse_inner_statement();
9316 current_switch = rem;
9318 if (statement->switchs.default_label == NULL) {
9319 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9321 check_enum_cases(&statement->switchs);
9328 static statement_t *parse_loop_body(statement_t *const loop)
9330 statement_t *const rem = current_loop;
9331 current_loop = loop;
9333 statement_t *const body = parse_inner_statement();
9340 * Parse a while statement.
9342 static statement_t *parse_while(void)
9344 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9348 PUSH_PARENT(statement);
9349 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9351 expression_t *const cond = parse_condition();
9352 statement->whiles.condition = cond;
9353 /* §6.8.5:2 The controlling expression of an iteration statement shall
9354 * have scalar type. */
9355 semantic_condition(cond, "condition of 'while'-statement");
9357 statement->whiles.body = parse_loop_body(statement);
9365 * Parse a do statement.
9367 static statement_t *parse_do(void)
9369 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9373 PUSH_PARENT(statement);
9374 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9376 add_anchor_token(T_while);
9377 statement->do_while.body = parse_loop_body(statement);
9378 rem_anchor_token(T_while);
9381 expression_t *const cond = parse_condition();
9382 statement->do_while.condition = cond;
9383 /* §6.8.5:2 The controlling expression of an iteration statement shall
9384 * have scalar type. */
9385 semantic_condition(cond, "condition of 'do-while'-statement");
9394 * Parse a for statement.
9396 static statement_t *parse_for(void)
9398 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9402 PUSH_PARENT(statement);
9403 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9406 add_anchor_token(')');
9411 } else if (is_declaration_specifier(&token)) {
9412 parse_declaration(record_entity, DECL_FLAGS_NONE);
9414 add_anchor_token(';');
9415 expression_t *const init = parse_expression();
9416 statement->fors.initialisation = init;
9417 mark_vars_read(init, ENT_ANY);
9418 if (!expression_has_effect(init)) {
9419 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9421 rem_anchor_token(';');
9427 if (token.kind != ';') {
9428 add_anchor_token(';');
9429 expression_t *const cond = parse_expression();
9430 statement->fors.condition = cond;
9431 /* §6.8.5:2 The controlling expression of an iteration statement
9432 * shall have scalar type. */
9433 semantic_condition(cond, "condition of 'for'-statement");
9434 mark_vars_read(cond, NULL);
9435 rem_anchor_token(';');
9438 if (token.kind != ')') {
9439 expression_t *const step = parse_expression();
9440 statement->fors.step = step;
9441 mark_vars_read(step, ENT_ANY);
9442 if (!expression_has_effect(step)) {
9443 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9446 rem_anchor_token(')');
9448 statement->fors.body = parse_loop_body(statement);
9456 * Parse a goto statement.
9458 static statement_t *parse_goto(void)
9460 statement_t *statement;
9461 if (GNU_MODE && look_ahead(1)->kind == '*') {
9462 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9466 expression_t *expression = parse_expression();
9467 mark_vars_read(expression, NULL);
9469 /* Argh: although documentation says the expression must be of type void*,
9470 * gcc accepts anything that can be casted into void* without error */
9471 type_t *type = expression->base.type;
9473 if (type != type_error_type) {
9474 if (!is_type_pointer(type) && !is_type_integer(type)) {
9475 errorf(&expression->base.source_position,
9476 "cannot convert to a pointer type");
9477 } else if (type != type_void_ptr) {
9478 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9480 expression = create_implicit_cast(expression, type_void_ptr);
9483 statement->computed_goto.expression = expression;
9485 statement = allocate_statement_zero(STATEMENT_GOTO);
9487 if (token.kind == T_IDENTIFIER) {
9488 label_t *const label = get_label();
9490 statement->gotos.label = label;
9492 /* remember the goto's in a list for later checking */
9493 *goto_anchor = &statement->gotos;
9494 goto_anchor = &statement->gotos.next;
9497 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9499 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9501 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9510 * Parse a continue statement.
9512 static statement_t *parse_continue(void)
9514 if (current_loop == NULL) {
9515 errorf(HERE, "continue statement not within loop");
9518 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9526 * Parse a break statement.
9528 static statement_t *parse_break(void)
9530 if (current_switch == NULL && current_loop == NULL) {
9531 errorf(HERE, "break statement not within loop or switch");
9534 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9542 * Parse a __leave statement.
9544 static statement_t *parse_leave_statement(void)
9546 if (current_try == NULL) {
9547 errorf(HERE, "__leave statement not within __try");
9550 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9558 * Check if a given entity represents a local variable.
9560 static bool is_local_variable(const entity_t *entity)
9562 if (entity->kind != ENTITY_VARIABLE)
9565 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9566 case STORAGE_CLASS_AUTO:
9567 case STORAGE_CLASS_REGISTER: {
9568 const type_t *type = skip_typeref(entity->declaration.type);
9569 if (is_type_function(type)) {
9581 * Check if a given expression represents a local variable.
9583 static bool expression_is_local_variable(const expression_t *expression)
9585 if (expression->base.kind != EXPR_REFERENCE) {
9588 const entity_t *entity = expression->reference.entity;
9589 return is_local_variable(entity);
9593 * Check if a given expression represents a local variable and
9594 * return its declaration then, else return NULL.
9596 entity_t *expression_is_variable(const expression_t *expression)
9598 if (expression->base.kind != EXPR_REFERENCE) {
9601 entity_t *entity = expression->reference.entity;
9602 if (entity->kind != ENTITY_VARIABLE)
9608 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9610 if (c_mode & _CXX || strict_mode) {
9613 warningf(WARN_OTHER, pos, msg);
9618 * Parse a return statement.
9620 static statement_t *parse_return(void)
9622 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9625 expression_t *return_value = NULL;
9626 if (token.kind != ';') {
9627 return_value = parse_expression();
9628 mark_vars_read(return_value, NULL);
9631 const type_t *const func_type = skip_typeref(current_function->base.type);
9632 assert(is_type_function(func_type));
9633 type_t *const return_type = skip_typeref(func_type->function.return_type);
9635 source_position_t const *const pos = &statement->base.source_position;
9636 if (return_value != NULL) {
9637 type_t *return_value_type = skip_typeref(return_value->base.type);
9639 if (is_type_void(return_type)) {
9640 if (!is_type_void(return_value_type)) {
9641 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9642 /* Only warn in C mode, because GCC does the same */
9643 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9644 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9645 /* Only warn in C mode, because GCC does the same */
9646 err_or_warn(pos, "'return' with expression in function returning 'void'");
9649 assign_error_t error = semantic_assign(return_type, return_value);
9650 report_assign_error(error, return_type, return_value, "'return'",
9653 return_value = create_implicit_cast(return_value, return_type);
9654 /* check for returning address of a local var */
9655 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9656 const expression_t *expression = return_value->unary.value;
9657 if (expression_is_local_variable(expression)) {
9658 warningf(WARN_OTHER, pos, "function returns address of local variable");
9661 } else if (!is_type_void(return_type)) {
9662 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9663 err_or_warn(pos, "'return' without value, in function returning non-void");
9665 statement->returns.value = return_value;
9672 * Parse a declaration statement.
9674 static statement_t *parse_declaration_statement(void)
9676 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9678 entity_t *before = current_scope->last_entity;
9680 parse_external_declaration();
9682 parse_declaration(record_entity, DECL_FLAGS_NONE);
9685 declaration_statement_t *const decl = &statement->declaration;
9686 entity_t *const begin =
9687 before != NULL ? before->base.next : current_scope->entities;
9688 decl->declarations_begin = begin;
9689 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9695 * Parse an expression statement, ie. expr ';'.
9697 static statement_t *parse_expression_statement(void)
9699 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9701 expression_t *const expr = parse_expression();
9702 statement->expression.expression = expr;
9703 mark_vars_read(expr, ENT_ANY);
9710 * Parse a microsoft __try { } __finally { } or
9711 * __try{ } __except() { }
9713 static statement_t *parse_ms_try_statment(void)
9715 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9718 PUSH_PARENT(statement);
9720 ms_try_statement_t *rem = current_try;
9721 current_try = &statement->ms_try;
9722 statement->ms_try.try_statement = parse_compound_statement(false);
9727 if (next_if(T___except)) {
9728 expression_t *const expr = parse_condition();
9729 type_t * type = skip_typeref(expr->base.type);
9730 if (is_type_integer(type)) {
9731 type = promote_integer(type);
9732 } else if (is_type_valid(type)) {
9733 errorf(&expr->base.source_position,
9734 "__expect expression is not an integer, but '%T'", type);
9735 type = type_error_type;
9737 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9738 } else if (!next_if(T__finally)) {
9739 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9741 statement->ms_try.final_statement = parse_compound_statement(false);
9745 static statement_t *parse_empty_statement(void)
9747 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9748 statement_t *const statement = create_empty_statement();
9753 static statement_t *parse_local_label_declaration(void)
9755 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9759 entity_t *begin = NULL;
9760 entity_t *end = NULL;
9761 entity_t **anchor = &begin;
9763 source_position_t pos;
9764 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9768 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9769 if (entity != NULL && entity->base.parent_scope == current_scope) {
9770 source_position_t const *const ppos = &entity->base.source_position;
9771 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9773 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9774 entity->base.parent_scope = current_scope;
9777 anchor = &entity->base.next;
9780 environment_push(entity);
9782 } while (next_if(','));
9785 statement->declaration.declarations_begin = begin;
9786 statement->declaration.declarations_end = end;
9790 static void parse_namespace_definition(void)
9794 entity_t *entity = NULL;
9795 symbol_t *symbol = NULL;
9797 if (token.kind == T_IDENTIFIER) {
9798 symbol = token.identifier.symbol;
9801 entity = get_entity(symbol, NAMESPACE_NORMAL);
9803 && entity->kind != ENTITY_NAMESPACE
9804 && entity->base.parent_scope == current_scope) {
9805 if (is_entity_valid(entity)) {
9806 error_redefined_as_different_kind(&token.base.source_position,
9807 entity, ENTITY_NAMESPACE);
9813 if (entity == NULL) {
9814 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9815 entity->base.parent_scope = current_scope;
9818 if (token.kind == '=') {
9819 /* TODO: parse namespace alias */
9820 panic("namespace alias definition not supported yet");
9823 environment_push(entity);
9824 append_entity(current_scope, entity);
9826 PUSH_SCOPE(&entity->namespacee.members);
9828 entity_t *old_current_entity = current_entity;
9829 current_entity = entity;
9831 add_anchor_token('}');
9834 rem_anchor_token('}');
9837 assert(current_entity == entity);
9838 current_entity = old_current_entity;
9843 * Parse a statement.
9844 * There's also parse_statement() which additionally checks for
9845 * "statement has no effect" warnings
9847 static statement_t *intern_parse_statement(void)
9849 /* declaration or statement */
9850 statement_t *statement;
9851 switch (token.kind) {
9852 case T_IDENTIFIER: {
9853 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9854 if (la1_type == ':') {
9855 statement = parse_label_statement();
9856 } else if (is_typedef_symbol(token.identifier.symbol)) {
9857 statement = parse_declaration_statement();
9859 /* it's an identifier, the grammar says this must be an
9860 * expression statement. However it is common that users mistype
9861 * declaration types, so we guess a bit here to improve robustness
9862 * for incorrect programs */
9866 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9868 statement = parse_expression_statement();
9872 statement = parse_declaration_statement();
9880 case T___extension__: {
9881 /* This can be a prefix to a declaration or an expression statement.
9882 * We simply eat it now and parse the rest with tail recursion. */
9884 statement = intern_parse_statement();
9890 statement = parse_declaration_statement();
9894 statement = parse_local_label_declaration();
9897 case ';': statement = parse_empty_statement(); break;
9898 case '{': statement = parse_compound_statement(false); break;
9899 case T___leave: statement = parse_leave_statement(); break;
9900 case T___try: statement = parse_ms_try_statment(); break;
9901 case T_asm: statement = parse_asm_statement(); break;
9902 case T_break: statement = parse_break(); break;
9903 case T_case: statement = parse_case_statement(); break;
9904 case T_continue: statement = parse_continue(); break;
9905 case T_default: statement = parse_default_statement(); break;
9906 case T_do: statement = parse_do(); break;
9907 case T_for: statement = parse_for(); break;
9908 case T_goto: statement = parse_goto(); break;
9909 case T_if: statement = parse_if(); break;
9910 case T_return: statement = parse_return(); break;
9911 case T_switch: statement = parse_switch(); break;
9912 case T_while: statement = parse_while(); break;
9915 statement = parse_expression_statement();
9919 errorf(HERE, "unexpected token %K while parsing statement", &token);
9920 statement = create_error_statement();
9929 * parse a statement and emits "statement has no effect" warning if needed
9930 * (This is really a wrapper around intern_parse_statement with check for 1
9931 * single warning. It is needed, because for statement expressions we have
9932 * to avoid the warning on the last statement)
9934 static statement_t *parse_statement(void)
9936 statement_t *statement = intern_parse_statement();
9938 if (statement->kind == STATEMENT_EXPRESSION) {
9939 expression_t *expression = statement->expression.expression;
9940 if (!expression_has_effect(expression)) {
9941 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9949 * Parse a compound statement.
9951 static statement_t *parse_compound_statement(bool inside_expression_statement)
9953 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9955 PUSH_PARENT(statement);
9956 PUSH_SCOPE(&statement->compound.scope);
9959 add_anchor_token('}');
9960 /* tokens, which can start a statement */
9961 /* TODO MS, __builtin_FOO */
9962 add_anchor_token('!');
9963 add_anchor_token('&');
9964 add_anchor_token('(');
9965 add_anchor_token('*');
9966 add_anchor_token('+');
9967 add_anchor_token('-');
9968 add_anchor_token(';');
9969 add_anchor_token('{');
9970 add_anchor_token('~');
9971 add_anchor_token(T_CHARACTER_CONSTANT);
9972 add_anchor_token(T_COLONCOLON);
9973 add_anchor_token(T_FLOATINGPOINT);
9974 add_anchor_token(T_IDENTIFIER);
9975 add_anchor_token(T_INTEGER);
9976 add_anchor_token(T_MINUSMINUS);
9977 add_anchor_token(T_PLUSPLUS);
9978 add_anchor_token(T_STRING_LITERAL);
9979 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9980 add_anchor_token(T_WIDE_STRING_LITERAL);
9981 add_anchor_token(T__Bool);
9982 add_anchor_token(T__Complex);
9983 add_anchor_token(T__Imaginary);
9984 add_anchor_token(T___FUNCTION__);
9985 add_anchor_token(T___PRETTY_FUNCTION__);
9986 add_anchor_token(T___alignof__);
9987 add_anchor_token(T___attribute__);
9988 add_anchor_token(T___builtin_va_start);
9989 add_anchor_token(T___extension__);
9990 add_anchor_token(T___func__);
9991 add_anchor_token(T___imag__);
9992 add_anchor_token(T___label__);
9993 add_anchor_token(T___real__);
9994 add_anchor_token(T___thread);
9995 add_anchor_token(T_asm);
9996 add_anchor_token(T_auto);
9997 add_anchor_token(T_bool);
9998 add_anchor_token(T_break);
9999 add_anchor_token(T_case);
10000 add_anchor_token(T_char);
10001 add_anchor_token(T_class);
10002 add_anchor_token(T_const);
10003 add_anchor_token(T_const_cast);
10004 add_anchor_token(T_continue);
10005 add_anchor_token(T_default);
10006 add_anchor_token(T_delete);
10007 add_anchor_token(T_double);
10008 add_anchor_token(T_do);
10009 add_anchor_token(T_dynamic_cast);
10010 add_anchor_token(T_enum);
10011 add_anchor_token(T_extern);
10012 add_anchor_token(T_false);
10013 add_anchor_token(T_float);
10014 add_anchor_token(T_for);
10015 add_anchor_token(T_goto);
10016 add_anchor_token(T_if);
10017 add_anchor_token(T_inline);
10018 add_anchor_token(T_int);
10019 add_anchor_token(T_long);
10020 add_anchor_token(T_new);
10021 add_anchor_token(T_operator);
10022 add_anchor_token(T_register);
10023 add_anchor_token(T_reinterpret_cast);
10024 add_anchor_token(T_restrict);
10025 add_anchor_token(T_return);
10026 add_anchor_token(T_short);
10027 add_anchor_token(T_signed);
10028 add_anchor_token(T_sizeof);
10029 add_anchor_token(T_static);
10030 add_anchor_token(T_static_cast);
10031 add_anchor_token(T_struct);
10032 add_anchor_token(T_switch);
10033 add_anchor_token(T_template);
10034 add_anchor_token(T_this);
10035 add_anchor_token(T_throw);
10036 add_anchor_token(T_true);
10037 add_anchor_token(T_try);
10038 add_anchor_token(T_typedef);
10039 add_anchor_token(T_typeid);
10040 add_anchor_token(T_typename);
10041 add_anchor_token(T_typeof);
10042 add_anchor_token(T_union);
10043 add_anchor_token(T_unsigned);
10044 add_anchor_token(T_using);
10045 add_anchor_token(T_void);
10046 add_anchor_token(T_volatile);
10047 add_anchor_token(T_wchar_t);
10048 add_anchor_token(T_while);
10050 statement_t **anchor = &statement->compound.statements;
10051 bool only_decls_so_far = true;
10052 while (token.kind != '}' && token.kind != T_EOF) {
10053 statement_t *sub_statement = intern_parse_statement();
10054 if (sub_statement->kind == STATEMENT_ERROR) {
10058 if (sub_statement->kind != STATEMENT_DECLARATION) {
10059 only_decls_so_far = false;
10060 } else if (!only_decls_so_far) {
10061 source_position_t const *const pos = &sub_statement->base.source_position;
10062 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10065 *anchor = sub_statement;
10066 anchor = &sub_statement->base.next;
10070 /* look over all statements again to produce no effect warnings */
10071 if (is_warn_on(WARN_UNUSED_VALUE)) {
10072 statement_t *sub_statement = statement->compound.statements;
10073 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10074 if (sub_statement->kind != STATEMENT_EXPRESSION)
10076 /* don't emit a warning for the last expression in an expression
10077 * statement as it has always an effect */
10078 if (inside_expression_statement && sub_statement->base.next == NULL)
10081 expression_t *expression = sub_statement->expression.expression;
10082 if (!expression_has_effect(expression)) {
10083 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10088 rem_anchor_token(T_while);
10089 rem_anchor_token(T_wchar_t);
10090 rem_anchor_token(T_volatile);
10091 rem_anchor_token(T_void);
10092 rem_anchor_token(T_using);
10093 rem_anchor_token(T_unsigned);
10094 rem_anchor_token(T_union);
10095 rem_anchor_token(T_typeof);
10096 rem_anchor_token(T_typename);
10097 rem_anchor_token(T_typeid);
10098 rem_anchor_token(T_typedef);
10099 rem_anchor_token(T_try);
10100 rem_anchor_token(T_true);
10101 rem_anchor_token(T_throw);
10102 rem_anchor_token(T_this);
10103 rem_anchor_token(T_template);
10104 rem_anchor_token(T_switch);
10105 rem_anchor_token(T_struct);
10106 rem_anchor_token(T_static_cast);
10107 rem_anchor_token(T_static);
10108 rem_anchor_token(T_sizeof);
10109 rem_anchor_token(T_signed);
10110 rem_anchor_token(T_short);
10111 rem_anchor_token(T_return);
10112 rem_anchor_token(T_restrict);
10113 rem_anchor_token(T_reinterpret_cast);
10114 rem_anchor_token(T_register);
10115 rem_anchor_token(T_operator);
10116 rem_anchor_token(T_new);
10117 rem_anchor_token(T_long);
10118 rem_anchor_token(T_int);
10119 rem_anchor_token(T_inline);
10120 rem_anchor_token(T_if);
10121 rem_anchor_token(T_goto);
10122 rem_anchor_token(T_for);
10123 rem_anchor_token(T_float);
10124 rem_anchor_token(T_false);
10125 rem_anchor_token(T_extern);
10126 rem_anchor_token(T_enum);
10127 rem_anchor_token(T_dynamic_cast);
10128 rem_anchor_token(T_do);
10129 rem_anchor_token(T_double);
10130 rem_anchor_token(T_delete);
10131 rem_anchor_token(T_default);
10132 rem_anchor_token(T_continue);
10133 rem_anchor_token(T_const_cast);
10134 rem_anchor_token(T_const);
10135 rem_anchor_token(T_class);
10136 rem_anchor_token(T_char);
10137 rem_anchor_token(T_case);
10138 rem_anchor_token(T_break);
10139 rem_anchor_token(T_bool);
10140 rem_anchor_token(T_auto);
10141 rem_anchor_token(T_asm);
10142 rem_anchor_token(T___thread);
10143 rem_anchor_token(T___real__);
10144 rem_anchor_token(T___label__);
10145 rem_anchor_token(T___imag__);
10146 rem_anchor_token(T___func__);
10147 rem_anchor_token(T___extension__);
10148 rem_anchor_token(T___builtin_va_start);
10149 rem_anchor_token(T___attribute__);
10150 rem_anchor_token(T___alignof__);
10151 rem_anchor_token(T___PRETTY_FUNCTION__);
10152 rem_anchor_token(T___FUNCTION__);
10153 rem_anchor_token(T__Imaginary);
10154 rem_anchor_token(T__Complex);
10155 rem_anchor_token(T__Bool);
10156 rem_anchor_token(T_WIDE_STRING_LITERAL);
10157 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10158 rem_anchor_token(T_STRING_LITERAL);
10159 rem_anchor_token(T_PLUSPLUS);
10160 rem_anchor_token(T_MINUSMINUS);
10161 rem_anchor_token(T_INTEGER);
10162 rem_anchor_token(T_IDENTIFIER);
10163 rem_anchor_token(T_FLOATINGPOINT);
10164 rem_anchor_token(T_COLONCOLON);
10165 rem_anchor_token(T_CHARACTER_CONSTANT);
10166 rem_anchor_token('~');
10167 rem_anchor_token('{');
10168 rem_anchor_token(';');
10169 rem_anchor_token('-');
10170 rem_anchor_token('+');
10171 rem_anchor_token('*');
10172 rem_anchor_token('(');
10173 rem_anchor_token('&');
10174 rem_anchor_token('!');
10175 rem_anchor_token('}');
10183 * Check for unused global static functions and variables
10185 static void check_unused_globals(void)
10187 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10190 for (const entity_t *entity = file_scope->entities; entity != NULL;
10191 entity = entity->base.next) {
10192 if (!is_declaration(entity))
10195 const declaration_t *declaration = &entity->declaration;
10196 if (declaration->used ||
10197 declaration->modifiers & DM_UNUSED ||
10198 declaration->modifiers & DM_USED ||
10199 declaration->storage_class != STORAGE_CLASS_STATIC)
10204 if (entity->kind == ENTITY_FUNCTION) {
10205 /* inhibit warning for static inline functions */
10206 if (entity->function.is_inline)
10209 why = WARN_UNUSED_FUNCTION;
10210 s = entity->function.statement != NULL ? "defined" : "declared";
10212 why = WARN_UNUSED_VARIABLE;
10216 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10220 static void parse_global_asm(void)
10222 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10225 add_anchor_token(';');
10226 add_anchor_token(')');
10227 add_anchor_token(T_STRING_LITERAL);
10230 rem_anchor_token(T_STRING_LITERAL);
10231 statement->asms.asm_text = parse_string_literals();
10232 statement->base.next = unit->global_asm;
10233 unit->global_asm = statement;
10235 rem_anchor_token(')');
10237 rem_anchor_token(';');
10241 static void parse_linkage_specification(void)
10245 source_position_t const pos = *HERE;
10246 char const *const linkage = parse_string_literals().begin;
10248 linkage_kind_t old_linkage = current_linkage;
10249 linkage_kind_t new_linkage;
10250 if (streq(linkage, "C")) {
10251 new_linkage = LINKAGE_C;
10252 } else if (streq(linkage, "C++")) {
10253 new_linkage = LINKAGE_CXX;
10255 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10256 new_linkage = LINKAGE_C;
10258 current_linkage = new_linkage;
10260 if (next_if('{')) {
10267 assert(current_linkage == new_linkage);
10268 current_linkage = old_linkage;
10271 static void parse_external(void)
10273 switch (token.kind) {
10275 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10276 parse_linkage_specification();
10278 DECLARATION_START_NO_EXTERN
10280 case T___extension__:
10281 /* tokens below are for implicit int */
10282 case '&': /* & x; -> int& x; (and error later, because C++ has no
10284 case '*': /* * x; -> int* x; */
10285 case '(': /* (x); -> int (x); */
10287 parse_external_declaration();
10293 parse_global_asm();
10297 parse_namespace_definition();
10301 if (!strict_mode) {
10302 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10309 errorf(HERE, "stray %K outside of function", &token);
10310 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10311 eat_until_matching_token(token.kind);
10317 static void parse_externals(void)
10319 add_anchor_token('}');
10320 add_anchor_token(T_EOF);
10323 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10324 unsigned short token_anchor_copy[T_LAST_TOKEN];
10325 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10328 while (token.kind != T_EOF && token.kind != '}') {
10330 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10331 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10333 /* the anchor set and its copy differs */
10334 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10337 if (in_gcc_extension) {
10338 /* an gcc extension scope was not closed */
10339 internal_errorf(HERE, "Leaked __extension__");
10346 rem_anchor_token(T_EOF);
10347 rem_anchor_token('}');
10351 * Parse a translation unit.
10353 static void parse_translation_unit(void)
10355 add_anchor_token(T_EOF);
10360 if (token.kind == T_EOF)
10363 errorf(HERE, "stray %K outside of function", &token);
10364 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10365 eat_until_matching_token(token.kind);
10370 void set_default_visibility(elf_visibility_tag_t visibility)
10372 default_visibility = visibility;
10378 * @return the translation unit or NULL if errors occurred.
10380 void start_parsing(void)
10382 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10383 label_stack = NEW_ARR_F(stack_entry_t, 0);
10384 diagnostic_count = 0;
10388 print_to_file(stderr);
10390 assert(unit == NULL);
10391 unit = allocate_ast_zero(sizeof(unit[0]));
10393 assert(file_scope == NULL);
10394 file_scope = &unit->scope;
10396 assert(current_scope == NULL);
10397 scope_push(&unit->scope);
10399 create_gnu_builtins();
10401 create_microsoft_intrinsics();
10404 translation_unit_t *finish_parsing(void)
10406 assert(current_scope == &unit->scope);
10409 assert(file_scope == &unit->scope);
10410 check_unused_globals();
10413 DEL_ARR_F(environment_stack);
10414 DEL_ARR_F(label_stack);
10416 translation_unit_t *result = unit;
10421 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10422 * are given length one. */
10423 static void complete_incomplete_arrays(void)
10425 size_t n = ARR_LEN(incomplete_arrays);
10426 for (size_t i = 0; i != n; ++i) {
10427 declaration_t *const decl = incomplete_arrays[i];
10428 type_t *const type = skip_typeref(decl->type);
10430 if (!is_type_incomplete(type))
10433 source_position_t const *const pos = &decl->base.source_position;
10434 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10436 type_t *const new_type = duplicate_type(type);
10437 new_type->array.size_constant = true;
10438 new_type->array.has_implicit_size = true;
10439 new_type->array.size = 1;
10441 type_t *const result = identify_new_type(new_type);
10443 decl->type = result;
10447 void prepare_main_collect2(entity_t *entity)
10449 PUSH_SCOPE(&entity->function.statement->compound.scope);
10451 // create call to __main
10452 symbol_t *symbol = symbol_table_insert("__main");
10453 entity_t *subsubmain_ent
10454 = create_implicit_function(symbol, &builtin_source_position);
10456 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10457 type_t *ftype = subsubmain_ent->declaration.type;
10458 ref->base.source_position = builtin_source_position;
10459 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10460 ref->reference.entity = subsubmain_ent;
10462 expression_t *call = allocate_expression_zero(EXPR_CALL);
10463 call->base.source_position = builtin_source_position;
10464 call->base.type = type_void;
10465 call->call.function = ref;
10467 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10468 expr_statement->base.source_position = builtin_source_position;
10469 expr_statement->expression.expression = call;
10471 statement_t *statement = entity->function.statement;
10472 assert(statement->kind == STATEMENT_COMPOUND);
10473 compound_statement_t *compounds = &statement->compound;
10475 expr_statement->base.next = compounds->statements;
10476 compounds->statements = expr_statement;
10483 lookahead_bufpos = 0;
10484 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10487 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10488 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10489 parse_translation_unit();
10490 complete_incomplete_arrays();
10491 DEL_ARR_F(incomplete_arrays);
10492 incomplete_arrays = NULL;
10496 * Initialize the parser.
10498 void init_parser(void)
10500 sym_anonymous = symbol_table_insert("<anonymous>");
10502 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10504 init_expression_parsers();
10505 obstack_init(&temp_obst);
10509 * Terminate the parser.
10511 void exit_parser(void)
10513 obstack_free(&temp_obst, NULL);