2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
254 case T_STRING_LITERAL: \
255 case T___FUNCDNAME__: \
256 case T___FUNCSIG__: \
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_FLOATINGPOINT] = sizeof(literal_expression_t),
328 [EXPR_LITERAL_CHARACTER] = sizeof(string_literal_expression_t),
329 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
330 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
331 [EXPR_CALL] = sizeof(call_expression_t),
332 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
333 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
334 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
335 [EXPR_SELECT] = sizeof(select_expression_t),
336 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
337 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
338 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
339 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
340 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
341 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
342 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
343 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
344 [EXPR_VA_START] = sizeof(va_start_expression_t),
345 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
346 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
347 [EXPR_STATEMENT] = sizeof(statement_expression_t),
348 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
350 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
351 return sizes[EXPR_UNARY_FIRST];
353 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
354 return sizes[EXPR_BINARY_FIRST];
356 assert((size_t)kind < lengthof(sizes));
357 assert(sizes[kind] != 0);
362 * Allocate a statement node of given kind and initialize all
363 * fields with zero. Sets its source position to the position
364 * of the current token.
366 static statement_t *allocate_statement_zero(statement_kind_t kind)
368 size_t size = get_statement_struct_size(kind);
369 statement_t *res = allocate_ast_zero(size);
371 res->base.kind = kind;
372 res->base.parent = current_parent;
373 res->base.source_position = *HERE;
378 * Allocate an expression node of given kind and initialize all
381 * @param kind the kind of the expression to allocate
383 static expression_t *allocate_expression_zero(expression_kind_t kind)
385 size_t size = get_expression_struct_size(kind);
386 expression_t *res = allocate_ast_zero(size);
388 res->base.kind = kind;
389 res->base.type = type_error_type;
390 res->base.source_position = *HERE;
395 * Creates a new invalid expression at the source position
396 * of the current token.
398 static expression_t *create_error_expression(void)
400 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
401 expression->base.type = type_error_type;
406 * Creates a new invalid statement.
408 static statement_t *create_error_statement(void)
410 return allocate_statement_zero(STATEMENT_ERROR);
414 * Allocate a new empty statement.
416 static statement_t *create_empty_statement(void)
418 return allocate_statement_zero(STATEMENT_EMPTY);
422 * Returns the size of an initializer node.
424 * @param kind the initializer kind
426 static size_t get_initializer_size(initializer_kind_t kind)
428 static const size_t sizes[] = {
429 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
430 [INITIALIZER_STRING] = sizeof(initializer_value_t),
431 [INITIALIZER_LIST] = sizeof(initializer_list_t),
432 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
434 assert((size_t)kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate an initializer node of given kind and initialize all
443 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
445 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
452 * Returns the index of the top element of the environment stack.
454 static size_t environment_top(void)
456 return ARR_LEN(environment_stack);
460 * Returns the index of the top element of the global label stack.
462 static size_t label_top(void)
464 return ARR_LEN(label_stack);
468 * Return the next token.
470 static inline void next_token(void)
472 token = lookahead_buffer[lookahead_bufpos];
473 lookahead_buffer[lookahead_bufpos] = lexer_token;
476 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
479 print_token(stderr, &token);
480 fprintf(stderr, "\n");
484 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
486 static inline bool next_if(token_kind_t const type)
488 if (token.kind == type) {
497 * Return the next token with a given lookahead.
499 static inline const token_t *look_ahead(size_t num)
501 assert(0 < num && num <= MAX_LOOKAHEAD);
502 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
503 return &lookahead_buffer[pos];
507 * Adds a token type to the token type anchor set (a multi-set).
509 static void add_anchor_token(token_kind_t const token_kind)
511 assert(token_kind < T_LAST_TOKEN);
512 ++token_anchor_set[token_kind];
516 * Remove a token type from the token type anchor set (a multi-set).
518 static void rem_anchor_token(token_kind_t const token_kind)
520 assert(token_kind < T_LAST_TOKEN);
521 assert(token_anchor_set[token_kind] != 0);
522 --token_anchor_set[token_kind];
526 * Eat tokens until a matching token type is found.
528 static void eat_until_matching_token(token_kind_t const type)
530 token_kind_t end_token;
532 case '(': end_token = ')'; break;
533 case '{': end_token = '}'; break;
534 case '[': end_token = ']'; break;
535 default: end_token = type; break;
538 unsigned parenthesis_count = 0;
539 unsigned brace_count = 0;
540 unsigned bracket_count = 0;
541 while (token.kind != end_token ||
542 parenthesis_count != 0 ||
544 bracket_count != 0) {
545 switch (token.kind) {
547 case '(': ++parenthesis_count; break;
548 case '{': ++brace_count; break;
549 case '[': ++bracket_count; break;
552 if (parenthesis_count > 0)
562 if (bracket_count > 0)
565 if (token.kind == end_token &&
566 parenthesis_count == 0 &&
580 * Eat input tokens until an anchor is found.
582 static void eat_until_anchor(void)
584 while (token_anchor_set[token.kind] == 0) {
585 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
586 eat_until_matching_token(token.kind);
592 * Eat a whole block from input tokens.
594 static void eat_block(void)
596 eat_until_matching_token('{');
601 * Report a parse error because an expected token was not found.
604 #if defined __GNUC__ && __GNUC__ >= 4
605 __attribute__((sentinel))
607 void parse_error_expected(const char *message, ...)
609 if (message != NULL) {
610 errorf(HERE, "%s", message);
613 va_start(ap, message);
614 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
619 * Report an incompatible type.
621 static void type_error_incompatible(const char *msg,
622 const source_position_t *source_position, type_t *type1, type_t *type2)
624 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
628 static bool skip_till(token_kind_t const expected, char const *const context)
630 if (UNLIKELY(token.kind != expected)) {
631 parse_error_expected(context, expected, NULL);
632 add_anchor_token(expected);
634 rem_anchor_token(expected);
635 if (token.kind != expected)
642 * Expect the current token is the expected token.
643 * If not, generate an error and skip until the next anchor.
645 static void expect(token_kind_t const expected)
647 if (skip_till(expected, NULL))
651 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
653 if (!skip_till(T_IDENTIFIER, context))
655 symbol_t *const sym = token.base.symbol;
663 * Push a given scope on the scope stack and make it the
666 static scope_t *scope_push(scope_t *new_scope)
668 if (current_scope != NULL) {
669 new_scope->depth = current_scope->depth + 1;
672 scope_t *old_scope = current_scope;
673 current_scope = new_scope;
678 * Pop the current scope from the scope stack.
680 static void scope_pop(scope_t *old_scope)
682 current_scope = old_scope;
686 * Search an entity by its symbol in a given namespace.
688 static entity_t *get_entity(const symbol_t *const symbol,
689 namespace_tag_t namespc)
691 entity_t *entity = symbol->entity;
692 for (; entity != NULL; entity = entity->base.symbol_next) {
693 if ((namespace_tag_t)entity->base.namespc == namespc)
700 /* §6.2.3:1 24) There is only one name space for tags even though three are
702 static entity_t *get_tag(symbol_t const *const symbol,
703 entity_kind_tag_t const kind)
705 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
706 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
708 "'%Y' defined as wrong kind of tag (previous definition %P)",
709 symbol, &entity->base.source_position);
716 * pushs an entity on the environment stack and links the corresponding symbol
719 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
721 symbol_t *symbol = entity->base.symbol;
722 entity_namespace_t namespc = entity->base.namespc;
723 assert(namespc != 0);
725 /* replace/add entity into entity list of the symbol */
728 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
733 /* replace an entry? */
734 if (iter->base.namespc == namespc) {
735 entity->base.symbol_next = iter->base.symbol_next;
741 /* remember old declaration */
743 entry.symbol = symbol;
744 entry.old_entity = iter;
745 entry.namespc = namespc;
746 ARR_APP1(stack_entry_t, *stack_ptr, entry);
750 * Push an entity on the environment stack.
752 static void environment_push(entity_t *entity)
754 assert(entity->base.source_position.input_name != NULL);
755 assert(entity->base.parent_scope != NULL);
756 stack_push(&environment_stack, entity);
760 * Push a declaration on the global label stack.
762 * @param declaration the declaration
764 static void label_push(entity_t *label)
766 /* we abuse the parameters scope as parent for the labels */
767 label->base.parent_scope = ¤t_function->parameters;
768 stack_push(&label_stack, label);
772 * pops symbols from the environment stack until @p new_top is the top element
774 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
776 stack_entry_t *stack = *stack_ptr;
777 size_t top = ARR_LEN(stack);
780 assert(new_top <= top);
784 for (i = top; i > new_top; --i) {
785 stack_entry_t *entry = &stack[i - 1];
787 entity_t *old_entity = entry->old_entity;
788 symbol_t *symbol = entry->symbol;
789 entity_namespace_t namespc = entry->namespc;
791 /* replace with old_entity/remove */
794 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
796 assert(iter != NULL);
797 /* replace an entry? */
798 if (iter->base.namespc == namespc)
802 /* restore definition from outer scopes (if there was one) */
803 if (old_entity != NULL) {
804 old_entity->base.symbol_next = iter->base.symbol_next;
805 *anchor = old_entity;
807 /* remove entry from list */
808 *anchor = iter->base.symbol_next;
812 ARR_SHRINKLEN(*stack_ptr, new_top);
816 * Pop all entries from the environment stack until the new_top
819 * @param new_top the new stack top
821 static void environment_pop_to(size_t new_top)
823 stack_pop_to(&environment_stack, new_top);
827 * Pop all entries from the global label stack until the new_top
830 * @param new_top the new stack top
832 static void label_pop_to(size_t new_top)
834 stack_pop_to(&label_stack, new_top);
837 static atomic_type_kind_t get_akind(const type_t *type)
839 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
840 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
841 return type->atomic.akind;
845 * §6.3.1.1:2 Do integer promotion for a given type.
847 * @param type the type to promote
848 * @return the promoted type
850 static type_t *promote_integer(type_t *type)
852 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
859 * Check if a given expression represents a null pointer constant.
861 * @param expression the expression to check
863 static bool is_null_pointer_constant(const expression_t *expression)
865 /* skip void* cast */
866 if (expression->kind == EXPR_UNARY_CAST) {
867 type_t *const type = skip_typeref(expression->base.type);
868 if (types_compatible(type, type_void_ptr))
869 expression = expression->unary.value;
872 type_t *const type = skip_typeref(expression->base.type);
873 if (!is_type_integer(type))
875 switch (is_constant_expression(expression)) {
876 case EXPR_CLASS_ERROR: return true;
877 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
878 default: return false;
883 * Create an implicit cast expression.
885 * @param expression the expression to cast
886 * @param dest_type the destination type
888 static expression_t *create_implicit_cast(expression_t *expression,
891 type_t *const source_type = expression->base.type;
893 if (source_type == dest_type)
896 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
897 cast->unary.value = expression;
898 cast->base.type = dest_type;
899 cast->base.implicit = true;
904 typedef enum assign_error_t {
906 ASSIGN_ERROR_INCOMPATIBLE,
907 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
908 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
909 ASSIGN_WARNING_POINTER_FROM_INT,
910 ASSIGN_WARNING_INT_FROM_POINTER
913 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)
915 type_t *const orig_type_right = right->base.type;
916 type_t *const type_left = skip_typeref(orig_type_left);
917 type_t *const type_right = skip_typeref(orig_type_right);
922 case ASSIGN_ERROR_INCOMPATIBLE:
923 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
926 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
927 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
928 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
930 /* the left type has all qualifiers from the right type */
931 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
932 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);
936 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
937 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
940 case ASSIGN_WARNING_POINTER_FROM_INT:
941 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
944 case ASSIGN_WARNING_INT_FROM_POINTER:
945 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
949 panic("invalid error value");
953 /** Implements the rules from §6.5.16.1 */
954 static assign_error_t semantic_assign(type_t *orig_type_left,
955 const expression_t *const right)
957 type_t *const orig_type_right = right->base.type;
958 type_t *const type_left = skip_typeref(orig_type_left);
959 type_t *const type_right = skip_typeref(orig_type_right);
961 if (is_type_pointer(type_left)) {
962 if (is_null_pointer_constant(right)) {
963 return ASSIGN_SUCCESS;
964 } else if (is_type_pointer(type_right)) {
965 type_t *points_to_left
966 = skip_typeref(type_left->pointer.points_to);
967 type_t *points_to_right
968 = skip_typeref(type_right->pointer.points_to);
969 assign_error_t res = ASSIGN_SUCCESS;
971 /* the left type has all qualifiers from the right type */
972 unsigned missing_qualifiers
973 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
974 if (missing_qualifiers != 0) {
975 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
978 points_to_left = get_unqualified_type(points_to_left);
979 points_to_right = get_unqualified_type(points_to_right);
981 if (is_type_void(points_to_left))
984 if (is_type_void(points_to_right)) {
985 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
986 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
989 if (!types_compatible(points_to_left, points_to_right)) {
990 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
994 } else if (is_type_integer(type_right)) {
995 return ASSIGN_WARNING_POINTER_FROM_INT;
997 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
998 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
999 && is_type_pointer(type_right))) {
1000 return ASSIGN_SUCCESS;
1001 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1002 type_t *const unqual_type_left = get_unqualified_type(type_left);
1003 type_t *const unqual_type_right = get_unqualified_type(type_right);
1004 if (types_compatible(unqual_type_left, unqual_type_right)) {
1005 return ASSIGN_SUCCESS;
1007 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1008 return ASSIGN_WARNING_INT_FROM_POINTER;
1011 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1012 return ASSIGN_SUCCESS;
1014 return ASSIGN_ERROR_INCOMPATIBLE;
1017 static expression_t *parse_constant_expression(void)
1019 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1021 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1022 errorf(&result->base.source_position,
1023 "expression '%E' is not constant", result);
1029 static expression_t *parse_assignment_expression(void)
1031 return parse_subexpression(PREC_ASSIGNMENT);
1034 static void append_string(string_t const *const s)
1036 /* FIXME Using the ast_obstack is a hack. Using the symbol_obstack is not
1037 * possible, because other tokens are grown there alongside. */
1038 obstack_grow(&ast_obstack, s->begin, s->size);
1041 static string_t finish_string(string_encoding_t const enc)
1043 obstack_1grow(&ast_obstack, '\0');
1044 size_t const size = obstack_object_size(&ast_obstack) - 1;
1045 char const *const string = obstack_finish(&ast_obstack);
1046 return (string_t){ string, size, enc };
1049 static string_t concat_string_literals(void)
1051 assert(token.kind == T_STRING_LITERAL);
1054 if (look_ahead(1)->kind == T_STRING_LITERAL) {
1055 append_string(&token.string.string);
1056 eat(T_STRING_LITERAL);
1057 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects string constant concatenation");
1058 string_encoding_t enc = token.string.string.encoding;
1060 if (token.string.string.encoding != STRING_ENCODING_CHAR) {
1061 enc = token.string.string.encoding;
1063 append_string(&token.string.string);
1064 eat(T_STRING_LITERAL);
1065 } while (token.kind == T_STRING_LITERAL);
1066 result = finish_string(enc);
1068 result = token.string.string;
1069 eat(T_STRING_LITERAL);
1075 static string_t parse_string_literals(char const *const context)
1077 if (!skip_till(T_STRING_LITERAL, context))
1078 return (string_t){ "", 0, STRING_ENCODING_CHAR };
1080 source_position_t const pos = *HERE;
1081 string_t const res = concat_string_literals();
1083 if (res.encoding != STRING_ENCODING_CHAR) {
1084 errorf(&pos, "expected plain string literal, got wide string literal");
1090 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1092 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1093 attribute->kind = kind;
1094 attribute->source_position = *HERE;
1099 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1102 * __attribute__ ( ( attribute-list ) )
1106 * attribute_list , attrib
1111 * any-word ( identifier )
1112 * any-word ( identifier , nonempty-expr-list )
1113 * any-word ( expr-list )
1115 * where the "identifier" must not be declared as a type, and
1116 * "any-word" may be any identifier (including one declared as a
1117 * type), a reserved word storage class specifier, type specifier or
1118 * type qualifier. ??? This still leaves out most reserved keywords
1119 * (following the old parser), shouldn't we include them, and why not
1120 * allow identifiers declared as types to start the arguments?
1122 * Matze: this all looks confusing and little systematic, so we're even less
1123 * strict and parse any list of things which are identifiers or
1124 * (assignment-)expressions.
1126 static attribute_argument_t *parse_attribute_arguments(void)
1128 attribute_argument_t *first = NULL;
1129 attribute_argument_t **anchor = &first;
1130 if (token.kind != ')') do {
1131 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1133 /* is it an identifier */
1134 if (token.kind == T_IDENTIFIER
1135 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1136 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1137 argument->v.symbol = token.base.symbol;
1140 /* must be an expression */
1141 expression_t *expression = parse_assignment_expression();
1143 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1144 argument->v.expression = expression;
1147 /* append argument */
1149 anchor = &argument->next;
1150 } while (next_if(','));
1155 static attribute_t *parse_attribute_asm(void)
1157 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1160 attribute->a.arguments = parse_attribute_arguments();
1164 static attribute_t *parse_attribute_gnu_single(void)
1166 /* parse "any-word" */
1167 symbol_t *const symbol = token.base.symbol;
1168 if (symbol == NULL) {
1169 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1173 attribute_kind_t kind;
1174 char const *const name = symbol->string;
1175 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1176 if (kind > ATTRIBUTE_GNU_LAST) {
1177 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1178 /* TODO: we should still save the attribute in the list... */
1179 kind = ATTRIBUTE_UNKNOWN;
1183 const char *attribute_name = get_attribute_name(kind);
1184 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1188 attribute_t *attribute = allocate_attribute_zero(kind);
1191 /* parse arguments */
1193 attribute->a.arguments = parse_attribute_arguments();
1198 static attribute_t *parse_attribute_gnu(void)
1200 attribute_t *first = NULL;
1201 attribute_t **anchor = &first;
1203 eat(T___attribute__);
1204 add_anchor_token(')');
1205 add_anchor_token(',');
1209 if (token.kind != ')') do {
1210 attribute_t *attribute = parse_attribute_gnu_single();
1212 *anchor = attribute;
1213 anchor = &attribute->next;
1215 } while (next_if(','));
1216 rem_anchor_token(',');
1217 rem_anchor_token(')');
1224 /** Parse attributes. */
1225 static attribute_t *parse_attributes(attribute_t *first)
1227 attribute_t **anchor = &first;
1229 while (*anchor != NULL)
1230 anchor = &(*anchor)->next;
1232 attribute_t *attribute;
1233 switch (token.kind) {
1234 case T___attribute__:
1235 attribute = parse_attribute_gnu();
1236 if (attribute == NULL)
1241 attribute = parse_attribute_asm();
1245 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1250 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1254 case T__forceinline:
1255 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1256 eat(T__forceinline);
1260 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1265 /* TODO record modifier */
1266 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1267 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1275 *anchor = attribute;
1276 anchor = &attribute->next;
1280 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1282 static entity_t *determine_lhs_ent(expression_t *const expr,
1285 switch (expr->kind) {
1286 case EXPR_REFERENCE: {
1287 entity_t *const entity = expr->reference.entity;
1288 /* we should only find variables as lvalues... */
1289 if (entity->base.kind != ENTITY_VARIABLE
1290 && entity->base.kind != ENTITY_PARAMETER)
1296 case EXPR_ARRAY_ACCESS: {
1297 expression_t *const ref = expr->array_access.array_ref;
1298 entity_t * ent = NULL;
1299 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1300 ent = determine_lhs_ent(ref, lhs_ent);
1303 mark_vars_read(ref, lhs_ent);
1305 mark_vars_read(expr->array_access.index, lhs_ent);
1310 mark_vars_read(expr->select.compound, lhs_ent);
1311 if (is_type_compound(skip_typeref(expr->base.type)))
1312 return determine_lhs_ent(expr->select.compound, lhs_ent);
1316 case EXPR_UNARY_DEREFERENCE: {
1317 expression_t *const val = expr->unary.value;
1318 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1320 return determine_lhs_ent(val->unary.value, lhs_ent);
1322 mark_vars_read(val, NULL);
1328 mark_vars_read(expr, NULL);
1333 #define ENT_ANY ((entity_t*)-1)
1336 * Mark declarations, which are read. This is used to detect variables, which
1340 * x is not marked as "read", because it is only read to calculate its own new
1344 * x and y are not detected as "not read", because multiple variables are
1347 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1349 switch (expr->kind) {
1350 case EXPR_REFERENCE: {
1351 entity_t *const entity = expr->reference.entity;
1352 if (entity->kind != ENTITY_VARIABLE
1353 && entity->kind != ENTITY_PARAMETER)
1356 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1357 entity->variable.read = true;
1363 // TODO respect pure/const
1364 mark_vars_read(expr->call.function, NULL);
1365 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1366 mark_vars_read(arg->expression, NULL);
1370 case EXPR_CONDITIONAL:
1371 // TODO lhs_decl should depend on whether true/false have an effect
1372 mark_vars_read(expr->conditional.condition, NULL);
1373 if (expr->conditional.true_expression != NULL)
1374 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1375 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1379 if (lhs_ent == ENT_ANY
1380 && !is_type_compound(skip_typeref(expr->base.type)))
1382 mark_vars_read(expr->select.compound, lhs_ent);
1385 case EXPR_ARRAY_ACCESS: {
1386 mark_vars_read(expr->array_access.index, lhs_ent);
1387 expression_t *const ref = expr->array_access.array_ref;
1388 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1389 if (lhs_ent == ENT_ANY)
1392 mark_vars_read(ref, lhs_ent);
1397 mark_vars_read(expr->va_arge.ap, lhs_ent);
1401 mark_vars_read(expr->va_copye.src, lhs_ent);
1404 case EXPR_UNARY_CAST:
1405 /* Special case: Use void cast to mark a variable as "read" */
1406 if (is_type_void(skip_typeref(expr->base.type)))
1411 case EXPR_UNARY_THROW:
1412 if (expr->unary.value == NULL)
1415 case EXPR_UNARY_DEREFERENCE:
1416 case EXPR_UNARY_DELETE:
1417 case EXPR_UNARY_DELETE_ARRAY:
1418 if (lhs_ent == ENT_ANY)
1422 case EXPR_UNARY_NEGATE:
1423 case EXPR_UNARY_PLUS:
1424 case EXPR_UNARY_BITWISE_NEGATE:
1425 case EXPR_UNARY_NOT:
1426 case EXPR_UNARY_TAKE_ADDRESS:
1427 case EXPR_UNARY_POSTFIX_INCREMENT:
1428 case EXPR_UNARY_POSTFIX_DECREMENT:
1429 case EXPR_UNARY_PREFIX_INCREMENT:
1430 case EXPR_UNARY_PREFIX_DECREMENT:
1431 case EXPR_UNARY_ASSUME:
1433 mark_vars_read(expr->unary.value, lhs_ent);
1436 case EXPR_BINARY_ADD:
1437 case EXPR_BINARY_SUB:
1438 case EXPR_BINARY_MUL:
1439 case EXPR_BINARY_DIV:
1440 case EXPR_BINARY_MOD:
1441 case EXPR_BINARY_EQUAL:
1442 case EXPR_BINARY_NOTEQUAL:
1443 case EXPR_BINARY_LESS:
1444 case EXPR_BINARY_LESSEQUAL:
1445 case EXPR_BINARY_GREATER:
1446 case EXPR_BINARY_GREATEREQUAL:
1447 case EXPR_BINARY_BITWISE_AND:
1448 case EXPR_BINARY_BITWISE_OR:
1449 case EXPR_BINARY_BITWISE_XOR:
1450 case EXPR_BINARY_LOGICAL_AND:
1451 case EXPR_BINARY_LOGICAL_OR:
1452 case EXPR_BINARY_SHIFTLEFT:
1453 case EXPR_BINARY_SHIFTRIGHT:
1454 case EXPR_BINARY_COMMA:
1455 case EXPR_BINARY_ISGREATER:
1456 case EXPR_BINARY_ISGREATEREQUAL:
1457 case EXPR_BINARY_ISLESS:
1458 case EXPR_BINARY_ISLESSEQUAL:
1459 case EXPR_BINARY_ISLESSGREATER:
1460 case EXPR_BINARY_ISUNORDERED:
1461 mark_vars_read(expr->binary.left, lhs_ent);
1462 mark_vars_read(expr->binary.right, lhs_ent);
1465 case EXPR_BINARY_ASSIGN:
1466 case EXPR_BINARY_MUL_ASSIGN:
1467 case EXPR_BINARY_DIV_ASSIGN:
1468 case EXPR_BINARY_MOD_ASSIGN:
1469 case EXPR_BINARY_ADD_ASSIGN:
1470 case EXPR_BINARY_SUB_ASSIGN:
1471 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1472 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1473 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1474 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1475 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1476 if (lhs_ent == ENT_ANY)
1478 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1479 mark_vars_read(expr->binary.right, lhs_ent);
1484 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1487 case EXPR_LITERAL_CASES:
1488 case EXPR_LITERAL_CHARACTER:
1490 case EXPR_STRING_LITERAL:
1491 case EXPR_COMPOUND_LITERAL: // TODO init?
1493 case EXPR_CLASSIFY_TYPE:
1496 case EXPR_BUILTIN_CONSTANT_P:
1497 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1499 case EXPR_STATEMENT: // TODO
1500 case EXPR_LABEL_ADDRESS:
1501 case EXPR_ENUM_CONSTANT:
1505 panic("unhandled expression");
1508 static designator_t *parse_designation(void)
1510 designator_t *result = NULL;
1511 designator_t **anchor = &result;
1514 designator_t *designator;
1515 switch (token.kind) {
1517 designator = allocate_ast_zero(sizeof(designator[0]));
1518 designator->source_position = *HERE;
1520 add_anchor_token(']');
1521 designator->array_index = parse_constant_expression();
1522 rem_anchor_token(']');
1526 designator = allocate_ast_zero(sizeof(designator[0]));
1527 designator->source_position = *HERE;
1529 designator->symbol = expect_identifier("while parsing designator", NULL);
1530 if (!designator->symbol)
1538 assert(designator != NULL);
1539 *anchor = designator;
1540 anchor = &designator->next;
1545 * Build an initializer from a given expression.
1547 static initializer_t *initializer_from_expression(type_t *orig_type,
1548 expression_t *expression)
1550 /* TODO check that expression is a constant expression */
1552 type_t *const type = skip_typeref(orig_type);
1554 /* §6.7.8.14/15 char array may be initialized by string literals */
1555 if (expression->kind == EXPR_STRING_LITERAL && is_type_array(type)) {
1556 array_type_t *const array_type = &type->array;
1557 type_t *const element_type = skip_typeref(array_type->element_type);
1558 switch (expression->string_literal.value.encoding) {
1559 case STRING_ENCODING_CHAR: {
1560 if (is_type_atomic(element_type, ATOMIC_TYPE_CHAR) ||
1561 is_type_atomic(element_type, ATOMIC_TYPE_SCHAR) ||
1562 is_type_atomic(element_type, ATOMIC_TYPE_UCHAR)) {
1563 goto make_string_init;
1568 case STRING_ENCODING_WIDE: {
1569 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1570 if (get_unqualified_type(element_type) == bare_wchar_type) {
1572 initializer_t *const init = allocate_initializer_zero(INITIALIZER_STRING);
1573 init->value.value = expression;
1581 assign_error_t error = semantic_assign(type, expression);
1582 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1584 report_assign_error(error, type, expression, "initializer",
1585 &expression->base.source_position);
1587 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1588 result->value.value = create_implicit_cast(expression, type);
1594 * Parses an scalar initializer.
1596 * §6.7.8.11; eat {} without warning
1598 static initializer_t *parse_scalar_initializer(type_t *type,
1599 bool must_be_constant)
1601 /* there might be extra {} hierarchies */
1603 if (token.kind == '{') {
1604 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1608 } while (token.kind == '{');
1611 expression_t *expression = parse_assignment_expression();
1612 mark_vars_read(expression, NULL);
1613 if (must_be_constant && !is_linker_constant(expression)) {
1614 errorf(&expression->base.source_position,
1615 "initialisation expression '%E' is not constant",
1619 initializer_t *initializer = initializer_from_expression(type, expression);
1621 if (initializer == NULL) {
1622 errorf(&expression->base.source_position,
1623 "expression '%E' (type '%T') doesn't match expected type '%T'",
1624 expression, expression->base.type, type);
1629 bool additional_warning_displayed = false;
1630 while (braces > 0) {
1632 if (token.kind != '}') {
1633 if (!additional_warning_displayed) {
1634 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1635 additional_warning_displayed = true;
1646 * An entry in the type path.
1648 typedef struct type_path_entry_t type_path_entry_t;
1649 struct type_path_entry_t {
1650 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1652 size_t index; /**< For array types: the current index. */
1653 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1658 * A type path expression a position inside compound or array types.
1660 typedef struct type_path_t type_path_t;
1661 struct type_path_t {
1662 type_path_entry_t *path; /**< An flexible array containing the current path. */
1663 type_t *top_type; /**< type of the element the path points */
1664 size_t max_index; /**< largest index in outermost array */
1668 * Prints a type path for debugging.
1670 static __attribute__((unused)) void debug_print_type_path(
1671 const type_path_t *path)
1673 size_t len = ARR_LEN(path->path);
1675 for (size_t i = 0; i < len; ++i) {
1676 const type_path_entry_t *entry = & path->path[i];
1678 type_t *type = skip_typeref(entry->type);
1679 if (is_type_compound(type)) {
1680 /* in gcc mode structs can have no members */
1681 if (entry->v.compound_entry == NULL) {
1685 fprintf(stderr, ".%s",
1686 entry->v.compound_entry->base.symbol->string);
1687 } else if (is_type_array(type)) {
1688 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1690 fprintf(stderr, "-INVALID-");
1693 if (path->top_type != NULL) {
1694 fprintf(stderr, " (");
1695 print_type(path->top_type);
1696 fprintf(stderr, ")");
1701 * Return the top type path entry, ie. in a path
1702 * (type).a.b returns the b.
1704 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1706 size_t len = ARR_LEN(path->path);
1708 return &path->path[len-1];
1712 * Enlarge the type path by an (empty) element.
1714 static type_path_entry_t *append_to_type_path(type_path_t *path)
1716 size_t len = ARR_LEN(path->path);
1717 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1719 type_path_entry_t *result = & path->path[len];
1720 memset(result, 0, sizeof(result[0]));
1725 * Descending into a sub-type. Enter the scope of the current top_type.
1727 static void descend_into_subtype(type_path_t *path)
1729 type_t *orig_top_type = path->top_type;
1730 type_t *top_type = skip_typeref(orig_top_type);
1732 type_path_entry_t *top = append_to_type_path(path);
1733 top->type = top_type;
1735 if (is_type_compound(top_type)) {
1736 compound_t *const compound = top_type->compound.compound;
1737 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1739 if (entry != NULL) {
1740 top->v.compound_entry = &entry->declaration;
1741 path->top_type = entry->declaration.type;
1743 path->top_type = NULL;
1745 } else if (is_type_array(top_type)) {
1747 path->top_type = top_type->array.element_type;
1749 assert(!is_type_valid(top_type));
1754 * Pop an entry from the given type path, ie. returning from
1755 * (type).a.b to (type).a
1757 static void ascend_from_subtype(type_path_t *path)
1759 type_path_entry_t *top = get_type_path_top(path);
1761 path->top_type = top->type;
1763 size_t len = ARR_LEN(path->path);
1764 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1768 * Pop entries from the given type path until the given
1769 * path level is reached.
1771 static void ascend_to(type_path_t *path, size_t top_path_level)
1773 size_t len = ARR_LEN(path->path);
1775 while (len > top_path_level) {
1776 ascend_from_subtype(path);
1777 len = ARR_LEN(path->path);
1781 static bool walk_designator(type_path_t *path, const designator_t *designator,
1782 bool used_in_offsetof)
1784 for (; designator != NULL; designator = designator->next) {
1785 type_path_entry_t *top = get_type_path_top(path);
1786 type_t *orig_type = top->type;
1788 type_t *type = skip_typeref(orig_type);
1790 if (designator->symbol != NULL) {
1791 symbol_t *symbol = designator->symbol;
1792 if (!is_type_compound(type)) {
1793 if (is_type_valid(type)) {
1794 errorf(&designator->source_position,
1795 "'.%Y' designator used for non-compound type '%T'",
1799 top->type = type_error_type;
1800 top->v.compound_entry = NULL;
1801 orig_type = type_error_type;
1803 compound_t *compound = type->compound.compound;
1804 entity_t *iter = compound->members.entities;
1805 for (; iter != NULL; iter = iter->base.next) {
1806 if (iter->base.symbol == symbol) {
1811 errorf(&designator->source_position,
1812 "'%T' has no member named '%Y'", orig_type, symbol);
1815 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1816 if (used_in_offsetof && iter->compound_member.bitfield) {
1817 errorf(&designator->source_position,
1818 "offsetof designator '%Y' must not specify bitfield",
1823 top->type = orig_type;
1824 top->v.compound_entry = &iter->declaration;
1825 orig_type = iter->declaration.type;
1828 expression_t *array_index = designator->array_index;
1829 if (is_constant_expression(array_index) != EXPR_CLASS_CONSTANT)
1832 if (!is_type_array(type)) {
1833 if (is_type_valid(type)) {
1834 errorf(&designator->source_position,
1835 "[%E] designator used for non-array type '%T'",
1836 array_index, orig_type);
1841 long index = fold_constant_to_int(array_index);
1842 if (!used_in_offsetof) {
1844 errorf(&designator->source_position,
1845 "array index [%E] must be positive", array_index);
1846 } else if (type->array.size_constant) {
1847 long array_size = type->array.size;
1848 if (index >= array_size) {
1849 errorf(&designator->source_position,
1850 "designator [%E] (%d) exceeds array size %d",
1851 array_index, index, array_size);
1856 top->type = orig_type;
1857 top->v.index = (size_t) index;
1858 orig_type = type->array.element_type;
1860 path->top_type = orig_type;
1862 if (designator->next != NULL) {
1863 descend_into_subtype(path);
1869 static void advance_current_object(type_path_t *path, size_t top_path_level)
1871 type_path_entry_t *top = get_type_path_top(path);
1873 type_t *type = skip_typeref(top->type);
1874 if (is_type_union(type)) {
1875 /* in unions only the first element is initialized */
1876 top->v.compound_entry = NULL;
1877 } else if (is_type_struct(type)) {
1878 declaration_t *entry = top->v.compound_entry;
1880 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1881 if (next_entity != NULL) {
1882 assert(is_declaration(next_entity));
1883 entry = &next_entity->declaration;
1888 top->v.compound_entry = entry;
1889 if (entry != NULL) {
1890 path->top_type = entry->type;
1893 } else if (is_type_array(type)) {
1894 assert(is_type_array(type));
1898 if (!type->array.size_constant || top->v.index < type->array.size) {
1902 assert(!is_type_valid(type));
1906 /* we're past the last member of the current sub-aggregate, try if we
1907 * can ascend in the type hierarchy and continue with another subobject */
1908 size_t len = ARR_LEN(path->path);
1910 if (len > top_path_level) {
1911 ascend_from_subtype(path);
1912 advance_current_object(path, top_path_level);
1914 path->top_type = NULL;
1919 * skip any {...} blocks until a closing bracket is reached.
1921 static void skip_initializers(void)
1925 while (token.kind != '}') {
1926 if (token.kind == T_EOF)
1928 if (token.kind == '{') {
1936 static initializer_t *create_empty_initializer(void)
1938 static initializer_t empty_initializer
1939 = { .list = { { INITIALIZER_LIST }, 0 } };
1940 return &empty_initializer;
1944 * Parse a part of an initialiser for a struct or union,
1946 static initializer_t *parse_sub_initializer(type_path_t *path,
1947 type_t *outer_type, size_t top_path_level,
1948 parse_initializer_env_t *env)
1950 if (token.kind == '}') {
1951 /* empty initializer */
1952 return create_empty_initializer();
1955 type_t *orig_type = path->top_type;
1956 type_t *type = NULL;
1958 if (orig_type == NULL) {
1959 /* We are initializing an empty compound. */
1961 type = skip_typeref(orig_type);
1964 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
1967 designator_t *designator = NULL;
1968 if (token.kind == '.' || token.kind == '[') {
1969 designator = parse_designation();
1970 goto finish_designator;
1971 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
1972 /* GNU-style designator ("identifier: value") */
1973 designator = allocate_ast_zero(sizeof(designator[0]));
1974 designator->source_position = *HERE;
1975 designator->symbol = token.base.symbol;
1980 /* reset path to toplevel, evaluate designator from there */
1981 ascend_to(path, top_path_level);
1982 if (!walk_designator(path, designator, false)) {
1983 /* can't continue after designation error */
1987 initializer_t *designator_initializer
1988 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
1989 designator_initializer->designator.designator = designator;
1990 ARR_APP1(initializer_t*, initializers, designator_initializer);
1992 orig_type = path->top_type;
1993 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
1998 if (token.kind == '{') {
1999 if (type != NULL && is_type_scalar(type)) {
2000 sub = parse_scalar_initializer(type, env->must_be_constant);
2003 if (env->entity != NULL) {
2004 errorf(HERE, "extra brace group at end of initializer for '%N'", env->entity);
2006 errorf(HERE, "extra brace group at end of initializer");
2011 descend_into_subtype(path);
2014 add_anchor_token('}');
2015 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2017 rem_anchor_token('}');
2022 goto error_parse_next;
2024 ascend_from_subtype(path);
2027 /* must be an expression */
2028 expression_t *expression = parse_assignment_expression();
2029 mark_vars_read(expression, NULL);
2031 if (env->must_be_constant && !is_linker_constant(expression)) {
2032 errorf(&expression->base.source_position,
2033 "Initialisation expression '%E' is not constant",
2038 /* we are already outside, ... */
2039 if (outer_type == NULL)
2040 goto error_parse_next;
2041 type_t *const outer_type_skip = skip_typeref(outer_type);
2042 if (is_type_compound(outer_type_skip) &&
2043 !outer_type_skip->compound.compound->complete) {
2044 goto error_parse_next;
2047 source_position_t const* const pos = &expression->base.source_position;
2048 if (env->entity != NULL) {
2049 warningf(WARN_OTHER, pos, "excess elements in initializer for '%N'", env->entity);
2051 warningf(WARN_OTHER, pos, "excess elements in initializer");
2053 goto error_parse_next;
2056 /* handle { "string" } special case */
2057 if (expression->kind == EXPR_STRING_LITERAL && outer_type != NULL) {
2058 sub = initializer_from_expression(outer_type, expression);
2061 if (token.kind != '}') {
2062 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2064 /* TODO: eat , ... */
2069 /* descend into subtypes until expression matches type */
2071 orig_type = path->top_type;
2072 type = skip_typeref(orig_type);
2074 sub = initializer_from_expression(orig_type, expression);
2078 if (!is_type_valid(type)) {
2081 if (is_type_scalar(type)) {
2082 errorf(&expression->base.source_position,
2083 "expression '%E' doesn't match expected type '%T'",
2084 expression, orig_type);
2088 descend_into_subtype(path);
2092 /* update largest index of top array */
2093 const type_path_entry_t *first = &path->path[0];
2094 type_t *first_type = first->type;
2095 first_type = skip_typeref(first_type);
2096 if (is_type_array(first_type)) {
2097 size_t index = first->v.index;
2098 if (index > path->max_index)
2099 path->max_index = index;
2102 /* append to initializers list */
2103 ARR_APP1(initializer_t*, initializers, sub);
2106 if (token.kind == '}') {
2109 add_anchor_token('}');
2111 rem_anchor_token('}');
2112 if (token.kind == '}') {
2117 /* advance to the next declaration if we are not at the end */
2118 advance_current_object(path, top_path_level);
2119 orig_type = path->top_type;
2120 if (orig_type != NULL)
2121 type = skip_typeref(orig_type);
2127 size_t len = ARR_LEN(initializers);
2128 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2129 initializer_t *result = allocate_ast_zero(size);
2130 result->kind = INITIALIZER_LIST;
2131 result->list.len = len;
2132 memcpy(&result->list.initializers, initializers,
2133 len * sizeof(initializers[0]));
2135 DEL_ARR_F(initializers);
2136 ascend_to(path, top_path_level+1);
2141 skip_initializers();
2142 DEL_ARR_F(initializers);
2143 ascend_to(path, top_path_level+1);
2147 static expression_t *make_size_literal(size_t value)
2149 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2150 literal->base.type = type_size_t;
2153 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2154 literal->literal.value = make_string(buf);
2160 * Parses an initializer. Parsers either a compound literal
2161 * (env->declaration == NULL) or an initializer of a declaration.
2163 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2165 type_t *type = skip_typeref(env->type);
2166 size_t max_index = 0;
2167 initializer_t *result;
2169 if (is_type_scalar(type)) {
2170 result = parse_scalar_initializer(type, env->must_be_constant);
2171 } else if (token.kind == '{') {
2175 memset(&path, 0, sizeof(path));
2176 path.top_type = env->type;
2177 path.path = NEW_ARR_F(type_path_entry_t, 0);
2179 descend_into_subtype(&path);
2181 add_anchor_token('}');
2182 result = parse_sub_initializer(&path, env->type, 1, env);
2183 rem_anchor_token('}');
2185 max_index = path.max_index;
2186 DEL_ARR_F(path.path);
2190 /* parse_scalar_initializer() also works in this case: we simply
2191 * have an expression without {} around it */
2192 result = parse_scalar_initializer(type, env->must_be_constant);
2195 /* §6.7.8:22 array initializers for arrays with unknown size determine
2196 * the array type size */
2197 if (is_type_array(type) && type->array.size_expression == NULL
2198 && result != NULL) {
2200 switch (result->kind) {
2201 case INITIALIZER_LIST:
2202 assert(max_index != 0xdeadbeaf);
2203 size = max_index + 1;
2206 case INITIALIZER_STRING: {
2207 size = get_string_len(&get_init_string(result)->value) + 1;
2211 case INITIALIZER_DESIGNATOR:
2212 case INITIALIZER_VALUE:
2213 /* can happen for parse errors */
2218 internal_errorf(HERE, "invalid initializer type");
2221 type_t *new_type = duplicate_type(type);
2223 new_type->array.size_expression = make_size_literal(size);
2224 new_type->array.size_constant = true;
2225 new_type->array.has_implicit_size = true;
2226 new_type->array.size = size;
2227 env->type = new_type;
2233 static void append_entity(scope_t *scope, entity_t *entity)
2235 if (scope->last_entity != NULL) {
2236 scope->last_entity->base.next = entity;
2238 scope->entities = entity;
2240 entity->base.parent_entity = current_entity;
2241 scope->last_entity = entity;
2245 static compound_t *parse_compound_type_specifier(bool is_struct)
2247 source_position_t const pos = *HERE;
2248 eat(is_struct ? T_struct : T_union);
2250 symbol_t *symbol = NULL;
2251 entity_t *entity = NULL;
2252 attribute_t *attributes = NULL;
2254 if (token.kind == T___attribute__) {
2255 attributes = parse_attributes(NULL);
2258 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2259 if (token.kind == T_IDENTIFIER) {
2260 /* the compound has a name, check if we have seen it already */
2261 symbol = token.base.symbol;
2262 entity = get_tag(symbol, kind);
2265 if (entity != NULL) {
2266 if (entity->base.parent_scope != current_scope &&
2267 (token.kind == '{' || token.kind == ';')) {
2268 /* we're in an inner scope and have a definition. Shadow
2269 * existing definition in outer scope */
2271 } else if (entity->compound.complete && token.kind == '{') {
2272 source_position_t const *const ppos = &entity->base.source_position;
2273 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2274 /* clear members in the hope to avoid further errors */
2275 entity->compound.members.entities = NULL;
2278 } else if (token.kind != '{') {
2279 char const *const msg =
2280 is_struct ? "while parsing struct type specifier" :
2281 "while parsing union type specifier";
2282 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2287 if (entity == NULL) {
2288 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2289 entity->compound.alignment = 1;
2290 entity->base.parent_scope = current_scope;
2291 if (symbol != NULL) {
2292 environment_push(entity);
2294 append_entity(current_scope, entity);
2297 if (token.kind == '{') {
2298 parse_compound_type_entries(&entity->compound);
2300 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2301 if (symbol == NULL) {
2302 assert(anonymous_entity == NULL);
2303 anonymous_entity = entity;
2307 if (attributes != NULL) {
2308 handle_entity_attributes(attributes, entity);
2311 return &entity->compound;
2314 static void parse_enum_entries(type_t *const enum_type)
2318 if (token.kind == '}') {
2319 errorf(HERE, "empty enum not allowed");
2324 add_anchor_token('}');
2325 add_anchor_token(',');
2327 add_anchor_token('=');
2328 source_position_t pos;
2329 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2330 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2331 entity->enum_value.enum_type = enum_type;
2332 rem_anchor_token('=');
2335 expression_t *value = parse_constant_expression();
2337 value = create_implicit_cast(value, enum_type);
2338 entity->enum_value.value = value;
2343 record_entity(entity, false);
2344 } while (next_if(',') && token.kind != '}');
2345 rem_anchor_token(',');
2346 rem_anchor_token('}');
2351 static type_t *parse_enum_specifier(void)
2353 source_position_t const pos = *HERE;
2358 switch (token.kind) {
2360 symbol = token.base.symbol;
2361 entity = get_tag(symbol, ENTITY_ENUM);
2364 if (entity != NULL) {
2365 if (entity->base.parent_scope != current_scope &&
2366 (token.kind == '{' || token.kind == ';')) {
2367 /* we're in an inner scope and have a definition. Shadow
2368 * existing definition in outer scope */
2370 } else if (entity->enume.complete && token.kind == '{') {
2371 source_position_t const *const ppos = &entity->base.source_position;
2372 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2383 parse_error_expected("while parsing enum type specifier",
2384 T_IDENTIFIER, '{', NULL);
2388 if (entity == NULL) {
2389 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2390 entity->base.parent_scope = current_scope;
2393 type_t *const type = allocate_type_zero(TYPE_ENUM);
2394 type->enumt.enume = &entity->enume;
2395 type->enumt.base.akind = ATOMIC_TYPE_INT;
2397 if (token.kind == '{') {
2398 if (symbol != NULL) {
2399 environment_push(entity);
2401 append_entity(current_scope, entity);
2402 entity->enume.complete = true;
2404 parse_enum_entries(type);
2405 parse_attributes(NULL);
2407 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2408 if (symbol == NULL) {
2409 assert(anonymous_entity == NULL);
2410 anonymous_entity = entity;
2412 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2413 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2420 * if a symbol is a typedef to another type, return true
2422 static bool is_typedef_symbol(symbol_t *symbol)
2424 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2425 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2428 static type_t *parse_typeof(void)
2434 add_anchor_token(')');
2437 expression_t *expression = NULL;
2439 switch (token.kind) {
2441 if (is_typedef_symbol(token.base.symbol)) {
2443 type = parse_typename();
2446 expression = parse_expression();
2447 type = revert_automatic_type_conversion(expression);
2452 rem_anchor_token(')');
2455 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2456 typeof_type->typeoft.expression = expression;
2457 typeof_type->typeoft.typeof_type = type;
2462 typedef enum specifiers_t {
2463 SPECIFIER_SIGNED = 1 << 0,
2464 SPECIFIER_UNSIGNED = 1 << 1,
2465 SPECIFIER_LONG = 1 << 2,
2466 SPECIFIER_INT = 1 << 3,
2467 SPECIFIER_DOUBLE = 1 << 4,
2468 SPECIFIER_CHAR = 1 << 5,
2469 SPECIFIER_WCHAR_T = 1 << 6,
2470 SPECIFIER_SHORT = 1 << 7,
2471 SPECIFIER_LONG_LONG = 1 << 8,
2472 SPECIFIER_FLOAT = 1 << 9,
2473 SPECIFIER_BOOL = 1 << 10,
2474 SPECIFIER_VOID = 1 << 11,
2475 SPECIFIER_INT8 = 1 << 12,
2476 SPECIFIER_INT16 = 1 << 13,
2477 SPECIFIER_INT32 = 1 << 14,
2478 SPECIFIER_INT64 = 1 << 15,
2479 SPECIFIER_INT128 = 1 << 16,
2480 SPECIFIER_COMPLEX = 1 << 17,
2481 SPECIFIER_IMAGINARY = 1 << 18,
2484 static type_t *get_typedef_type(symbol_t *symbol)
2486 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2487 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2490 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2491 type->typedeft.typedefe = &entity->typedefe;
2496 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2498 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2500 add_anchor_token(')');
2501 add_anchor_token(',');
2505 add_anchor_token('=');
2506 source_position_t pos;
2507 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2508 rem_anchor_token('=');
2510 symbol_t **prop = NULL;
2512 if (streq(prop_sym->string, "put")) {
2513 prop = &property->put_symbol;
2514 } else if (streq(prop_sym->string, "get")) {
2515 prop = &property->get_symbol;
2517 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2521 add_anchor_token(T_IDENTIFIER);
2523 rem_anchor_token(T_IDENTIFIER);
2525 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2527 *prop = sym ? sym : sym_anonymous;
2528 } while (next_if(','));
2529 rem_anchor_token(',');
2530 rem_anchor_token(')');
2532 attribute->a.property = property;
2538 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2540 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2541 if (next_if(T_restrict)) {
2542 kind = ATTRIBUTE_MS_RESTRICT;
2543 } else if (token.kind == T_IDENTIFIER) {
2544 char const *const name = token.base.symbol->string;
2545 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2547 const char *attribute_name = get_attribute_name(k);
2548 if (attribute_name != NULL && streq(attribute_name, name)) {
2554 if (kind == ATTRIBUTE_UNKNOWN) {
2555 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2558 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2562 attribute_t *attribute = allocate_attribute_zero(kind);
2565 if (kind == ATTRIBUTE_MS_PROPERTY) {
2566 return parse_attribute_ms_property(attribute);
2569 /* parse arguments */
2571 attribute->a.arguments = parse_attribute_arguments();
2576 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2580 add_anchor_token(')');
2582 if (token.kind != ')') {
2583 attribute_t **anchor = &first;
2585 while (*anchor != NULL)
2586 anchor = &(*anchor)->next;
2588 attribute_t *attribute
2589 = parse_microsoft_extended_decl_modifier_single();
2590 if (attribute == NULL)
2593 *anchor = attribute;
2594 anchor = &attribute->next;
2595 } while (next_if(','));
2597 rem_anchor_token(')');
2602 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2604 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2605 if (is_declaration(entity)) {
2606 entity->declaration.type = type_error_type;
2607 entity->declaration.implicit = true;
2608 } else if (kind == ENTITY_TYPEDEF) {
2609 entity->typedefe.type = type_error_type;
2610 entity->typedefe.builtin = true;
2612 if (kind != ENTITY_COMPOUND_MEMBER)
2613 record_entity(entity, false);
2617 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2619 type_t *type = NULL;
2620 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2621 unsigned type_specifiers = 0;
2622 bool newtype = false;
2623 bool saw_error = false;
2625 memset(specifiers, 0, sizeof(*specifiers));
2626 specifiers->source_position = *HERE;
2629 specifiers->attributes = parse_attributes(specifiers->attributes);
2631 switch (token.kind) {
2633 #define MATCH_STORAGE_CLASS(token, class) \
2635 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2636 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2638 specifiers->storage_class = class; \
2639 if (specifiers->thread_local) \
2640 goto check_thread_storage_class; \
2644 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2645 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2646 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2647 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2648 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2651 specifiers->attributes
2652 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2656 if (specifiers->thread_local) {
2657 errorf(HERE, "duplicate '__thread'");
2659 specifiers->thread_local = true;
2660 check_thread_storage_class:
2661 switch (specifiers->storage_class) {
2662 case STORAGE_CLASS_EXTERN:
2663 case STORAGE_CLASS_NONE:
2664 case STORAGE_CLASS_STATIC:
2668 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2669 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2670 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2671 wrong_thread_storage_class:
2672 errorf(HERE, "'__thread' used with '%s'", wrong);
2679 /* type qualifiers */
2680 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2682 qualifiers |= qualifier; \
2686 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2687 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2688 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2689 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2690 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2691 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2692 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2693 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2695 /* type specifiers */
2696 #define MATCH_SPECIFIER(token, specifier, name) \
2698 if (type_specifiers & specifier) { \
2699 errorf(HERE, "multiple " name " type specifiers given"); \
2701 type_specifiers |= specifier; \
2706 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2707 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2708 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2709 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2710 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2711 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2712 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2713 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2714 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2715 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2716 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2717 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2718 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2719 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2720 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2721 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2722 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2723 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2727 specifiers->is_inline = true;
2731 case T__forceinline:
2732 eat(T__forceinline);
2733 specifiers->modifiers |= DM_FORCEINLINE;
2738 if (type_specifiers & SPECIFIER_LONG_LONG) {
2739 errorf(HERE, "too many long type specifiers given");
2740 } else if (type_specifiers & SPECIFIER_LONG) {
2741 type_specifiers |= SPECIFIER_LONG_LONG;
2743 type_specifiers |= SPECIFIER_LONG;
2748 #define CHECK_DOUBLE_TYPE() \
2749 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2752 CHECK_DOUBLE_TYPE();
2753 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2755 type->compound.compound = parse_compound_type_specifier(true);
2758 CHECK_DOUBLE_TYPE();
2759 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2760 type->compound.compound = parse_compound_type_specifier(false);
2763 CHECK_DOUBLE_TYPE();
2764 type = parse_enum_specifier();
2767 CHECK_DOUBLE_TYPE();
2768 type = parse_typeof();
2770 case T___builtin_va_list:
2771 CHECK_DOUBLE_TYPE();
2772 type = duplicate_type(type_valist);
2773 eat(T___builtin_va_list);
2776 case T_IDENTIFIER: {
2777 /* only parse identifier if we haven't found a type yet */
2778 if (type != NULL || type_specifiers != 0) {
2779 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2780 * declaration, so it doesn't generate errors about expecting '(' or
2782 switch (look_ahead(1)->kind) {
2789 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2793 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2798 goto finish_specifiers;
2802 type_t *const typedef_type = get_typedef_type(token.base.symbol);
2803 if (typedef_type == NULL) {
2804 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2805 * declaration, so it doesn't generate 'implicit int' followed by more
2806 * errors later on. */
2807 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2813 errorf(HERE, "%K does not name a type", &token);
2815 entity_t *const entity = create_error_entity(token.base.symbol, ENTITY_TYPEDEF);
2817 type = allocate_type_zero(TYPE_TYPEDEF);
2818 type->typedeft.typedefe = &entity->typedefe;
2826 goto finish_specifiers;
2831 type = typedef_type;
2835 /* function specifier */
2837 goto finish_specifiers;
2842 specifiers->attributes = parse_attributes(specifiers->attributes);
2844 if (type == NULL || (saw_error && type_specifiers != 0)) {
2845 atomic_type_kind_t atomic_type;
2847 /* match valid basic types */
2848 switch (type_specifiers) {
2849 case SPECIFIER_VOID:
2850 atomic_type = ATOMIC_TYPE_VOID;
2852 case SPECIFIER_WCHAR_T:
2853 atomic_type = ATOMIC_TYPE_WCHAR_T;
2855 case SPECIFIER_CHAR:
2856 atomic_type = ATOMIC_TYPE_CHAR;
2858 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2859 atomic_type = ATOMIC_TYPE_SCHAR;
2861 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2862 atomic_type = ATOMIC_TYPE_UCHAR;
2864 case SPECIFIER_SHORT:
2865 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2866 case SPECIFIER_SHORT | SPECIFIER_INT:
2867 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2868 atomic_type = ATOMIC_TYPE_SHORT;
2870 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2871 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2872 atomic_type = ATOMIC_TYPE_USHORT;
2875 case SPECIFIER_SIGNED:
2876 case SPECIFIER_SIGNED | SPECIFIER_INT:
2877 atomic_type = ATOMIC_TYPE_INT;
2879 case SPECIFIER_UNSIGNED:
2880 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2881 atomic_type = ATOMIC_TYPE_UINT;
2883 case SPECIFIER_LONG:
2884 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2885 case SPECIFIER_LONG | SPECIFIER_INT:
2886 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2887 atomic_type = ATOMIC_TYPE_LONG;
2889 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2890 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2891 atomic_type = ATOMIC_TYPE_ULONG;
2894 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2895 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2896 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2897 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2899 atomic_type = ATOMIC_TYPE_LONGLONG;
2900 goto warn_about_long_long;
2902 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2903 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2905 atomic_type = ATOMIC_TYPE_ULONGLONG;
2906 warn_about_long_long:
2907 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2910 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2911 atomic_type = unsigned_int8_type_kind;
2914 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2915 atomic_type = unsigned_int16_type_kind;
2918 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2919 atomic_type = unsigned_int32_type_kind;
2922 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2923 atomic_type = unsigned_int64_type_kind;
2926 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2927 atomic_type = unsigned_int128_type_kind;
2930 case SPECIFIER_INT8:
2931 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2932 atomic_type = int8_type_kind;
2935 case SPECIFIER_INT16:
2936 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2937 atomic_type = int16_type_kind;
2940 case SPECIFIER_INT32:
2941 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2942 atomic_type = int32_type_kind;
2945 case SPECIFIER_INT64:
2946 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2947 atomic_type = int64_type_kind;
2950 case SPECIFIER_INT128:
2951 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2952 atomic_type = int128_type_kind;
2955 case SPECIFIER_FLOAT:
2956 atomic_type = ATOMIC_TYPE_FLOAT;
2958 case SPECIFIER_DOUBLE:
2959 atomic_type = ATOMIC_TYPE_DOUBLE;
2961 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
2962 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2964 case SPECIFIER_BOOL:
2965 atomic_type = ATOMIC_TYPE_BOOL;
2967 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
2968 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
2969 atomic_type = ATOMIC_TYPE_FLOAT;
2971 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2972 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2973 atomic_type = ATOMIC_TYPE_DOUBLE;
2975 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
2976 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
2977 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
2980 /* invalid specifier combination, give an error message */
2981 source_position_t const* const pos = &specifiers->source_position;
2982 if (type_specifiers == 0) {
2984 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
2985 if (!(c_mode & _CXX) && !strict_mode) {
2986 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
2987 atomic_type = ATOMIC_TYPE_INT;
2990 errorf(pos, "no type specifiers given in declaration");
2993 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
2994 (type_specifiers & SPECIFIER_UNSIGNED)) {
2995 errorf(pos, "signed and unsigned specifiers given");
2996 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
2997 errorf(pos, "only integer types can be signed or unsigned");
2999 errorf(pos, "multiple datatypes in declaration");
3001 specifiers->type = type_error_type;
3006 if (type_specifiers & SPECIFIER_COMPLEX) {
3007 type = allocate_type_zero(TYPE_COMPLEX);
3008 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3009 type = allocate_type_zero(TYPE_IMAGINARY);
3011 type = allocate_type_zero(TYPE_ATOMIC);
3013 type->atomic.akind = atomic_type;
3015 } else if (type_specifiers != 0) {
3016 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3019 /* FIXME: check type qualifiers here */
3020 type->base.qualifiers = qualifiers;
3023 type = identify_new_type(type);
3025 type = typehash_insert(type);
3028 if (specifiers->attributes != NULL)
3029 type = handle_type_attributes(specifiers->attributes, type);
3030 specifiers->type = type;
3033 static type_qualifiers_t parse_type_qualifiers(void)
3035 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3038 switch (token.kind) {
3039 /* type qualifiers */
3040 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3041 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3042 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3043 /* microsoft extended type modifiers */
3044 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3045 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3046 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3047 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3048 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3057 * Parses an K&R identifier list
3059 static void parse_identifier_list(scope_t *scope)
3061 assert(token.kind == T_IDENTIFIER);
3063 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.base.symbol, HERE);
3064 /* a K&R parameter has no type, yet */
3068 append_entity(scope, entity);
3069 } while (next_if(',') && token.kind == T_IDENTIFIER);
3072 static entity_t *parse_parameter(void)
3074 declaration_specifiers_t specifiers;
3075 parse_declaration_specifiers(&specifiers);
3077 entity_t *entity = parse_declarator(&specifiers,
3078 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3079 anonymous_entity = NULL;
3083 static void semantic_parameter_incomplete(const entity_t *entity)
3085 assert(entity->kind == ENTITY_PARAMETER);
3087 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3088 * list in a function declarator that is part of a
3089 * definition of that function shall not have
3090 * incomplete type. */
3091 type_t *type = skip_typeref(entity->declaration.type);
3092 if (is_type_incomplete(type)) {
3093 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3097 static bool has_parameters(void)
3099 /* func(void) is not a parameter */
3100 if (look_ahead(1)->kind != ')')
3102 if (token.kind == T_IDENTIFIER) {
3103 entity_t const *const entity = get_entity(token.base.symbol, NAMESPACE_NORMAL);
3106 if (entity->kind != ENTITY_TYPEDEF)
3108 type_t const *const type = skip_typeref(entity->typedefe.type);
3109 if (!is_type_void(type))
3111 if (c_mode & _CXX) {
3112 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3113 * is not allowed. */
3114 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3115 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3116 /* §6.7.5.3:10 Qualification is not allowed here. */
3117 errorf(HERE, "'void' as parameter must not have type qualifiers");
3119 } else if (token.kind != T_void) {
3127 * Parses function type parameters (and optionally creates variable_t entities
3128 * for them in a scope)
3130 static void parse_parameters(function_type_t *type, scope_t *scope)
3132 add_anchor_token(')');
3135 if (token.kind == T_IDENTIFIER &&
3136 !is_typedef_symbol(token.base.symbol) &&
3137 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3138 type->kr_style_parameters = true;
3139 parse_identifier_list(scope);
3140 } else if (token.kind == ')') {
3141 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3142 if (!(c_mode & _CXX))
3143 type->unspecified_parameters = true;
3144 } else if (has_parameters()) {
3145 function_parameter_t **anchor = &type->parameters;
3146 add_anchor_token(',');
3148 switch (token.kind) {
3151 type->variadic = true;
3152 goto parameters_finished;
3157 entity_t *entity = parse_parameter();
3158 if (entity->kind == ENTITY_TYPEDEF) {
3159 errorf(&entity->base.source_position,
3160 "typedef not allowed as function parameter");
3163 assert(is_declaration(entity));
3165 semantic_parameter_incomplete(entity);
3167 function_parameter_t *const parameter =
3168 allocate_parameter(entity->declaration.type);
3170 if (scope != NULL) {
3171 append_entity(scope, entity);
3174 *anchor = parameter;
3175 anchor = ¶meter->next;
3180 goto parameters_finished;
3182 } while (next_if(','));
3183 parameters_finished:
3184 rem_anchor_token(',');
3187 rem_anchor_token(')');
3191 typedef enum construct_type_kind_t {
3192 CONSTRUCT_POINTER = 1,
3193 CONSTRUCT_REFERENCE,
3196 } construct_type_kind_t;
3198 typedef union construct_type_t construct_type_t;
3200 typedef struct construct_type_base_t {
3201 construct_type_kind_t kind;
3202 source_position_t pos;
3203 construct_type_t *next;
3204 } construct_type_base_t;
3206 typedef struct parsed_pointer_t {
3207 construct_type_base_t base;
3208 type_qualifiers_t type_qualifiers;
3209 variable_t *base_variable; /**< MS __based extension. */
3212 typedef struct parsed_reference_t {
3213 construct_type_base_t base;
3214 } parsed_reference_t;
3216 typedef struct construct_function_type_t {
3217 construct_type_base_t base;
3218 type_t *function_type;
3219 } construct_function_type_t;
3221 typedef struct parsed_array_t {
3222 construct_type_base_t base;
3223 type_qualifiers_t type_qualifiers;
3229 union construct_type_t {
3230 construct_type_kind_t kind;
3231 construct_type_base_t base;
3232 parsed_pointer_t pointer;
3233 parsed_reference_t reference;
3234 construct_function_type_t function;
3235 parsed_array_t array;
3238 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3240 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3241 memset(cons, 0, size);
3243 cons->base.pos = *HERE;
3248 static construct_type_t *parse_pointer_declarator(void)
3250 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3252 cons->pointer.type_qualifiers = parse_type_qualifiers();
3253 //cons->pointer.base_variable = base_variable;
3258 /* ISO/IEC 14882:1998(E) §8.3.2 */
3259 static construct_type_t *parse_reference_declarator(void)
3261 if (!(c_mode & _CXX))
3262 errorf(HERE, "references are only available for C++");
3264 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3271 static construct_type_t *parse_array_declarator(void)
3273 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3274 parsed_array_t *const array = &cons->array;
3277 add_anchor_token(']');
3279 bool is_static = next_if(T_static);
3281 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3284 is_static = next_if(T_static);
3286 array->type_qualifiers = type_qualifiers;
3287 array->is_static = is_static;
3289 expression_t *size = NULL;
3290 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3291 array->is_variable = true;
3293 } else if (token.kind != ']') {
3294 size = parse_assignment_expression();
3296 /* §6.7.5.2:1 Array size must have integer type */
3297 type_t *const orig_type = size->base.type;
3298 type_t *const type = skip_typeref(orig_type);
3299 if (!is_type_integer(type) && is_type_valid(type)) {
3300 errorf(&size->base.source_position,
3301 "array size '%E' must have integer type but has type '%T'",
3306 mark_vars_read(size, NULL);
3309 if (is_static && size == NULL)
3310 errorf(&array->base.pos, "static array parameters require a size");
3312 rem_anchor_token(']');
3318 static construct_type_t *parse_function_declarator(scope_t *scope)
3320 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3322 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3323 function_type_t *ftype = &type->function;
3325 ftype->linkage = current_linkage;
3326 ftype->calling_convention = CC_DEFAULT;
3328 parse_parameters(ftype, scope);
3330 cons->function.function_type = type;
3335 typedef struct parse_declarator_env_t {
3336 bool may_be_abstract : 1;
3337 bool must_be_abstract : 1;
3338 decl_modifiers_t modifiers;
3340 source_position_t source_position;
3342 attribute_t *attributes;
3343 } parse_declarator_env_t;
3346 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3348 /* construct a single linked list of construct_type_t's which describe
3349 * how to construct the final declarator type */
3350 construct_type_t *first = NULL;
3351 construct_type_t **anchor = &first;
3353 env->attributes = parse_attributes(env->attributes);
3356 construct_type_t *type;
3357 //variable_t *based = NULL; /* MS __based extension */
3358 switch (token.kind) {
3360 type = parse_reference_declarator();
3364 panic("based not supported anymore");
3369 type = parse_pointer_declarator();
3373 goto ptr_operator_end;
3377 anchor = &type->base.next;
3379 /* TODO: find out if this is correct */
3380 env->attributes = parse_attributes(env->attributes);
3384 construct_type_t *inner_types = NULL;
3386 switch (token.kind) {
3388 if (env->must_be_abstract) {
3389 errorf(HERE, "no identifier expected in typename");
3391 env->symbol = token.base.symbol;
3392 env->source_position = *HERE;
3398 /* Parenthesized declarator or function declarator? */
3399 token_t const *const la1 = look_ahead(1);
3400 switch (la1->kind) {
3402 if (is_typedef_symbol(la1->base.symbol)) {
3404 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3405 * interpreted as ``function with no parameter specification'', rather
3406 * than redundant parentheses around the omitted identifier. */
3408 /* Function declarator. */
3409 if (!env->may_be_abstract) {
3410 errorf(HERE, "function declarator must have a name");
3417 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3418 /* Paranthesized declarator. */
3420 add_anchor_token(')');
3421 inner_types = parse_inner_declarator(env);
3422 if (inner_types != NULL) {
3423 /* All later declarators only modify the return type */
3424 env->must_be_abstract = true;
3426 rem_anchor_token(')');
3435 if (env->may_be_abstract)
3437 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3442 construct_type_t **const p = anchor;
3445 construct_type_t *type;
3446 switch (token.kind) {
3448 scope_t *scope = NULL;
3449 if (!env->must_be_abstract) {
3450 scope = &env->parameters;
3453 type = parse_function_declarator(scope);
3457 type = parse_array_declarator();
3460 goto declarator_finished;
3463 /* insert in the middle of the list (at p) */
3464 type->base.next = *p;
3467 anchor = &type->base.next;
3470 declarator_finished:
3471 /* append inner_types at the end of the list, we don't to set anchor anymore
3472 * as it's not needed anymore */
3473 *anchor = inner_types;
3478 static type_t *construct_declarator_type(construct_type_t *construct_list,
3481 construct_type_t *iter = construct_list;
3482 for (; iter != NULL; iter = iter->base.next) {
3483 source_position_t const* const pos = &iter->base.pos;
3484 switch (iter->kind) {
3485 case CONSTRUCT_FUNCTION: {
3486 construct_function_type_t *function = &iter->function;
3487 type_t *function_type = function->function_type;
3489 function_type->function.return_type = type;
3491 type_t *skipped_return_type = skip_typeref(type);
3493 if (is_type_function(skipped_return_type)) {
3494 errorf(pos, "function returning function is not allowed");
3495 } else if (is_type_array(skipped_return_type)) {
3496 errorf(pos, "function returning array is not allowed");
3498 if (skipped_return_type->base.qualifiers != 0) {
3499 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3503 /* The function type was constructed earlier. Freeing it here will
3504 * destroy other types. */
3505 type = typehash_insert(function_type);
3509 case CONSTRUCT_POINTER: {
3510 if (is_type_reference(skip_typeref(type)))
3511 errorf(pos, "cannot declare a pointer to reference");
3513 parsed_pointer_t *pointer = &iter->pointer;
3514 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3518 case CONSTRUCT_REFERENCE:
3519 if (is_type_reference(skip_typeref(type)))
3520 errorf(pos, "cannot declare a reference to reference");
3522 type = make_reference_type(type);
3525 case CONSTRUCT_ARRAY: {
3526 if (is_type_reference(skip_typeref(type)))
3527 errorf(pos, "cannot declare an array of references");
3529 parsed_array_t *array = &iter->array;
3530 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3532 expression_t *size_expression = array->size;
3533 if (size_expression != NULL) {
3535 = create_implicit_cast(size_expression, type_size_t);
3538 array_type->base.qualifiers = array->type_qualifiers;
3539 array_type->array.element_type = type;
3540 array_type->array.is_static = array->is_static;
3541 array_type->array.is_variable = array->is_variable;
3542 array_type->array.size_expression = size_expression;
3544 if (size_expression != NULL) {
3545 switch (is_constant_expression(size_expression)) {
3546 case EXPR_CLASS_CONSTANT: {
3547 long const size = fold_constant_to_int(size_expression);
3548 array_type->array.size = size;
3549 array_type->array.size_constant = true;
3550 /* §6.7.5.2:1 If the expression is a constant expression,
3551 * it shall have a value greater than zero. */
3553 errorf(&size_expression->base.source_position,
3554 "size of array must be greater than zero");
3555 } else if (size == 0 && !GNU_MODE) {
3556 errorf(&size_expression->base.source_position,
3557 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3562 case EXPR_CLASS_VARIABLE:
3563 array_type->array.is_vla = true;
3566 case EXPR_CLASS_ERROR:
3571 type_t *skipped_type = skip_typeref(type);
3573 if (is_type_incomplete(skipped_type)) {
3574 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3575 } else if (is_type_function(skipped_type)) {
3576 errorf(pos, "array of functions is not allowed");
3578 type = identify_new_type(array_type);
3582 internal_errorf(pos, "invalid type construction found");
3588 static type_t *automatic_type_conversion(type_t *orig_type);
3590 static type_t *semantic_parameter(const source_position_t *pos,
3592 const declaration_specifiers_t *specifiers,
3593 entity_t const *const param)
3595 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3596 * shall be adjusted to ``qualified pointer to type'',
3598 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3599 * type'' shall be adjusted to ``pointer to function
3600 * returning type'', as in 6.3.2.1. */
3601 type = automatic_type_conversion(type);
3603 if (specifiers->is_inline && is_type_valid(type)) {
3604 errorf(pos, "'%N' declared 'inline'", param);
3607 /* §6.9.1:6 The declarations in the declaration list shall contain
3608 * no storage-class specifier other than register and no
3609 * initializations. */
3610 if (specifiers->thread_local || (
3611 specifiers->storage_class != STORAGE_CLASS_NONE &&
3612 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3614 errorf(pos, "invalid storage class for '%N'", param);
3617 /* delay test for incomplete type, because we might have (void)
3618 * which is legal but incomplete... */
3623 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3624 declarator_flags_t flags)
3626 parse_declarator_env_t env;
3627 memset(&env, 0, sizeof(env));
3628 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3630 construct_type_t *construct_type = parse_inner_declarator(&env);
3632 construct_declarator_type(construct_type, specifiers->type);
3633 type_t *type = skip_typeref(orig_type);
3635 if (construct_type != NULL) {
3636 obstack_free(&temp_obst, construct_type);
3639 attribute_t *attributes = parse_attributes(env.attributes);
3640 /* append (shared) specifier attribute behind attributes of this
3642 attribute_t **anchor = &attributes;
3643 while (*anchor != NULL)
3644 anchor = &(*anchor)->next;
3645 *anchor = specifiers->attributes;
3648 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3649 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3650 entity->typedefe.type = orig_type;
3652 if (anonymous_entity != NULL) {
3653 if (is_type_compound(type)) {
3654 assert(anonymous_entity->compound.alias == NULL);
3655 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3656 anonymous_entity->kind == ENTITY_UNION);
3657 anonymous_entity->compound.alias = entity;
3658 anonymous_entity = NULL;
3659 } else if (is_type_enum(type)) {
3660 assert(anonymous_entity->enume.alias == NULL);
3661 assert(anonymous_entity->kind == ENTITY_ENUM);
3662 anonymous_entity->enume.alias = entity;
3663 anonymous_entity = NULL;
3667 /* create a declaration type entity */
3668 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3669 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3670 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3672 if (env.symbol != NULL) {
3673 if (specifiers->is_inline && is_type_valid(type)) {
3674 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3677 if (specifiers->thread_local ||
3678 specifiers->storage_class != STORAGE_CLASS_NONE) {
3679 errorf(&env.source_position, "'%N' must have no storage class", entity);
3682 } else if (flags & DECL_IS_PARAMETER) {
3683 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3684 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3685 } else if (is_type_function(type)) {
3686 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3687 entity->function.is_inline = specifiers->is_inline;
3688 entity->function.elf_visibility = default_visibility;
3689 entity->function.parameters = env.parameters;
3691 if (env.symbol != NULL) {
3692 /* this needs fixes for C++ */
3693 bool in_function_scope = current_function != NULL;
3695 if (specifiers->thread_local || (
3696 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3697 specifiers->storage_class != STORAGE_CLASS_NONE &&
3698 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3700 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3704 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3705 entity->variable.elf_visibility = default_visibility;
3706 entity->variable.thread_local = specifiers->thread_local;
3708 if (env.symbol != NULL) {
3709 if (specifiers->is_inline && is_type_valid(type)) {
3710 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3713 bool invalid_storage_class = false;
3714 if (current_scope == file_scope) {
3715 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3716 specifiers->storage_class != STORAGE_CLASS_NONE &&
3717 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3718 invalid_storage_class = true;
3721 if (specifiers->thread_local &&
3722 specifiers->storage_class == STORAGE_CLASS_NONE) {
3723 invalid_storage_class = true;
3726 if (invalid_storage_class) {
3727 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3732 entity->declaration.type = orig_type;
3733 entity->declaration.alignment = get_type_alignment(orig_type);
3734 entity->declaration.modifiers = env.modifiers;
3735 entity->declaration.attributes = attributes;
3737 storage_class_t storage_class = specifiers->storage_class;
3738 entity->declaration.declared_storage_class = storage_class;
3740 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3741 storage_class = STORAGE_CLASS_AUTO;
3742 entity->declaration.storage_class = storage_class;
3745 if (attributes != NULL) {
3746 handle_entity_attributes(attributes, entity);
3749 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3750 adapt_special_functions(&entity->function);
3756 static type_t *parse_abstract_declarator(type_t *base_type)
3758 parse_declarator_env_t env;
3759 memset(&env, 0, sizeof(env));
3760 env.may_be_abstract = true;
3761 env.must_be_abstract = true;
3763 construct_type_t *construct_type = parse_inner_declarator(&env);
3765 type_t *result = construct_declarator_type(construct_type, base_type);
3766 if (construct_type != NULL) {
3767 obstack_free(&temp_obst, construct_type);
3769 result = handle_type_attributes(env.attributes, result);
3775 * Check if the declaration of main is suspicious. main should be a
3776 * function with external linkage, returning int, taking either zero
3777 * arguments, two, or three arguments of appropriate types, ie.
3779 * int main([ int argc, char **argv [, char **env ] ]).
3781 * @param decl the declaration to check
3782 * @param type the function type of the declaration
3784 static void check_main(const entity_t *entity)
3786 const source_position_t *pos = &entity->base.source_position;
3787 if (entity->kind != ENTITY_FUNCTION) {
3788 warningf(WARN_MAIN, pos, "'main' is not a function");
3792 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3793 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3796 type_t *type = skip_typeref(entity->declaration.type);
3797 assert(is_type_function(type));
3799 function_type_t const *const func_type = &type->function;
3800 type_t *const ret_type = func_type->return_type;
3801 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3802 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3804 const function_parameter_t *parm = func_type->parameters;
3806 type_t *const first_type = skip_typeref(parm->type);
3807 type_t *const first_type_unqual = get_unqualified_type(first_type);
3808 if (!types_compatible(first_type_unqual, type_int)) {
3809 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3813 type_t *const second_type = skip_typeref(parm->type);
3814 type_t *const second_type_unqual
3815 = get_unqualified_type(second_type);
3816 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3817 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3821 type_t *const third_type = skip_typeref(parm->type);
3822 type_t *const third_type_unqual
3823 = get_unqualified_type(third_type);
3824 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3825 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3829 goto warn_arg_count;
3833 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3838 static void error_redefined_as_different_kind(const source_position_t *pos,
3839 const entity_t *old, entity_kind_t new_kind)
3841 char const *const what = get_entity_kind_name(new_kind);
3842 source_position_t const *const ppos = &old->base.source_position;
3843 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3846 static bool is_entity_valid(entity_t *const ent)
3848 if (is_declaration(ent)) {
3849 return is_type_valid(skip_typeref(ent->declaration.type));
3850 } else if (ent->kind == ENTITY_TYPEDEF) {
3851 return is_type_valid(skip_typeref(ent->typedefe.type));
3856 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3858 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3859 if (attributes_equal(tattr, attr))
3866 * test wether new_list contains any attributes not included in old_list
3868 static bool has_new_attributes(const attribute_t *old_list,
3869 const attribute_t *new_list)
3871 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3872 if (!contains_attribute(old_list, attr))
3879 * Merge in attributes from an attribute list (probably from a previous
3880 * declaration with the same name). Warning: destroys the old structure
3881 * of the attribute list - don't reuse attributes after this call.
3883 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3886 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3888 if (contains_attribute(decl->attributes, attr))
3891 /* move attribute to new declarations attributes list */
3892 attr->next = decl->attributes;
3893 decl->attributes = attr;
3897 static bool is_main(entity_t*);
3900 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3901 * for various problems that occur for multiple definitions
3903 entity_t *record_entity(entity_t *entity, const bool is_definition)
3905 const symbol_t *const symbol = entity->base.symbol;
3906 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3907 const source_position_t *pos = &entity->base.source_position;
3909 /* can happen in error cases */
3913 assert(!entity->base.parent_scope);
3914 assert(current_scope);
3915 entity->base.parent_scope = current_scope;
3917 entity_t *const previous_entity = get_entity(symbol, namespc);
3918 /* pushing the same entity twice will break the stack structure */
3919 assert(previous_entity != entity);
3921 if (entity->kind == ENTITY_FUNCTION) {
3922 type_t *const orig_type = entity->declaration.type;
3923 type_t *const type = skip_typeref(orig_type);
3925 assert(is_type_function(type));
3926 if (type->function.unspecified_parameters &&
3927 previous_entity == NULL &&
3928 !entity->declaration.implicit) {
3929 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3932 if (is_main(entity)) {
3937 if (is_declaration(entity) &&
3938 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3939 current_scope != file_scope &&
3940 !entity->declaration.implicit) {
3941 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3944 if (previous_entity != NULL) {
3945 source_position_t const *const ppos = &previous_entity->base.source_position;
3947 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
3948 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
3949 assert(previous_entity->kind == ENTITY_PARAMETER);
3950 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
3954 if (previous_entity->base.parent_scope == current_scope) {
3955 if (previous_entity->kind != entity->kind) {
3956 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
3957 error_redefined_as_different_kind(pos, previous_entity,
3962 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
3963 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
3966 if (previous_entity->kind == ENTITY_TYPEDEF) {
3967 type_t *const type = skip_typeref(entity->typedefe.type);
3968 type_t *const prev_type
3969 = skip_typeref(previous_entity->typedefe.type);
3970 if (c_mode & _CXX) {
3971 /* C++ allows double typedef if they are identical
3972 * (after skipping typedefs) */
3973 if (type == prev_type)
3976 /* GCC extension: redef in system headers is allowed */
3977 if ((pos->is_system_header || ppos->is_system_header) &&
3978 types_compatible(type, prev_type))
3981 errorf(pos, "redefinition of '%N' (declared %P)",
3986 /* at this point we should have only VARIABLES or FUNCTIONS */
3987 assert(is_declaration(previous_entity) && is_declaration(entity));
3989 declaration_t *const prev_decl = &previous_entity->declaration;
3990 declaration_t *const decl = &entity->declaration;
3992 /* can happen for K&R style declarations */
3993 if (prev_decl->type == NULL &&
3994 previous_entity->kind == ENTITY_PARAMETER &&
3995 entity->kind == ENTITY_PARAMETER) {
3996 prev_decl->type = decl->type;
3997 prev_decl->storage_class = decl->storage_class;
3998 prev_decl->declared_storage_class = decl->declared_storage_class;
3999 prev_decl->modifiers = decl->modifiers;
4000 return previous_entity;
4003 type_t *const type = skip_typeref(decl->type);
4004 type_t *const prev_type = skip_typeref(prev_decl->type);
4006 if (!types_compatible(type, prev_type)) {
4007 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4009 unsigned old_storage_class = prev_decl->storage_class;
4011 if (is_definition &&
4013 !(prev_decl->modifiers & DM_USED) &&
4014 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4015 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4018 storage_class_t new_storage_class = decl->storage_class;
4020 /* pretend no storage class means extern for function
4021 * declarations (except if the previous declaration is neither
4022 * none nor extern) */
4023 if (entity->kind == ENTITY_FUNCTION) {
4024 /* the previous declaration could have unspecified parameters or
4025 * be a typedef, so use the new type */
4026 if (prev_type->function.unspecified_parameters || is_definition)
4027 prev_decl->type = type;
4029 switch (old_storage_class) {
4030 case STORAGE_CLASS_NONE:
4031 old_storage_class = STORAGE_CLASS_EXTERN;
4034 case STORAGE_CLASS_EXTERN:
4035 if (is_definition) {
4036 if (prev_type->function.unspecified_parameters && !is_main(entity)) {
4037 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4039 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4040 new_storage_class = STORAGE_CLASS_EXTERN;
4047 } else if (is_type_incomplete(prev_type)) {
4048 prev_decl->type = type;
4051 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4052 new_storage_class == STORAGE_CLASS_EXTERN) {
4054 warn_redundant_declaration: ;
4056 = has_new_attributes(prev_decl->attributes,
4058 if (has_new_attrs) {
4059 merge_in_attributes(decl, prev_decl->attributes);
4060 } else if (!is_definition &&
4061 is_type_valid(prev_type) &&
4062 !pos->is_system_header) {
4063 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%N' (declared %P)", entity, ppos);
4065 } else if (current_function == NULL) {
4066 if (old_storage_class != STORAGE_CLASS_STATIC &&
4067 new_storage_class == STORAGE_CLASS_STATIC) {
4068 errorf(pos, "static declaration of '%N' follows non-static declaration (declared %P)", entity, ppos);
4069 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4070 prev_decl->storage_class = STORAGE_CLASS_NONE;
4071 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4073 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4075 goto error_redeclaration;
4076 goto warn_redundant_declaration;
4078 } else if (is_type_valid(prev_type)) {
4079 if (old_storage_class == new_storage_class) {
4080 error_redeclaration:
4081 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4083 errorf(pos, "redeclaration of '%N' with different linkage (declared %P)", entity, ppos);
4088 prev_decl->modifiers |= decl->modifiers;
4089 if (entity->kind == ENTITY_FUNCTION) {
4090 previous_entity->function.is_inline |= entity->function.is_inline;
4092 return previous_entity;
4096 if (is_warn_on(why = WARN_SHADOW) ||
4097 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4098 char const *const what = get_entity_kind_name(previous_entity->kind);
4099 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4103 if (entity->kind == ENTITY_FUNCTION) {
4104 if (is_definition &&
4105 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4107 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4108 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4110 goto warn_missing_declaration;
4113 } else if (entity->kind == ENTITY_VARIABLE) {
4114 if (current_scope == file_scope &&
4115 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4116 !entity->declaration.implicit) {
4117 warn_missing_declaration:
4118 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4123 environment_push(entity);
4124 append_entity(current_scope, entity);
4129 static void parser_error_multiple_definition(entity_t *entity,
4130 const source_position_t *source_position)
4132 errorf(source_position, "redefinition of '%N' (declared %P)", entity, &entity->base.source_position);
4135 static bool is_declaration_specifier(const token_t *token)
4137 switch (token->kind) {
4141 return is_typedef_symbol(token->base.symbol);
4148 static void parse_init_declarator_rest(entity_t *entity)
4150 type_t *orig_type = type_error_type;
4152 if (entity->base.kind == ENTITY_TYPEDEF) {
4153 source_position_t const *const pos = &entity->base.source_position;
4154 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4156 assert(is_declaration(entity));
4157 orig_type = entity->declaration.type;
4160 type_t *type = skip_typeref(orig_type);
4162 if (entity->kind == ENTITY_VARIABLE
4163 && entity->variable.initializer != NULL) {
4164 parser_error_multiple_definition(entity, HERE);
4168 declaration_t *const declaration = &entity->declaration;
4169 bool must_be_constant = false;
4170 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4171 entity->base.parent_scope == file_scope) {
4172 must_be_constant = true;
4175 if (is_type_function(type)) {
4176 source_position_t const *const pos = &entity->base.source_position;
4177 errorf(pos, "'%N' is initialized like a variable", entity);
4178 orig_type = type_error_type;
4181 parse_initializer_env_t env;
4182 env.type = orig_type;
4183 env.must_be_constant = must_be_constant;
4184 env.entity = entity;
4186 initializer_t *initializer = parse_initializer(&env);
4188 if (entity->kind == ENTITY_VARIABLE) {
4189 /* §6.7.5:22 array initializers for arrays with unknown size
4190 * determine the array type size */
4191 declaration->type = env.type;
4192 entity->variable.initializer = initializer;
4196 /* parse rest of a declaration without any declarator */
4197 static void parse_anonymous_declaration_rest(
4198 const declaration_specifiers_t *specifiers)
4201 anonymous_entity = NULL;
4203 source_position_t const *const pos = &specifiers->source_position;
4204 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4205 specifiers->thread_local) {
4206 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4209 type_t *type = specifiers->type;
4210 switch (type->kind) {
4211 case TYPE_COMPOUND_STRUCT:
4212 case TYPE_COMPOUND_UNION: {
4213 if (type->compound.compound->base.symbol == NULL) {
4214 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4223 warningf(WARN_OTHER, pos, "empty declaration");
4228 static void check_variable_type_complete(entity_t *ent)
4230 if (ent->kind != ENTITY_VARIABLE)
4233 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4234 * type for the object shall be complete [...] */
4235 declaration_t *decl = &ent->declaration;
4236 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4237 decl->storage_class == STORAGE_CLASS_STATIC)
4240 type_t *const type = skip_typeref(decl->type);
4241 if (!is_type_incomplete(type))
4244 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4245 * are given length one. */
4246 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4247 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4251 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4255 static void parse_declaration_rest(entity_t *ndeclaration,
4256 const declaration_specifiers_t *specifiers,
4257 parsed_declaration_func finished_declaration,
4258 declarator_flags_t flags)
4260 add_anchor_token(';');
4261 add_anchor_token(',');
4263 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4265 if (token.kind == '=') {
4266 parse_init_declarator_rest(entity);
4267 } else if (entity->kind == ENTITY_VARIABLE) {
4268 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4269 * [...] where the extern specifier is explicitly used. */
4270 declaration_t *decl = &entity->declaration;
4271 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4272 is_type_reference(skip_typeref(decl->type))) {
4273 source_position_t const *const pos = &entity->base.source_position;
4274 errorf(pos, "reference '%#N' must be initialized", entity);
4278 check_variable_type_complete(entity);
4283 add_anchor_token('=');
4284 ndeclaration = parse_declarator(specifiers, flags);
4285 rem_anchor_token('=');
4287 rem_anchor_token(',');
4288 rem_anchor_token(';');
4291 anonymous_entity = NULL;
4294 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4296 symbol_t *symbol = entity->base.symbol;
4300 assert(entity->base.namespc == NAMESPACE_NORMAL);
4301 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4302 if (previous_entity == NULL
4303 || previous_entity->base.parent_scope != current_scope) {
4304 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4309 if (is_definition) {
4310 errorf(HERE, "'%N' is initialised", entity);
4313 return record_entity(entity, false);
4316 static void parse_declaration(parsed_declaration_func finished_declaration,
4317 declarator_flags_t flags)
4319 add_anchor_token(';');
4320 declaration_specifiers_t specifiers;
4321 parse_declaration_specifiers(&specifiers);
4322 rem_anchor_token(';');
4324 if (token.kind == ';') {
4325 parse_anonymous_declaration_rest(&specifiers);
4327 entity_t *entity = parse_declarator(&specifiers, flags);
4328 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4333 static type_t *get_default_promoted_type(type_t *orig_type)
4335 type_t *result = orig_type;
4337 type_t *type = skip_typeref(orig_type);
4338 if (is_type_integer(type)) {
4339 result = promote_integer(type);
4340 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4341 result = type_double;
4347 static void parse_kr_declaration_list(entity_t *entity)
4349 if (entity->kind != ENTITY_FUNCTION)
4352 type_t *type = skip_typeref(entity->declaration.type);
4353 assert(is_type_function(type));
4354 if (!type->function.kr_style_parameters)
4357 add_anchor_token('{');
4359 PUSH_SCOPE(&entity->function.parameters);
4361 entity_t *parameter = entity->function.parameters.entities;
4362 for ( ; parameter != NULL; parameter = parameter->base.next) {
4363 assert(parameter->base.parent_scope == NULL);
4364 parameter->base.parent_scope = current_scope;
4365 environment_push(parameter);
4368 /* parse declaration list */
4370 switch (token.kind) {
4372 /* This covers symbols, which are no type, too, and results in
4373 * better error messages. The typical cases are misspelled type
4374 * names and missing includes. */
4376 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4386 /* update function type */
4387 type_t *new_type = duplicate_type(type);
4389 function_parameter_t *parameters = NULL;
4390 function_parameter_t **anchor = ¶meters;
4392 /* did we have an earlier prototype? */
4393 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4394 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4397 function_parameter_t *proto_parameter = NULL;
4398 if (proto_type != NULL) {
4399 type_t *proto_type_type = proto_type->declaration.type;
4400 proto_parameter = proto_type_type->function.parameters;
4401 /* If a K&R function definition has a variadic prototype earlier, then
4402 * make the function definition variadic, too. This should conform to
4403 * §6.7.5.3:15 and §6.9.1:8. */
4404 new_type->function.variadic = proto_type_type->function.variadic;
4406 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4408 new_type->function.unspecified_parameters = true;
4411 bool need_incompatible_warning = false;
4412 parameter = entity->function.parameters.entities;
4413 for (; parameter != NULL; parameter = parameter->base.next,
4415 proto_parameter == NULL ? NULL : proto_parameter->next) {
4416 if (parameter->kind != ENTITY_PARAMETER)
4419 type_t *parameter_type = parameter->declaration.type;
4420 if (parameter_type == NULL) {
4421 source_position_t const* const pos = ¶meter->base.source_position;
4423 errorf(pos, "no type specified for function '%N'", parameter);
4424 parameter_type = type_error_type;
4426 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4427 parameter_type = type_int;
4429 parameter->declaration.type = parameter_type;
4432 semantic_parameter_incomplete(parameter);
4434 /* we need the default promoted types for the function type */
4435 type_t *not_promoted = parameter_type;
4436 parameter_type = get_default_promoted_type(parameter_type);
4438 /* gcc special: if the type of the prototype matches the unpromoted
4439 * type don't promote */
4440 if (!strict_mode && proto_parameter != NULL) {
4441 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4442 type_t *promo_skip = skip_typeref(parameter_type);
4443 type_t *param_skip = skip_typeref(not_promoted);
4444 if (!types_compatible(proto_p_type, promo_skip)
4445 && types_compatible(proto_p_type, param_skip)) {
4447 need_incompatible_warning = true;
4448 parameter_type = not_promoted;
4451 function_parameter_t *const function_parameter
4452 = allocate_parameter(parameter_type);
4454 *anchor = function_parameter;
4455 anchor = &function_parameter->next;
4458 new_type->function.parameters = parameters;
4459 new_type = identify_new_type(new_type);
4461 if (need_incompatible_warning) {
4462 symbol_t const *const sym = entity->base.symbol;
4463 source_position_t const *const pos = &entity->base.source_position;
4464 source_position_t const *const ppos = &proto_type->base.source_position;
4465 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4467 entity->declaration.type = new_type;
4469 rem_anchor_token('{');
4472 static bool first_err = true;
4475 * When called with first_err set, prints the name of the current function,
4478 static void print_in_function(void)
4482 char const *const file = current_function->base.base.source_position.input_name;
4483 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4488 * Check if all labels are defined in the current function.
4489 * Check if all labels are used in the current function.
4491 static void check_labels(void)
4493 for (const goto_statement_t *goto_statement = goto_first;
4494 goto_statement != NULL;
4495 goto_statement = goto_statement->next) {
4496 label_t *label = goto_statement->label;
4497 if (label->base.source_position.input_name == NULL) {
4498 print_in_function();
4499 source_position_t const *const pos = &goto_statement->base.source_position;
4500 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4504 if (is_warn_on(WARN_UNUSED_LABEL)) {
4505 for (const label_statement_t *label_statement = label_first;
4506 label_statement != NULL;
4507 label_statement = label_statement->next) {
4508 label_t *label = label_statement->label;
4510 if (! label->used) {
4511 print_in_function();
4512 source_position_t const *const pos = &label_statement->base.source_position;
4513 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4519 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4521 entity_t const *const end = last != NULL ? last->base.next : NULL;
4522 for (; entity != end; entity = entity->base.next) {
4523 if (!is_declaration(entity))
4526 declaration_t *declaration = &entity->declaration;
4527 if (declaration->implicit)
4530 if (!declaration->used) {
4531 print_in_function();
4532 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4533 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4534 print_in_function();
4535 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4540 static void check_unused_variables(statement_t *const stmt, void *const env)
4544 switch (stmt->kind) {
4545 case STATEMENT_DECLARATION: {
4546 declaration_statement_t const *const decls = &stmt->declaration;
4547 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4552 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4561 * Check declarations of current_function for unused entities.
4563 static void check_declarations(void)
4565 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4566 const scope_t *scope = ¤t_function->parameters;
4567 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4569 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4570 walk_statements(current_function->statement, check_unused_variables,
4575 static int determine_truth(expression_t const* const cond)
4578 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4579 fold_constant_to_bool(cond) ? 1 :
4583 static void check_reachable(statement_t *);
4584 static bool reaches_end;
4586 static bool expression_returns(expression_t const *const expr)
4588 switch (expr->kind) {
4590 expression_t const *const func = expr->call.function;
4591 type_t const *const type = skip_typeref(func->base.type);
4592 if (type->kind == TYPE_POINTER) {
4593 type_t const *const points_to
4594 = skip_typeref(type->pointer.points_to);
4595 if (points_to->kind == TYPE_FUNCTION
4596 && points_to->function.modifiers & DM_NORETURN)
4600 if (!expression_returns(func))
4603 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4604 if (!expression_returns(arg->expression))
4611 case EXPR_REFERENCE:
4612 case EXPR_ENUM_CONSTANT:
4613 case EXPR_LITERAL_CASES:
4614 case EXPR_LITERAL_CHARACTER:
4615 case EXPR_STRING_LITERAL:
4616 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4617 case EXPR_LABEL_ADDRESS:
4618 case EXPR_CLASSIFY_TYPE:
4619 case EXPR_SIZEOF: // TODO handle obscure VLA case
4622 case EXPR_BUILTIN_CONSTANT_P:
4623 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4628 case EXPR_STATEMENT: {
4629 bool old_reaches_end = reaches_end;
4630 reaches_end = false;
4631 check_reachable(expr->statement.statement);
4632 bool returns = reaches_end;
4633 reaches_end = old_reaches_end;
4637 case EXPR_CONDITIONAL:
4638 // TODO handle constant expression
4640 if (!expression_returns(expr->conditional.condition))
4643 if (expr->conditional.true_expression != NULL
4644 && expression_returns(expr->conditional.true_expression))
4647 return expression_returns(expr->conditional.false_expression);
4650 return expression_returns(expr->select.compound);
4652 case EXPR_ARRAY_ACCESS:
4654 expression_returns(expr->array_access.array_ref) &&
4655 expression_returns(expr->array_access.index);
4658 return expression_returns(expr->va_starte.ap);
4661 return expression_returns(expr->va_arge.ap);
4664 return expression_returns(expr->va_copye.src);
4666 case EXPR_UNARY_CASES_MANDATORY:
4667 return expression_returns(expr->unary.value);
4669 case EXPR_UNARY_THROW:
4672 case EXPR_BINARY_CASES:
4673 // TODO handle constant lhs of && and ||
4675 expression_returns(expr->binary.left) &&
4676 expression_returns(expr->binary.right);
4679 panic("unhandled expression");
4682 static bool initializer_returns(initializer_t const *const init)
4684 switch (init->kind) {
4685 case INITIALIZER_VALUE:
4686 return expression_returns(init->value.value);
4688 case INITIALIZER_LIST: {
4689 initializer_t * const* i = init->list.initializers;
4690 initializer_t * const* const end = i + init->list.len;
4691 bool returns = true;
4692 for (; i != end; ++i) {
4693 if (!initializer_returns(*i))
4699 case INITIALIZER_STRING:
4700 case INITIALIZER_DESIGNATOR: // designators have no payload
4703 panic("unhandled initializer");
4706 static bool noreturn_candidate;
4708 static void check_reachable(statement_t *const stmt)
4710 if (stmt->base.reachable)
4712 if (stmt->kind != STATEMENT_DO_WHILE)
4713 stmt->base.reachable = true;
4715 statement_t *last = stmt;
4717 switch (stmt->kind) {
4718 case STATEMENT_ERROR:
4719 case STATEMENT_EMPTY:
4721 next = stmt->base.next;
4724 case STATEMENT_DECLARATION: {
4725 declaration_statement_t const *const decl = &stmt->declaration;
4726 entity_t const * ent = decl->declarations_begin;
4727 entity_t const *const last_decl = decl->declarations_end;
4729 for (;; ent = ent->base.next) {
4730 if (ent->kind == ENTITY_VARIABLE &&
4731 ent->variable.initializer != NULL &&
4732 !initializer_returns(ent->variable.initializer)) {
4735 if (ent == last_decl)
4739 next = stmt->base.next;
4743 case STATEMENT_COMPOUND:
4744 next = stmt->compound.statements;
4746 next = stmt->base.next;
4749 case STATEMENT_RETURN: {
4750 expression_t const *const val = stmt->returns.value;
4751 if (val == NULL || expression_returns(val))
4752 noreturn_candidate = false;
4756 case STATEMENT_IF: {
4757 if_statement_t const *const ifs = &stmt->ifs;
4758 expression_t const *const cond = ifs->condition;
4760 if (!expression_returns(cond))
4763 int const val = determine_truth(cond);
4766 check_reachable(ifs->true_statement);
4771 if (ifs->false_statement != NULL) {
4772 check_reachable(ifs->false_statement);
4776 next = stmt->base.next;
4780 case STATEMENT_SWITCH: {
4781 switch_statement_t const *const switchs = &stmt->switchs;
4782 expression_t const *const expr = switchs->expression;
4784 if (!expression_returns(expr))
4787 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4788 long const val = fold_constant_to_int(expr);
4789 case_label_statement_t * defaults = NULL;
4790 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4791 if (i->expression == NULL) {
4796 if (i->first_case <= val && val <= i->last_case) {
4797 check_reachable((statement_t*)i);
4802 if (defaults != NULL) {
4803 check_reachable((statement_t*)defaults);
4807 bool has_default = false;
4808 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4809 if (i->expression == NULL)
4812 check_reachable((statement_t*)i);
4819 next = stmt->base.next;
4823 case STATEMENT_EXPRESSION: {
4824 /* Check for noreturn function call */
4825 expression_t const *const expr = stmt->expression.expression;
4826 if (!expression_returns(expr))
4829 next = stmt->base.next;
4833 case STATEMENT_CONTINUE:
4834 for (statement_t *parent = stmt;;) {
4835 parent = parent->base.parent;
4836 if (parent == NULL) /* continue not within loop */
4840 switch (parent->kind) {
4841 case STATEMENT_WHILE: goto continue_while;
4842 case STATEMENT_DO_WHILE: goto continue_do_while;
4843 case STATEMENT_FOR: goto continue_for;
4849 case STATEMENT_BREAK:
4850 for (statement_t *parent = stmt;;) {
4851 parent = parent->base.parent;
4852 if (parent == NULL) /* break not within loop/switch */
4855 switch (parent->kind) {
4856 case STATEMENT_SWITCH:
4857 case STATEMENT_WHILE:
4858 case STATEMENT_DO_WHILE:
4861 next = parent->base.next;
4862 goto found_break_parent;
4870 case STATEMENT_COMPUTED_GOTO: {
4871 if (!expression_returns(stmt->computed_goto.expression))
4874 statement_t *parent = stmt->base.parent;
4875 if (parent == NULL) /* top level goto */
4881 case STATEMENT_GOTO:
4882 next = stmt->gotos.label->statement;
4883 if (next == NULL) /* missing label */
4887 case STATEMENT_LABEL:
4888 next = stmt->label.statement;
4891 case STATEMENT_CASE_LABEL:
4892 next = stmt->case_label.statement;
4895 case STATEMENT_WHILE: {
4896 while_statement_t const *const whiles = &stmt->whiles;
4897 expression_t const *const cond = whiles->condition;
4899 if (!expression_returns(cond))
4902 int const val = determine_truth(cond);
4905 check_reachable(whiles->body);
4910 next = stmt->base.next;
4914 case STATEMENT_DO_WHILE:
4915 next = stmt->do_while.body;
4918 case STATEMENT_FOR: {
4919 for_statement_t *const fors = &stmt->fors;
4921 if (fors->condition_reachable)
4923 fors->condition_reachable = true;
4925 expression_t const *const cond = fors->condition;
4930 } else if (expression_returns(cond)) {
4931 val = determine_truth(cond);
4937 check_reachable(fors->body);
4942 next = stmt->base.next;
4946 case STATEMENT_MS_TRY: {
4947 ms_try_statement_t const *const ms_try = &stmt->ms_try;
4948 check_reachable(ms_try->try_statement);
4949 next = ms_try->final_statement;
4953 case STATEMENT_LEAVE: {
4954 statement_t *parent = stmt;
4956 parent = parent->base.parent;
4957 if (parent == NULL) /* __leave not within __try */
4960 if (parent->kind == STATEMENT_MS_TRY) {
4962 next = parent->ms_try.final_statement;
4970 panic("invalid statement kind");
4973 while (next == NULL) {
4974 next = last->base.parent;
4976 noreturn_candidate = false;
4978 type_t *const type = skip_typeref(current_function->base.type);
4979 assert(is_type_function(type));
4980 type_t *const ret = skip_typeref(type->function.return_type);
4981 if (!is_type_void(ret) &&
4982 is_type_valid(ret) &&
4983 !is_main(current_entity)) {
4984 source_position_t const *const pos = &stmt->base.source_position;
4985 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
4990 switch (next->kind) {
4991 case STATEMENT_ERROR:
4992 case STATEMENT_EMPTY:
4993 case STATEMENT_DECLARATION:
4994 case STATEMENT_EXPRESSION:
4996 case STATEMENT_RETURN:
4997 case STATEMENT_CONTINUE:
4998 case STATEMENT_BREAK:
4999 case STATEMENT_COMPUTED_GOTO:
5000 case STATEMENT_GOTO:
5001 case STATEMENT_LEAVE:
5002 panic("invalid control flow in function");
5004 case STATEMENT_COMPOUND:
5005 if (next->compound.stmt_expr) {
5011 case STATEMENT_SWITCH:
5012 case STATEMENT_LABEL:
5013 case STATEMENT_CASE_LABEL:
5015 next = next->base.next;
5018 case STATEMENT_WHILE: {
5020 if (next->base.reachable)
5022 next->base.reachable = true;
5024 while_statement_t const *const whiles = &next->whiles;
5025 expression_t const *const cond = whiles->condition;
5027 if (!expression_returns(cond))
5030 int const val = determine_truth(cond);
5033 check_reachable(whiles->body);
5039 next = next->base.next;
5043 case STATEMENT_DO_WHILE: {
5045 if (next->base.reachable)
5047 next->base.reachable = true;
5049 do_while_statement_t const *const dw = &next->do_while;
5050 expression_t const *const cond = dw->condition;
5052 if (!expression_returns(cond))
5055 int const val = determine_truth(cond);
5058 check_reachable(dw->body);
5064 next = next->base.next;
5068 case STATEMENT_FOR: {
5070 for_statement_t *const fors = &next->fors;
5072 fors->step_reachable = true;
5074 if (fors->condition_reachable)
5076 fors->condition_reachable = true;
5078 expression_t const *const cond = fors->condition;
5083 } else if (expression_returns(cond)) {
5084 val = determine_truth(cond);
5090 check_reachable(fors->body);
5096 next = next->base.next;
5100 case STATEMENT_MS_TRY:
5102 next = next->ms_try.final_statement;
5107 check_reachable(next);
5110 static void check_unreachable(statement_t* const stmt, void *const env)
5114 switch (stmt->kind) {
5115 case STATEMENT_DO_WHILE:
5116 if (!stmt->base.reachable) {
5117 expression_t const *const cond = stmt->do_while.condition;
5118 if (determine_truth(cond) >= 0) {
5119 source_position_t const *const pos = &cond->base.source_position;
5120 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5125 case STATEMENT_FOR: {
5126 for_statement_t const* const fors = &stmt->fors;
5128 // if init and step are unreachable, cond is unreachable, too
5129 if (!stmt->base.reachable && !fors->step_reachable) {
5130 goto warn_unreachable;
5132 if (!stmt->base.reachable && fors->initialisation != NULL) {
5133 source_position_t const *const pos = &fors->initialisation->base.source_position;
5134 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5137 if (!fors->condition_reachable && fors->condition != NULL) {
5138 source_position_t const *const pos = &fors->condition->base.source_position;
5139 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5142 if (!fors->step_reachable && fors->step != NULL) {
5143 source_position_t const *const pos = &fors->step->base.source_position;
5144 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5150 case STATEMENT_COMPOUND:
5151 if (stmt->compound.statements != NULL)
5153 goto warn_unreachable;
5155 case STATEMENT_DECLARATION: {
5156 /* Only warn if there is at least one declarator with an initializer.
5157 * This typically occurs in switch statements. */
5158 declaration_statement_t const *const decl = &stmt->declaration;
5159 entity_t const * ent = decl->declarations_begin;
5160 entity_t const *const last = decl->declarations_end;
5162 for (;; ent = ent->base.next) {
5163 if (ent->kind == ENTITY_VARIABLE &&
5164 ent->variable.initializer != NULL) {
5165 goto warn_unreachable;
5175 if (!stmt->base.reachable) {
5176 source_position_t const *const pos = &stmt->base.source_position;
5177 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5183 static bool is_main(entity_t *entity)
5185 static symbol_t *sym_main = NULL;
5186 if (sym_main == NULL) {
5187 sym_main = symbol_table_insert("main");
5190 if (entity->base.symbol != sym_main)
5192 /* must be in outermost scope */
5193 if (entity->base.parent_scope != file_scope)
5199 static void prepare_main_collect2(entity_t*);
5201 static void parse_external_declaration(void)
5203 /* function-definitions and declarations both start with declaration
5205 add_anchor_token(';');
5206 declaration_specifiers_t specifiers;
5207 parse_declaration_specifiers(&specifiers);
5208 rem_anchor_token(';');
5210 /* must be a declaration */
5211 if (token.kind == ';') {
5212 parse_anonymous_declaration_rest(&specifiers);
5216 add_anchor_token(',');
5217 add_anchor_token('=');
5218 add_anchor_token(';');
5219 add_anchor_token('{');
5221 /* declarator is common to both function-definitions and declarations */
5222 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5224 rem_anchor_token('{');
5225 rem_anchor_token(';');
5226 rem_anchor_token('=');
5227 rem_anchor_token(',');
5229 /* must be a declaration */
5230 switch (token.kind) {
5234 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5239 /* must be a function definition */
5240 parse_kr_declaration_list(ndeclaration);
5242 if (token.kind != '{') {
5243 parse_error_expected("while parsing function definition", '{', NULL);
5244 eat_until_matching_token(';');
5248 assert(is_declaration(ndeclaration));
5249 type_t *const orig_type = ndeclaration->declaration.type;
5250 type_t * type = skip_typeref(orig_type);
5252 if (!is_type_function(type)) {
5253 if (is_type_valid(type)) {
5254 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5260 source_position_t const *const pos = &ndeclaration->base.source_position;
5261 if (is_typeref(orig_type)) {
5263 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5266 if (is_type_compound(skip_typeref(type->function.return_type))) {
5267 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5269 if (type->function.unspecified_parameters) {
5270 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5272 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5275 /* §6.7.5.3:14 a function definition with () means no
5276 * parameters (and not unspecified parameters) */
5277 if (type->function.unspecified_parameters &&
5278 type->function.parameters == NULL) {
5279 type_t *copy = duplicate_type(type);
5280 copy->function.unspecified_parameters = false;
5281 type = identify_new_type(copy);
5283 ndeclaration->declaration.type = type;
5286 entity_t *const entity = record_entity(ndeclaration, true);
5287 assert(entity->kind == ENTITY_FUNCTION);
5288 assert(ndeclaration->kind == ENTITY_FUNCTION);
5290 function_t *const function = &entity->function;
5291 if (ndeclaration != entity) {
5292 function->parameters = ndeclaration->function.parameters;
5295 PUSH_SCOPE(&function->parameters);
5297 entity_t *parameter = function->parameters.entities;
5298 for (; parameter != NULL; parameter = parameter->base.next) {
5299 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5300 parameter->base.parent_scope = current_scope;
5302 assert(parameter->base.parent_scope == NULL
5303 || parameter->base.parent_scope == current_scope);
5304 parameter->base.parent_scope = current_scope;
5305 if (parameter->base.symbol == NULL) {
5306 errorf(¶meter->base.source_position, "parameter name omitted");
5309 environment_push(parameter);
5312 if (function->statement != NULL) {
5313 parser_error_multiple_definition(entity, HERE);
5316 /* parse function body */
5317 int label_stack_top = label_top();
5318 function_t *old_current_function = current_function;
5319 current_function = function;
5320 PUSH_CURRENT_ENTITY(entity);
5324 goto_anchor = &goto_first;
5326 label_anchor = &label_first;
5328 statement_t *const body = parse_compound_statement(false);
5329 function->statement = body;
5332 check_declarations();
5333 if (is_warn_on(WARN_RETURN_TYPE) ||
5334 is_warn_on(WARN_UNREACHABLE_CODE) ||
5335 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5336 noreturn_candidate = true;
5337 check_reachable(body);
5338 if (is_warn_on(WARN_UNREACHABLE_CODE))
5339 walk_statements(body, check_unreachable, NULL);
5340 if (noreturn_candidate &&
5341 !(function->base.modifiers & DM_NORETURN)) {
5342 source_position_t const *const pos = &body->base.source_position;
5343 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5347 if (is_main(entity)) {
5348 /* Force main to C linkage. */
5349 type_t *const type = entity->declaration.type;
5350 assert(is_type_function(type));
5351 if (type->function.linkage != LINKAGE_C) {
5352 type_t *new_type = duplicate_type(type);
5353 new_type->function.linkage = LINKAGE_C;
5354 entity->declaration.type = identify_new_type(new_type);
5357 if (enable_main_collect2_hack)
5358 prepare_main_collect2(entity);
5361 POP_CURRENT_ENTITY();
5363 assert(current_function == function);
5364 current_function = old_current_function;
5365 label_pop_to(label_stack_top);
5371 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5373 entity_t *iter = compound->members.entities;
5374 for (; iter != NULL; iter = iter->base.next) {
5375 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5378 if (iter->base.symbol == symbol) {
5380 } else if (iter->base.symbol == NULL) {
5381 /* search in anonymous structs and unions */
5382 type_t *type = skip_typeref(iter->declaration.type);
5383 if (is_type_compound(type)) {
5384 if (find_compound_entry(type->compound.compound, symbol)
5395 static void check_deprecated(const source_position_t *source_position,
5396 const entity_t *entity)
5398 if (!is_declaration(entity))
5400 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5403 source_position_t const *const epos = &entity->base.source_position;
5404 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5406 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5408 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5413 static expression_t *create_select(const source_position_t *pos,
5415 type_qualifiers_t qualifiers,
5418 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5420 check_deprecated(pos, entry);
5422 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5423 select->select.compound = addr;
5424 select->select.compound_entry = entry;
5426 type_t *entry_type = entry->declaration.type;
5427 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5429 /* bitfields need special treatment */
5430 if (entry->compound_member.bitfield) {
5431 unsigned bit_size = entry->compound_member.bit_size;
5432 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5433 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5434 res_type = type_int;
5438 /* we always do the auto-type conversions; the & and sizeof parser contains
5439 * code to revert this! */
5440 select->base.type = automatic_type_conversion(res_type);
5447 * Find entry with symbol in compound. Search anonymous structs and unions and
5448 * creates implicit select expressions for them.
5449 * Returns the adress for the innermost compound.
5451 static expression_t *find_create_select(const source_position_t *pos,
5453 type_qualifiers_t qualifiers,
5454 compound_t *compound, symbol_t *symbol)
5456 entity_t *iter = compound->members.entities;
5457 for (; iter != NULL; iter = iter->base.next) {
5458 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5461 symbol_t *iter_symbol = iter->base.symbol;
5462 if (iter_symbol == NULL) {
5463 type_t *type = iter->declaration.type;
5464 if (!is_type_compound(type))
5467 compound_t *sub_compound = type->compound.compound;
5469 if (find_compound_entry(sub_compound, symbol) == NULL)
5472 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5473 sub_addr->base.source_position = *pos;
5474 sub_addr->base.implicit = true;
5475 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5479 if (iter_symbol == symbol) {
5480 return create_select(pos, addr, qualifiers, iter);
5487 static void parse_bitfield_member(entity_t *entity)
5491 expression_t *size = parse_constant_expression();
5494 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5495 type_t *type = entity->declaration.type;
5496 if (!is_type_integer(skip_typeref(type))) {
5497 errorf(HERE, "bitfield base type '%T' is not an integer type",
5501 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5502 /* error already reported by parse_constant_expression */
5503 size_long = get_type_size(type) * 8;
5505 size_long = fold_constant_to_int(size);
5507 const symbol_t *symbol = entity->base.symbol;
5508 const symbol_t *user_symbol
5509 = symbol == NULL ? sym_anonymous : symbol;
5510 unsigned bit_size = get_type_size(type) * 8;
5511 if (size_long < 0) {
5512 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5513 } else if (size_long == 0 && symbol != NULL) {
5514 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5515 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5516 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5519 /* hope that people don't invent crazy types with more bits
5520 * than our struct can hold */
5522 (1 << sizeof(entity->compound_member.bit_size)*8));
5526 entity->compound_member.bitfield = true;
5527 entity->compound_member.bit_size = (unsigned char)size_long;
5530 static void parse_compound_declarators(compound_t *compound,
5531 const declaration_specifiers_t *specifiers)
5533 add_anchor_token(';');
5534 add_anchor_token(',');
5538 if (token.kind == ':') {
5539 /* anonymous bitfield */
5540 type_t *type = specifiers->type;
5541 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5542 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5543 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5544 entity->declaration.type = type;
5546 parse_bitfield_member(entity);
5548 attribute_t *attributes = parse_attributes(NULL);
5549 attribute_t **anchor = &attributes;
5550 while (*anchor != NULL)
5551 anchor = &(*anchor)->next;
5552 *anchor = specifiers->attributes;
5553 if (attributes != NULL) {
5554 handle_entity_attributes(attributes, entity);
5556 entity->declaration.attributes = attributes;
5558 append_entity(&compound->members, entity);
5560 entity = parse_declarator(specifiers,
5561 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5562 source_position_t const *const pos = &entity->base.source_position;
5563 if (entity->kind == ENTITY_TYPEDEF) {
5564 errorf(pos, "typedef not allowed as compound member");
5566 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5568 /* make sure we don't define a symbol multiple times */
5569 symbol_t *symbol = entity->base.symbol;
5570 if (symbol != NULL) {
5571 entity_t *prev = find_compound_entry(compound, symbol);
5573 source_position_t const *const ppos = &prev->base.source_position;
5574 errorf(pos, "multiple declarations of '%N' (declared %P)", entity, ppos);
5578 if (token.kind == ':') {
5579 parse_bitfield_member(entity);
5581 attribute_t *attributes = parse_attributes(NULL);
5582 handle_entity_attributes(attributes, entity);
5584 type_t *orig_type = entity->declaration.type;
5585 type_t *type = skip_typeref(orig_type);
5586 if (is_type_function(type)) {
5587 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5588 } else if (is_type_incomplete(type)) {
5589 /* §6.7.2.1:16 flexible array member */
5590 if (!is_type_array(type) ||
5591 token.kind != ';' ||
5592 look_ahead(1)->kind != '}') {
5593 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5594 } else if (compound->members.entities == NULL) {
5595 errorf(pos, "flexible array member in otherwise empty struct");
5600 append_entity(&compound->members, entity);
5603 } while (next_if(','));
5604 rem_anchor_token(',');
5605 rem_anchor_token(';');
5608 anonymous_entity = NULL;
5611 static void parse_compound_type_entries(compound_t *compound)
5614 add_anchor_token('}');
5617 switch (token.kind) {
5619 case T___extension__:
5620 case T_IDENTIFIER: {
5622 declaration_specifiers_t specifiers;
5623 parse_declaration_specifiers(&specifiers);
5624 parse_compound_declarators(compound, &specifiers);
5630 rem_anchor_token('}');
5633 compound->complete = true;
5639 static type_t *parse_typename(void)
5641 declaration_specifiers_t specifiers;
5642 parse_declaration_specifiers(&specifiers);
5643 if (specifiers.storage_class != STORAGE_CLASS_NONE
5644 || specifiers.thread_local) {
5645 /* TODO: improve error message, user does probably not know what a
5646 * storage class is...
5648 errorf(&specifiers.source_position, "typename must not have a storage class");
5651 type_t *result = parse_abstract_declarator(specifiers.type);
5659 typedef expression_t* (*parse_expression_function)(void);
5660 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5662 typedef struct expression_parser_function_t expression_parser_function_t;
5663 struct expression_parser_function_t {
5664 parse_expression_function parser;
5665 precedence_t infix_precedence;
5666 parse_expression_infix_function infix_parser;
5669 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5671 static type_t *get_string_type(string_encoding_t const enc)
5673 bool const warn = is_warn_on(WARN_WRITE_STRINGS);
5675 case STRING_ENCODING_CHAR: return warn ? type_const_char_ptr : type_char_ptr;
5676 case STRING_ENCODING_WIDE: return warn ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5678 panic("invalid string encoding");
5682 * Parse a string constant.
5684 static expression_t *parse_string_literal(void)
5686 expression_t *const expr = allocate_expression_zero(EXPR_STRING_LITERAL);
5687 expr->string_literal.value = concat_string_literals();
5688 expr->base.type = get_string_type(expr->string_literal.value.encoding);
5693 * Parse a boolean constant.
5695 static expression_t *parse_boolean_literal(bool value)
5697 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5698 literal->base.type = type_bool;
5699 literal->literal.value.begin = value ? "true" : "false";
5700 literal->literal.value.size = value ? 4 : 5;
5702 eat(value ? T_true : T_false);
5706 static void warn_traditional_suffix(void)
5708 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5709 &token.number.suffix);
5712 static void check_integer_suffix(void)
5714 const string_t *suffix = &token.number.suffix;
5715 if (suffix->size == 0)
5718 bool not_traditional = false;
5719 const char *c = suffix->begin;
5720 if (*c == 'l' || *c == 'L') {
5723 not_traditional = true;
5725 if (*c == 'u' || *c == 'U') {
5728 } else if (*c == 'u' || *c == 'U') {
5729 not_traditional = true;
5732 } else if (*c == 'u' || *c == 'U') {
5733 not_traditional = true;
5735 if (*c == 'l' || *c == 'L') {
5743 errorf(HERE, "invalid suffix '%S' on integer constant", suffix);
5744 } else if (not_traditional) {
5745 warn_traditional_suffix();
5749 static type_t *check_floatingpoint_suffix(void)
5751 const string_t *suffix = &token.number.suffix;
5752 type_t *type = type_double;
5753 if (suffix->size == 0)
5756 bool not_traditional = false;
5757 const char *c = suffix->begin;
5758 if (*c == 'f' || *c == 'F') {
5761 } else if (*c == 'l' || *c == 'L') {
5763 type = type_long_double;
5766 errorf(HERE, "invalid suffix '%S' on floatingpoint constant", suffix);
5767 } else if (not_traditional) {
5768 warn_traditional_suffix();
5775 * Parse an integer constant.
5777 static expression_t *parse_number_literal(void)
5779 expression_kind_t kind;
5782 switch (token.kind) {
5784 kind = EXPR_LITERAL_INTEGER;
5785 check_integer_suffix();
5789 case T_FLOATINGPOINT:
5790 kind = EXPR_LITERAL_FLOATINGPOINT;
5791 type = check_floatingpoint_suffix();
5795 panic("unexpected token type in parse_number_literal");
5798 expression_t *literal = allocate_expression_zero(kind);
5799 literal->base.type = type;
5800 literal->literal.value = token.number.number;
5801 literal->literal.suffix = token.number.suffix;
5804 /* integer type depends on the size of the number and the size
5805 * representable by the types. The backend/codegeneration has to determine
5808 determine_literal_type(&literal->literal);
5813 * Parse a character constant.
5815 static expression_t *parse_character_constant(void)
5817 expression_t *const literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5818 literal->string_literal.value = token.string.string;
5820 size_t const size = get_string_len(&token.string.string);
5821 switch (token.string.string.encoding) {
5822 case STRING_ENCODING_CHAR:
5823 literal->base.type = c_mode & _CXX ? type_char : type_int;
5825 if (!GNU_MODE && !(c_mode & _C99)) {
5826 errorf(HERE, "more than 1 character in character constant");
5828 literal->base.type = type_int;
5829 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5834 case STRING_ENCODING_WIDE:
5835 literal->base.type = type_int;
5837 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5842 eat(T_CHARACTER_CONSTANT);
5846 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5848 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5849 ntype->function.return_type = type_int;
5850 ntype->function.unspecified_parameters = true;
5851 ntype->function.linkage = LINKAGE_C;
5852 type_t *type = identify_new_type(ntype);
5854 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5855 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5856 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5857 entity->declaration.type = type;
5858 entity->declaration.implicit = true;
5860 if (current_scope != NULL)
5861 record_entity(entity, false);
5867 * Performs automatic type cast as described in §6.3.2.1.
5869 * @param orig_type the original type
5871 static type_t *automatic_type_conversion(type_t *orig_type)
5873 type_t *type = skip_typeref(orig_type);
5874 if (is_type_array(type)) {
5875 array_type_t *array_type = &type->array;
5876 type_t *element_type = array_type->element_type;
5877 unsigned qualifiers = array_type->base.qualifiers;
5879 return make_pointer_type(element_type, qualifiers);
5882 if (is_type_function(type)) {
5883 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5890 * reverts the automatic casts of array to pointer types and function
5891 * to function-pointer types as defined §6.3.2.1
5893 type_t *revert_automatic_type_conversion(const expression_t *expression)
5895 switch (expression->kind) {
5896 case EXPR_REFERENCE: {
5897 entity_t *entity = expression->reference.entity;
5898 if (is_declaration(entity)) {
5899 return entity->declaration.type;
5900 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5901 return entity->enum_value.enum_type;
5903 panic("no declaration or enum in reference");
5908 entity_t *entity = expression->select.compound_entry;
5909 assert(is_declaration(entity));
5910 type_t *type = entity->declaration.type;
5911 return get_qualified_type(type, expression->base.type->base.qualifiers);
5914 case EXPR_UNARY_DEREFERENCE: {
5915 const expression_t *const value = expression->unary.value;
5916 type_t *const type = skip_typeref(value->base.type);
5917 if (!is_type_pointer(type))
5918 return type_error_type;
5919 return type->pointer.points_to;
5922 case EXPR_ARRAY_ACCESS: {
5923 const expression_t *array_ref = expression->array_access.array_ref;
5924 type_t *type_left = skip_typeref(array_ref->base.type);
5925 if (!is_type_pointer(type_left))
5926 return type_error_type;
5927 return type_left->pointer.points_to;
5930 case EXPR_STRING_LITERAL: {
5931 size_t const size = get_string_len(&expression->string_literal.value) + 1;
5932 type_t *const elem = get_unqualified_type(expression->base.type->pointer.points_to);
5933 return make_array_type(elem, size, TYPE_QUALIFIER_NONE);
5936 case EXPR_COMPOUND_LITERAL:
5937 return expression->compound_literal.type;
5942 return expression->base.type;
5946 * Find an entity matching a symbol in a scope.
5947 * Uses current scope if scope is NULL
5949 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
5950 namespace_tag_t namespc)
5952 if (scope == NULL) {
5953 return get_entity(symbol, namespc);
5956 /* we should optimize here, if scope grows above a certain size we should
5957 construct a hashmap here... */
5958 entity_t *entity = scope->entities;
5959 for ( ; entity != NULL; entity = entity->base.next) {
5960 if (entity->base.symbol == symbol
5961 && (namespace_tag_t)entity->base.namespc == namespc)
5968 static entity_t *parse_qualified_identifier(void)
5970 /* namespace containing the symbol */
5972 source_position_t pos;
5973 const scope_t *lookup_scope = NULL;
5975 if (next_if(T_COLONCOLON))
5976 lookup_scope = &unit->scope;
5980 symbol = expect_identifier("while parsing identifier", &pos);
5982 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
5985 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
5987 if (!next_if(T_COLONCOLON))
5990 switch (entity->kind) {
5991 case ENTITY_NAMESPACE:
5992 lookup_scope = &entity->namespacee.members;
5997 lookup_scope = &entity->compound.members;
6000 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6001 symbol, get_entity_kind_name(entity->kind));
6003 /* skip further qualifications */
6004 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6006 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6010 if (entity == NULL) {
6011 if (!strict_mode && token.kind == '(') {
6012 /* an implicitly declared function */
6013 entity = create_implicit_function(symbol, &pos);
6014 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of '%N'", entity);
6016 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6017 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6024 static expression_t *parse_reference(void)
6026 source_position_t const pos = *HERE;
6027 entity_t *const entity = parse_qualified_identifier();
6030 if (is_declaration(entity)) {
6031 orig_type = entity->declaration.type;
6032 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6033 orig_type = entity->enum_value.enum_type;
6035 panic("expected declaration or enum value in reference");
6038 /* we always do the auto-type conversions; the & and sizeof parser contains
6039 * code to revert this! */
6040 type_t *type = automatic_type_conversion(orig_type);
6042 expression_kind_t kind = EXPR_REFERENCE;
6043 if (entity->kind == ENTITY_ENUM_VALUE)
6044 kind = EXPR_ENUM_CONSTANT;
6046 expression_t *expression = allocate_expression_zero(kind);
6047 expression->base.source_position = pos;
6048 expression->base.type = type;
6049 expression->reference.entity = entity;
6051 /* this declaration is used */
6052 if (is_declaration(entity)) {
6053 entity->declaration.used = true;
6056 if (entity->base.parent_scope != file_scope
6057 && (current_function != NULL
6058 && entity->base.parent_scope->depth < current_function->parameters.depth)
6059 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6060 /* access of a variable from an outer function */
6061 entity->variable.address_taken = true;
6062 current_function->need_closure = true;
6065 check_deprecated(&pos, entity);
6070 static bool semantic_cast(expression_t *cast)
6072 expression_t *expression = cast->unary.value;
6073 type_t *orig_dest_type = cast->base.type;
6074 type_t *orig_type_right = expression->base.type;
6075 type_t const *dst_type = skip_typeref(orig_dest_type);
6076 type_t const *src_type = skip_typeref(orig_type_right);
6077 source_position_t const *pos = &cast->base.source_position;
6079 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6080 if (is_type_void(dst_type))
6083 /* only integer and pointer can be casted to pointer */
6084 if (is_type_pointer(dst_type) &&
6085 !is_type_pointer(src_type) &&
6086 !is_type_integer(src_type) &&
6087 is_type_valid(src_type)) {
6088 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6092 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6093 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6097 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6098 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6102 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6103 type_t *src = skip_typeref(src_type->pointer.points_to);
6104 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6105 unsigned missing_qualifiers =
6106 src->base.qualifiers & ~dst->base.qualifiers;
6107 if (missing_qualifiers != 0) {
6108 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6114 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6116 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6117 expression->base.source_position = *pos;
6119 parse_initializer_env_t env;
6122 env.must_be_constant = false;
6123 initializer_t *initializer = parse_initializer(&env);
6126 expression->compound_literal.initializer = initializer;
6127 expression->compound_literal.type = type;
6128 expression->base.type = automatic_type_conversion(type);
6134 * Parse a cast expression.
6136 static expression_t *parse_cast(void)
6138 source_position_t const pos = *HERE;
6141 add_anchor_token(')');
6143 type_t *type = parse_typename();
6145 rem_anchor_token(')');
6148 if (token.kind == '{') {
6149 return parse_compound_literal(&pos, type);
6152 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6153 cast->base.source_position = pos;
6155 expression_t *value = parse_subexpression(PREC_CAST);
6156 cast->base.type = type;
6157 cast->unary.value = value;
6159 if (! semantic_cast(cast)) {
6160 /* TODO: record the error in the AST. else it is impossible to detect it */
6167 * Parse a statement expression.
6169 static expression_t *parse_statement_expression(void)
6171 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6174 add_anchor_token(')');
6176 statement_t *statement = parse_compound_statement(true);
6177 statement->compound.stmt_expr = true;
6178 expression->statement.statement = statement;
6180 /* find last statement and use its type */
6181 type_t *type = type_void;
6182 const statement_t *stmt = statement->compound.statements;
6184 while (stmt->base.next != NULL)
6185 stmt = stmt->base.next;
6187 if (stmt->kind == STATEMENT_EXPRESSION) {
6188 type = stmt->expression.expression->base.type;
6191 source_position_t const *const pos = &expression->base.source_position;
6192 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6194 expression->base.type = type;
6196 rem_anchor_token(')');
6202 * Parse a parenthesized expression.
6204 static expression_t *parse_parenthesized_expression(void)
6206 token_t const* const la1 = look_ahead(1);
6207 switch (la1->kind) {
6209 /* gcc extension: a statement expression */
6210 return parse_statement_expression();
6213 if (is_typedef_symbol(la1->base.symbol)) {
6215 return parse_cast();
6220 add_anchor_token(')');
6221 expression_t *result = parse_expression();
6222 result->base.parenthesized = true;
6223 rem_anchor_token(')');
6229 static expression_t *parse_function_keyword(funcname_kind_t const kind)
6231 if (current_function == NULL) {
6232 errorf(HERE, "'%K' used outside of a function", &token);
6235 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6236 expression->base.type = type_char_ptr;
6237 expression->funcname.kind = kind;
6244 static designator_t *parse_designator(void)
6246 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6247 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6248 if (!result->symbol)
6251 designator_t *last_designator = result;
6254 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6255 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6256 if (!designator->symbol)
6259 last_designator->next = designator;
6260 last_designator = designator;
6264 add_anchor_token(']');
6265 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6266 designator->source_position = *HERE;
6267 designator->array_index = parse_expression();
6268 rem_anchor_token(']');
6270 if (designator->array_index == NULL) {
6274 last_designator->next = designator;
6275 last_designator = designator;
6285 * Parse the __builtin_offsetof() expression.
6287 static expression_t *parse_offsetof(void)
6289 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6290 expression->base.type = type_size_t;
6292 eat(T___builtin_offsetof);
6294 add_anchor_token(')');
6295 add_anchor_token(',');
6297 type_t *type = parse_typename();
6298 rem_anchor_token(',');
6300 designator_t *designator = parse_designator();
6301 rem_anchor_token(')');
6304 expression->offsetofe.type = type;
6305 expression->offsetofe.designator = designator;
6308 memset(&path, 0, sizeof(path));
6309 path.top_type = type;
6310 path.path = NEW_ARR_F(type_path_entry_t, 0);
6312 descend_into_subtype(&path);
6314 if (!walk_designator(&path, designator, true)) {
6315 return create_error_expression();
6318 DEL_ARR_F(path.path);
6323 static bool is_last_parameter(expression_t *const param)
6325 if (param->kind == EXPR_REFERENCE) {
6326 entity_t *const entity = param->reference.entity;
6327 if (entity->kind == ENTITY_PARAMETER &&
6328 !entity->base.next &&
6329 entity->base.parent_scope == ¤t_function->parameters) {
6334 if (!is_type_valid(skip_typeref(param->base.type)))
6341 * Parses a __builtin_va_start() expression.
6343 static expression_t *parse_va_start(void)
6345 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6347 eat(T___builtin_va_start);
6349 add_anchor_token(')');
6350 add_anchor_token(',');
6352 expression->va_starte.ap = parse_assignment_expression();
6353 rem_anchor_token(',');
6355 expression_t *const param = parse_assignment_expression();
6356 expression->va_starte.parameter = param;
6357 rem_anchor_token(')');
6360 if (!current_function) {
6361 errorf(&expression->base.source_position, "'va_start' used outside of function");
6362 } else if (!current_function->base.type->function.variadic) {
6363 errorf(&expression->base.source_position, "'va_start' used in non-variadic function");
6364 } else if (!is_last_parameter(param)) {
6365 errorf(¶m->base.source_position, "second argument of 'va_start' must be last parameter of the current function");
6372 * Parses a __builtin_va_arg() expression.
6374 static expression_t *parse_va_arg(void)
6376 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6378 eat(T___builtin_va_arg);
6380 add_anchor_token(')');
6381 add_anchor_token(',');
6384 ap.expression = parse_assignment_expression();
6385 expression->va_arge.ap = ap.expression;
6386 check_call_argument(type_valist, &ap, 1);
6388 rem_anchor_token(',');
6390 expression->base.type = parse_typename();
6391 rem_anchor_token(')');
6398 * Parses a __builtin_va_copy() expression.
6400 static expression_t *parse_va_copy(void)
6402 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6404 eat(T___builtin_va_copy);
6406 add_anchor_token(')');
6407 add_anchor_token(',');
6409 expression_t *dst = parse_assignment_expression();
6410 assign_error_t error = semantic_assign(type_valist, dst);
6411 report_assign_error(error, type_valist, dst, "call argument 1",
6412 &dst->base.source_position);
6413 expression->va_copye.dst = dst;
6415 rem_anchor_token(',');
6418 call_argument_t src;
6419 src.expression = parse_assignment_expression();
6420 check_call_argument(type_valist, &src, 2);
6421 expression->va_copye.src = src.expression;
6422 rem_anchor_token(')');
6429 * Parses a __builtin_constant_p() expression.
6431 static expression_t *parse_builtin_constant(void)
6433 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6435 eat(T___builtin_constant_p);
6437 add_anchor_token(')');
6439 expression->builtin_constant.value = parse_assignment_expression();
6440 rem_anchor_token(')');
6442 expression->base.type = type_int;
6448 * Parses a __builtin_types_compatible_p() expression.
6450 static expression_t *parse_builtin_types_compatible(void)
6452 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6454 eat(T___builtin_types_compatible_p);
6456 add_anchor_token(')');
6457 add_anchor_token(',');
6459 expression->builtin_types_compatible.left = parse_typename();
6460 rem_anchor_token(',');
6462 expression->builtin_types_compatible.right = parse_typename();
6463 rem_anchor_token(')');
6465 expression->base.type = type_int;
6471 * Parses a __builtin_is_*() compare expression.
6473 static expression_t *parse_compare_builtin(void)
6475 expression_kind_t kind;
6476 switch (token.kind) {
6477 case T___builtin_isgreater: kind = EXPR_BINARY_ISGREATER; break;
6478 case T___builtin_isgreaterequal: kind = EXPR_BINARY_ISGREATEREQUAL; break;
6479 case T___builtin_isless: kind = EXPR_BINARY_ISLESS; break;
6480 case T___builtin_islessequal: kind = EXPR_BINARY_ISLESSEQUAL; break;
6481 case T___builtin_islessgreater: kind = EXPR_BINARY_ISLESSGREATER; break;
6482 case T___builtin_isunordered: kind = EXPR_BINARY_ISUNORDERED; break;
6483 default: internal_errorf(HERE, "invalid compare builtin found");
6485 expression_t *const expression = allocate_expression_zero(kind);
6488 add_anchor_token(')');
6489 add_anchor_token(',');
6491 expression->binary.left = parse_assignment_expression();
6492 rem_anchor_token(',');
6494 expression->binary.right = parse_assignment_expression();
6495 rem_anchor_token(')');
6498 type_t *const orig_type_left = expression->binary.left->base.type;
6499 type_t *const orig_type_right = expression->binary.right->base.type;
6501 type_t *const type_left = skip_typeref(orig_type_left);
6502 type_t *const type_right = skip_typeref(orig_type_right);
6503 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6504 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6505 type_error_incompatible("invalid operands in comparison",
6506 &expression->base.source_position, orig_type_left, orig_type_right);
6509 semantic_comparison(&expression->binary);
6516 * Parses a MS assume() expression.
6518 static expression_t *parse_assume(void)
6520 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6524 add_anchor_token(')');
6526 expression->unary.value = parse_assignment_expression();
6527 rem_anchor_token(')');
6530 expression->base.type = type_void;
6535 * Return the label for the current symbol or create a new one.
6537 static label_t *get_label(char const *const context)
6539 assert(current_function != NULL);
6541 symbol_t *const sym = expect_identifier(context, NULL);
6545 entity_t *label = get_entity(sym, NAMESPACE_LABEL);
6546 /* If we find a local label, we already created the declaration. */
6547 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6548 if (label->base.parent_scope != current_scope) {
6549 assert(label->base.parent_scope->depth < current_scope->depth);
6550 current_function->goto_to_outer = true;
6552 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6553 /* There is no matching label in the same function, so create a new one. */
6554 source_position_t const nowhere = { NULL, 0, 0, false };
6555 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym, &nowhere);
6559 return &label->label;
6563 * Parses a GNU && label address expression.
6565 static expression_t *parse_label_address(void)
6567 source_position_t const source_position = *HERE;
6570 label_t *const label = get_label("while parsing label address");
6572 return create_error_expression();
6575 label->address_taken = true;
6577 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6578 expression->base.source_position = source_position;
6580 /* label address is treated as a void pointer */
6581 expression->base.type = type_void_ptr;
6582 expression->label_address.label = label;
6587 * Parse a microsoft __noop expression.
6589 static expression_t *parse_noop_expression(void)
6591 /* the result is a (int)0 */
6592 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6593 literal->base.type = type_int;
6594 literal->literal.value.begin = "__noop";
6595 literal->literal.value.size = 6;
6599 if (token.kind == '(') {
6600 /* parse arguments */
6602 add_anchor_token(')');
6603 add_anchor_token(',');
6605 if (token.kind != ')') do {
6606 (void)parse_assignment_expression();
6607 } while (next_if(','));
6609 rem_anchor_token(',');
6610 rem_anchor_token(')');
6618 * Parses a primary expression.
6620 static expression_t *parse_primary_expression(void)
6622 switch (token.kind) {
6623 case T_false: return parse_boolean_literal(false);
6624 case T_true: return parse_boolean_literal(true);
6626 case T_FLOATINGPOINT: return parse_number_literal();
6627 case T_CHARACTER_CONSTANT: return parse_character_constant();
6628 case T_STRING_LITERAL: return parse_string_literal();
6629 case T___func__: return parse_function_keyword(FUNCNAME_FUNCTION);
6630 case T___PRETTY_FUNCTION__: return parse_function_keyword(FUNCNAME_PRETTY_FUNCTION);
6631 case T___FUNCSIG__: return parse_function_keyword(FUNCNAME_FUNCSIG);
6632 case T___FUNCDNAME__: return parse_function_keyword(FUNCNAME_FUNCDNAME);
6633 case T___builtin_offsetof: return parse_offsetof();
6634 case T___builtin_va_start: return parse_va_start();
6635 case T___builtin_va_arg: return parse_va_arg();
6636 case T___builtin_va_copy: return parse_va_copy();
6637 case T___builtin_isgreater:
6638 case T___builtin_isgreaterequal:
6639 case T___builtin_isless:
6640 case T___builtin_islessequal:
6641 case T___builtin_islessgreater:
6642 case T___builtin_isunordered: return parse_compare_builtin();
6643 case T___builtin_constant_p: return parse_builtin_constant();
6644 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6645 case T__assume: return parse_assume();
6648 return parse_label_address();
6651 case '(': return parse_parenthesized_expression();
6652 case T___noop: return parse_noop_expression();
6654 /* Gracefully handle type names while parsing expressions. */
6656 return parse_reference();
6658 if (!is_typedef_symbol(token.base.symbol)) {
6659 return parse_reference();
6663 source_position_t const pos = *HERE;
6664 declaration_specifiers_t specifiers;
6665 parse_declaration_specifiers(&specifiers);
6666 type_t const *const type = parse_abstract_declarator(specifiers.type);
6667 errorf(&pos, "encountered type '%T' while parsing expression", type);
6668 return create_error_expression();
6672 errorf(HERE, "unexpected token %K, expected an expression", &token);
6674 return create_error_expression();
6677 static expression_t *parse_array_expression(expression_t *left)
6679 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6680 array_access_expression_t *const arr = &expr->array_access;
6683 add_anchor_token(']');
6685 expression_t *const inside = parse_expression();
6687 type_t *const orig_type_left = left->base.type;
6688 type_t *const orig_type_inside = inside->base.type;
6690 type_t *const type_left = skip_typeref(orig_type_left);
6691 type_t *const type_inside = skip_typeref(orig_type_inside);
6697 if (is_type_pointer(type_left)) {
6700 idx_type = type_inside;
6701 res_type = type_left->pointer.points_to;
6703 } else if (is_type_pointer(type_inside)) {
6704 arr->flipped = true;
6707 idx_type = type_left;
6708 res_type = type_inside->pointer.points_to;
6710 res_type = automatic_type_conversion(res_type);
6711 if (!is_type_integer(idx_type)) {
6712 errorf(&idx->base.source_position, "array subscript must have integer type");
6713 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6714 source_position_t const *const pos = &idx->base.source_position;
6715 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6718 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6719 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6721 res_type = type_error_type;
6726 arr->array_ref = ref;
6728 arr->base.type = res_type;
6730 rem_anchor_token(']');
6735 static bool is_bitfield(const expression_t *expression)
6737 return expression->kind == EXPR_SELECT
6738 && expression->select.compound_entry->compound_member.bitfield;
6741 static expression_t *parse_typeprop(expression_kind_t const kind)
6743 expression_t *tp_expression = allocate_expression_zero(kind);
6744 tp_expression->base.type = type_size_t;
6746 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6749 expression_t *expression;
6750 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6751 source_position_t const pos = *HERE;
6753 add_anchor_token(')');
6754 orig_type = parse_typename();
6755 rem_anchor_token(')');
6758 if (token.kind == '{') {
6759 /* It was not sizeof(type) after all. It is sizeof of an expression
6760 * starting with a compound literal */
6761 expression = parse_compound_literal(&pos, orig_type);
6762 goto typeprop_expression;
6765 expression = parse_subexpression(PREC_UNARY);
6767 typeprop_expression:
6768 if (is_bitfield(expression)) {
6769 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6770 errorf(&tp_expression->base.source_position,
6771 "operand of %s expression must not be a bitfield", what);
6774 tp_expression->typeprop.tp_expression = expression;
6776 orig_type = revert_automatic_type_conversion(expression);
6777 expression->base.type = orig_type;
6780 tp_expression->typeprop.type = orig_type;
6781 type_t const* const type = skip_typeref(orig_type);
6782 char const* wrong_type = NULL;
6783 if (is_type_incomplete(type)) {
6784 if (!is_type_void(type) || !GNU_MODE)
6785 wrong_type = "incomplete";
6786 } else if (type->kind == TYPE_FUNCTION) {
6788 /* function types are allowed (and return 1) */
6789 source_position_t const *const pos = &tp_expression->base.source_position;
6790 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6791 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6793 wrong_type = "function";
6797 if (wrong_type != NULL) {
6798 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6799 errorf(&tp_expression->base.source_position,
6800 "operand of %s expression must not be of %s type '%T'",
6801 what, wrong_type, orig_type);
6804 return tp_expression;
6807 static expression_t *parse_sizeof(void)
6809 return parse_typeprop(EXPR_SIZEOF);
6812 static expression_t *parse_alignof(void)
6814 return parse_typeprop(EXPR_ALIGNOF);
6817 static expression_t *parse_select_expression(expression_t *addr)
6819 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6820 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6821 source_position_t const pos = *HERE;
6824 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6826 return create_error_expression();
6828 type_t *const orig_type = addr->base.type;
6829 type_t *const type = skip_typeref(orig_type);
6832 bool saw_error = false;
6833 if (is_type_pointer(type)) {
6834 if (!select_left_arrow) {
6836 "request for member '%Y' in something not a struct or union, but '%T'",
6840 type_left = skip_typeref(type->pointer.points_to);
6842 if (select_left_arrow && is_type_valid(type)) {
6843 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
6849 if (!is_type_compound(type_left)) {
6850 if (is_type_valid(type_left) && !saw_error) {
6852 "request for member '%Y' in something not a struct or union, but '%T'",
6855 return create_error_expression();
6858 compound_t *compound = type_left->compound.compound;
6859 if (!compound->complete) {
6860 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
6862 return create_error_expression();
6865 type_qualifiers_t qualifiers = type_left->base.qualifiers;
6866 expression_t *result =
6867 find_create_select(&pos, addr, qualifiers, compound, symbol);
6869 if (result == NULL) {
6870 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
6871 return create_error_expression();
6877 static void check_call_argument(type_t *expected_type,
6878 call_argument_t *argument, unsigned pos)
6880 type_t *expected_type_skip = skip_typeref(expected_type);
6881 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
6882 expression_t *arg_expr = argument->expression;
6883 type_t *arg_type = skip_typeref(arg_expr->base.type);
6885 /* handle transparent union gnu extension */
6886 if (is_type_union(expected_type_skip)
6887 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
6888 compound_t *union_decl = expected_type_skip->compound.compound;
6889 type_t *best_type = NULL;
6890 entity_t *entry = union_decl->members.entities;
6891 for ( ; entry != NULL; entry = entry->base.next) {
6892 assert(is_declaration(entry));
6893 type_t *decl_type = entry->declaration.type;
6894 error = semantic_assign(decl_type, arg_expr);
6895 if (error == ASSIGN_ERROR_INCOMPATIBLE
6896 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
6899 if (error == ASSIGN_SUCCESS) {
6900 best_type = decl_type;
6901 } else if (best_type == NULL) {
6902 best_type = decl_type;
6906 if (best_type != NULL) {
6907 expected_type = best_type;
6911 error = semantic_assign(expected_type, arg_expr);
6912 argument->expression = create_implicit_cast(arg_expr, expected_type);
6914 if (error != ASSIGN_SUCCESS) {
6915 /* report exact scope in error messages (like "in argument 3") */
6917 snprintf(buf, sizeof(buf), "call argument %u", pos);
6918 report_assign_error(error, expected_type, arg_expr, buf,
6919 &arg_expr->base.source_position);
6921 type_t *const promoted_type = get_default_promoted_type(arg_type);
6922 if (!types_compatible(expected_type_skip, promoted_type) &&
6923 !types_compatible(expected_type_skip, type_void_ptr) &&
6924 !types_compatible(type_void_ptr, promoted_type)) {
6925 /* Deliberately show the skipped types in this warning */
6926 source_position_t const *const apos = &arg_expr->base.source_position;
6927 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
6933 * Handle the semantic restrictions of builtin calls
6935 static void handle_builtin_argument_restrictions(call_expression_t *call)
6937 entity_t *entity = call->function->reference.entity;
6938 switch (entity->function.btk) {
6940 switch (entity->function.b.firm_builtin_kind) {
6941 case ir_bk_return_address:
6942 case ir_bk_frame_address: {
6943 /* argument must be constant */
6944 call_argument_t *argument = call->arguments;
6946 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
6947 errorf(&call->base.source_position,
6948 "argument of '%Y' must be a constant expression",
6949 call->function->reference.entity->base.symbol);
6953 case ir_bk_prefetch:
6954 /* second and third argument must be constant if existent */
6955 if (call->arguments == NULL)
6957 call_argument_t *rw = call->arguments->next;
6958 call_argument_t *locality = NULL;
6961 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
6962 errorf(&call->base.source_position,
6963 "second argument of '%Y' must be a constant expression",
6964 call->function->reference.entity->base.symbol);
6966 locality = rw->next;
6968 if (locality != NULL) {
6969 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
6970 errorf(&call->base.source_position,
6971 "third argument of '%Y' must be a constant expression",
6972 call->function->reference.entity->base.symbol);
6974 locality = rw->next;
6981 case BUILTIN_OBJECT_SIZE:
6982 if (call->arguments == NULL)
6985 call_argument_t *arg = call->arguments->next;
6986 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
6987 errorf(&call->base.source_position,
6988 "second argument of '%Y' must be a constant expression",
6989 call->function->reference.entity->base.symbol);
6998 * Parse a call expression, ie. expression '( ... )'.
7000 * @param expression the function address
7002 static expression_t *parse_call_expression(expression_t *expression)
7004 expression_t *result = allocate_expression_zero(EXPR_CALL);
7005 call_expression_t *call = &result->call;
7006 call->function = expression;
7008 type_t *const orig_type = expression->base.type;
7009 type_t *const type = skip_typeref(orig_type);
7011 function_type_t *function_type = NULL;
7012 if (is_type_pointer(type)) {
7013 type_t *const to_type = skip_typeref(type->pointer.points_to);
7015 if (is_type_function(to_type)) {
7016 function_type = &to_type->function;
7017 call->base.type = function_type->return_type;
7021 if (function_type == NULL && is_type_valid(type)) {
7023 "called object '%E' (type '%T') is not a pointer to a function",
7024 expression, orig_type);
7027 /* parse arguments */
7029 add_anchor_token(')');
7030 add_anchor_token(',');
7032 if (token.kind != ')') {
7033 call_argument_t **anchor = &call->arguments;
7035 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7036 argument->expression = parse_assignment_expression();
7039 anchor = &argument->next;
7040 } while (next_if(','));
7042 rem_anchor_token(',');
7043 rem_anchor_token(')');
7046 if (function_type == NULL)
7049 /* check type and count of call arguments */
7050 function_parameter_t *parameter = function_type->parameters;
7051 call_argument_t *argument = call->arguments;
7052 if (!function_type->unspecified_parameters) {
7053 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7054 parameter = parameter->next, argument = argument->next) {
7055 check_call_argument(parameter->type, argument, ++pos);
7058 if (parameter != NULL) {
7059 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7060 } else if (argument != NULL && !function_type->variadic) {
7061 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7065 /* do default promotion for other arguments */
7066 for (; argument != NULL; argument = argument->next) {
7067 type_t *argument_type = argument->expression->base.type;
7068 if (!is_type_object(skip_typeref(argument_type))) {
7069 errorf(&argument->expression->base.source_position,
7070 "call argument '%E' must not be void", argument->expression);
7073 argument_type = get_default_promoted_type(argument_type);
7075 argument->expression
7076 = create_implicit_cast(argument->expression, argument_type);
7081 if (is_type_compound(skip_typeref(function_type->return_type))) {
7082 source_position_t const *const pos = &expression->base.source_position;
7083 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7086 if (expression->kind == EXPR_REFERENCE) {
7087 reference_expression_t *reference = &expression->reference;
7088 if (reference->entity->kind == ENTITY_FUNCTION &&
7089 reference->entity->function.btk != BUILTIN_NONE)
7090 handle_builtin_argument_restrictions(call);
7096 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7098 static bool same_compound_type(const type_t *type1, const type_t *type2)
7101 is_type_compound(type1) &&
7102 type1->kind == type2->kind &&
7103 type1->compound.compound == type2->compound.compound;
7106 static expression_t const *get_reference_address(expression_t const *expr)
7108 bool regular_take_address = true;
7110 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7111 expr = expr->unary.value;
7113 regular_take_address = false;
7116 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7119 expr = expr->unary.value;
7122 if (expr->kind != EXPR_REFERENCE)
7125 /* special case for functions which are automatically converted to a
7126 * pointer to function without an extra TAKE_ADDRESS operation */
7127 if (!regular_take_address &&
7128 expr->reference.entity->kind != ENTITY_FUNCTION) {
7135 static void warn_reference_address_as_bool(expression_t const* expr)
7137 expr = get_reference_address(expr);
7139 source_position_t const *const pos = &expr->base.source_position;
7140 entity_t const *const ent = expr->reference.entity;
7141 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7145 static void warn_assignment_in_condition(const expression_t *const expr)
7147 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7149 if (expr->base.parenthesized)
7151 source_position_t const *const pos = &expr->base.source_position;
7152 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7155 static void semantic_condition(expression_t const *const expr,
7156 char const *const context)
7158 type_t *const type = skip_typeref(expr->base.type);
7159 if (is_type_scalar(type)) {
7160 warn_reference_address_as_bool(expr);
7161 warn_assignment_in_condition(expr);
7162 } else if (is_type_valid(type)) {
7163 errorf(&expr->base.source_position,
7164 "%s must have scalar type", context);
7169 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7171 * @param expression the conditional expression
7173 static expression_t *parse_conditional_expression(expression_t *expression)
7175 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7177 conditional_expression_t *conditional = &result->conditional;
7178 conditional->condition = expression;
7181 add_anchor_token(':');
7183 /* §6.5.15:2 The first operand shall have scalar type. */
7184 semantic_condition(expression, "condition of conditional operator");
7186 expression_t *true_expression = expression;
7187 bool gnu_cond = false;
7188 if (GNU_MODE && token.kind == ':') {
7191 true_expression = parse_expression();
7193 rem_anchor_token(':');
7195 expression_t *false_expression =
7196 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7198 type_t *const orig_true_type = true_expression->base.type;
7199 type_t *const orig_false_type = false_expression->base.type;
7200 type_t *const true_type = skip_typeref(orig_true_type);
7201 type_t *const false_type = skip_typeref(orig_false_type);
7204 source_position_t const *const pos = &conditional->base.source_position;
7205 type_t *result_type;
7206 if (is_type_void(true_type) || is_type_void(false_type)) {
7207 /* ISO/IEC 14882:1998(E) §5.16:2 */
7208 if (true_expression->kind == EXPR_UNARY_THROW) {
7209 result_type = false_type;
7210 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7211 result_type = true_type;
7213 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7214 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7216 result_type = type_void;
7218 } else if (is_type_arithmetic(true_type)
7219 && is_type_arithmetic(false_type)) {
7220 result_type = semantic_arithmetic(true_type, false_type);
7221 } else if (same_compound_type(true_type, false_type)) {
7222 /* just take 1 of the 2 types */
7223 result_type = true_type;
7224 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7225 type_t *pointer_type;
7227 expression_t *other_expression;
7228 if (is_type_pointer(true_type) &&
7229 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7230 pointer_type = true_type;
7231 other_type = false_type;
7232 other_expression = false_expression;
7234 pointer_type = false_type;
7235 other_type = true_type;
7236 other_expression = true_expression;
7239 if (is_null_pointer_constant(other_expression)) {
7240 result_type = pointer_type;
7241 } else if (is_type_pointer(other_type)) {
7242 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7243 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7246 if (is_type_void(to1) || is_type_void(to2)) {
7248 } else if (types_compatible(get_unqualified_type(to1),
7249 get_unqualified_type(to2))) {
7252 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7256 type_t *const type =
7257 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7258 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7259 } else if (is_type_integer(other_type)) {
7260 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7261 result_type = pointer_type;
7263 goto types_incompatible;
7267 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7268 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7270 result_type = type_error_type;
7273 conditional->true_expression
7274 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7275 conditional->false_expression
7276 = create_implicit_cast(false_expression, result_type);
7277 conditional->base.type = result_type;
7282 * Parse an extension expression.
7284 static expression_t *parse_extension(void)
7287 expression_t *expression = parse_subexpression(PREC_UNARY);
7293 * Parse a __builtin_classify_type() expression.
7295 static expression_t *parse_builtin_classify_type(void)
7297 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7298 result->base.type = type_int;
7300 eat(T___builtin_classify_type);
7302 add_anchor_token(')');
7304 expression_t *expression = parse_expression();
7305 rem_anchor_token(')');
7307 result->classify_type.type_expression = expression;
7313 * Parse a delete expression
7314 * ISO/IEC 14882:1998(E) §5.3.5
7316 static expression_t *parse_delete(void)
7318 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7319 result->base.type = type_void;
7324 result->kind = EXPR_UNARY_DELETE_ARRAY;
7328 expression_t *const value = parse_subexpression(PREC_CAST);
7329 result->unary.value = value;
7331 type_t *const type = skip_typeref(value->base.type);
7332 if (!is_type_pointer(type)) {
7333 if (is_type_valid(type)) {
7334 errorf(&value->base.source_position,
7335 "operand of delete must have pointer type");
7337 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7338 source_position_t const *const pos = &value->base.source_position;
7339 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7346 * Parse a throw expression
7347 * ISO/IEC 14882:1998(E) §15:1
7349 static expression_t *parse_throw(void)
7351 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7352 result->base.type = type_void;
7356 expression_t *value = NULL;
7357 switch (token.kind) {
7359 value = parse_assignment_expression();
7360 /* ISO/IEC 14882:1998(E) §15.1:3 */
7361 type_t *const orig_type = value->base.type;
7362 type_t *const type = skip_typeref(orig_type);
7363 if (is_type_incomplete(type)) {
7364 errorf(&value->base.source_position,
7365 "cannot throw object of incomplete type '%T'", orig_type);
7366 } else if (is_type_pointer(type)) {
7367 type_t *const points_to = skip_typeref(type->pointer.points_to);
7368 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7369 errorf(&value->base.source_position,
7370 "cannot throw pointer to incomplete type '%T'", orig_type);
7378 result->unary.value = value;
7383 static bool check_pointer_arithmetic(const source_position_t *source_position,
7384 type_t *pointer_type,
7385 type_t *orig_pointer_type)
7387 type_t *points_to = pointer_type->pointer.points_to;
7388 points_to = skip_typeref(points_to);
7390 if (is_type_incomplete(points_to)) {
7391 if (!GNU_MODE || !is_type_void(points_to)) {
7392 errorf(source_position,
7393 "arithmetic with pointer to incomplete type '%T' not allowed",
7397 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7399 } else if (is_type_function(points_to)) {
7401 errorf(source_position,
7402 "arithmetic with pointer to function type '%T' not allowed",
7406 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7412 static bool is_lvalue(const expression_t *expression)
7414 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7415 switch (expression->kind) {
7416 case EXPR_ARRAY_ACCESS:
7417 case EXPR_COMPOUND_LITERAL:
7418 case EXPR_REFERENCE:
7420 case EXPR_UNARY_DEREFERENCE:
7424 type_t *type = skip_typeref(expression->base.type);
7426 /* ISO/IEC 14882:1998(E) §3.10:3 */
7427 is_type_reference(type) ||
7428 /* Claim it is an lvalue, if the type is invalid. There was a parse
7429 * error before, which maybe prevented properly recognizing it as
7431 !is_type_valid(type);
7436 static void semantic_incdec(unary_expression_t *expression)
7438 type_t *const orig_type = expression->value->base.type;
7439 type_t *const type = skip_typeref(orig_type);
7440 if (is_type_pointer(type)) {
7441 if (!check_pointer_arithmetic(&expression->base.source_position,
7445 } else if (!is_type_real(type) && is_type_valid(type)) {
7446 /* TODO: improve error message */
7447 errorf(&expression->base.source_position,
7448 "operation needs an arithmetic or pointer type");
7451 if (!is_lvalue(expression->value)) {
7452 /* TODO: improve error message */
7453 errorf(&expression->base.source_position, "lvalue required as operand");
7455 expression->base.type = orig_type;
7458 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7460 type_t *const res_type = promote_integer(type);
7461 expr->base.type = res_type;
7462 expr->value = create_implicit_cast(expr->value, res_type);
7465 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7467 type_t *const orig_type = expression->value->base.type;
7468 type_t *const type = skip_typeref(orig_type);
7469 if (!is_type_arithmetic(type)) {
7470 if (is_type_valid(type)) {
7471 /* TODO: improve error message */
7472 errorf(&expression->base.source_position,
7473 "operation needs an arithmetic type");
7476 } else if (is_type_integer(type)) {
7477 promote_unary_int_expr(expression, type);
7479 expression->base.type = orig_type;
7483 static void semantic_unexpr_plus(unary_expression_t *expression)
7485 semantic_unexpr_arithmetic(expression);
7486 source_position_t const *const pos = &expression->base.source_position;
7487 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7490 static void semantic_not(unary_expression_t *expression)
7492 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7493 semantic_condition(expression->value, "operand of !");
7494 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7497 static void semantic_unexpr_integer(unary_expression_t *expression)
7499 type_t *const orig_type = expression->value->base.type;
7500 type_t *const type = skip_typeref(orig_type);
7501 if (!is_type_integer(type)) {
7502 if (is_type_valid(type)) {
7503 errorf(&expression->base.source_position,
7504 "operand of ~ must be of integer type");
7509 promote_unary_int_expr(expression, type);
7512 static void semantic_dereference(unary_expression_t *expression)
7514 type_t *const orig_type = expression->value->base.type;
7515 type_t *const type = skip_typeref(orig_type);
7516 if (!is_type_pointer(type)) {
7517 if (is_type_valid(type)) {
7518 errorf(&expression->base.source_position,
7519 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7524 type_t *result_type = type->pointer.points_to;
7525 result_type = automatic_type_conversion(result_type);
7526 expression->base.type = result_type;
7530 * Record that an address is taken (expression represents an lvalue).
7532 * @param expression the expression
7533 * @param may_be_register if true, the expression might be an register
7535 static void set_address_taken(expression_t *expression, bool may_be_register)
7537 if (expression->kind != EXPR_REFERENCE)
7540 entity_t *const entity = expression->reference.entity;
7542 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7545 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7546 && !may_be_register) {
7547 source_position_t const *const pos = &expression->base.source_position;
7548 errorf(pos, "address of register '%N' requested", entity);
7551 entity->variable.address_taken = true;
7555 * Check the semantic of the address taken expression.
7557 static void semantic_take_addr(unary_expression_t *expression)
7559 expression_t *value = expression->value;
7560 value->base.type = revert_automatic_type_conversion(value);
7562 type_t *orig_type = value->base.type;
7563 type_t *type = skip_typeref(orig_type);
7564 if (!is_type_valid(type))
7568 if (!is_lvalue(value)) {
7569 errorf(&expression->base.source_position, "'&' requires an lvalue");
7571 if (is_bitfield(value)) {
7572 errorf(&expression->base.source_position,
7573 "'&' not allowed on bitfield");
7576 set_address_taken(value, false);
7578 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7581 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7582 static expression_t *parse_##unexpression_type(void) \
7584 expression_t *unary_expression \
7585 = allocate_expression_zero(unexpression_type); \
7587 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7589 sfunc(&unary_expression->unary); \
7591 return unary_expression; \
7594 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7595 semantic_unexpr_arithmetic)
7596 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7597 semantic_unexpr_plus)
7598 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7600 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7601 semantic_dereference)
7602 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7604 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7605 semantic_unexpr_integer)
7606 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7608 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7611 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7613 static expression_t *parse_##unexpression_type(expression_t *left) \
7615 expression_t *unary_expression \
7616 = allocate_expression_zero(unexpression_type); \
7618 unary_expression->unary.value = left; \
7620 sfunc(&unary_expression->unary); \
7622 return unary_expression; \
7625 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7626 EXPR_UNARY_POSTFIX_INCREMENT,
7628 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7629 EXPR_UNARY_POSTFIX_DECREMENT,
7632 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7634 /* TODO: handle complex + imaginary types */
7636 type_left = get_unqualified_type(type_left);
7637 type_right = get_unqualified_type(type_right);
7639 /* §6.3.1.8 Usual arithmetic conversions */
7640 if (type_left == type_long_double || type_right == type_long_double) {
7641 return type_long_double;
7642 } else if (type_left == type_double || type_right == type_double) {
7644 } else if (type_left == type_float || type_right == type_float) {
7648 type_left = promote_integer(type_left);
7649 type_right = promote_integer(type_right);
7651 if (type_left == type_right)
7654 bool const signed_left = is_type_signed(type_left);
7655 bool const signed_right = is_type_signed(type_right);
7656 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7657 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7659 if (signed_left == signed_right)
7660 return rank_left >= rank_right ? type_left : type_right;
7664 atomic_type_kind_t s_akind;
7665 atomic_type_kind_t u_akind;
7670 u_type = type_right;
7672 s_type = type_right;
7675 s_akind = get_akind(s_type);
7676 u_akind = get_akind(u_type);
7677 s_rank = get_akind_rank(s_akind);
7678 u_rank = get_akind_rank(u_akind);
7680 if (u_rank >= s_rank)
7683 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7687 case ATOMIC_TYPE_INT: return type_unsigned_int;
7688 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7689 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7691 default: panic("invalid atomic type");
7696 * Check the semantic restrictions for a binary expression.
7698 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7700 expression_t *const left = expression->left;
7701 expression_t *const right = expression->right;
7702 type_t *const orig_type_left = left->base.type;
7703 type_t *const orig_type_right = right->base.type;
7704 type_t *const type_left = skip_typeref(orig_type_left);
7705 type_t *const type_right = skip_typeref(orig_type_right);
7707 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7708 /* TODO: improve error message */
7709 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7710 errorf(&expression->base.source_position,
7711 "operation needs arithmetic types");
7716 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7717 expression->left = create_implicit_cast(left, arithmetic_type);
7718 expression->right = create_implicit_cast(right, arithmetic_type);
7719 expression->base.type = arithmetic_type;
7722 static void semantic_binexpr_integer(binary_expression_t *const expression)
7724 expression_t *const left = expression->left;
7725 expression_t *const right = expression->right;
7726 type_t *const orig_type_left = left->base.type;
7727 type_t *const orig_type_right = right->base.type;
7728 type_t *const type_left = skip_typeref(orig_type_left);
7729 type_t *const type_right = skip_typeref(orig_type_right);
7731 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7732 /* TODO: improve error message */
7733 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7734 errorf(&expression->base.source_position,
7735 "operation needs integer types");
7740 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7741 expression->left = create_implicit_cast(left, result_type);
7742 expression->right = create_implicit_cast(right, result_type);
7743 expression->base.type = result_type;
7746 static void warn_div_by_zero(binary_expression_t const *const expression)
7748 if (!is_type_integer(expression->base.type))
7751 expression_t const *const right = expression->right;
7752 /* The type of the right operand can be different for /= */
7753 if (is_type_integer(right->base.type) &&
7754 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7755 !fold_constant_to_bool(right)) {
7756 source_position_t const *const pos = &expression->base.source_position;
7757 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7762 * Check the semantic restrictions for a div/mod expression.
7764 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7766 semantic_binexpr_arithmetic(expression);
7767 warn_div_by_zero(expression);
7770 static void warn_addsub_in_shift(const expression_t *const expr)
7772 if (expr->base.parenthesized)
7776 switch (expr->kind) {
7777 case EXPR_BINARY_ADD: op = '+'; break;
7778 case EXPR_BINARY_SUB: op = '-'; break;
7782 source_position_t const *const pos = &expr->base.source_position;
7783 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7786 static bool semantic_shift(binary_expression_t *expression)
7788 expression_t *const left = expression->left;
7789 expression_t *const right = expression->right;
7790 type_t *const orig_type_left = left->base.type;
7791 type_t *const orig_type_right = right->base.type;
7792 type_t * type_left = skip_typeref(orig_type_left);
7793 type_t * type_right = skip_typeref(orig_type_right);
7795 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7796 /* TODO: improve error message */
7797 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7798 errorf(&expression->base.source_position,
7799 "operands of shift operation must have integer types");
7804 type_left = promote_integer(type_left);
7806 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7807 source_position_t const *const pos = &right->base.source_position;
7808 long const count = fold_constant_to_int(right);
7810 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7811 } else if ((unsigned long)count >=
7812 get_atomic_type_size(type_left->atomic.akind) * 8) {
7813 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7817 type_right = promote_integer(type_right);
7818 expression->right = create_implicit_cast(right, type_right);
7823 static void semantic_shift_op(binary_expression_t *expression)
7825 expression_t *const left = expression->left;
7826 expression_t *const right = expression->right;
7828 if (!semantic_shift(expression))
7831 warn_addsub_in_shift(left);
7832 warn_addsub_in_shift(right);
7834 type_t *const orig_type_left = left->base.type;
7835 type_t * type_left = skip_typeref(orig_type_left);
7837 type_left = promote_integer(type_left);
7838 expression->left = create_implicit_cast(left, type_left);
7839 expression->base.type = type_left;
7842 static void semantic_add(binary_expression_t *expression)
7844 expression_t *const left = expression->left;
7845 expression_t *const right = expression->right;
7846 type_t *const orig_type_left = left->base.type;
7847 type_t *const orig_type_right = right->base.type;
7848 type_t *const type_left = skip_typeref(orig_type_left);
7849 type_t *const type_right = skip_typeref(orig_type_right);
7852 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7853 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7854 expression->left = create_implicit_cast(left, arithmetic_type);
7855 expression->right = create_implicit_cast(right, arithmetic_type);
7856 expression->base.type = arithmetic_type;
7857 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7858 check_pointer_arithmetic(&expression->base.source_position,
7859 type_left, orig_type_left);
7860 expression->base.type = type_left;
7861 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
7862 check_pointer_arithmetic(&expression->base.source_position,
7863 type_right, orig_type_right);
7864 expression->base.type = type_right;
7865 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7866 errorf(&expression->base.source_position,
7867 "invalid operands to binary + ('%T', '%T')",
7868 orig_type_left, orig_type_right);
7872 static void semantic_sub(binary_expression_t *expression)
7874 expression_t *const left = expression->left;
7875 expression_t *const right = expression->right;
7876 type_t *const orig_type_left = left->base.type;
7877 type_t *const orig_type_right = right->base.type;
7878 type_t *const type_left = skip_typeref(orig_type_left);
7879 type_t *const type_right = skip_typeref(orig_type_right);
7880 source_position_t const *const pos = &expression->base.source_position;
7883 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7884 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7885 expression->left = create_implicit_cast(left, arithmetic_type);
7886 expression->right = create_implicit_cast(right, arithmetic_type);
7887 expression->base.type = arithmetic_type;
7888 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
7889 check_pointer_arithmetic(&expression->base.source_position,
7890 type_left, orig_type_left);
7891 expression->base.type = type_left;
7892 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
7893 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
7894 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
7895 if (!types_compatible(unqual_left, unqual_right)) {
7897 "subtracting pointers to incompatible types '%T' and '%T'",
7898 orig_type_left, orig_type_right);
7899 } else if (!is_type_object(unqual_left)) {
7900 if (!is_type_void(unqual_left)) {
7901 errorf(pos, "subtracting pointers to non-object types '%T'",
7904 warningf(WARN_OTHER, pos, "subtracting pointers to void");
7907 expression->base.type = type_ptrdiff_t;
7908 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
7909 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
7910 orig_type_left, orig_type_right);
7914 static void warn_string_literal_address(expression_t const* expr)
7916 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7917 expr = expr->unary.value;
7918 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7920 expr = expr->unary.value;
7923 if (expr->kind == EXPR_STRING_LITERAL) {
7924 source_position_t const *const pos = &expr->base.source_position;
7925 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
7929 static bool maybe_negative(expression_t const *const expr)
7931 switch (is_constant_expression(expr)) {
7932 case EXPR_CLASS_ERROR: return false;
7933 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
7934 default: return true;
7938 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
7940 warn_string_literal_address(expr);
7942 expression_t const* const ref = get_reference_address(expr);
7943 if (ref != NULL && is_null_pointer_constant(other)) {
7944 entity_t const *const ent = ref->reference.entity;
7945 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
7948 if (!expr->base.parenthesized) {
7949 switch (expr->base.kind) {
7950 case EXPR_BINARY_LESS:
7951 case EXPR_BINARY_GREATER:
7952 case EXPR_BINARY_LESSEQUAL:
7953 case EXPR_BINARY_GREATEREQUAL:
7954 case EXPR_BINARY_NOTEQUAL:
7955 case EXPR_BINARY_EQUAL:
7956 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
7965 * Check the semantics of comparison expressions.
7967 * @param expression The expression to check.
7969 static void semantic_comparison(binary_expression_t *expression)
7971 source_position_t const *const pos = &expression->base.source_position;
7972 expression_t *const left = expression->left;
7973 expression_t *const right = expression->right;
7975 warn_comparison(pos, left, right);
7976 warn_comparison(pos, right, left);
7978 type_t *orig_type_left = left->base.type;
7979 type_t *orig_type_right = right->base.type;
7980 type_t *type_left = skip_typeref(orig_type_left);
7981 type_t *type_right = skip_typeref(orig_type_right);
7983 /* TODO non-arithmetic types */
7984 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
7985 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7987 /* test for signed vs unsigned compares */
7988 if (is_type_integer(arithmetic_type)) {
7989 bool const signed_left = is_type_signed(type_left);
7990 bool const signed_right = is_type_signed(type_right);
7991 if (signed_left != signed_right) {
7992 /* FIXME long long needs better const folding magic */
7993 /* TODO check whether constant value can be represented by other type */
7994 if ((signed_left && maybe_negative(left)) ||
7995 (signed_right && maybe_negative(right))) {
7996 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8001 expression->left = create_implicit_cast(left, arithmetic_type);
8002 expression->right = create_implicit_cast(right, arithmetic_type);
8003 expression->base.type = arithmetic_type;
8004 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8005 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8006 is_type_float(arithmetic_type)) {
8007 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8009 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8010 /* TODO check compatibility */
8011 } else if (is_type_pointer(type_left)) {
8012 expression->right = create_implicit_cast(right, type_left);
8013 } else if (is_type_pointer(type_right)) {
8014 expression->left = create_implicit_cast(left, type_right);
8015 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8016 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8018 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8022 * Checks if a compound type has constant fields.
8024 static bool has_const_fields(const compound_type_t *type)
8026 compound_t *compound = type->compound;
8027 entity_t *entry = compound->members.entities;
8029 for (; entry != NULL; entry = entry->base.next) {
8030 if (!is_declaration(entry))
8033 const type_t *decl_type = skip_typeref(entry->declaration.type);
8034 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8041 static bool is_valid_assignment_lhs(expression_t const* const left)
8043 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8044 type_t *const type_left = skip_typeref(orig_type_left);
8046 if (!is_lvalue(left)) {
8047 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8052 if (left->kind == EXPR_REFERENCE
8053 && left->reference.entity->kind == ENTITY_FUNCTION) {
8054 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8058 if (is_type_array(type_left)) {
8059 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8062 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8063 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8067 if (is_type_incomplete(type_left)) {
8068 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8069 left, orig_type_left);
8072 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8073 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8074 left, orig_type_left);
8081 static void semantic_arithmetic_assign(binary_expression_t *expression)
8083 expression_t *left = expression->left;
8084 expression_t *right = expression->right;
8085 type_t *orig_type_left = left->base.type;
8086 type_t *orig_type_right = right->base.type;
8088 if (!is_valid_assignment_lhs(left))
8091 type_t *type_left = skip_typeref(orig_type_left);
8092 type_t *type_right = skip_typeref(orig_type_right);
8094 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8095 /* TODO: improve error message */
8096 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8097 errorf(&expression->base.source_position,
8098 "operation needs arithmetic types");
8103 /* combined instructions are tricky. We can't create an implicit cast on
8104 * the left side, because we need the uncasted form for the store.
8105 * The ast2firm pass has to know that left_type must be right_type
8106 * for the arithmetic operation and create a cast by itself */
8107 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8108 expression->right = create_implicit_cast(right, arithmetic_type);
8109 expression->base.type = type_left;
8112 static void semantic_divmod_assign(binary_expression_t *expression)
8114 semantic_arithmetic_assign(expression);
8115 warn_div_by_zero(expression);
8118 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8120 expression_t *const left = expression->left;
8121 expression_t *const right = expression->right;
8122 type_t *const orig_type_left = left->base.type;
8123 type_t *const orig_type_right = right->base.type;
8124 type_t *const type_left = skip_typeref(orig_type_left);
8125 type_t *const type_right = skip_typeref(orig_type_right);
8127 if (!is_valid_assignment_lhs(left))
8130 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8131 /* combined instructions are tricky. We can't create an implicit cast on
8132 * the left side, because we need the uncasted form for the store.
8133 * The ast2firm pass has to know that left_type must be right_type
8134 * for the arithmetic operation and create a cast by itself */
8135 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8136 expression->right = create_implicit_cast(right, arithmetic_type);
8137 expression->base.type = type_left;
8138 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8139 check_pointer_arithmetic(&expression->base.source_position,
8140 type_left, orig_type_left);
8141 expression->base.type = type_left;
8142 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8143 errorf(&expression->base.source_position,
8144 "incompatible types '%T' and '%T' in assignment",
8145 orig_type_left, orig_type_right);
8149 static void semantic_integer_assign(binary_expression_t *expression)
8151 expression_t *left = expression->left;
8152 expression_t *right = expression->right;
8153 type_t *orig_type_left = left->base.type;
8154 type_t *orig_type_right = right->base.type;
8156 if (!is_valid_assignment_lhs(left))
8159 type_t *type_left = skip_typeref(orig_type_left);
8160 type_t *type_right = skip_typeref(orig_type_right);
8162 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8163 /* TODO: improve error message */
8164 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8165 errorf(&expression->base.source_position,
8166 "operation needs integer types");
8171 /* combined instructions are tricky. We can't create an implicit cast on
8172 * the left side, because we need the uncasted form for the store.
8173 * The ast2firm pass has to know that left_type must be right_type
8174 * for the arithmetic operation and create a cast by itself */
8175 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8176 expression->right = create_implicit_cast(right, arithmetic_type);
8177 expression->base.type = type_left;
8180 static void semantic_shift_assign(binary_expression_t *expression)
8182 expression_t *left = expression->left;
8184 if (!is_valid_assignment_lhs(left))
8187 if (!semantic_shift(expression))
8190 expression->base.type = skip_typeref(left->base.type);
8193 static void warn_logical_and_within_or(const expression_t *const expr)
8195 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8197 if (expr->base.parenthesized)
8199 source_position_t const *const pos = &expr->base.source_position;
8200 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8204 * Check the semantic restrictions of a logical expression.
8206 static void semantic_logical_op(binary_expression_t *expression)
8208 /* §6.5.13:2 Each of the operands shall have scalar type.
8209 * §6.5.14:2 Each of the operands shall have scalar type. */
8210 semantic_condition(expression->left, "left operand of logical operator");
8211 semantic_condition(expression->right, "right operand of logical operator");
8212 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8213 warn_logical_and_within_or(expression->left);
8214 warn_logical_and_within_or(expression->right);
8216 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8220 * Check the semantic restrictions of a binary assign expression.
8222 static void semantic_binexpr_assign(binary_expression_t *expression)
8224 expression_t *left = expression->left;
8225 type_t *orig_type_left = left->base.type;
8227 if (!is_valid_assignment_lhs(left))
8230 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8231 report_assign_error(error, orig_type_left, expression->right,
8232 "assignment", &left->base.source_position);
8233 expression->right = create_implicit_cast(expression->right, orig_type_left);
8234 expression->base.type = orig_type_left;
8238 * Determine if the outermost operation (or parts thereof) of the given
8239 * expression has no effect in order to generate a warning about this fact.
8240 * Therefore in some cases this only examines some of the operands of the
8241 * expression (see comments in the function and examples below).
8243 * f() + 23; // warning, because + has no effect
8244 * x || f(); // no warning, because x controls execution of f()
8245 * x ? y : f(); // warning, because y has no effect
8246 * (void)x; // no warning to be able to suppress the warning
8247 * This function can NOT be used for an "expression has definitely no effect"-
8249 static bool expression_has_effect(const expression_t *const expr)
8251 switch (expr->kind) {
8252 case EXPR_ERROR: return true; /* do NOT warn */
8253 case EXPR_REFERENCE: return false;
8254 case EXPR_ENUM_CONSTANT: return false;
8255 case EXPR_LABEL_ADDRESS: return false;
8257 /* suppress the warning for microsoft __noop operations */
8258 case EXPR_LITERAL_MS_NOOP: return true;
8259 case EXPR_LITERAL_BOOLEAN:
8260 case EXPR_LITERAL_CHARACTER:
8261 case EXPR_LITERAL_INTEGER:
8262 case EXPR_LITERAL_FLOATINGPOINT:
8263 case EXPR_STRING_LITERAL: return false;
8266 const call_expression_t *const call = &expr->call;
8267 if (call->function->kind != EXPR_REFERENCE)
8270 switch (call->function->reference.entity->function.btk) {
8271 /* FIXME: which builtins have no effect? */
8272 default: return true;
8276 /* Generate the warning if either the left or right hand side of a
8277 * conditional expression has no effect */
8278 case EXPR_CONDITIONAL: {
8279 conditional_expression_t const *const cond = &expr->conditional;
8280 expression_t const *const t = cond->true_expression;
8282 (t == NULL || expression_has_effect(t)) &&
8283 expression_has_effect(cond->false_expression);
8286 case EXPR_SELECT: return false;
8287 case EXPR_ARRAY_ACCESS: return false;
8288 case EXPR_SIZEOF: return false;
8289 case EXPR_CLASSIFY_TYPE: return false;
8290 case EXPR_ALIGNOF: return false;
8292 case EXPR_FUNCNAME: return false;
8293 case EXPR_BUILTIN_CONSTANT_P: return false;
8294 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8295 case EXPR_OFFSETOF: return false;
8296 case EXPR_VA_START: return true;
8297 case EXPR_VA_ARG: return true;
8298 case EXPR_VA_COPY: return true;
8299 case EXPR_STATEMENT: return true; // TODO
8300 case EXPR_COMPOUND_LITERAL: return false;
8302 case EXPR_UNARY_NEGATE: return false;
8303 case EXPR_UNARY_PLUS: return false;
8304 case EXPR_UNARY_BITWISE_NEGATE: return false;
8305 case EXPR_UNARY_NOT: return false;
8306 case EXPR_UNARY_DEREFERENCE: return false;
8307 case EXPR_UNARY_TAKE_ADDRESS: return false;
8308 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8309 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8310 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8311 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8313 /* Treat void casts as if they have an effect in order to being able to
8314 * suppress the warning */
8315 case EXPR_UNARY_CAST: {
8316 type_t *const type = skip_typeref(expr->base.type);
8317 return is_type_void(type);
8320 case EXPR_UNARY_ASSUME: return true;
8321 case EXPR_UNARY_DELETE: return true;
8322 case EXPR_UNARY_DELETE_ARRAY: return true;
8323 case EXPR_UNARY_THROW: return true;
8325 case EXPR_BINARY_ADD: return false;
8326 case EXPR_BINARY_SUB: return false;
8327 case EXPR_BINARY_MUL: return false;
8328 case EXPR_BINARY_DIV: return false;
8329 case EXPR_BINARY_MOD: return false;
8330 case EXPR_BINARY_EQUAL: return false;
8331 case EXPR_BINARY_NOTEQUAL: return false;
8332 case EXPR_BINARY_LESS: return false;
8333 case EXPR_BINARY_LESSEQUAL: return false;
8334 case EXPR_BINARY_GREATER: return false;
8335 case EXPR_BINARY_GREATEREQUAL: return false;
8336 case EXPR_BINARY_BITWISE_AND: return false;
8337 case EXPR_BINARY_BITWISE_OR: return false;
8338 case EXPR_BINARY_BITWISE_XOR: return false;
8339 case EXPR_BINARY_SHIFTLEFT: return false;
8340 case EXPR_BINARY_SHIFTRIGHT: return false;
8341 case EXPR_BINARY_ASSIGN: return true;
8342 case EXPR_BINARY_MUL_ASSIGN: return true;
8343 case EXPR_BINARY_DIV_ASSIGN: return true;
8344 case EXPR_BINARY_MOD_ASSIGN: return true;
8345 case EXPR_BINARY_ADD_ASSIGN: return true;
8346 case EXPR_BINARY_SUB_ASSIGN: return true;
8347 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8348 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8349 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8350 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8351 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8353 /* Only examine the right hand side of && and ||, because the left hand
8354 * side already has the effect of controlling the execution of the right
8356 case EXPR_BINARY_LOGICAL_AND:
8357 case EXPR_BINARY_LOGICAL_OR:
8358 /* Only examine the right hand side of a comma expression, because the left
8359 * hand side has a separate warning */
8360 case EXPR_BINARY_COMMA:
8361 return expression_has_effect(expr->binary.right);
8363 case EXPR_BINARY_ISGREATER: return false;
8364 case EXPR_BINARY_ISGREATEREQUAL: return false;
8365 case EXPR_BINARY_ISLESS: return false;
8366 case EXPR_BINARY_ISLESSEQUAL: return false;
8367 case EXPR_BINARY_ISLESSGREATER: return false;
8368 case EXPR_BINARY_ISUNORDERED: return false;
8371 internal_errorf(HERE, "unexpected expression");
8374 static void semantic_comma(binary_expression_t *expression)
8376 const expression_t *const left = expression->left;
8377 if (!expression_has_effect(left)) {
8378 source_position_t const *const pos = &left->base.source_position;
8379 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8381 expression->base.type = expression->right->base.type;
8385 * @param prec_r precedence of the right operand
8387 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8388 static expression_t *parse_##binexpression_type(expression_t *left) \
8390 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8391 binexpr->binary.left = left; \
8394 expression_t *right = parse_subexpression(prec_r); \
8396 binexpr->binary.right = right; \
8397 sfunc(&binexpr->binary); \
8402 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8403 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8404 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8405 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8406 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8407 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8408 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8409 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8410 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8411 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8412 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8413 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8414 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8415 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8416 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8417 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8418 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8419 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8420 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8421 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8422 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8423 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8424 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8425 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8426 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8427 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8428 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8429 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8430 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8431 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8434 static expression_t *parse_subexpression(precedence_t precedence)
8436 expression_parser_function_t *parser
8437 = &expression_parsers[token.kind];
8440 if (parser->parser != NULL) {
8441 left = parser->parser();
8443 left = parse_primary_expression();
8445 assert(left != NULL);
8448 parser = &expression_parsers[token.kind];
8449 if (parser->infix_parser == NULL)
8451 if (parser->infix_precedence < precedence)
8454 left = parser->infix_parser(left);
8456 assert(left != NULL);
8463 * Parse an expression.
8465 static expression_t *parse_expression(void)
8467 return parse_subexpression(PREC_EXPRESSION);
8471 * Register a parser for a prefix-like operator.
8473 * @param parser the parser function
8474 * @param token_kind the token type of the prefix token
8476 static void register_expression_parser(parse_expression_function parser,
8479 expression_parser_function_t *entry = &expression_parsers[token_kind];
8481 assert(!entry->parser);
8482 entry->parser = parser;
8486 * Register a parser for an infix operator with given precedence.
8488 * @param parser the parser function
8489 * @param token_kind the token type of the infix operator
8490 * @param precedence the precedence of the operator
8492 static void register_infix_parser(parse_expression_infix_function parser,
8493 int token_kind, precedence_t precedence)
8495 expression_parser_function_t *entry = &expression_parsers[token_kind];
8497 assert(!entry->infix_parser);
8498 entry->infix_parser = parser;
8499 entry->infix_precedence = precedence;
8503 * Initialize the expression parsers.
8505 static void init_expression_parsers(void)
8507 memset(&expression_parsers, 0, sizeof(expression_parsers));
8509 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8510 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8511 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8512 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8513 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8514 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8515 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8516 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8517 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8518 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8519 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8520 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8521 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8522 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8523 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8524 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8525 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8526 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8527 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8528 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8529 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8530 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8531 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8532 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8533 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8534 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8535 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8536 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8537 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8538 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8539 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8540 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8541 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8542 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8543 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8544 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8545 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8547 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8548 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8549 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8550 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8551 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8552 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8553 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8554 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8555 register_expression_parser(parse_sizeof, T_sizeof);
8556 register_expression_parser(parse_alignof, T___alignof__);
8557 register_expression_parser(parse_extension, T___extension__);
8558 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8559 register_expression_parser(parse_delete, T_delete);
8560 register_expression_parser(parse_throw, T_throw);
8564 * Parse a asm statement arguments specification.
8566 static asm_argument_t *parse_asm_arguments(bool is_out)
8568 asm_argument_t *result = NULL;
8569 asm_argument_t **anchor = &result;
8571 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8572 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8575 add_anchor_token(']');
8576 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8577 rem_anchor_token(']');
8579 if (!argument->symbol)
8583 argument->constraints = parse_string_literals("asm argument");
8584 add_anchor_token(')');
8586 expression_t *expression = parse_expression();
8587 rem_anchor_token(')');
8589 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8590 * change size or type representation (e.g. int -> long is ok, but
8591 * int -> float is not) */
8592 if (expression->kind == EXPR_UNARY_CAST) {
8593 type_t *const type = expression->base.type;
8594 type_kind_t const kind = type->kind;
8595 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8598 if (kind == TYPE_ATOMIC) {
8599 atomic_type_kind_t const akind = type->atomic.akind;
8600 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8601 size = get_atomic_type_size(akind);
8603 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8604 size = get_type_size(type_void_ptr);
8608 expression_t *const value = expression->unary.value;
8609 type_t *const value_type = value->base.type;
8610 type_kind_t const value_kind = value_type->kind;
8612 unsigned value_flags;
8613 unsigned value_size;
8614 if (value_kind == TYPE_ATOMIC) {
8615 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8616 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8617 value_size = get_atomic_type_size(value_akind);
8618 } else if (value_kind == TYPE_POINTER) {
8619 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8620 value_size = get_type_size(type_void_ptr);
8625 if (value_flags != flags || value_size != size)
8629 } while (expression->kind == EXPR_UNARY_CAST);
8633 if (!is_lvalue(expression)) {
8634 errorf(&expression->base.source_position,
8635 "asm output argument is not an lvalue");
8638 if (argument->constraints.begin[0] == '=')
8639 determine_lhs_ent(expression, NULL);
8641 mark_vars_read(expression, NULL);
8643 mark_vars_read(expression, NULL);
8645 argument->expression = expression;
8648 set_address_taken(expression, true);
8651 anchor = &argument->next;
8661 * Parse a asm statement clobber specification.
8663 static asm_clobber_t *parse_asm_clobbers(void)
8665 asm_clobber_t *result = NULL;
8666 asm_clobber_t **anchor = &result;
8668 while (token.kind == T_STRING_LITERAL) {
8669 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8670 clobber->clobber = parse_string_literals(NULL);
8673 anchor = &clobber->next;
8683 * Parse an asm statement.
8685 static statement_t *parse_asm_statement(void)
8687 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8688 asm_statement_t *asm_statement = &statement->asms;
8691 add_anchor_token(')');
8692 add_anchor_token(':');
8693 add_anchor_token(T_STRING_LITERAL);
8695 if (next_if(T_volatile))
8696 asm_statement->is_volatile = true;
8699 rem_anchor_token(T_STRING_LITERAL);
8700 asm_statement->asm_text = parse_string_literals("asm statement");
8703 asm_statement->outputs = parse_asm_arguments(true);
8706 asm_statement->inputs = parse_asm_arguments(false);
8708 rem_anchor_token(':');
8710 asm_statement->clobbers = parse_asm_clobbers();
8712 rem_anchor_token(')');
8716 if (asm_statement->outputs == NULL) {
8717 /* GCC: An 'asm' instruction without any output operands will be treated
8718 * identically to a volatile 'asm' instruction. */
8719 asm_statement->is_volatile = true;
8725 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8727 statement_t *inner_stmt;
8728 switch (token.kind) {
8730 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8731 inner_stmt = create_error_statement();
8735 if (label->kind == STATEMENT_LABEL) {
8736 /* Eat an empty statement here, to avoid the warning about an empty
8737 * statement after a label. label:; is commonly used to have a label
8738 * before a closing brace. */
8739 inner_stmt = create_empty_statement();
8746 inner_stmt = parse_statement();
8747 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8748 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8749 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8750 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8758 * Parse a case statement.
8760 static statement_t *parse_case_statement(void)
8762 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8763 source_position_t *const pos = &statement->base.source_position;
8766 add_anchor_token(':');
8768 expression_t *expression = parse_expression();
8769 type_t *expression_type = expression->base.type;
8770 type_t *skipped = skip_typeref(expression_type);
8771 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8772 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8773 expression, expression_type);
8776 type_t *type = expression_type;
8777 if (current_switch != NULL) {
8778 type_t *switch_type = current_switch->expression->base.type;
8779 if (is_type_valid(switch_type)) {
8780 expression = create_implicit_cast(expression, switch_type);
8784 statement->case_label.expression = expression;
8785 expression_classification_t const expr_class = is_constant_expression(expression);
8786 if (expr_class != EXPR_CLASS_CONSTANT) {
8787 if (expr_class != EXPR_CLASS_ERROR) {
8788 errorf(pos, "case label does not reduce to an integer constant");
8790 statement->case_label.is_bad = true;
8792 long const val = fold_constant_to_int(expression);
8793 statement->case_label.first_case = val;
8794 statement->case_label.last_case = val;
8798 if (next_if(T_DOTDOTDOT)) {
8799 expression_t *end_range = parse_expression();
8800 expression_type = expression->base.type;
8801 skipped = skip_typeref(expression_type);
8802 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8803 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8804 expression, expression_type);
8807 end_range = create_implicit_cast(end_range, type);
8808 statement->case_label.end_range = end_range;
8809 expression_classification_t const end_class = is_constant_expression(end_range);
8810 if (end_class != EXPR_CLASS_CONSTANT) {
8811 if (end_class != EXPR_CLASS_ERROR) {
8812 errorf(pos, "case range does not reduce to an integer constant");
8814 statement->case_label.is_bad = true;
8816 long const val = fold_constant_to_int(end_range);
8817 statement->case_label.last_case = val;
8819 if (val < statement->case_label.first_case) {
8820 statement->case_label.is_empty_range = true;
8821 warningf(WARN_OTHER, pos, "empty range specified");
8827 PUSH_PARENT(statement);
8829 rem_anchor_token(':');
8832 if (current_switch != NULL) {
8833 if (! statement->case_label.is_bad) {
8834 /* Check for duplicate case values */
8835 case_label_statement_t *c = &statement->case_label;
8836 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
8837 if (l->is_bad || l->is_empty_range || l->expression == NULL)
8840 if (c->last_case < l->first_case || c->first_case > l->last_case)
8843 errorf(pos, "duplicate case value (previously used %P)",
8844 &l->base.source_position);
8848 /* link all cases into the switch statement */
8849 if (current_switch->last_case == NULL) {
8850 current_switch->first_case = &statement->case_label;
8852 current_switch->last_case->next = &statement->case_label;
8854 current_switch->last_case = &statement->case_label;
8856 errorf(pos, "case label not within a switch statement");
8859 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
8866 * Parse a default statement.
8868 static statement_t *parse_default_statement(void)
8870 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8874 PUSH_PARENT(statement);
8878 if (current_switch != NULL) {
8879 const case_label_statement_t *def_label = current_switch->default_label;
8880 if (def_label != NULL) {
8881 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
8883 current_switch->default_label = &statement->case_label;
8885 /* link all cases into the switch statement */
8886 if (current_switch->last_case == NULL) {
8887 current_switch->first_case = &statement->case_label;
8889 current_switch->last_case->next = &statement->case_label;
8891 current_switch->last_case = &statement->case_label;
8894 errorf(&statement->base.source_position,
8895 "'default' label not within a switch statement");
8898 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
8905 * Parse a label statement.
8907 static statement_t *parse_label_statement(void)
8909 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
8910 label_t *const label = get_label(NULL /* Cannot fail, token is T_IDENTIFIER. */);
8911 statement->label.label = label;
8913 PUSH_PARENT(statement);
8915 /* if statement is already set then the label is defined twice,
8916 * otherwise it was just mentioned in a goto/local label declaration so far
8918 source_position_t const* const pos = &statement->base.source_position;
8919 if (label->statement != NULL) {
8920 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
8922 label->base.source_position = *pos;
8923 label->statement = statement;
8928 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
8929 parse_attributes(NULL); // TODO process attributes
8932 statement->label.statement = parse_label_inner_statement(statement, "label");
8934 /* remember the labels in a list for later checking */
8935 *label_anchor = &statement->label;
8936 label_anchor = &statement->label.next;
8942 static statement_t *parse_inner_statement(void)
8944 statement_t *const stmt = parse_statement();
8945 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8946 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8947 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8948 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
8954 * Parse an expression in parentheses and mark its variables as read.
8956 static expression_t *parse_condition(void)
8958 add_anchor_token(')');
8960 expression_t *const expr = parse_expression();
8961 mark_vars_read(expr, NULL);
8962 rem_anchor_token(')');
8968 * Parse an if statement.
8970 static statement_t *parse_if(void)
8972 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
8976 PUSH_PARENT(statement);
8977 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
8979 add_anchor_token(T_else);
8981 expression_t *const expr = parse_condition();
8982 statement->ifs.condition = expr;
8983 /* §6.8.4.1:1 The controlling expression of an if statement shall have
8985 semantic_condition(expr, "condition of 'if'-statment");
8987 statement_t *const true_stmt = parse_inner_statement();
8988 statement->ifs.true_statement = true_stmt;
8989 rem_anchor_token(T_else);
8991 if (true_stmt->kind == STATEMENT_EMPTY) {
8992 warningf(WARN_EMPTY_BODY, HERE,
8993 "suggest braces around empty body in an ‘if’ statement");
8996 if (next_if(T_else)) {
8997 statement->ifs.false_statement = parse_inner_statement();
8999 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9000 warningf(WARN_EMPTY_BODY, HERE,
9001 "suggest braces around empty body in an ‘if’ statement");
9003 } else if (true_stmt->kind == STATEMENT_IF &&
9004 true_stmt->ifs.false_statement != NULL) {
9005 source_position_t const *const pos = &true_stmt->base.source_position;
9006 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9015 * Check that all enums are handled in a switch.
9017 * @param statement the switch statement to check
9019 static void check_enum_cases(const switch_statement_t *statement)
9021 if (!is_warn_on(WARN_SWITCH_ENUM))
9023 const type_t *type = skip_typeref(statement->expression->base.type);
9024 if (! is_type_enum(type))
9026 const enum_type_t *enumt = &type->enumt;
9028 /* if we have a default, no warnings */
9029 if (statement->default_label != NULL)
9032 /* FIXME: calculation of value should be done while parsing */
9033 /* TODO: quadratic algorithm here. Change to an n log n one */
9034 long last_value = -1;
9035 const entity_t *entry = enumt->enume->base.next;
9036 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9037 entry = entry->base.next) {
9038 const expression_t *expression = entry->enum_value.value;
9039 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9041 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9042 if (l->expression == NULL)
9044 if (l->first_case <= value && value <= l->last_case) {
9050 source_position_t const *const pos = &statement->base.source_position;
9051 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9058 * Parse a switch statement.
9060 static statement_t *parse_switch(void)
9062 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9066 PUSH_PARENT(statement);
9067 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9069 expression_t *const expr = parse_condition();
9070 type_t * type = skip_typeref(expr->base.type);
9071 if (is_type_integer(type)) {
9072 type = promote_integer(type);
9073 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9074 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9076 } else if (is_type_valid(type)) {
9077 errorf(&expr->base.source_position,
9078 "switch quantity is not an integer, but '%T'", type);
9079 type = type_error_type;
9081 statement->switchs.expression = create_implicit_cast(expr, type);
9083 switch_statement_t *rem = current_switch;
9084 current_switch = &statement->switchs;
9085 statement->switchs.body = parse_inner_statement();
9086 current_switch = rem;
9088 if (statement->switchs.default_label == NULL) {
9089 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9091 check_enum_cases(&statement->switchs);
9098 static statement_t *parse_loop_body(statement_t *const loop)
9100 statement_t *const rem = current_loop;
9101 current_loop = loop;
9103 statement_t *const body = parse_inner_statement();
9110 * Parse a while statement.
9112 static statement_t *parse_while(void)
9114 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9118 PUSH_PARENT(statement);
9119 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9121 expression_t *const cond = parse_condition();
9122 statement->whiles.condition = cond;
9123 /* §6.8.5:2 The controlling expression of an iteration statement shall
9124 * have scalar type. */
9125 semantic_condition(cond, "condition of 'while'-statement");
9127 statement->whiles.body = parse_loop_body(statement);
9135 * Parse a do statement.
9137 static statement_t *parse_do(void)
9139 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9143 PUSH_PARENT(statement);
9144 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9146 add_anchor_token(T_while);
9147 statement->do_while.body = parse_loop_body(statement);
9148 rem_anchor_token(T_while);
9151 expression_t *const cond = parse_condition();
9152 statement->do_while.condition = cond;
9153 /* §6.8.5:2 The controlling expression of an iteration statement shall
9154 * have scalar type. */
9155 semantic_condition(cond, "condition of 'do-while'-statement");
9164 * Parse a for statement.
9166 static statement_t *parse_for(void)
9168 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9172 PUSH_PARENT(statement);
9173 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9175 add_anchor_token(')');
9181 } else if (is_declaration_specifier(&token)) {
9182 parse_declaration(record_entity, DECL_FLAGS_NONE);
9184 add_anchor_token(';');
9185 expression_t *const init = parse_expression();
9186 statement->fors.initialisation = init;
9187 mark_vars_read(init, ENT_ANY);
9188 if (!expression_has_effect(init)) {
9189 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9191 rem_anchor_token(';');
9197 if (token.kind != ';') {
9198 add_anchor_token(';');
9199 expression_t *const cond = parse_expression();
9200 statement->fors.condition = cond;
9201 /* §6.8.5:2 The controlling expression of an iteration statement
9202 * shall have scalar type. */
9203 semantic_condition(cond, "condition of 'for'-statement");
9204 mark_vars_read(cond, NULL);
9205 rem_anchor_token(';');
9208 if (token.kind != ')') {
9209 expression_t *const step = parse_expression();
9210 statement->fors.step = step;
9211 mark_vars_read(step, ENT_ANY);
9212 if (!expression_has_effect(step)) {
9213 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9216 rem_anchor_token(')');
9218 statement->fors.body = parse_loop_body(statement);
9226 * Parse a goto statement.
9228 static statement_t *parse_goto(void)
9230 statement_t *statement;
9231 if (GNU_MODE && look_ahead(1)->kind == '*') {
9232 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9236 expression_t *expression = parse_expression();
9237 mark_vars_read(expression, NULL);
9239 /* Argh: although documentation says the expression must be of type void*,
9240 * gcc accepts anything that can be casted into void* without error */
9241 type_t *type = expression->base.type;
9243 if (type != type_error_type) {
9244 if (!is_type_pointer(type) && !is_type_integer(type)) {
9245 errorf(&expression->base.source_position,
9246 "cannot convert to a pointer type");
9247 } else if (type != type_void_ptr) {
9248 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9250 expression = create_implicit_cast(expression, type_void_ptr);
9253 statement->computed_goto.expression = expression;
9255 statement = allocate_statement_zero(STATEMENT_GOTO);
9258 label_t *const label = get_label("while parsing goto");
9261 statement->gotos.label = label;
9263 /* remember the goto's in a list for later checking */
9264 *goto_anchor = &statement->gotos;
9265 goto_anchor = &statement->gotos.next;
9267 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9276 * Parse a continue statement.
9278 static statement_t *parse_continue(void)
9280 if (current_loop == NULL) {
9281 errorf(HERE, "continue statement not within loop");
9284 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9292 * Parse a break statement.
9294 static statement_t *parse_break(void)
9296 if (current_switch == NULL && current_loop == NULL) {
9297 errorf(HERE, "break statement not within loop or switch");
9300 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9308 * Parse a __leave statement.
9310 static statement_t *parse_leave_statement(void)
9312 if (current_try == NULL) {
9313 errorf(HERE, "__leave statement not within __try");
9316 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9324 * Check if a given entity represents a local variable.
9326 static bool is_local_variable(const entity_t *entity)
9328 if (entity->kind != ENTITY_VARIABLE)
9331 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9332 case STORAGE_CLASS_AUTO:
9333 case STORAGE_CLASS_REGISTER: {
9334 const type_t *type = skip_typeref(entity->declaration.type);
9335 if (is_type_function(type)) {
9347 * Check if a given expression represents a local variable.
9349 static bool expression_is_local_variable(const expression_t *expression)
9351 if (expression->base.kind != EXPR_REFERENCE) {
9354 const entity_t *entity = expression->reference.entity;
9355 return is_local_variable(entity);
9358 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9360 if (c_mode & _CXX || strict_mode) {
9363 warningf(WARN_OTHER, pos, msg);
9368 * Parse a return statement.
9370 static statement_t *parse_return(void)
9372 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9375 expression_t *return_value = NULL;
9376 if (token.kind != ';') {
9377 return_value = parse_expression();
9378 mark_vars_read(return_value, NULL);
9381 const type_t *const func_type = skip_typeref(current_function->base.type);
9382 assert(is_type_function(func_type));
9383 type_t *const return_type = skip_typeref(func_type->function.return_type);
9385 source_position_t const *const pos = &statement->base.source_position;
9386 if (return_value != NULL) {
9387 type_t *return_value_type = skip_typeref(return_value->base.type);
9389 if (is_type_void(return_type)) {
9390 if (!is_type_void(return_value_type)) {
9391 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9392 /* Only warn in C mode, because GCC does the same */
9393 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9394 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9395 /* Only warn in C mode, because GCC does the same */
9396 err_or_warn(pos, "'return' with expression in function returning 'void'");
9399 assign_error_t error = semantic_assign(return_type, return_value);
9400 report_assign_error(error, return_type, return_value, "'return'",
9403 return_value = create_implicit_cast(return_value, return_type);
9404 /* check for returning address of a local var */
9405 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9406 const expression_t *expression = return_value->unary.value;
9407 if (expression_is_local_variable(expression)) {
9408 warningf(WARN_OTHER, pos, "function returns address of local variable");
9411 } else if (!is_type_void(return_type)) {
9412 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9413 err_or_warn(pos, "'return' without value, in function returning non-void");
9415 statement->returns.value = return_value;
9422 * Parse a declaration statement.
9424 static statement_t *parse_declaration_statement(void)
9426 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9428 entity_t *before = current_scope->last_entity;
9430 parse_external_declaration();
9432 parse_declaration(record_entity, DECL_FLAGS_NONE);
9435 declaration_statement_t *const decl = &statement->declaration;
9436 entity_t *const begin =
9437 before != NULL ? before->base.next : current_scope->entities;
9438 decl->declarations_begin = begin;
9439 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9445 * Parse an expression statement, ie. expr ';'.
9447 static statement_t *parse_expression_statement(void)
9449 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9451 expression_t *const expr = parse_expression();
9452 statement->expression.expression = expr;
9453 mark_vars_read(expr, ENT_ANY);
9460 * Parse a microsoft __try { } __finally { } or
9461 * __try{ } __except() { }
9463 static statement_t *parse_ms_try_statment(void)
9465 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9468 PUSH_PARENT(statement);
9470 ms_try_statement_t *rem = current_try;
9471 current_try = &statement->ms_try;
9472 statement->ms_try.try_statement = parse_compound_statement(false);
9477 if (next_if(T___except)) {
9478 expression_t *const expr = parse_condition();
9479 type_t * type = skip_typeref(expr->base.type);
9480 if (is_type_integer(type)) {
9481 type = promote_integer(type);
9482 } else if (is_type_valid(type)) {
9483 errorf(&expr->base.source_position,
9484 "__expect expression is not an integer, but '%T'", type);
9485 type = type_error_type;
9487 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9488 } else if (!next_if(T__finally)) {
9489 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9491 statement->ms_try.final_statement = parse_compound_statement(false);
9495 static statement_t *parse_empty_statement(void)
9497 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9498 statement_t *const statement = create_empty_statement();
9503 static statement_t *parse_local_label_declaration(void)
9505 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9509 entity_t *begin = NULL;
9510 entity_t *end = NULL;
9511 entity_t **anchor = &begin;
9512 add_anchor_token(';');
9513 add_anchor_token(',');
9515 source_position_t pos;
9516 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9518 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9519 if (entity != NULL && entity->base.parent_scope == current_scope) {
9520 source_position_t const *const ppos = &entity->base.source_position;
9521 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9523 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9524 entity->base.parent_scope = current_scope;
9527 anchor = &entity->base.next;
9530 environment_push(entity);
9533 } while (next_if(','));
9534 rem_anchor_token(',');
9535 rem_anchor_token(';');
9537 statement->declaration.declarations_begin = begin;
9538 statement->declaration.declarations_end = end;
9542 static void parse_namespace_definition(void)
9546 entity_t *entity = NULL;
9547 symbol_t *symbol = NULL;
9549 if (token.kind == T_IDENTIFIER) {
9550 symbol = token.base.symbol;
9551 entity = get_entity(symbol, NAMESPACE_NORMAL);
9552 if (entity && entity->kind != ENTITY_NAMESPACE) {
9554 if (entity->base.parent_scope == current_scope && is_entity_valid(entity)) {
9555 error_redefined_as_different_kind(HERE, entity, ENTITY_NAMESPACE);
9561 if (entity == NULL) {
9562 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9563 entity->base.parent_scope = current_scope;
9566 if (token.kind == '=') {
9567 /* TODO: parse namespace alias */
9568 panic("namespace alias definition not supported yet");
9571 environment_push(entity);
9572 append_entity(current_scope, entity);
9574 PUSH_SCOPE(&entity->namespacee.members);
9575 PUSH_CURRENT_ENTITY(entity);
9577 add_anchor_token('}');
9580 rem_anchor_token('}');
9583 POP_CURRENT_ENTITY();
9588 * Parse a statement.
9589 * There's also parse_statement() which additionally checks for
9590 * "statement has no effect" warnings
9592 static statement_t *intern_parse_statement(void)
9594 /* declaration or statement */
9595 statement_t *statement;
9596 switch (token.kind) {
9597 case T_IDENTIFIER: {
9598 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9599 if (la1_type == ':') {
9600 statement = parse_label_statement();
9601 } else if (is_typedef_symbol(token.base.symbol)) {
9602 statement = parse_declaration_statement();
9604 /* it's an identifier, the grammar says this must be an
9605 * expression statement. However it is common that users mistype
9606 * declaration types, so we guess a bit here to improve robustness
9607 * for incorrect programs */
9611 if (get_entity(token.base.symbol, NAMESPACE_NORMAL) != NULL) {
9613 statement = parse_expression_statement();
9617 statement = parse_declaration_statement();
9625 case T___extension__: {
9626 /* This can be a prefix to a declaration or an expression statement.
9627 * We simply eat it now and parse the rest with tail recursion. */
9629 statement = intern_parse_statement();
9635 statement = parse_declaration_statement();
9639 statement = parse_local_label_declaration();
9642 case ';': statement = parse_empty_statement(); break;
9643 case '{': statement = parse_compound_statement(false); break;
9644 case T___leave: statement = parse_leave_statement(); break;
9645 case T___try: statement = parse_ms_try_statment(); break;
9646 case T_asm: statement = parse_asm_statement(); break;
9647 case T_break: statement = parse_break(); break;
9648 case T_case: statement = parse_case_statement(); break;
9649 case T_continue: statement = parse_continue(); break;
9650 case T_default: statement = parse_default_statement(); break;
9651 case T_do: statement = parse_do(); break;
9652 case T_for: statement = parse_for(); break;
9653 case T_goto: statement = parse_goto(); break;
9654 case T_if: statement = parse_if(); break;
9655 case T_return: statement = parse_return(); break;
9656 case T_switch: statement = parse_switch(); break;
9657 case T_while: statement = parse_while(); break;
9660 statement = parse_expression_statement();
9664 errorf(HERE, "unexpected token %K while parsing statement", &token);
9665 statement = create_error_statement();
9674 * parse a statement and emits "statement has no effect" warning if needed
9675 * (This is really a wrapper around intern_parse_statement with check for 1
9676 * single warning. It is needed, because for statement expressions we have
9677 * to avoid the warning on the last statement)
9679 static statement_t *parse_statement(void)
9681 statement_t *statement = intern_parse_statement();
9683 if (statement->kind == STATEMENT_EXPRESSION) {
9684 expression_t *expression = statement->expression.expression;
9685 if (!expression_has_effect(expression)) {
9686 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9694 * Parse a compound statement.
9696 static statement_t *parse_compound_statement(bool inside_expression_statement)
9698 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9700 PUSH_PARENT(statement);
9701 PUSH_SCOPE(&statement->compound.scope);
9704 add_anchor_token('}');
9705 /* tokens, which can start a statement */
9706 /* TODO MS, __builtin_FOO */
9707 add_anchor_token('!');
9708 add_anchor_token('&');
9709 add_anchor_token('(');
9710 add_anchor_token('*');
9711 add_anchor_token('+');
9712 add_anchor_token('-');
9713 add_anchor_token(';');
9714 add_anchor_token('{');
9715 add_anchor_token('~');
9716 add_anchor_token(T_CHARACTER_CONSTANT);
9717 add_anchor_token(T_COLONCOLON);
9718 add_anchor_token(T_FLOATINGPOINT);
9719 add_anchor_token(T_IDENTIFIER);
9720 add_anchor_token(T_INTEGER);
9721 add_anchor_token(T_MINUSMINUS);
9722 add_anchor_token(T_PLUSPLUS);
9723 add_anchor_token(T_STRING_LITERAL);
9724 add_anchor_token(T__Bool);
9725 add_anchor_token(T__Complex);
9726 add_anchor_token(T__Imaginary);
9727 add_anchor_token(T___PRETTY_FUNCTION__);
9728 add_anchor_token(T___alignof__);
9729 add_anchor_token(T___attribute__);
9730 add_anchor_token(T___builtin_va_start);
9731 add_anchor_token(T___extension__);
9732 add_anchor_token(T___func__);
9733 add_anchor_token(T___imag__);
9734 add_anchor_token(T___label__);
9735 add_anchor_token(T___real__);
9736 add_anchor_token(T___thread);
9737 add_anchor_token(T_asm);
9738 add_anchor_token(T_auto);
9739 add_anchor_token(T_bool);
9740 add_anchor_token(T_break);
9741 add_anchor_token(T_case);
9742 add_anchor_token(T_char);
9743 add_anchor_token(T_class);
9744 add_anchor_token(T_const);
9745 add_anchor_token(T_const_cast);
9746 add_anchor_token(T_continue);
9747 add_anchor_token(T_default);
9748 add_anchor_token(T_delete);
9749 add_anchor_token(T_double);
9750 add_anchor_token(T_do);
9751 add_anchor_token(T_dynamic_cast);
9752 add_anchor_token(T_enum);
9753 add_anchor_token(T_extern);
9754 add_anchor_token(T_false);
9755 add_anchor_token(T_float);
9756 add_anchor_token(T_for);
9757 add_anchor_token(T_goto);
9758 add_anchor_token(T_if);
9759 add_anchor_token(T_inline);
9760 add_anchor_token(T_int);
9761 add_anchor_token(T_long);
9762 add_anchor_token(T_new);
9763 add_anchor_token(T_operator);
9764 add_anchor_token(T_register);
9765 add_anchor_token(T_reinterpret_cast);
9766 add_anchor_token(T_restrict);
9767 add_anchor_token(T_return);
9768 add_anchor_token(T_short);
9769 add_anchor_token(T_signed);
9770 add_anchor_token(T_sizeof);
9771 add_anchor_token(T_static);
9772 add_anchor_token(T_static_cast);
9773 add_anchor_token(T_struct);
9774 add_anchor_token(T_switch);
9775 add_anchor_token(T_template);
9776 add_anchor_token(T_this);
9777 add_anchor_token(T_throw);
9778 add_anchor_token(T_true);
9779 add_anchor_token(T_try);
9780 add_anchor_token(T_typedef);
9781 add_anchor_token(T_typeid);
9782 add_anchor_token(T_typename);
9783 add_anchor_token(T_typeof);
9784 add_anchor_token(T_union);
9785 add_anchor_token(T_unsigned);
9786 add_anchor_token(T_using);
9787 add_anchor_token(T_void);
9788 add_anchor_token(T_volatile);
9789 add_anchor_token(T_wchar_t);
9790 add_anchor_token(T_while);
9792 statement_t **anchor = &statement->compound.statements;
9793 bool only_decls_so_far = true;
9794 while (token.kind != '}' && token.kind != T_EOF) {
9795 statement_t *sub_statement = intern_parse_statement();
9796 if (sub_statement->kind == STATEMENT_ERROR) {
9800 if (sub_statement->kind != STATEMENT_DECLARATION) {
9801 only_decls_so_far = false;
9802 } else if (!only_decls_so_far) {
9803 source_position_t const *const pos = &sub_statement->base.source_position;
9804 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
9807 *anchor = sub_statement;
9808 anchor = &sub_statement->base.next;
9812 /* look over all statements again to produce no effect warnings */
9813 if (is_warn_on(WARN_UNUSED_VALUE)) {
9814 statement_t *sub_statement = statement->compound.statements;
9815 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
9816 if (sub_statement->kind != STATEMENT_EXPRESSION)
9818 /* don't emit a warning for the last expression in an expression
9819 * statement as it has always an effect */
9820 if (inside_expression_statement && sub_statement->base.next == NULL)
9823 expression_t *expression = sub_statement->expression.expression;
9824 if (!expression_has_effect(expression)) {
9825 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9830 rem_anchor_token(T_while);
9831 rem_anchor_token(T_wchar_t);
9832 rem_anchor_token(T_volatile);
9833 rem_anchor_token(T_void);
9834 rem_anchor_token(T_using);
9835 rem_anchor_token(T_unsigned);
9836 rem_anchor_token(T_union);
9837 rem_anchor_token(T_typeof);
9838 rem_anchor_token(T_typename);
9839 rem_anchor_token(T_typeid);
9840 rem_anchor_token(T_typedef);
9841 rem_anchor_token(T_try);
9842 rem_anchor_token(T_true);
9843 rem_anchor_token(T_throw);
9844 rem_anchor_token(T_this);
9845 rem_anchor_token(T_template);
9846 rem_anchor_token(T_switch);
9847 rem_anchor_token(T_struct);
9848 rem_anchor_token(T_static_cast);
9849 rem_anchor_token(T_static);
9850 rem_anchor_token(T_sizeof);
9851 rem_anchor_token(T_signed);
9852 rem_anchor_token(T_short);
9853 rem_anchor_token(T_return);
9854 rem_anchor_token(T_restrict);
9855 rem_anchor_token(T_reinterpret_cast);
9856 rem_anchor_token(T_register);
9857 rem_anchor_token(T_operator);
9858 rem_anchor_token(T_new);
9859 rem_anchor_token(T_long);
9860 rem_anchor_token(T_int);
9861 rem_anchor_token(T_inline);
9862 rem_anchor_token(T_if);
9863 rem_anchor_token(T_goto);
9864 rem_anchor_token(T_for);
9865 rem_anchor_token(T_float);
9866 rem_anchor_token(T_false);
9867 rem_anchor_token(T_extern);
9868 rem_anchor_token(T_enum);
9869 rem_anchor_token(T_dynamic_cast);
9870 rem_anchor_token(T_do);
9871 rem_anchor_token(T_double);
9872 rem_anchor_token(T_delete);
9873 rem_anchor_token(T_default);
9874 rem_anchor_token(T_continue);
9875 rem_anchor_token(T_const_cast);
9876 rem_anchor_token(T_const);
9877 rem_anchor_token(T_class);
9878 rem_anchor_token(T_char);
9879 rem_anchor_token(T_case);
9880 rem_anchor_token(T_break);
9881 rem_anchor_token(T_bool);
9882 rem_anchor_token(T_auto);
9883 rem_anchor_token(T_asm);
9884 rem_anchor_token(T___thread);
9885 rem_anchor_token(T___real__);
9886 rem_anchor_token(T___label__);
9887 rem_anchor_token(T___imag__);
9888 rem_anchor_token(T___func__);
9889 rem_anchor_token(T___extension__);
9890 rem_anchor_token(T___builtin_va_start);
9891 rem_anchor_token(T___attribute__);
9892 rem_anchor_token(T___alignof__);
9893 rem_anchor_token(T___PRETTY_FUNCTION__);
9894 rem_anchor_token(T__Imaginary);
9895 rem_anchor_token(T__Complex);
9896 rem_anchor_token(T__Bool);
9897 rem_anchor_token(T_STRING_LITERAL);
9898 rem_anchor_token(T_PLUSPLUS);
9899 rem_anchor_token(T_MINUSMINUS);
9900 rem_anchor_token(T_INTEGER);
9901 rem_anchor_token(T_IDENTIFIER);
9902 rem_anchor_token(T_FLOATINGPOINT);
9903 rem_anchor_token(T_COLONCOLON);
9904 rem_anchor_token(T_CHARACTER_CONSTANT);
9905 rem_anchor_token('~');
9906 rem_anchor_token('{');
9907 rem_anchor_token(';');
9908 rem_anchor_token('-');
9909 rem_anchor_token('+');
9910 rem_anchor_token('*');
9911 rem_anchor_token('(');
9912 rem_anchor_token('&');
9913 rem_anchor_token('!');
9914 rem_anchor_token('}');
9922 * Check for unused global static functions and variables
9924 static void check_unused_globals(void)
9926 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
9929 for (const entity_t *entity = file_scope->entities; entity != NULL;
9930 entity = entity->base.next) {
9931 if (!is_declaration(entity))
9934 const declaration_t *declaration = &entity->declaration;
9935 if (declaration->used ||
9936 declaration->modifiers & DM_UNUSED ||
9937 declaration->modifiers & DM_USED ||
9938 declaration->storage_class != STORAGE_CLASS_STATIC)
9943 if (entity->kind == ENTITY_FUNCTION) {
9944 /* inhibit warning for static inline functions */
9945 if (entity->function.is_inline)
9948 why = WARN_UNUSED_FUNCTION;
9949 s = entity->function.statement != NULL ? "defined" : "declared";
9951 why = WARN_UNUSED_VARIABLE;
9955 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
9959 static void parse_global_asm(void)
9961 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9964 add_anchor_token(';');
9965 add_anchor_token(')');
9966 add_anchor_token(T_STRING_LITERAL);
9969 rem_anchor_token(T_STRING_LITERAL);
9970 statement->asms.asm_text = parse_string_literals("global asm");
9971 statement->base.next = unit->global_asm;
9972 unit->global_asm = statement;
9974 rem_anchor_token(')');
9976 rem_anchor_token(';');
9980 static void parse_linkage_specification(void)
9984 source_position_t const pos = *HERE;
9985 char const *const linkage = parse_string_literals(NULL).begin;
9987 linkage_kind_t old_linkage = current_linkage;
9988 linkage_kind_t new_linkage;
9989 if (streq(linkage, "C")) {
9990 new_linkage = LINKAGE_C;
9991 } else if (streq(linkage, "C++")) {
9992 new_linkage = LINKAGE_CXX;
9994 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
9995 new_linkage = LINKAGE_C;
9997 current_linkage = new_linkage;
10006 assert(current_linkage == new_linkage);
10007 current_linkage = old_linkage;
10010 static void parse_external(void)
10012 switch (token.kind) {
10014 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10015 parse_linkage_specification();
10017 DECLARATION_START_NO_EXTERN
10019 case T___extension__:
10020 /* tokens below are for implicit int */
10021 case '&': /* & x; -> int& x; (and error later, because C++ has no
10023 case '*': /* * x; -> int* x; */
10024 case '(': /* (x); -> int (x); */
10026 parse_external_declaration();
10032 parse_global_asm();
10036 parse_namespace_definition();
10040 if (!strict_mode) {
10041 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10048 errorf(HERE, "stray %K outside of function", &token);
10049 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10050 eat_until_matching_token(token.kind);
10056 static void parse_externals(void)
10058 add_anchor_token('}');
10059 add_anchor_token(T_EOF);
10062 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10063 unsigned short token_anchor_copy[T_LAST_TOKEN];
10064 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10067 while (token.kind != T_EOF && token.kind != '}') {
10069 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10070 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10072 /* the anchor set and its copy differs */
10073 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10076 if (in_gcc_extension) {
10077 /* an gcc extension scope was not closed */
10078 internal_errorf(HERE, "Leaked __extension__");
10085 rem_anchor_token(T_EOF);
10086 rem_anchor_token('}');
10090 * Parse a translation unit.
10092 static void parse_translation_unit(void)
10094 add_anchor_token(T_EOF);
10099 if (token.kind == T_EOF)
10102 errorf(HERE, "stray %K outside of function", &token);
10103 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10104 eat_until_matching_token(token.kind);
10109 void set_default_visibility(elf_visibility_tag_t visibility)
10111 default_visibility = visibility;
10117 * @return the translation unit or NULL if errors occurred.
10119 void start_parsing(void)
10121 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10122 label_stack = NEW_ARR_F(stack_entry_t, 0);
10126 print_to_file(stderr);
10128 assert(unit == NULL);
10129 unit = allocate_ast_zero(sizeof(unit[0]));
10131 assert(file_scope == NULL);
10132 file_scope = &unit->scope;
10134 assert(current_scope == NULL);
10135 scope_push(&unit->scope);
10137 create_gnu_builtins();
10139 create_microsoft_intrinsics();
10142 translation_unit_t *finish_parsing(void)
10144 assert(current_scope == &unit->scope);
10147 assert(file_scope == &unit->scope);
10148 check_unused_globals();
10151 DEL_ARR_F(environment_stack);
10152 DEL_ARR_F(label_stack);
10154 translation_unit_t *result = unit;
10159 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10160 * are given length one. */
10161 static void complete_incomplete_arrays(void)
10163 size_t n = ARR_LEN(incomplete_arrays);
10164 for (size_t i = 0; i != n; ++i) {
10165 declaration_t *const decl = incomplete_arrays[i];
10166 type_t *const type = skip_typeref(decl->type);
10168 if (!is_type_incomplete(type))
10171 source_position_t const *const pos = &decl->base.source_position;
10172 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10174 type_t *const new_type = duplicate_type(type);
10175 new_type->array.size_constant = true;
10176 new_type->array.has_implicit_size = true;
10177 new_type->array.size = 1;
10179 type_t *const result = identify_new_type(new_type);
10181 decl->type = result;
10185 static void prepare_main_collect2(entity_t *const entity)
10187 PUSH_SCOPE(&entity->function.statement->compound.scope);
10189 // create call to __main
10190 symbol_t *symbol = symbol_table_insert("__main");
10191 entity_t *subsubmain_ent
10192 = create_implicit_function(symbol, &builtin_source_position);
10194 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10195 type_t *ftype = subsubmain_ent->declaration.type;
10196 ref->base.source_position = builtin_source_position;
10197 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10198 ref->reference.entity = subsubmain_ent;
10200 expression_t *call = allocate_expression_zero(EXPR_CALL);
10201 call->base.source_position = builtin_source_position;
10202 call->base.type = type_void;
10203 call->call.function = ref;
10205 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10206 expr_statement->base.source_position = builtin_source_position;
10207 expr_statement->expression.expression = call;
10209 statement_t *statement = entity->function.statement;
10210 assert(statement->kind == STATEMENT_COMPOUND);
10211 compound_statement_t *compounds = &statement->compound;
10213 expr_statement->base.next = compounds->statements;
10214 compounds->statements = expr_statement;
10221 lookahead_bufpos = 0;
10222 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10225 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10226 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10227 parse_translation_unit();
10228 complete_incomplete_arrays();
10229 DEL_ARR_F(incomplete_arrays);
10230 incomplete_arrays = NULL;
10234 * Initialize the parser.
10236 void init_parser(void)
10238 sym_anonymous = symbol_table_insert("<anonymous>");
10240 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10242 init_expression_parsers();
10243 obstack_init(&temp_obst);
10247 * Terminate the parser.
10249 void exit_parser(void)
10251 obstack_free(&temp_obst, NULL);