2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_CURRENT_ENTITY(entity) \
113 entity_t *const new_current_entity = (entity); \
114 entity_t *const old_current_entity = current_entity; \
115 ((void)(current_entity = new_current_entity))
116 #define POP_CURRENT_ENTITY() (assert(current_entity == new_current_entity), (void)(current_entity = old_current_entity))
118 #define PUSH_PARENT(stmt) \
119 statement_t *const new_parent = (stmt); \
120 statement_t *const old_parent = current_parent; \
121 ((void)(current_parent = new_parent))
122 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
124 #define PUSH_SCOPE(scope) \
125 size_t const top = environment_top(); \
126 scope_t *const new_scope = (scope); \
127 scope_t *const old_scope = (new_scope ? scope_push(new_scope) : NULL)
128 #define PUSH_SCOPE_STATEMENT(scope) PUSH_SCOPE(c_mode & (_C99 | _CXX) ? (scope) : NULL)
129 #define POP_SCOPE() (new_scope ? assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top) : (void)0)
131 #define PUSH_EXTENSION() \
133 bool const old_gcc_extension = in_gcc_extension; \
134 while (next_if(T___extension__)) { \
135 in_gcc_extension = true; \
138 #define POP_EXTENSION() \
139 ((void)(in_gcc_extension = old_gcc_extension))
141 /** special symbol used for anonymous entities. */
142 static symbol_t *sym_anonymous = NULL;
144 /** The token anchor set */
145 static unsigned short token_anchor_set[T_LAST_TOKEN];
147 /** The current source position. */
148 #define HERE (&token.base.source_position)
150 /** true if we are in GCC mode. */
151 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
153 static statement_t *parse_compound_statement(bool inside_expression_statement);
154 static statement_t *parse_statement(void);
156 static expression_t *parse_subexpression(precedence_t);
157 static expression_t *parse_expression(void);
158 static type_t *parse_typename(void);
159 static void parse_externals(void);
160 static void parse_external(void);
162 static void parse_compound_type_entries(compound_t *compound_declaration);
164 static void check_call_argument(type_t *expected_type,
165 call_argument_t *argument, unsigned pos);
167 typedef enum declarator_flags_t {
169 DECL_MAY_BE_ABSTRACT = 1U << 0,
170 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
171 DECL_IS_PARAMETER = 1U << 2
172 } declarator_flags_t;
174 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
175 declarator_flags_t flags);
177 static void semantic_comparison(binary_expression_t *expression);
179 #define STORAGE_CLASSES \
180 STORAGE_CLASSES_NO_EXTERN \
183 #define STORAGE_CLASSES_NO_EXTERN \
190 #define TYPE_QUALIFIERS \
195 case T__forceinline: \
196 case T___attribute__:
198 #define COMPLEX_SPECIFIERS \
200 #define IMAGINARY_SPECIFIERS \
203 #define TYPE_SPECIFIERS \
205 case T___builtin_va_list: \
230 #define DECLARATION_START \
235 #define DECLARATION_START_NO_EXTERN \
236 STORAGE_CLASSES_NO_EXTERN \
240 #define EXPRESSION_START \
249 case T_CHARACTER_CONSTANT: \
250 case T_FLOATINGPOINT: \
251 case T_FLOATINGPOINT_HEXADECIMAL: \
253 case T_INTEGER_HEXADECIMAL: \
254 case T_INTEGER_OCTAL: \
257 case T_STRING_LITERAL: \
258 case T_WIDE_CHARACTER_CONSTANT: \
259 case T_WIDE_STRING_LITERAL: \
260 case T___FUNCDNAME__: \
261 case T___FUNCSIG__: \
262 case T___FUNCTION__: \
263 case T___PRETTY_FUNCTION__: \
264 case T___alignof__: \
265 case T___builtin_classify_type: \
266 case T___builtin_constant_p: \
267 case T___builtin_isgreater: \
268 case T___builtin_isgreaterequal: \
269 case T___builtin_isless: \
270 case T___builtin_islessequal: \
271 case T___builtin_islessgreater: \
272 case T___builtin_isunordered: \
273 case T___builtin_offsetof: \
274 case T___builtin_va_arg: \
275 case T___builtin_va_copy: \
276 case T___builtin_va_start: \
287 * Returns the size of a statement node.
289 * @param kind the statement kind
291 static size_t get_statement_struct_size(statement_kind_t kind)
293 static const size_t sizes[] = {
294 [STATEMENT_ERROR] = sizeof(statement_base_t),
295 [STATEMENT_EMPTY] = sizeof(statement_base_t),
296 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
297 [STATEMENT_RETURN] = sizeof(return_statement_t),
298 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
299 [STATEMENT_IF] = sizeof(if_statement_t),
300 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
301 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
302 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
303 [STATEMENT_BREAK] = sizeof(statement_base_t),
304 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
305 [STATEMENT_GOTO] = sizeof(goto_statement_t),
306 [STATEMENT_LABEL] = sizeof(label_statement_t),
307 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
308 [STATEMENT_WHILE] = sizeof(while_statement_t),
309 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
310 [STATEMENT_FOR] = sizeof(for_statement_t),
311 [STATEMENT_ASM] = sizeof(asm_statement_t),
312 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
313 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
315 assert((size_t)kind < lengthof(sizes));
316 assert(sizes[kind] != 0);
321 * Returns the size of an expression node.
323 * @param kind the expression kind
325 static size_t get_expression_struct_size(expression_kind_t kind)
327 static const size_t sizes[] = {
328 [EXPR_ERROR] = sizeof(expression_base_t),
329 [EXPR_REFERENCE] = sizeof(reference_expression_t),
330 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
331 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
332 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
333 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
334 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
335 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
336 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
337 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
338 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
339 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
340 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
341 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
342 [EXPR_CALL] = sizeof(call_expression_t),
343 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
344 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
345 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
346 [EXPR_SELECT] = sizeof(select_expression_t),
347 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
348 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
349 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
350 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
351 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
352 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
353 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
354 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
355 [EXPR_VA_START] = sizeof(va_start_expression_t),
356 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
357 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
358 [EXPR_STATEMENT] = sizeof(statement_expression_t),
359 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
361 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
362 return sizes[EXPR_UNARY_FIRST];
364 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
365 return sizes[EXPR_BINARY_FIRST];
367 assert((size_t)kind < lengthof(sizes));
368 assert(sizes[kind] != 0);
373 * Allocate a statement node of given kind and initialize all
374 * fields with zero. Sets its source position to the position
375 * of the current token.
377 static statement_t *allocate_statement_zero(statement_kind_t kind)
379 size_t size = get_statement_struct_size(kind);
380 statement_t *res = allocate_ast_zero(size);
382 res->base.kind = kind;
383 res->base.parent = current_parent;
384 res->base.source_position = token.base.source_position;
389 * Allocate an expression node of given kind and initialize all
392 * @param kind the kind of the expression to allocate
394 static expression_t *allocate_expression_zero(expression_kind_t kind)
396 size_t size = get_expression_struct_size(kind);
397 expression_t *res = allocate_ast_zero(size);
399 res->base.kind = kind;
400 res->base.type = type_error_type;
401 res->base.source_position = token.base.source_position;
406 * Creates a new invalid expression at the source position
407 * of the current token.
409 static expression_t *create_error_expression(void)
411 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
412 expression->base.type = type_error_type;
417 * Creates a new invalid statement.
419 static statement_t *create_error_statement(void)
421 return allocate_statement_zero(STATEMENT_ERROR);
425 * Allocate a new empty statement.
427 static statement_t *create_empty_statement(void)
429 return allocate_statement_zero(STATEMENT_EMPTY);
433 * Returns the size of an initializer node.
435 * @param kind the initializer kind
437 static size_t get_initializer_size(initializer_kind_t kind)
439 static const size_t sizes[] = {
440 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
441 [INITIALIZER_STRING] = sizeof(initializer_string_t),
442 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
443 [INITIALIZER_LIST] = sizeof(initializer_list_t),
444 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
446 assert((size_t)kind < lengthof(sizes));
447 assert(sizes[kind] != 0);
452 * Allocate an initializer node of given kind and initialize all
455 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
457 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
464 * Returns the index of the top element of the environment stack.
466 static size_t environment_top(void)
468 return ARR_LEN(environment_stack);
472 * Returns the index of the top element of the global label stack.
474 static size_t label_top(void)
476 return ARR_LEN(label_stack);
480 * Return the next token.
482 static inline void next_token(void)
484 token = lookahead_buffer[lookahead_bufpos];
485 lookahead_buffer[lookahead_bufpos] = lexer_token;
488 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
491 print_token(stderr, &token);
492 fprintf(stderr, "\n");
496 static inline bool next_if(token_kind_t const type)
498 if (token.kind == type) {
507 * Return the next token with a given lookahead.
509 static inline const token_t *look_ahead(size_t num)
511 assert(0 < num && num <= MAX_LOOKAHEAD);
512 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
513 return &lookahead_buffer[pos];
517 * Adds a token type to the token type anchor set (a multi-set).
519 static void add_anchor_token(token_kind_t const token_kind)
521 assert(token_kind < T_LAST_TOKEN);
522 ++token_anchor_set[token_kind];
526 * Remove a token type from the token type anchor set (a multi-set).
528 static void rem_anchor_token(token_kind_t const token_kind)
530 assert(token_kind < T_LAST_TOKEN);
531 assert(token_anchor_set[token_kind] != 0);
532 --token_anchor_set[token_kind];
536 * Eat tokens until a matching token type is found.
538 static void eat_until_matching_token(token_kind_t const type)
540 token_kind_t end_token;
542 case '(': end_token = ')'; break;
543 case '{': end_token = '}'; break;
544 case '[': end_token = ']'; break;
545 default: end_token = type; break;
548 unsigned parenthesis_count = 0;
549 unsigned brace_count = 0;
550 unsigned bracket_count = 0;
551 while (token.kind != end_token ||
552 parenthesis_count != 0 ||
554 bracket_count != 0) {
555 switch (token.kind) {
557 case '(': ++parenthesis_count; break;
558 case '{': ++brace_count; break;
559 case '[': ++bracket_count; break;
562 if (parenthesis_count > 0)
572 if (bracket_count > 0)
575 if (token.kind == end_token &&
576 parenthesis_count == 0 &&
590 * Eat input tokens until an anchor is found.
592 static void eat_until_anchor(void)
594 while (token_anchor_set[token.kind] == 0) {
595 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
596 eat_until_matching_token(token.kind);
602 * Eat a whole block from input tokens.
604 static void eat_block(void)
606 eat_until_matching_token('{');
610 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
613 * Report a parse error because an expected token was not found.
616 #if defined __GNUC__ && __GNUC__ >= 4
617 __attribute__((sentinel))
619 void parse_error_expected(const char *message, ...)
621 if (message != NULL) {
622 errorf(HERE, "%s", message);
625 va_start(ap, message);
626 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
631 * Report an incompatible type.
633 static void type_error_incompatible(const char *msg,
634 const source_position_t *source_position, type_t *type1, type_t *type2)
636 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
641 * Expect the current token is the expected token.
642 * If not, generate an error and skip until the next anchor.
644 static void expect(token_kind_t const expected)
646 if (UNLIKELY(token.kind != expected)) {
647 parse_error_expected(NULL, expected, NULL);
648 add_anchor_token(expected);
650 rem_anchor_token(expected);
651 if (token.kind != expected)
657 static symbol_t *expect_identifier(char const *const context, source_position_t *const pos)
659 if (token.kind != T_IDENTIFIER) {
660 parse_error_expected(context, T_IDENTIFIER, NULL);
661 add_anchor_token(T_IDENTIFIER);
663 rem_anchor_token(T_IDENTIFIER);
664 if (token.kind != T_IDENTIFIER)
667 symbol_t *const sym = token.identifier.symbol;
675 * Push a given scope on the scope stack and make it the
678 static scope_t *scope_push(scope_t *new_scope)
680 if (current_scope != NULL) {
681 new_scope->depth = current_scope->depth + 1;
684 scope_t *old_scope = current_scope;
685 current_scope = new_scope;
690 * Pop the current scope from the scope stack.
692 static void scope_pop(scope_t *old_scope)
694 current_scope = old_scope;
698 * Search an entity by its symbol in a given namespace.
700 static entity_t *get_entity(const symbol_t *const symbol,
701 namespace_tag_t namespc)
703 entity_t *entity = symbol->entity;
704 for (; entity != NULL; entity = entity->base.symbol_next) {
705 if ((namespace_tag_t)entity->base.namespc == namespc)
712 /* §6.2.3:1 24) There is only one name space for tags even though three are
714 static entity_t *get_tag(symbol_t const *const symbol,
715 entity_kind_tag_t const kind)
717 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
718 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
720 "'%Y' defined as wrong kind of tag (previous definition %P)",
721 symbol, &entity->base.source_position);
728 * pushs an entity on the environment stack and links the corresponding symbol
731 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
733 symbol_t *symbol = entity->base.symbol;
734 entity_namespace_t namespc = entity->base.namespc;
735 assert(namespc != 0);
737 /* replace/add entity into entity list of the symbol */
740 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
745 /* replace an entry? */
746 if (iter->base.namespc == namespc) {
747 entity->base.symbol_next = iter->base.symbol_next;
753 /* remember old declaration */
755 entry.symbol = symbol;
756 entry.old_entity = iter;
757 entry.namespc = namespc;
758 ARR_APP1(stack_entry_t, *stack_ptr, entry);
762 * Push an entity on the environment stack.
764 static void environment_push(entity_t *entity)
766 assert(entity->base.source_position.input_name != NULL);
767 assert(entity->base.parent_scope != NULL);
768 stack_push(&environment_stack, entity);
772 * Push a declaration on the global label stack.
774 * @param declaration the declaration
776 static void label_push(entity_t *label)
778 /* we abuse the parameters scope as parent for the labels */
779 label->base.parent_scope = ¤t_function->parameters;
780 stack_push(&label_stack, label);
784 * pops symbols from the environment stack until @p new_top is the top element
786 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
788 stack_entry_t *stack = *stack_ptr;
789 size_t top = ARR_LEN(stack);
792 assert(new_top <= top);
796 for (i = top; i > new_top; --i) {
797 stack_entry_t *entry = &stack[i - 1];
799 entity_t *old_entity = entry->old_entity;
800 symbol_t *symbol = entry->symbol;
801 entity_namespace_t namespc = entry->namespc;
803 /* replace with old_entity/remove */
806 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
808 assert(iter != NULL);
809 /* replace an entry? */
810 if (iter->base.namespc == namespc)
814 /* restore definition from outer scopes (if there was one) */
815 if (old_entity != NULL) {
816 old_entity->base.symbol_next = iter->base.symbol_next;
817 *anchor = old_entity;
819 /* remove entry from list */
820 *anchor = iter->base.symbol_next;
824 ARR_SHRINKLEN(*stack_ptr, new_top);
828 * Pop all entries from the environment stack until the new_top
831 * @param new_top the new stack top
833 static void environment_pop_to(size_t new_top)
835 stack_pop_to(&environment_stack, new_top);
839 * Pop all entries from the global label stack until the new_top
842 * @param new_top the new stack top
844 static void label_pop_to(size_t new_top)
846 stack_pop_to(&label_stack, new_top);
849 static atomic_type_kind_t get_akind(const type_t *type)
851 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
852 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
853 return type->atomic.akind;
857 * §6.3.1.1:2 Do integer promotion for a given type.
859 * @param type the type to promote
860 * @return the promoted type
862 static type_t *promote_integer(type_t *type)
864 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
871 * Check if a given expression represents a null pointer constant.
873 * @param expression the expression to check
875 static bool is_null_pointer_constant(const expression_t *expression)
877 /* skip void* cast */
878 if (expression->kind == EXPR_UNARY_CAST) {
879 type_t *const type = skip_typeref(expression->base.type);
880 if (types_compatible(type, type_void_ptr))
881 expression = expression->unary.value;
884 type_t *const type = skip_typeref(expression->base.type);
885 if (!is_type_integer(type))
887 switch (is_constant_expression(expression)) {
888 case EXPR_CLASS_ERROR: return true;
889 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
890 default: return false;
895 * Create an implicit cast expression.
897 * @param expression the expression to cast
898 * @param dest_type the destination type
900 static expression_t *create_implicit_cast(expression_t *expression,
903 type_t *const source_type = expression->base.type;
905 if (source_type == dest_type)
908 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
909 cast->unary.value = expression;
910 cast->base.type = dest_type;
911 cast->base.implicit = true;
916 typedef enum assign_error_t {
918 ASSIGN_ERROR_INCOMPATIBLE,
919 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
920 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
921 ASSIGN_WARNING_POINTER_FROM_INT,
922 ASSIGN_WARNING_INT_FROM_POINTER
925 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)
927 type_t *const orig_type_right = right->base.type;
928 type_t *const type_left = skip_typeref(orig_type_left);
929 type_t *const type_right = skip_typeref(orig_type_right);
934 case ASSIGN_ERROR_INCOMPATIBLE:
935 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
938 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
939 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
940 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
942 /* the left type has all qualifiers from the right type */
943 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
944 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);
948 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
949 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
952 case ASSIGN_WARNING_POINTER_FROM_INT:
953 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
956 case ASSIGN_WARNING_INT_FROM_POINTER:
957 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
961 panic("invalid error value");
965 /** Implements the rules from §6.5.16.1 */
966 static assign_error_t semantic_assign(type_t *orig_type_left,
967 const expression_t *const right)
969 type_t *const orig_type_right = right->base.type;
970 type_t *const type_left = skip_typeref(orig_type_left);
971 type_t *const type_right = skip_typeref(orig_type_right);
973 if (is_type_pointer(type_left)) {
974 if (is_null_pointer_constant(right)) {
975 return ASSIGN_SUCCESS;
976 } else if (is_type_pointer(type_right)) {
977 type_t *points_to_left
978 = skip_typeref(type_left->pointer.points_to);
979 type_t *points_to_right
980 = skip_typeref(type_right->pointer.points_to);
981 assign_error_t res = ASSIGN_SUCCESS;
983 /* the left type has all qualifiers from the right type */
984 unsigned missing_qualifiers
985 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
986 if (missing_qualifiers != 0) {
987 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
990 points_to_left = get_unqualified_type(points_to_left);
991 points_to_right = get_unqualified_type(points_to_right);
993 if (is_type_void(points_to_left))
996 if (is_type_void(points_to_right)) {
997 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
998 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1001 if (!types_compatible(points_to_left, points_to_right)) {
1002 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1006 } else if (is_type_integer(type_right)) {
1007 return ASSIGN_WARNING_POINTER_FROM_INT;
1009 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1010 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1011 && is_type_pointer(type_right))) {
1012 return ASSIGN_SUCCESS;
1013 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1014 type_t *const unqual_type_left = get_unqualified_type(type_left);
1015 type_t *const unqual_type_right = get_unqualified_type(type_right);
1016 if (types_compatible(unqual_type_left, unqual_type_right)) {
1017 return ASSIGN_SUCCESS;
1019 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1020 return ASSIGN_WARNING_INT_FROM_POINTER;
1023 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1024 return ASSIGN_SUCCESS;
1026 return ASSIGN_ERROR_INCOMPATIBLE;
1029 static expression_t *parse_constant_expression(void)
1031 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1033 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1034 errorf(&result->base.source_position,
1035 "expression '%E' is not constant", result);
1041 static expression_t *parse_assignment_expression(void)
1043 return parse_subexpression(PREC_ASSIGNMENT);
1046 static void warn_string_concat(const source_position_t *pos)
1048 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1051 static string_t parse_string_literals(void)
1053 assert(token.kind == T_STRING_LITERAL);
1054 string_t result = token.string.string;
1058 while (token.kind == T_STRING_LITERAL) {
1059 warn_string_concat(&token.base.source_position);
1060 result = concat_strings(&result, &token.string.string);
1067 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1069 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1070 attribute->kind = kind;
1071 attribute->source_position = *HERE;
1076 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1079 * __attribute__ ( ( attribute-list ) )
1083 * attribute_list , attrib
1088 * any-word ( identifier )
1089 * any-word ( identifier , nonempty-expr-list )
1090 * any-word ( expr-list )
1092 * where the "identifier" must not be declared as a type, and
1093 * "any-word" may be any identifier (including one declared as a
1094 * type), a reserved word storage class specifier, type specifier or
1095 * type qualifier. ??? This still leaves out most reserved keywords
1096 * (following the old parser), shouldn't we include them, and why not
1097 * allow identifiers declared as types to start the arguments?
1099 * Matze: this all looks confusing and little systematic, so we're even less
1100 * strict and parse any list of things which are identifiers or
1101 * (assignment-)expressions.
1103 static attribute_argument_t *parse_attribute_arguments(void)
1105 attribute_argument_t *first = NULL;
1106 attribute_argument_t **anchor = &first;
1107 if (token.kind != ')') do {
1108 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1110 /* is it an identifier */
1111 if (token.kind == T_IDENTIFIER
1112 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1113 symbol_t *symbol = token.identifier.symbol;
1114 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1115 argument->v.symbol = symbol;
1118 /* must be an expression */
1119 expression_t *expression = parse_assignment_expression();
1121 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1122 argument->v.expression = expression;
1125 /* append argument */
1127 anchor = &argument->next;
1128 } while (next_if(','));
1133 static attribute_t *parse_attribute_asm(void)
1135 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1138 attribute->a.arguments = parse_attribute_arguments();
1142 static symbol_t *get_symbol_from_token(void)
1144 switch(token.kind) {
1145 case T_CHARACTER_CONSTANT:
1147 case T_FLOATINGPOINT:
1148 case T_FLOATINGPOINT_HEXADECIMAL:
1150 case T_INTEGER_HEXADECIMAL:
1151 case T_INTEGER_OCTAL:
1152 case T_STRING_LITERAL:
1153 case T_WIDE_CHARACTER_CONSTANT:
1154 case T_WIDE_STRING_LITERAL:
1158 return token.identifier.symbol;
1162 static attribute_t *parse_attribute_gnu_single(void)
1164 /* parse "any-word" */
1165 symbol_t *symbol = get_symbol_from_token();
1166 if (symbol == NULL) {
1167 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1171 attribute_kind_t kind;
1172 char const *const name = symbol->string;
1173 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1174 if (kind > ATTRIBUTE_GNU_LAST) {
1175 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1176 /* TODO: we should still save the attribute in the list... */
1177 kind = ATTRIBUTE_UNKNOWN;
1181 const char *attribute_name = get_attribute_name(kind);
1182 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1186 attribute_t *attribute = allocate_attribute_zero(kind);
1189 /* parse arguments */
1191 attribute->a.arguments = parse_attribute_arguments();
1196 static attribute_t *parse_attribute_gnu(void)
1198 attribute_t *first = NULL;
1199 attribute_t **anchor = &first;
1201 eat(T___attribute__);
1205 add_anchor_token(')');
1206 add_anchor_token(',');
1207 if (token.kind != ')') do {
1208 attribute_t *attribute = parse_attribute_gnu_single();
1210 *anchor = attribute;
1211 anchor = &attribute->next;
1213 } while (next_if(','));
1214 rem_anchor_token(',');
1215 rem_anchor_token(')');
1222 /** Parse attributes. */
1223 static attribute_t *parse_attributes(attribute_t *first)
1225 attribute_t **anchor = &first;
1227 while (*anchor != NULL)
1228 anchor = &(*anchor)->next;
1230 attribute_t *attribute;
1231 switch (token.kind) {
1232 case T___attribute__:
1233 attribute = parse_attribute_gnu();
1234 if (attribute == NULL)
1239 attribute = parse_attribute_asm();
1243 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1248 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1252 case T__forceinline:
1253 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1254 eat(T__forceinline);
1258 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1263 /* TODO record modifier */
1264 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1265 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1273 *anchor = attribute;
1274 anchor = &attribute->next;
1278 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1280 static entity_t *determine_lhs_ent(expression_t *const expr,
1283 switch (expr->kind) {
1284 case EXPR_REFERENCE: {
1285 entity_t *const entity = expr->reference.entity;
1286 /* we should only find variables as lvalues... */
1287 if (entity->base.kind != ENTITY_VARIABLE
1288 && entity->base.kind != ENTITY_PARAMETER)
1294 case EXPR_ARRAY_ACCESS: {
1295 expression_t *const ref = expr->array_access.array_ref;
1296 entity_t * ent = NULL;
1297 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1298 ent = determine_lhs_ent(ref, lhs_ent);
1301 mark_vars_read(ref, lhs_ent);
1303 mark_vars_read(expr->array_access.index, lhs_ent);
1308 mark_vars_read(expr->select.compound, lhs_ent);
1309 if (is_type_compound(skip_typeref(expr->base.type)))
1310 return determine_lhs_ent(expr->select.compound, lhs_ent);
1314 case EXPR_UNARY_DEREFERENCE: {
1315 expression_t *const val = expr->unary.value;
1316 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1318 return determine_lhs_ent(val->unary.value, lhs_ent);
1320 mark_vars_read(val, NULL);
1326 mark_vars_read(expr, NULL);
1331 #define ENT_ANY ((entity_t*)-1)
1334 * Mark declarations, which are read. This is used to detect variables, which
1338 * x is not marked as "read", because it is only read to calculate its own new
1342 * x and y are not detected as "not read", because multiple variables are
1345 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1347 switch (expr->kind) {
1348 case EXPR_REFERENCE: {
1349 entity_t *const entity = expr->reference.entity;
1350 if (entity->kind != ENTITY_VARIABLE
1351 && entity->kind != ENTITY_PARAMETER)
1354 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1355 if (entity->kind == ENTITY_VARIABLE) {
1356 entity->variable.read = true;
1358 entity->parameter.read = true;
1365 // TODO respect pure/const
1366 mark_vars_read(expr->call.function, NULL);
1367 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1368 mark_vars_read(arg->expression, NULL);
1372 case EXPR_CONDITIONAL:
1373 // TODO lhs_decl should depend on whether true/false have an effect
1374 mark_vars_read(expr->conditional.condition, NULL);
1375 if (expr->conditional.true_expression != NULL)
1376 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1377 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1381 if (lhs_ent == ENT_ANY
1382 && !is_type_compound(skip_typeref(expr->base.type)))
1384 mark_vars_read(expr->select.compound, lhs_ent);
1387 case EXPR_ARRAY_ACCESS: {
1388 mark_vars_read(expr->array_access.index, lhs_ent);
1389 expression_t *const ref = expr->array_access.array_ref;
1390 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1391 if (lhs_ent == ENT_ANY)
1394 mark_vars_read(ref, lhs_ent);
1399 mark_vars_read(expr->va_arge.ap, lhs_ent);
1403 mark_vars_read(expr->va_copye.src, lhs_ent);
1406 case EXPR_UNARY_CAST:
1407 /* Special case: Use void cast to mark a variable as "read" */
1408 if (is_type_void(skip_typeref(expr->base.type)))
1413 case EXPR_UNARY_THROW:
1414 if (expr->unary.value == NULL)
1417 case EXPR_UNARY_DEREFERENCE:
1418 case EXPR_UNARY_DELETE:
1419 case EXPR_UNARY_DELETE_ARRAY:
1420 if (lhs_ent == ENT_ANY)
1424 case EXPR_UNARY_NEGATE:
1425 case EXPR_UNARY_PLUS:
1426 case EXPR_UNARY_BITWISE_NEGATE:
1427 case EXPR_UNARY_NOT:
1428 case EXPR_UNARY_TAKE_ADDRESS:
1429 case EXPR_UNARY_POSTFIX_INCREMENT:
1430 case EXPR_UNARY_POSTFIX_DECREMENT:
1431 case EXPR_UNARY_PREFIX_INCREMENT:
1432 case EXPR_UNARY_PREFIX_DECREMENT:
1433 case EXPR_UNARY_ASSUME:
1435 mark_vars_read(expr->unary.value, lhs_ent);
1438 case EXPR_BINARY_ADD:
1439 case EXPR_BINARY_SUB:
1440 case EXPR_BINARY_MUL:
1441 case EXPR_BINARY_DIV:
1442 case EXPR_BINARY_MOD:
1443 case EXPR_BINARY_EQUAL:
1444 case EXPR_BINARY_NOTEQUAL:
1445 case EXPR_BINARY_LESS:
1446 case EXPR_BINARY_LESSEQUAL:
1447 case EXPR_BINARY_GREATER:
1448 case EXPR_BINARY_GREATEREQUAL:
1449 case EXPR_BINARY_BITWISE_AND:
1450 case EXPR_BINARY_BITWISE_OR:
1451 case EXPR_BINARY_BITWISE_XOR:
1452 case EXPR_BINARY_LOGICAL_AND:
1453 case EXPR_BINARY_LOGICAL_OR:
1454 case EXPR_BINARY_SHIFTLEFT:
1455 case EXPR_BINARY_SHIFTRIGHT:
1456 case EXPR_BINARY_COMMA:
1457 case EXPR_BINARY_ISGREATER:
1458 case EXPR_BINARY_ISGREATEREQUAL:
1459 case EXPR_BINARY_ISLESS:
1460 case EXPR_BINARY_ISLESSEQUAL:
1461 case EXPR_BINARY_ISLESSGREATER:
1462 case EXPR_BINARY_ISUNORDERED:
1463 mark_vars_read(expr->binary.left, lhs_ent);
1464 mark_vars_read(expr->binary.right, lhs_ent);
1467 case EXPR_BINARY_ASSIGN:
1468 case EXPR_BINARY_MUL_ASSIGN:
1469 case EXPR_BINARY_DIV_ASSIGN:
1470 case EXPR_BINARY_MOD_ASSIGN:
1471 case EXPR_BINARY_ADD_ASSIGN:
1472 case EXPR_BINARY_SUB_ASSIGN:
1473 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1474 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1475 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1476 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1477 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1478 if (lhs_ent == ENT_ANY)
1480 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1481 mark_vars_read(expr->binary.right, lhs_ent);
1486 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1489 case EXPR_LITERAL_CASES:
1491 case EXPR_STRING_LITERAL:
1492 case EXPR_WIDE_STRING_LITERAL:
1493 case EXPR_COMPOUND_LITERAL: // TODO init?
1495 case EXPR_CLASSIFY_TYPE:
1498 case EXPR_BUILTIN_CONSTANT_P:
1499 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1501 case EXPR_STATEMENT: // TODO
1502 case EXPR_LABEL_ADDRESS:
1503 case EXPR_ENUM_CONSTANT:
1507 panic("unhandled expression");
1510 static designator_t *parse_designation(void)
1512 designator_t *result = NULL;
1513 designator_t **anchor = &result;
1516 designator_t *designator;
1517 switch (token.kind) {
1519 designator = allocate_ast_zero(sizeof(designator[0]));
1520 designator->source_position = token.base.source_position;
1522 add_anchor_token(']');
1523 designator->array_index = parse_constant_expression();
1524 rem_anchor_token(']');
1528 designator = allocate_ast_zero(sizeof(designator[0]));
1529 designator->source_position = token.base.source_position;
1531 designator->symbol = expect_identifier("while parsing designator", NULL);
1532 if (!designator->symbol)
1540 assert(designator != NULL);
1541 *anchor = designator;
1542 anchor = &designator->next;
1546 static initializer_t *initializer_from_string(array_type_t *const type,
1547 const string_t *const string)
1549 /* TODO: check len vs. size of array type */
1552 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1553 initializer->string.string = *string;
1558 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1559 const string_t *const string)
1561 /* TODO: check len vs. size of array type */
1564 initializer_t *const initializer =
1565 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1566 initializer->wide_string.string = *string;
1572 * Build an initializer from a given expression.
1574 static initializer_t *initializer_from_expression(type_t *orig_type,
1575 expression_t *expression)
1577 /* TODO check that expression is a constant expression */
1579 /* §6.7.8.14/15 char array may be initialized by string literals */
1580 type_t *type = skip_typeref(orig_type);
1581 type_t *expr_type_orig = expression->base.type;
1582 type_t *expr_type = skip_typeref(expr_type_orig);
1584 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1585 array_type_t *const array_type = &type->array;
1586 type_t *const element_type = skip_typeref(array_type->element_type);
1588 if (element_type->kind == TYPE_ATOMIC) {
1589 atomic_type_kind_t akind = element_type->atomic.akind;
1590 switch (expression->kind) {
1591 case EXPR_STRING_LITERAL:
1592 if (akind == ATOMIC_TYPE_CHAR
1593 || akind == ATOMIC_TYPE_SCHAR
1594 || akind == ATOMIC_TYPE_UCHAR) {
1595 return initializer_from_string(array_type,
1596 &expression->string_literal.value);
1600 case EXPR_WIDE_STRING_LITERAL: {
1601 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1602 if (get_unqualified_type(element_type) == bare_wchar_type) {
1603 return initializer_from_wide_string(array_type,
1604 &expression->string_literal.value);
1615 assign_error_t error = semantic_assign(type, expression);
1616 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1618 report_assign_error(error, type, expression, "initializer",
1619 &expression->base.source_position);
1621 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1622 result->value.value = create_implicit_cast(expression, type);
1628 * Parses an scalar initializer.
1630 * §6.7.8.11; eat {} without warning
1632 static initializer_t *parse_scalar_initializer(type_t *type,
1633 bool must_be_constant)
1635 /* there might be extra {} hierarchies */
1637 if (token.kind == '{') {
1638 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1642 } while (token.kind == '{');
1645 expression_t *expression = parse_assignment_expression();
1646 mark_vars_read(expression, NULL);
1647 if (must_be_constant && !is_linker_constant(expression)) {
1648 errorf(&expression->base.source_position,
1649 "initialisation expression '%E' is not constant",
1653 initializer_t *initializer = initializer_from_expression(type, expression);
1655 if (initializer == NULL) {
1656 errorf(&expression->base.source_position,
1657 "expression '%E' (type '%T') doesn't match expected type '%T'",
1658 expression, expression->base.type, type);
1663 bool additional_warning_displayed = false;
1664 while (braces > 0) {
1666 if (token.kind != '}') {
1667 if (!additional_warning_displayed) {
1668 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1669 additional_warning_displayed = true;
1680 * An entry in the type path.
1682 typedef struct type_path_entry_t type_path_entry_t;
1683 struct type_path_entry_t {
1684 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1686 size_t index; /**< For array types: the current index. */
1687 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1692 * A type path expression a position inside compound or array types.
1694 typedef struct type_path_t type_path_t;
1695 struct type_path_t {
1696 type_path_entry_t *path; /**< An flexible array containing the current path. */
1697 type_t *top_type; /**< type of the element the path points */
1698 size_t max_index; /**< largest index in outermost array */
1702 * Prints a type path for debugging.
1704 static __attribute__((unused)) void debug_print_type_path(
1705 const type_path_t *path)
1707 size_t len = ARR_LEN(path->path);
1709 for (size_t i = 0; i < len; ++i) {
1710 const type_path_entry_t *entry = & path->path[i];
1712 type_t *type = skip_typeref(entry->type);
1713 if (is_type_compound(type)) {
1714 /* in gcc mode structs can have no members */
1715 if (entry->v.compound_entry == NULL) {
1719 fprintf(stderr, ".%s",
1720 entry->v.compound_entry->base.symbol->string);
1721 } else if (is_type_array(type)) {
1722 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1724 fprintf(stderr, "-INVALID-");
1727 if (path->top_type != NULL) {
1728 fprintf(stderr, " (");
1729 print_type(path->top_type);
1730 fprintf(stderr, ")");
1735 * Return the top type path entry, ie. in a path
1736 * (type).a.b returns the b.
1738 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1740 size_t len = ARR_LEN(path->path);
1742 return &path->path[len-1];
1746 * Enlarge the type path by an (empty) element.
1748 static type_path_entry_t *append_to_type_path(type_path_t *path)
1750 size_t len = ARR_LEN(path->path);
1751 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1753 type_path_entry_t *result = & path->path[len];
1754 memset(result, 0, sizeof(result[0]));
1759 * Descending into a sub-type. Enter the scope of the current top_type.
1761 static void descend_into_subtype(type_path_t *path)
1763 type_t *orig_top_type = path->top_type;
1764 type_t *top_type = skip_typeref(orig_top_type);
1766 type_path_entry_t *top = append_to_type_path(path);
1767 top->type = top_type;
1769 if (is_type_compound(top_type)) {
1770 compound_t *const compound = top_type->compound.compound;
1771 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1773 if (entry != NULL) {
1774 top->v.compound_entry = &entry->declaration;
1775 path->top_type = entry->declaration.type;
1777 path->top_type = NULL;
1779 } else if (is_type_array(top_type)) {
1781 path->top_type = top_type->array.element_type;
1783 assert(!is_type_valid(top_type));
1788 * Pop an entry from the given type path, ie. returning from
1789 * (type).a.b to (type).a
1791 static void ascend_from_subtype(type_path_t *path)
1793 type_path_entry_t *top = get_type_path_top(path);
1795 path->top_type = top->type;
1797 size_t len = ARR_LEN(path->path);
1798 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1802 * Pop entries from the given type path until the given
1803 * path level is reached.
1805 static void ascend_to(type_path_t *path, size_t top_path_level)
1807 size_t len = ARR_LEN(path->path);
1809 while (len > top_path_level) {
1810 ascend_from_subtype(path);
1811 len = ARR_LEN(path->path);
1815 static bool walk_designator(type_path_t *path, const designator_t *designator,
1816 bool used_in_offsetof)
1818 for (; designator != NULL; designator = designator->next) {
1819 type_path_entry_t *top = get_type_path_top(path);
1820 type_t *orig_type = top->type;
1822 type_t *type = skip_typeref(orig_type);
1824 if (designator->symbol != NULL) {
1825 symbol_t *symbol = designator->symbol;
1826 if (!is_type_compound(type)) {
1827 if (is_type_valid(type)) {
1828 errorf(&designator->source_position,
1829 "'.%Y' designator used for non-compound type '%T'",
1833 top->type = type_error_type;
1834 top->v.compound_entry = NULL;
1835 orig_type = type_error_type;
1837 compound_t *compound = type->compound.compound;
1838 entity_t *iter = compound->members.entities;
1839 for (; iter != NULL; iter = iter->base.next) {
1840 if (iter->base.symbol == symbol) {
1845 errorf(&designator->source_position,
1846 "'%T' has no member named '%Y'", orig_type, symbol);
1849 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1850 if (used_in_offsetof && iter->compound_member.bitfield) {
1851 errorf(&designator->source_position,
1852 "offsetof designator '%Y' must not specify bitfield",
1857 top->type = orig_type;
1858 top->v.compound_entry = &iter->declaration;
1859 orig_type = iter->declaration.type;
1862 expression_t *array_index = designator->array_index;
1863 assert(designator->array_index != NULL);
1865 if (!is_type_array(type)) {
1866 if (is_type_valid(type)) {
1867 errorf(&designator->source_position,
1868 "[%E] designator used for non-array type '%T'",
1869 array_index, orig_type);
1874 long index = fold_constant_to_int(array_index);
1875 if (!used_in_offsetof) {
1877 errorf(&designator->source_position,
1878 "array index [%E] must be positive", array_index);
1879 } else if (type->array.size_constant) {
1880 long array_size = type->array.size;
1881 if (index >= array_size) {
1882 errorf(&designator->source_position,
1883 "designator [%E] (%d) exceeds array size %d",
1884 array_index, index, array_size);
1889 top->type = orig_type;
1890 top->v.index = (size_t) index;
1891 orig_type = type->array.element_type;
1893 path->top_type = orig_type;
1895 if (designator->next != NULL) {
1896 descend_into_subtype(path);
1902 static void advance_current_object(type_path_t *path, size_t top_path_level)
1904 type_path_entry_t *top = get_type_path_top(path);
1906 type_t *type = skip_typeref(top->type);
1907 if (is_type_union(type)) {
1908 /* in unions only the first element is initialized */
1909 top->v.compound_entry = NULL;
1910 } else if (is_type_struct(type)) {
1911 declaration_t *entry = top->v.compound_entry;
1913 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1914 if (next_entity != NULL) {
1915 assert(is_declaration(next_entity));
1916 entry = &next_entity->declaration;
1921 top->v.compound_entry = entry;
1922 if (entry != NULL) {
1923 path->top_type = entry->type;
1926 } else if (is_type_array(type)) {
1927 assert(is_type_array(type));
1931 if (!type->array.size_constant || top->v.index < type->array.size) {
1935 assert(!is_type_valid(type));
1939 /* we're past the last member of the current sub-aggregate, try if we
1940 * can ascend in the type hierarchy and continue with another subobject */
1941 size_t len = ARR_LEN(path->path);
1943 if (len > top_path_level) {
1944 ascend_from_subtype(path);
1945 advance_current_object(path, top_path_level);
1947 path->top_type = NULL;
1952 * skip any {...} blocks until a closing bracket is reached.
1954 static void skip_initializers(void)
1958 while (token.kind != '}') {
1959 if (token.kind == T_EOF)
1961 if (token.kind == '{') {
1969 static initializer_t *create_empty_initializer(void)
1971 static initializer_t empty_initializer
1972 = { .list = { { INITIALIZER_LIST }, 0 } };
1973 return &empty_initializer;
1977 * Parse a part of an initialiser for a struct or union,
1979 static initializer_t *parse_sub_initializer(type_path_t *path,
1980 type_t *outer_type, size_t top_path_level,
1981 parse_initializer_env_t *env)
1983 if (token.kind == '}') {
1984 /* empty initializer */
1985 return create_empty_initializer();
1988 type_t *orig_type = path->top_type;
1989 type_t *type = NULL;
1991 if (orig_type == NULL) {
1992 /* We are initializing an empty compound. */
1994 type = skip_typeref(orig_type);
1997 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2000 designator_t *designator = NULL;
2001 if (token.kind == '.' || token.kind == '[') {
2002 designator = parse_designation();
2003 goto finish_designator;
2004 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2005 /* GNU-style designator ("identifier: value") */
2006 designator = allocate_ast_zero(sizeof(designator[0]));
2007 designator->source_position = token.base.source_position;
2008 designator->symbol = token.identifier.symbol;
2013 /* reset path to toplevel, evaluate designator from there */
2014 ascend_to(path, top_path_level);
2015 if (!walk_designator(path, designator, false)) {
2016 /* can't continue after designation error */
2020 initializer_t *designator_initializer
2021 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2022 designator_initializer->designator.designator = designator;
2023 ARR_APP1(initializer_t*, initializers, designator_initializer);
2025 orig_type = path->top_type;
2026 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2031 if (token.kind == '{') {
2032 if (type != NULL && is_type_scalar(type)) {
2033 sub = parse_scalar_initializer(type, env->must_be_constant);
2036 if (env->entity != NULL) {
2038 "extra brace group at end of initializer for '%Y'",
2039 env->entity->base.symbol);
2041 errorf(HERE, "extra brace group at end of initializer");
2046 descend_into_subtype(path);
2049 add_anchor_token('}');
2050 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2052 rem_anchor_token('}');
2057 goto error_parse_next;
2059 ascend_from_subtype(path);
2062 /* must be an expression */
2063 expression_t *expression = parse_assignment_expression();
2064 mark_vars_read(expression, NULL);
2066 if (env->must_be_constant && !is_linker_constant(expression)) {
2067 errorf(&expression->base.source_position,
2068 "Initialisation expression '%E' is not constant",
2073 /* we are already outside, ... */
2074 if (outer_type == NULL)
2075 goto error_parse_next;
2076 type_t *const outer_type_skip = skip_typeref(outer_type);
2077 if (is_type_compound(outer_type_skip) &&
2078 !outer_type_skip->compound.compound->complete) {
2079 goto error_parse_next;
2082 source_position_t const* const pos = &expression->base.source_position;
2083 if (env->entity != NULL) {
2084 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2086 warningf(WARN_OTHER, pos, "excess elements in initializer");
2088 goto error_parse_next;
2091 /* handle { "string" } special case */
2092 if ((expression->kind == EXPR_STRING_LITERAL
2093 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2094 && outer_type != NULL) {
2095 sub = initializer_from_expression(outer_type, expression);
2098 if (token.kind != '}') {
2099 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2101 /* TODO: eat , ... */
2106 /* descend into subtypes until expression matches type */
2108 orig_type = path->top_type;
2109 type = skip_typeref(orig_type);
2111 sub = initializer_from_expression(orig_type, expression);
2115 if (!is_type_valid(type)) {
2118 if (is_type_scalar(type)) {
2119 errorf(&expression->base.source_position,
2120 "expression '%E' doesn't match expected type '%T'",
2121 expression, orig_type);
2125 descend_into_subtype(path);
2129 /* update largest index of top array */
2130 const type_path_entry_t *first = &path->path[0];
2131 type_t *first_type = first->type;
2132 first_type = skip_typeref(first_type);
2133 if (is_type_array(first_type)) {
2134 size_t index = first->v.index;
2135 if (index > path->max_index)
2136 path->max_index = index;
2139 /* append to initializers list */
2140 ARR_APP1(initializer_t*, initializers, sub);
2143 if (token.kind == '}') {
2146 add_anchor_token('}');
2148 rem_anchor_token('}');
2149 if (token.kind == '}') {
2154 /* advance to the next declaration if we are not at the end */
2155 advance_current_object(path, top_path_level);
2156 orig_type = path->top_type;
2157 if (orig_type != NULL)
2158 type = skip_typeref(orig_type);
2164 size_t len = ARR_LEN(initializers);
2165 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2166 initializer_t *result = allocate_ast_zero(size);
2167 result->kind = INITIALIZER_LIST;
2168 result->list.len = len;
2169 memcpy(&result->list.initializers, initializers,
2170 len * sizeof(initializers[0]));
2172 DEL_ARR_F(initializers);
2173 ascend_to(path, top_path_level+1);
2178 skip_initializers();
2179 DEL_ARR_F(initializers);
2180 ascend_to(path, top_path_level+1);
2184 static expression_t *make_size_literal(size_t value)
2186 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2187 literal->base.type = type_size_t;
2190 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2191 literal->literal.value = make_string(buf);
2197 * Parses an initializer. Parsers either a compound literal
2198 * (env->declaration == NULL) or an initializer of a declaration.
2200 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2202 type_t *type = skip_typeref(env->type);
2203 size_t max_index = 0;
2204 initializer_t *result;
2206 if (is_type_scalar(type)) {
2207 result = parse_scalar_initializer(type, env->must_be_constant);
2208 } else if (token.kind == '{') {
2212 memset(&path, 0, sizeof(path));
2213 path.top_type = env->type;
2214 path.path = NEW_ARR_F(type_path_entry_t, 0);
2216 descend_into_subtype(&path);
2218 add_anchor_token('}');
2219 result = parse_sub_initializer(&path, env->type, 1, env);
2220 rem_anchor_token('}');
2222 max_index = path.max_index;
2223 DEL_ARR_F(path.path);
2227 /* parse_scalar_initializer() also works in this case: we simply
2228 * have an expression without {} around it */
2229 result = parse_scalar_initializer(type, env->must_be_constant);
2232 /* §6.7.8:22 array initializers for arrays with unknown size determine
2233 * the array type size */
2234 if (is_type_array(type) && type->array.size_expression == NULL
2235 && result != NULL) {
2237 switch (result->kind) {
2238 case INITIALIZER_LIST:
2239 assert(max_index != 0xdeadbeaf);
2240 size = max_index + 1;
2243 case INITIALIZER_STRING:
2244 size = result->string.string.size;
2247 case INITIALIZER_WIDE_STRING:
2248 size = result->wide_string.string.size;
2251 case INITIALIZER_DESIGNATOR:
2252 case INITIALIZER_VALUE:
2253 /* can happen for parse errors */
2258 internal_errorf(HERE, "invalid initializer type");
2261 type_t *new_type = duplicate_type(type);
2263 new_type->array.size_expression = make_size_literal(size);
2264 new_type->array.size_constant = true;
2265 new_type->array.has_implicit_size = true;
2266 new_type->array.size = size;
2267 env->type = new_type;
2273 static void append_entity(scope_t *scope, entity_t *entity)
2275 if (scope->last_entity != NULL) {
2276 scope->last_entity->base.next = entity;
2278 scope->entities = entity;
2280 entity->base.parent_entity = current_entity;
2281 scope->last_entity = entity;
2285 static compound_t *parse_compound_type_specifier(bool is_struct)
2287 source_position_t const pos = *HERE;
2288 eat(is_struct ? T_struct : T_union);
2290 symbol_t *symbol = NULL;
2291 entity_t *entity = NULL;
2292 attribute_t *attributes = NULL;
2294 if (token.kind == T___attribute__) {
2295 attributes = parse_attributes(NULL);
2298 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2299 if (token.kind == T_IDENTIFIER) {
2300 /* the compound has a name, check if we have seen it already */
2301 symbol = token.identifier.symbol;
2302 entity = get_tag(symbol, kind);
2305 if (entity != NULL) {
2306 if (entity->base.parent_scope != current_scope &&
2307 (token.kind == '{' || token.kind == ';')) {
2308 /* we're in an inner scope and have a definition. Shadow
2309 * existing definition in outer scope */
2311 } else if (entity->compound.complete && token.kind == '{') {
2312 source_position_t const *const ppos = &entity->base.source_position;
2313 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2314 /* clear members in the hope to avoid further errors */
2315 entity->compound.members.entities = NULL;
2318 } else if (token.kind != '{') {
2319 char const *const msg =
2320 is_struct ? "while parsing struct type specifier" :
2321 "while parsing union type specifier";
2322 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2327 if (entity == NULL) {
2328 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol, &pos);
2329 entity->compound.alignment = 1;
2330 entity->base.parent_scope = current_scope;
2331 if (symbol != NULL) {
2332 environment_push(entity);
2334 append_entity(current_scope, entity);
2337 if (token.kind == '{') {
2338 parse_compound_type_entries(&entity->compound);
2340 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2341 if (symbol == NULL) {
2342 assert(anonymous_entity == NULL);
2343 anonymous_entity = entity;
2347 if (attributes != NULL) {
2348 handle_entity_attributes(attributes, entity);
2351 return &entity->compound;
2354 static void parse_enum_entries(type_t *const enum_type)
2358 if (token.kind == '}') {
2359 errorf(HERE, "empty enum not allowed");
2364 add_anchor_token('}');
2365 add_anchor_token(',');
2367 add_anchor_token('=');
2368 source_position_t pos;
2369 symbol_t *const symbol = expect_identifier("while parsing enum entry", &pos);
2370 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, &pos);
2371 entity->enum_value.enum_type = enum_type;
2372 rem_anchor_token('=');
2375 expression_t *value = parse_constant_expression();
2377 value = create_implicit_cast(value, enum_type);
2378 entity->enum_value.value = value;
2383 record_entity(entity, false);
2384 } while (next_if(',') && token.kind != '}');
2385 rem_anchor_token(',');
2386 rem_anchor_token('}');
2391 static type_t *parse_enum_specifier(void)
2393 source_position_t const pos = *HERE;
2398 switch (token.kind) {
2400 symbol = token.identifier.symbol;
2401 entity = get_tag(symbol, ENTITY_ENUM);
2404 if (entity != NULL) {
2405 if (entity->base.parent_scope != current_scope &&
2406 (token.kind == '{' || token.kind == ';')) {
2407 /* we're in an inner scope and have a definition. Shadow
2408 * existing definition in outer scope */
2410 } else if (entity->enume.complete && token.kind == '{') {
2411 source_position_t const *const ppos = &entity->base.source_position;
2412 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2423 parse_error_expected("while parsing enum type specifier",
2424 T_IDENTIFIER, '{', NULL);
2428 if (entity == NULL) {
2429 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2430 entity->base.parent_scope = current_scope;
2433 type_t *const type = allocate_type_zero(TYPE_ENUM);
2434 type->enumt.enume = &entity->enume;
2435 type->enumt.base.akind = ATOMIC_TYPE_INT;
2437 if (token.kind == '{') {
2438 if (symbol != NULL) {
2439 environment_push(entity);
2441 append_entity(current_scope, entity);
2442 entity->enume.complete = true;
2444 parse_enum_entries(type);
2445 parse_attributes(NULL);
2447 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2448 if (symbol == NULL) {
2449 assert(anonymous_entity == NULL);
2450 anonymous_entity = entity;
2452 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2453 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2460 * if a symbol is a typedef to another type, return true
2462 static bool is_typedef_symbol(symbol_t *symbol)
2464 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2465 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2468 static type_t *parse_typeof(void)
2475 add_anchor_token(')');
2477 expression_t *expression = NULL;
2479 switch (token.kind) {
2481 if (is_typedef_symbol(token.identifier.symbol)) {
2483 type = parse_typename();
2486 expression = parse_expression();
2487 type = revert_automatic_type_conversion(expression);
2492 rem_anchor_token(')');
2495 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2496 typeof_type->typeoft.expression = expression;
2497 typeof_type->typeoft.typeof_type = type;
2502 typedef enum specifiers_t {
2503 SPECIFIER_SIGNED = 1 << 0,
2504 SPECIFIER_UNSIGNED = 1 << 1,
2505 SPECIFIER_LONG = 1 << 2,
2506 SPECIFIER_INT = 1 << 3,
2507 SPECIFIER_DOUBLE = 1 << 4,
2508 SPECIFIER_CHAR = 1 << 5,
2509 SPECIFIER_WCHAR_T = 1 << 6,
2510 SPECIFIER_SHORT = 1 << 7,
2511 SPECIFIER_LONG_LONG = 1 << 8,
2512 SPECIFIER_FLOAT = 1 << 9,
2513 SPECIFIER_BOOL = 1 << 10,
2514 SPECIFIER_VOID = 1 << 11,
2515 SPECIFIER_INT8 = 1 << 12,
2516 SPECIFIER_INT16 = 1 << 13,
2517 SPECIFIER_INT32 = 1 << 14,
2518 SPECIFIER_INT64 = 1 << 15,
2519 SPECIFIER_INT128 = 1 << 16,
2520 SPECIFIER_COMPLEX = 1 << 17,
2521 SPECIFIER_IMAGINARY = 1 << 18,
2524 static type_t *get_typedef_type(symbol_t *symbol)
2526 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2527 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2530 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2531 type->typedeft.typedefe = &entity->typedefe;
2536 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2538 attribute_property_argument_t *const property = allocate_ast_zero(sizeof(*property));
2542 add_anchor_token(')');
2543 add_anchor_token(',');
2545 add_anchor_token('=');
2546 source_position_t pos;
2547 symbol_t *const prop_sym = expect_identifier("while parsing property declspec", &pos);
2548 rem_anchor_token('=');
2550 symbol_t **prop = NULL;
2552 if (streq(prop_sym->string, "put")) {
2553 prop = &property->put_symbol;
2554 } else if (streq(prop_sym->string, "get")) {
2555 prop = &property->get_symbol;
2557 errorf(&pos, "expected put or get in property declspec, but got '%Y'", prop_sym);
2561 add_anchor_token(T_IDENTIFIER);
2563 rem_anchor_token(T_IDENTIFIER);
2565 symbol_t *const sym = expect_identifier("while parsing property declspec", NULL);
2567 *prop = sym ? sym : sym_anonymous;
2568 } while (next_if(','));
2569 rem_anchor_token(',');
2570 rem_anchor_token(')');
2572 attribute->a.property = property;
2578 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2580 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2581 if (next_if(T_restrict)) {
2582 kind = ATTRIBUTE_MS_RESTRICT;
2583 } else if (token.kind == T_IDENTIFIER) {
2584 const char *name = token.identifier.symbol->string;
2585 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2587 const char *attribute_name = get_attribute_name(k);
2588 if (attribute_name != NULL && streq(attribute_name, name)) {
2594 if (kind == ATTRIBUTE_UNKNOWN) {
2595 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2598 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2602 attribute_t *attribute = allocate_attribute_zero(kind);
2605 if (kind == ATTRIBUTE_MS_PROPERTY) {
2606 return parse_attribute_ms_property(attribute);
2609 /* parse arguments */
2611 attribute->a.arguments = parse_attribute_arguments();
2616 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2621 if (token.kind != ')') {
2622 add_anchor_token(')');
2624 attribute_t **anchor = &first;
2626 while (*anchor != NULL)
2627 anchor = &(*anchor)->next;
2629 attribute_t *attribute
2630 = parse_microsoft_extended_decl_modifier_single();
2631 if (attribute == NULL)
2634 *anchor = attribute;
2635 anchor = &attribute->next;
2636 } while (next_if(','));
2638 rem_anchor_token(')');
2644 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2646 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2647 if (is_declaration(entity)) {
2648 entity->declaration.type = type_error_type;
2649 entity->declaration.implicit = true;
2650 } else if (kind == ENTITY_TYPEDEF) {
2651 entity->typedefe.type = type_error_type;
2652 entity->typedefe.builtin = true;
2654 if (kind != ENTITY_COMPOUND_MEMBER)
2655 record_entity(entity, false);
2659 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2661 type_t *type = NULL;
2662 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2663 unsigned type_specifiers = 0;
2664 bool newtype = false;
2665 bool saw_error = false;
2667 memset(specifiers, 0, sizeof(*specifiers));
2668 specifiers->source_position = token.base.source_position;
2671 specifiers->attributes = parse_attributes(specifiers->attributes);
2673 switch (token.kind) {
2675 #define MATCH_STORAGE_CLASS(token, class) \
2677 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2678 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2680 specifiers->storage_class = class; \
2681 if (specifiers->thread_local) \
2682 goto check_thread_storage_class; \
2686 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2687 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2688 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2689 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2690 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2693 specifiers->attributes
2694 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2698 if (specifiers->thread_local) {
2699 errorf(HERE, "duplicate '__thread'");
2701 specifiers->thread_local = true;
2702 check_thread_storage_class:
2703 switch (specifiers->storage_class) {
2704 case STORAGE_CLASS_EXTERN:
2705 case STORAGE_CLASS_NONE:
2706 case STORAGE_CLASS_STATIC:
2710 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2711 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2712 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2713 wrong_thread_storage_class:
2714 errorf(HERE, "'__thread' used with '%s'", wrong);
2721 /* type qualifiers */
2722 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2724 qualifiers |= qualifier; \
2728 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2729 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2730 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2731 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2732 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2733 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2734 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2735 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2737 /* type specifiers */
2738 #define MATCH_SPECIFIER(token, specifier, name) \
2740 if (type_specifiers & specifier) { \
2741 errorf(HERE, "multiple " name " type specifiers given"); \
2743 type_specifiers |= specifier; \
2748 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2749 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2750 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2751 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2752 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2753 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2754 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2755 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2756 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2757 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2758 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2759 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2760 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2761 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2762 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2763 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2764 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2765 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2769 specifiers->is_inline = true;
2773 case T__forceinline:
2775 specifiers->modifiers |= DM_FORCEINLINE;
2780 if (type_specifiers & SPECIFIER_LONG_LONG) {
2781 errorf(HERE, "too many long type specifiers given");
2782 } else if (type_specifiers & SPECIFIER_LONG) {
2783 type_specifiers |= SPECIFIER_LONG_LONG;
2785 type_specifiers |= SPECIFIER_LONG;
2790 #define CHECK_DOUBLE_TYPE() \
2791 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2794 CHECK_DOUBLE_TYPE();
2795 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2797 type->compound.compound = parse_compound_type_specifier(true);
2800 CHECK_DOUBLE_TYPE();
2801 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2802 type->compound.compound = parse_compound_type_specifier(false);
2805 CHECK_DOUBLE_TYPE();
2806 type = parse_enum_specifier();
2809 CHECK_DOUBLE_TYPE();
2810 type = parse_typeof();
2812 case T___builtin_va_list:
2813 CHECK_DOUBLE_TYPE();
2814 type = duplicate_type(type_valist);
2818 case T_IDENTIFIER: {
2819 /* only parse identifier if we haven't found a type yet */
2820 if (type != NULL || type_specifiers != 0) {
2821 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2822 * declaration, so it doesn't generate errors about expecting '(' or
2824 switch (look_ahead(1)->kind) {
2831 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2835 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2840 goto finish_specifiers;
2844 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2845 if (typedef_type == NULL) {
2846 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2847 * declaration, so it doesn't generate 'implicit int' followed by more
2848 * errors later on. */
2849 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2855 errorf(HERE, "%K does not name a type", &token);
2857 symbol_t *symbol = token.identifier.symbol;
2859 = create_error_entity(symbol, ENTITY_TYPEDEF);
2861 type = allocate_type_zero(TYPE_TYPEDEF);
2862 type->typedeft.typedefe = &entity->typedefe;
2870 goto finish_specifiers;
2875 type = typedef_type;
2879 /* function specifier */
2881 goto finish_specifiers;
2886 specifiers->attributes = parse_attributes(specifiers->attributes);
2888 if (type == NULL || (saw_error && type_specifiers != 0)) {
2889 atomic_type_kind_t atomic_type;
2891 /* match valid basic types */
2892 switch (type_specifiers) {
2893 case SPECIFIER_VOID:
2894 atomic_type = ATOMIC_TYPE_VOID;
2896 case SPECIFIER_WCHAR_T:
2897 atomic_type = ATOMIC_TYPE_WCHAR_T;
2899 case SPECIFIER_CHAR:
2900 atomic_type = ATOMIC_TYPE_CHAR;
2902 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2903 atomic_type = ATOMIC_TYPE_SCHAR;
2905 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2906 atomic_type = ATOMIC_TYPE_UCHAR;
2908 case SPECIFIER_SHORT:
2909 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2910 case SPECIFIER_SHORT | SPECIFIER_INT:
2911 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2912 atomic_type = ATOMIC_TYPE_SHORT;
2914 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2915 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2916 atomic_type = ATOMIC_TYPE_USHORT;
2919 case SPECIFIER_SIGNED:
2920 case SPECIFIER_SIGNED | SPECIFIER_INT:
2921 atomic_type = ATOMIC_TYPE_INT;
2923 case SPECIFIER_UNSIGNED:
2924 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2925 atomic_type = ATOMIC_TYPE_UINT;
2927 case SPECIFIER_LONG:
2928 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2929 case SPECIFIER_LONG | SPECIFIER_INT:
2930 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2931 atomic_type = ATOMIC_TYPE_LONG;
2933 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2934 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2935 atomic_type = ATOMIC_TYPE_ULONG;
2938 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2939 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2940 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2941 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2943 atomic_type = ATOMIC_TYPE_LONGLONG;
2944 goto warn_about_long_long;
2946 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2947 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2949 atomic_type = ATOMIC_TYPE_ULONGLONG;
2950 warn_about_long_long:
2951 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2954 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2955 atomic_type = unsigned_int8_type_kind;
2958 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2959 atomic_type = unsigned_int16_type_kind;
2962 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
2963 atomic_type = unsigned_int32_type_kind;
2966 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
2967 atomic_type = unsigned_int64_type_kind;
2970 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
2971 atomic_type = unsigned_int128_type_kind;
2974 case SPECIFIER_INT8:
2975 case SPECIFIER_SIGNED | SPECIFIER_INT8:
2976 atomic_type = int8_type_kind;
2979 case SPECIFIER_INT16:
2980 case SPECIFIER_SIGNED | SPECIFIER_INT16:
2981 atomic_type = int16_type_kind;
2984 case SPECIFIER_INT32:
2985 case SPECIFIER_SIGNED | SPECIFIER_INT32:
2986 atomic_type = int32_type_kind;
2989 case SPECIFIER_INT64:
2990 case SPECIFIER_SIGNED | SPECIFIER_INT64:
2991 atomic_type = int64_type_kind;
2994 case SPECIFIER_INT128:
2995 case SPECIFIER_SIGNED | SPECIFIER_INT128:
2996 atomic_type = int128_type_kind;
2999 case SPECIFIER_FLOAT:
3000 atomic_type = ATOMIC_TYPE_FLOAT;
3002 case SPECIFIER_DOUBLE:
3003 atomic_type = ATOMIC_TYPE_DOUBLE;
3005 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3006 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3008 case SPECIFIER_BOOL:
3009 atomic_type = ATOMIC_TYPE_BOOL;
3011 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3012 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3013 atomic_type = ATOMIC_TYPE_FLOAT;
3015 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3016 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3017 atomic_type = ATOMIC_TYPE_DOUBLE;
3019 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3020 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3021 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3024 /* invalid specifier combination, give an error message */
3025 source_position_t const* const pos = &specifiers->source_position;
3026 if (type_specifiers == 0) {
3028 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3029 if (!(c_mode & _CXX) && !strict_mode) {
3030 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3031 atomic_type = ATOMIC_TYPE_INT;
3034 errorf(pos, "no type specifiers given in declaration");
3037 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3038 (type_specifiers & SPECIFIER_UNSIGNED)) {
3039 errorf(pos, "signed and unsigned specifiers given");
3040 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3041 errorf(pos, "only integer types can be signed or unsigned");
3043 errorf(pos, "multiple datatypes in declaration");
3049 if (type_specifiers & SPECIFIER_COMPLEX) {
3050 type = allocate_type_zero(TYPE_COMPLEX);
3051 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3052 type = allocate_type_zero(TYPE_IMAGINARY);
3054 type = allocate_type_zero(TYPE_ATOMIC);
3056 type->atomic.akind = atomic_type;
3058 } else if (type_specifiers != 0) {
3059 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3062 /* FIXME: check type qualifiers here */
3063 type->base.qualifiers = qualifiers;
3066 type = identify_new_type(type);
3068 type = typehash_insert(type);
3071 if (specifiers->attributes != NULL)
3072 type = handle_type_attributes(specifiers->attributes, type);
3073 specifiers->type = type;
3077 specifiers->type = type_error_type;
3080 static type_qualifiers_t parse_type_qualifiers(void)
3082 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3085 switch (token.kind) {
3086 /* type qualifiers */
3087 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3088 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3089 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3090 /* microsoft extended type modifiers */
3091 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3092 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3093 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3094 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3095 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3104 * Parses an K&R identifier list
3106 static void parse_identifier_list(scope_t *scope)
3108 assert(token.kind == T_IDENTIFIER);
3110 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3111 /* a K&R parameter has no type, yet */
3115 append_entity(scope, entity);
3116 } while (next_if(',') && token.kind == T_IDENTIFIER);
3119 static entity_t *parse_parameter(void)
3121 declaration_specifiers_t specifiers;
3122 parse_declaration_specifiers(&specifiers);
3124 entity_t *entity = parse_declarator(&specifiers,
3125 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3126 anonymous_entity = NULL;
3130 static void semantic_parameter_incomplete(const entity_t *entity)
3132 assert(entity->kind == ENTITY_PARAMETER);
3134 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3135 * list in a function declarator that is part of a
3136 * definition of that function shall not have
3137 * incomplete type. */
3138 type_t *type = skip_typeref(entity->declaration.type);
3139 if (is_type_incomplete(type)) {
3140 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3144 static bool has_parameters(void)
3146 /* func(void) is not a parameter */
3147 if (look_ahead(1)->kind != ')')
3149 if (token.kind == T_IDENTIFIER) {
3150 entity_t const *const entity
3151 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3154 if (entity->kind != ENTITY_TYPEDEF)
3156 type_t const *const type = skip_typeref(entity->typedefe.type);
3157 if (!is_type_void(type))
3159 if (c_mode & _CXX) {
3160 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3161 * is not allowed. */
3162 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3163 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3164 /* §6.7.5.3:10 Qualification is not allowed here. */
3165 errorf(HERE, "'void' as parameter must not have type qualifiers");
3167 } else if (token.kind != T_void) {
3175 * Parses function type parameters (and optionally creates variable_t entities
3176 * for them in a scope)
3178 static void parse_parameters(function_type_t *type, scope_t *scope)
3181 add_anchor_token(')');
3183 if (token.kind == T_IDENTIFIER &&
3184 !is_typedef_symbol(token.identifier.symbol) &&
3185 (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
3186 type->kr_style_parameters = true;
3187 parse_identifier_list(scope);
3188 } else if (token.kind == ')') {
3189 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3190 if (!(c_mode & _CXX))
3191 type->unspecified_parameters = true;
3192 } else if (has_parameters()) {
3193 function_parameter_t **anchor = &type->parameters;
3194 add_anchor_token(',');
3196 switch (token.kind) {
3199 type->variadic = true;
3200 goto parameters_finished;
3205 entity_t *entity = parse_parameter();
3206 if (entity->kind == ENTITY_TYPEDEF) {
3207 errorf(&entity->base.source_position,
3208 "typedef not allowed as function parameter");
3211 assert(is_declaration(entity));
3213 semantic_parameter_incomplete(entity);
3215 function_parameter_t *const parameter =
3216 allocate_parameter(entity->declaration.type);
3218 if (scope != NULL) {
3219 append_entity(scope, entity);
3222 *anchor = parameter;
3223 anchor = ¶meter->next;
3228 goto parameters_finished;
3230 } while (next_if(','));
3231 parameters_finished:
3232 rem_anchor_token(',');
3235 rem_anchor_token(')');
3239 typedef enum construct_type_kind_t {
3240 CONSTRUCT_POINTER = 1,
3241 CONSTRUCT_REFERENCE,
3244 } construct_type_kind_t;
3246 typedef union construct_type_t construct_type_t;
3248 typedef struct construct_type_base_t {
3249 construct_type_kind_t kind;
3250 source_position_t pos;
3251 construct_type_t *next;
3252 } construct_type_base_t;
3254 typedef struct parsed_pointer_t {
3255 construct_type_base_t base;
3256 type_qualifiers_t type_qualifiers;
3257 variable_t *base_variable; /**< MS __based extension. */
3260 typedef struct parsed_reference_t {
3261 construct_type_base_t base;
3262 } parsed_reference_t;
3264 typedef struct construct_function_type_t {
3265 construct_type_base_t base;
3266 type_t *function_type;
3267 } construct_function_type_t;
3269 typedef struct parsed_array_t {
3270 construct_type_base_t base;
3271 type_qualifiers_t type_qualifiers;
3277 union construct_type_t {
3278 construct_type_kind_t kind;
3279 construct_type_base_t base;
3280 parsed_pointer_t pointer;
3281 parsed_reference_t reference;
3282 construct_function_type_t function;
3283 parsed_array_t array;
3286 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3288 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3289 memset(cons, 0, size);
3291 cons->base.pos = *HERE;
3296 static construct_type_t *parse_pointer_declarator(void)
3298 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3300 cons->pointer.type_qualifiers = parse_type_qualifiers();
3301 //cons->pointer.base_variable = base_variable;
3306 /* ISO/IEC 14882:1998(E) §8.3.2 */
3307 static construct_type_t *parse_reference_declarator(void)
3309 if (!(c_mode & _CXX))
3310 errorf(HERE, "references are only available for C++");
3312 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3319 static construct_type_t *parse_array_declarator(void)
3321 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3322 parsed_array_t *const array = &cons->array;
3325 add_anchor_token(']');
3327 bool is_static = next_if(T_static);
3329 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3332 is_static = next_if(T_static);
3334 array->type_qualifiers = type_qualifiers;
3335 array->is_static = is_static;
3337 expression_t *size = NULL;
3338 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3339 array->is_variable = true;
3341 } else if (token.kind != ']') {
3342 size = parse_assignment_expression();
3344 /* §6.7.5.2:1 Array size must have integer type */
3345 type_t *const orig_type = size->base.type;
3346 type_t *const type = skip_typeref(orig_type);
3347 if (!is_type_integer(type) && is_type_valid(type)) {
3348 errorf(&size->base.source_position,
3349 "array size '%E' must have integer type but has type '%T'",
3354 mark_vars_read(size, NULL);
3357 if (is_static && size == NULL)
3358 errorf(&array->base.pos, "static array parameters require a size");
3360 rem_anchor_token(']');
3366 static construct_type_t *parse_function_declarator(scope_t *scope)
3368 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3370 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3371 function_type_t *ftype = &type->function;
3373 ftype->linkage = current_linkage;
3374 ftype->calling_convention = CC_DEFAULT;
3376 parse_parameters(ftype, scope);
3378 cons->function.function_type = type;
3383 typedef struct parse_declarator_env_t {
3384 bool may_be_abstract : 1;
3385 bool must_be_abstract : 1;
3386 decl_modifiers_t modifiers;
3388 source_position_t source_position;
3390 attribute_t *attributes;
3391 } parse_declarator_env_t;
3394 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3396 /* construct a single linked list of construct_type_t's which describe
3397 * how to construct the final declarator type */
3398 construct_type_t *first = NULL;
3399 construct_type_t **anchor = &first;
3401 env->attributes = parse_attributes(env->attributes);
3404 construct_type_t *type;
3405 //variable_t *based = NULL; /* MS __based extension */
3406 switch (token.kind) {
3408 type = parse_reference_declarator();
3412 panic("based not supported anymore");
3417 type = parse_pointer_declarator();
3421 goto ptr_operator_end;
3425 anchor = &type->base.next;
3427 /* TODO: find out if this is correct */
3428 env->attributes = parse_attributes(env->attributes);
3432 construct_type_t *inner_types = NULL;
3434 switch (token.kind) {
3436 if (env->must_be_abstract) {
3437 errorf(HERE, "no identifier expected in typename");
3439 env->symbol = token.identifier.symbol;
3440 env->source_position = token.base.source_position;
3446 /* Parenthesized declarator or function declarator? */
3447 token_t const *const la1 = look_ahead(1);
3448 switch (la1->kind) {
3450 if (is_typedef_symbol(la1->identifier.symbol)) {
3452 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3453 * interpreted as ``function with no parameter specification'', rather
3454 * than redundant parentheses around the omitted identifier. */
3456 /* Function declarator. */
3457 if (!env->may_be_abstract) {
3458 errorf(HERE, "function declarator must have a name");
3465 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3466 /* Paranthesized declarator. */
3468 add_anchor_token(')');
3469 inner_types = parse_inner_declarator(env);
3470 if (inner_types != NULL) {
3471 /* All later declarators only modify the return type */
3472 env->must_be_abstract = true;
3474 rem_anchor_token(')');
3483 if (env->may_be_abstract)
3485 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3490 construct_type_t **const p = anchor;
3493 construct_type_t *type;
3494 switch (token.kind) {
3496 scope_t *scope = NULL;
3497 if (!env->must_be_abstract) {
3498 scope = &env->parameters;
3501 type = parse_function_declarator(scope);
3505 type = parse_array_declarator();
3508 goto declarator_finished;
3511 /* insert in the middle of the list (at p) */
3512 type->base.next = *p;
3515 anchor = &type->base.next;
3518 declarator_finished:
3519 /* append inner_types at the end of the list, we don't to set anchor anymore
3520 * as it's not needed anymore */
3521 *anchor = inner_types;
3526 static type_t *construct_declarator_type(construct_type_t *construct_list,
3529 construct_type_t *iter = construct_list;
3530 for (; iter != NULL; iter = iter->base.next) {
3531 source_position_t const* const pos = &iter->base.pos;
3532 switch (iter->kind) {
3533 case CONSTRUCT_FUNCTION: {
3534 construct_function_type_t *function = &iter->function;
3535 type_t *function_type = function->function_type;
3537 function_type->function.return_type = type;
3539 type_t *skipped_return_type = skip_typeref(type);
3541 if (is_type_function(skipped_return_type)) {
3542 errorf(pos, "function returning function is not allowed");
3543 } else if (is_type_array(skipped_return_type)) {
3544 errorf(pos, "function returning array is not allowed");
3546 if (skipped_return_type->base.qualifiers != 0) {
3547 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3551 /* The function type was constructed earlier. Freeing it here will
3552 * destroy other types. */
3553 type = typehash_insert(function_type);
3557 case CONSTRUCT_POINTER: {
3558 if (is_type_reference(skip_typeref(type)))
3559 errorf(pos, "cannot declare a pointer to reference");
3561 parsed_pointer_t *pointer = &iter->pointer;
3562 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3566 case CONSTRUCT_REFERENCE:
3567 if (is_type_reference(skip_typeref(type)))
3568 errorf(pos, "cannot declare a reference to reference");
3570 type = make_reference_type(type);
3573 case CONSTRUCT_ARRAY: {
3574 if (is_type_reference(skip_typeref(type)))
3575 errorf(pos, "cannot declare an array of references");
3577 parsed_array_t *array = &iter->array;
3578 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3580 expression_t *size_expression = array->size;
3581 if (size_expression != NULL) {
3583 = create_implicit_cast(size_expression, type_size_t);
3586 array_type->base.qualifiers = array->type_qualifiers;
3587 array_type->array.element_type = type;
3588 array_type->array.is_static = array->is_static;
3589 array_type->array.is_variable = array->is_variable;
3590 array_type->array.size_expression = size_expression;
3592 if (size_expression != NULL) {
3593 switch (is_constant_expression(size_expression)) {
3594 case EXPR_CLASS_CONSTANT: {
3595 long const size = fold_constant_to_int(size_expression);
3596 array_type->array.size = size;
3597 array_type->array.size_constant = true;
3598 /* §6.7.5.2:1 If the expression is a constant expression,
3599 * it shall have a value greater than zero. */
3601 errorf(&size_expression->base.source_position,
3602 "size of array must be greater than zero");
3603 } else if (size == 0 && !GNU_MODE) {
3604 errorf(&size_expression->base.source_position,
3605 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3610 case EXPR_CLASS_VARIABLE:
3611 array_type->array.is_vla = true;
3614 case EXPR_CLASS_ERROR:
3619 type_t *skipped_type = skip_typeref(type);
3621 if (is_type_incomplete(skipped_type)) {
3622 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3623 } else if (is_type_function(skipped_type)) {
3624 errorf(pos, "array of functions is not allowed");
3626 type = identify_new_type(array_type);
3630 internal_errorf(pos, "invalid type construction found");
3636 static type_t *automatic_type_conversion(type_t *orig_type);
3638 static type_t *semantic_parameter(const source_position_t *pos,
3640 const declaration_specifiers_t *specifiers,
3641 entity_t const *const param)
3643 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3644 * shall be adjusted to ``qualified pointer to type'',
3646 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3647 * type'' shall be adjusted to ``pointer to function
3648 * returning type'', as in 6.3.2.1. */
3649 type = automatic_type_conversion(type);
3651 if (specifiers->is_inline && is_type_valid(type)) {
3652 errorf(pos, "'%N' declared 'inline'", param);
3655 /* §6.9.1:6 The declarations in the declaration list shall contain
3656 * no storage-class specifier other than register and no
3657 * initializations. */
3658 if (specifiers->thread_local || (
3659 specifiers->storage_class != STORAGE_CLASS_NONE &&
3660 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3662 errorf(pos, "invalid storage class for '%N'", param);
3665 /* delay test for incomplete type, because we might have (void)
3666 * which is legal but incomplete... */
3671 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3672 declarator_flags_t flags)
3674 parse_declarator_env_t env;
3675 memset(&env, 0, sizeof(env));
3676 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3678 construct_type_t *construct_type = parse_inner_declarator(&env);
3680 construct_declarator_type(construct_type, specifiers->type);
3681 type_t *type = skip_typeref(orig_type);
3683 if (construct_type != NULL) {
3684 obstack_free(&temp_obst, construct_type);
3687 attribute_t *attributes = parse_attributes(env.attributes);
3688 /* append (shared) specifier attribute behind attributes of this
3690 attribute_t **anchor = &attributes;
3691 while (*anchor != NULL)
3692 anchor = &(*anchor)->next;
3693 *anchor = specifiers->attributes;
3696 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3697 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3698 entity->typedefe.type = orig_type;
3700 if (anonymous_entity != NULL) {
3701 if (is_type_compound(type)) {
3702 assert(anonymous_entity->compound.alias == NULL);
3703 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3704 anonymous_entity->kind == ENTITY_UNION);
3705 anonymous_entity->compound.alias = entity;
3706 anonymous_entity = NULL;
3707 } else if (is_type_enum(type)) {
3708 assert(anonymous_entity->enume.alias == NULL);
3709 assert(anonymous_entity->kind == ENTITY_ENUM);
3710 anonymous_entity->enume.alias = entity;
3711 anonymous_entity = NULL;
3715 /* create a declaration type entity */
3716 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3717 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3718 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3720 if (env.symbol != NULL) {
3721 if (specifiers->is_inline && is_type_valid(type)) {
3722 errorf(&env.source_position,
3723 "compound member '%Y' declared 'inline'", env.symbol);
3726 if (specifiers->thread_local ||
3727 specifiers->storage_class != STORAGE_CLASS_NONE) {
3728 errorf(&env.source_position,
3729 "compound member '%Y' must have no storage class",
3733 } else if (flags & DECL_IS_PARAMETER) {
3734 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3735 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3736 } else if (is_type_function(type)) {
3737 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3738 entity->function.is_inline = specifiers->is_inline;
3739 entity->function.elf_visibility = default_visibility;
3740 entity->function.parameters = env.parameters;
3742 if (env.symbol != NULL) {
3743 /* this needs fixes for C++ */
3744 bool in_function_scope = current_function != NULL;
3746 if (specifiers->thread_local || (
3747 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3748 specifiers->storage_class != STORAGE_CLASS_NONE &&
3749 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3751 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3755 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3756 entity->variable.elf_visibility = default_visibility;
3757 entity->variable.thread_local = specifiers->thread_local;
3759 if (env.symbol != NULL) {
3760 if (specifiers->is_inline && is_type_valid(type)) {
3761 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3764 bool invalid_storage_class = false;
3765 if (current_scope == file_scope) {
3766 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3767 specifiers->storage_class != STORAGE_CLASS_NONE &&
3768 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3769 invalid_storage_class = true;
3772 if (specifiers->thread_local &&
3773 specifiers->storage_class == STORAGE_CLASS_NONE) {
3774 invalid_storage_class = true;
3777 if (invalid_storage_class) {
3778 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3783 entity->declaration.type = orig_type;
3784 entity->declaration.alignment = get_type_alignment(orig_type);
3785 entity->declaration.modifiers = env.modifiers;
3786 entity->declaration.attributes = attributes;
3788 storage_class_t storage_class = specifiers->storage_class;
3789 entity->declaration.declared_storage_class = storage_class;
3791 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3792 storage_class = STORAGE_CLASS_AUTO;
3793 entity->declaration.storage_class = storage_class;
3796 if (attributes != NULL) {
3797 handle_entity_attributes(attributes, entity);
3800 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3801 adapt_special_functions(&entity->function);
3807 static type_t *parse_abstract_declarator(type_t *base_type)
3809 parse_declarator_env_t env;
3810 memset(&env, 0, sizeof(env));
3811 env.may_be_abstract = true;
3812 env.must_be_abstract = true;
3814 construct_type_t *construct_type = parse_inner_declarator(&env);
3816 type_t *result = construct_declarator_type(construct_type, base_type);
3817 if (construct_type != NULL) {
3818 obstack_free(&temp_obst, construct_type);
3820 result = handle_type_attributes(env.attributes, result);
3826 * Check if the declaration of main is suspicious. main should be a
3827 * function with external linkage, returning int, taking either zero
3828 * arguments, two, or three arguments of appropriate types, ie.
3830 * int main([ int argc, char **argv [, char **env ] ]).
3832 * @param decl the declaration to check
3833 * @param type the function type of the declaration
3835 static void check_main(const entity_t *entity)
3837 const source_position_t *pos = &entity->base.source_position;
3838 if (entity->kind != ENTITY_FUNCTION) {
3839 warningf(WARN_MAIN, pos, "'main' is not a function");
3843 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3844 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3847 type_t *type = skip_typeref(entity->declaration.type);
3848 assert(is_type_function(type));
3850 function_type_t const *const func_type = &type->function;
3851 type_t *const ret_type = func_type->return_type;
3852 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3853 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3855 const function_parameter_t *parm = func_type->parameters;
3857 type_t *const first_type = skip_typeref(parm->type);
3858 type_t *const first_type_unqual = get_unqualified_type(first_type);
3859 if (!types_compatible(first_type_unqual, type_int)) {
3860 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3864 type_t *const second_type = skip_typeref(parm->type);
3865 type_t *const second_type_unqual
3866 = get_unqualified_type(second_type);
3867 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3868 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3872 type_t *const third_type = skip_typeref(parm->type);
3873 type_t *const third_type_unqual
3874 = get_unqualified_type(third_type);
3875 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3876 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3880 goto warn_arg_count;
3884 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3890 * Check if a symbol is the equal to "main".
3892 static bool is_sym_main(const symbol_t *const sym)
3894 return streq(sym->string, "main");
3897 static void error_redefined_as_different_kind(const source_position_t *pos,
3898 const entity_t *old, entity_kind_t new_kind)
3900 char const *const what = get_entity_kind_name(new_kind);
3901 source_position_t const *const ppos = &old->base.source_position;
3902 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3905 static bool is_entity_valid(entity_t *const ent)
3907 if (is_declaration(ent)) {
3908 return is_type_valid(skip_typeref(ent->declaration.type));
3909 } else if (ent->kind == ENTITY_TYPEDEF) {
3910 return is_type_valid(skip_typeref(ent->typedefe.type));
3915 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3917 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3918 if (attributes_equal(tattr, attr))
3925 * test wether new_list contains any attributes not included in old_list
3927 static bool has_new_attributes(const attribute_t *old_list,
3928 const attribute_t *new_list)
3930 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3931 if (!contains_attribute(old_list, attr))
3938 * Merge in attributes from an attribute list (probably from a previous
3939 * declaration with the same name). Warning: destroys the old structure
3940 * of the attribute list - don't reuse attributes after this call.
3942 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3945 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3947 if (contains_attribute(decl->attributes, attr))
3950 /* move attribute to new declarations attributes list */
3951 attr->next = decl->attributes;
3952 decl->attributes = attr;
3957 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
3958 * for various problems that occur for multiple definitions
3960 entity_t *record_entity(entity_t *entity, const bool is_definition)
3962 const symbol_t *const symbol = entity->base.symbol;
3963 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
3964 const source_position_t *pos = &entity->base.source_position;
3966 /* can happen in error cases */
3970 entity_t *const previous_entity = get_entity(symbol, namespc);
3971 /* pushing the same entity twice will break the stack structure */
3972 assert(previous_entity != entity);
3974 if (entity->kind == ENTITY_FUNCTION) {
3975 type_t *const orig_type = entity->declaration.type;
3976 type_t *const type = skip_typeref(orig_type);
3978 assert(is_type_function(type));
3979 if (type->function.unspecified_parameters &&
3980 previous_entity == NULL &&
3981 !entity->declaration.implicit) {
3982 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
3985 if (current_scope == file_scope && is_sym_main(symbol)) {
3990 if (is_declaration(entity) &&
3991 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
3992 current_scope != file_scope &&
3993 !entity->declaration.implicit) {
3994 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
3997 if (previous_entity != NULL) {
3998 source_position_t const *const ppos = &previous_entity->base.source_position;
4000 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4001 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4002 assert(previous_entity->kind == ENTITY_PARAMETER);
4003 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4007 if (previous_entity->base.parent_scope == current_scope) {
4008 if (previous_entity->kind != entity->kind) {
4009 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4010 error_redefined_as_different_kind(pos, previous_entity,
4015 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4016 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4019 if (previous_entity->kind == ENTITY_TYPEDEF) {
4020 type_t *const type = skip_typeref(entity->typedefe.type);
4021 type_t *const prev_type
4022 = skip_typeref(previous_entity->typedefe.type);
4023 if (c_mode & _CXX) {
4024 /* C++ allows double typedef if they are identical
4025 * (after skipping typedefs) */
4026 if (type == prev_type)
4029 /* GCC extension: redef in system headers is allowed */
4030 if ((pos->is_system_header || ppos->is_system_header) &&
4031 types_compatible(type, prev_type))
4034 errorf(pos, "redefinition of '%N' (declared %P)",
4039 /* at this point we should have only VARIABLES or FUNCTIONS */
4040 assert(is_declaration(previous_entity) && is_declaration(entity));
4042 declaration_t *const prev_decl = &previous_entity->declaration;
4043 declaration_t *const decl = &entity->declaration;
4045 /* can happen for K&R style declarations */
4046 if (prev_decl->type == NULL &&
4047 previous_entity->kind == ENTITY_PARAMETER &&
4048 entity->kind == ENTITY_PARAMETER) {
4049 prev_decl->type = decl->type;
4050 prev_decl->storage_class = decl->storage_class;
4051 prev_decl->declared_storage_class = decl->declared_storage_class;
4052 prev_decl->modifiers = decl->modifiers;
4053 return previous_entity;
4056 type_t *const type = skip_typeref(decl->type);
4057 type_t *const prev_type = skip_typeref(prev_decl->type);
4059 if (!types_compatible(type, prev_type)) {
4060 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4062 unsigned old_storage_class = prev_decl->storage_class;
4064 if (is_definition &&
4066 !(prev_decl->modifiers & DM_USED) &&
4067 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4068 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4071 storage_class_t new_storage_class = decl->storage_class;
4073 /* pretend no storage class means extern for function
4074 * declarations (except if the previous declaration is neither
4075 * none nor extern) */
4076 if (entity->kind == ENTITY_FUNCTION) {
4077 /* the previous declaration could have unspecified parameters or
4078 * be a typedef, so use the new type */
4079 if (prev_type->function.unspecified_parameters || is_definition)
4080 prev_decl->type = type;
4082 switch (old_storage_class) {
4083 case STORAGE_CLASS_NONE:
4084 old_storage_class = STORAGE_CLASS_EXTERN;
4087 case STORAGE_CLASS_EXTERN:
4088 if (is_definition) {
4089 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4090 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4092 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4093 new_storage_class = STORAGE_CLASS_EXTERN;
4100 } else if (is_type_incomplete(prev_type)) {
4101 prev_decl->type = type;
4104 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4105 new_storage_class == STORAGE_CLASS_EXTERN) {
4107 warn_redundant_declaration: ;
4109 = has_new_attributes(prev_decl->attributes,
4111 if (has_new_attrs) {
4112 merge_in_attributes(decl, prev_decl->attributes);
4113 } else if (!is_definition &&
4114 is_type_valid(prev_type) &&
4115 !pos->is_system_header) {
4116 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4118 } else if (current_function == NULL) {
4119 if (old_storage_class != STORAGE_CLASS_STATIC &&
4120 new_storage_class == STORAGE_CLASS_STATIC) {
4121 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4122 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4123 prev_decl->storage_class = STORAGE_CLASS_NONE;
4124 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4126 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4128 goto error_redeclaration;
4129 goto warn_redundant_declaration;
4131 } else if (is_type_valid(prev_type)) {
4132 if (old_storage_class == new_storage_class) {
4133 error_redeclaration:
4134 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4136 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4141 prev_decl->modifiers |= decl->modifiers;
4142 if (entity->kind == ENTITY_FUNCTION) {
4143 previous_entity->function.is_inline |= entity->function.is_inline;
4145 return previous_entity;
4149 if (is_warn_on(why = WARN_SHADOW) ||
4150 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4151 char const *const what = get_entity_kind_name(previous_entity->kind);
4152 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4156 if (entity->kind == ENTITY_FUNCTION) {
4157 if (is_definition &&
4158 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4159 !is_sym_main(symbol)) {
4160 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4161 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4163 goto warn_missing_declaration;
4166 } else if (entity->kind == ENTITY_VARIABLE) {
4167 if (current_scope == file_scope &&
4168 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4169 !entity->declaration.implicit) {
4170 warn_missing_declaration:
4171 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4176 assert(entity->base.parent_scope == NULL);
4177 assert(current_scope != NULL);
4179 entity->base.parent_scope = current_scope;
4180 environment_push(entity);
4181 append_entity(current_scope, entity);
4186 static void parser_error_multiple_definition(entity_t *entity,
4187 const source_position_t *source_position)
4189 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4190 entity->base.symbol, &entity->base.source_position);
4193 static bool is_declaration_specifier(const token_t *token)
4195 switch (token->kind) {
4199 return is_typedef_symbol(token->identifier.symbol);
4206 static void parse_init_declarator_rest(entity_t *entity)
4208 type_t *orig_type = type_error_type;
4210 if (entity->base.kind == ENTITY_TYPEDEF) {
4211 source_position_t const *const pos = &entity->base.source_position;
4212 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4214 assert(is_declaration(entity));
4215 orig_type = entity->declaration.type;
4218 type_t *type = skip_typeref(orig_type);
4220 if (entity->kind == ENTITY_VARIABLE
4221 && entity->variable.initializer != NULL) {
4222 parser_error_multiple_definition(entity, HERE);
4226 declaration_t *const declaration = &entity->declaration;
4227 bool must_be_constant = false;
4228 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4229 entity->base.parent_scope == file_scope) {
4230 must_be_constant = true;
4233 if (is_type_function(type)) {
4234 source_position_t const *const pos = &entity->base.source_position;
4235 errorf(pos, "'%N' is initialized like a variable", entity);
4236 orig_type = type_error_type;
4239 parse_initializer_env_t env;
4240 env.type = orig_type;
4241 env.must_be_constant = must_be_constant;
4242 env.entity = entity;
4244 initializer_t *initializer = parse_initializer(&env);
4246 if (entity->kind == ENTITY_VARIABLE) {
4247 /* §6.7.5:22 array initializers for arrays with unknown size
4248 * determine the array type size */
4249 declaration->type = env.type;
4250 entity->variable.initializer = initializer;
4254 /* parse rest of a declaration without any declarator */
4255 static void parse_anonymous_declaration_rest(
4256 const declaration_specifiers_t *specifiers)
4259 anonymous_entity = NULL;
4261 source_position_t const *const pos = &specifiers->source_position;
4262 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4263 specifiers->thread_local) {
4264 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4267 type_t *type = specifiers->type;
4268 switch (type->kind) {
4269 case TYPE_COMPOUND_STRUCT:
4270 case TYPE_COMPOUND_UNION: {
4271 if (type->compound.compound->base.symbol == NULL) {
4272 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4281 warningf(WARN_OTHER, pos, "empty declaration");
4286 static void check_variable_type_complete(entity_t *ent)
4288 if (ent->kind != ENTITY_VARIABLE)
4291 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4292 * type for the object shall be complete [...] */
4293 declaration_t *decl = &ent->declaration;
4294 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4295 decl->storage_class == STORAGE_CLASS_STATIC)
4298 type_t *const type = skip_typeref(decl->type);
4299 if (!is_type_incomplete(type))
4302 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4303 * are given length one. */
4304 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4305 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4309 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4313 static void parse_declaration_rest(entity_t *ndeclaration,
4314 const declaration_specifiers_t *specifiers,
4315 parsed_declaration_func finished_declaration,
4316 declarator_flags_t flags)
4318 add_anchor_token(';');
4319 add_anchor_token(',');
4321 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4323 if (token.kind == '=') {
4324 parse_init_declarator_rest(entity);
4325 } else if (entity->kind == ENTITY_VARIABLE) {
4326 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4327 * [...] where the extern specifier is explicitly used. */
4328 declaration_t *decl = &entity->declaration;
4329 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4330 is_type_reference(skip_typeref(decl->type))) {
4331 source_position_t const *const pos = &entity->base.source_position;
4332 errorf(pos, "reference '%#N' must be initialized", entity);
4336 check_variable_type_complete(entity);
4341 add_anchor_token('=');
4342 ndeclaration = parse_declarator(specifiers, flags);
4343 rem_anchor_token('=');
4345 rem_anchor_token(',');
4346 rem_anchor_token(';');
4349 anonymous_entity = NULL;
4352 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4354 symbol_t *symbol = entity->base.symbol;
4358 assert(entity->base.namespc == NAMESPACE_NORMAL);
4359 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4360 if (previous_entity == NULL
4361 || previous_entity->base.parent_scope != current_scope) {
4362 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4367 if (is_definition) {
4368 errorf(HERE, "'%N' is initialised", entity);
4371 return record_entity(entity, false);
4374 static void parse_declaration(parsed_declaration_func finished_declaration,
4375 declarator_flags_t flags)
4377 add_anchor_token(';');
4378 declaration_specifiers_t specifiers;
4379 parse_declaration_specifiers(&specifiers);
4380 rem_anchor_token(';');
4382 if (token.kind == ';') {
4383 parse_anonymous_declaration_rest(&specifiers);
4385 entity_t *entity = parse_declarator(&specifiers, flags);
4386 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4391 static type_t *get_default_promoted_type(type_t *orig_type)
4393 type_t *result = orig_type;
4395 type_t *type = skip_typeref(orig_type);
4396 if (is_type_integer(type)) {
4397 result = promote_integer(type);
4398 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4399 result = type_double;
4405 static void parse_kr_declaration_list(entity_t *entity)
4407 if (entity->kind != ENTITY_FUNCTION)
4410 type_t *type = skip_typeref(entity->declaration.type);
4411 assert(is_type_function(type));
4412 if (!type->function.kr_style_parameters)
4415 add_anchor_token('{');
4417 PUSH_SCOPE(&entity->function.parameters);
4419 entity_t *parameter = entity->function.parameters.entities;
4420 for ( ; parameter != NULL; parameter = parameter->base.next) {
4421 assert(parameter->base.parent_scope == NULL);
4422 parameter->base.parent_scope = current_scope;
4423 environment_push(parameter);
4426 /* parse declaration list */
4428 switch (token.kind) {
4430 /* This covers symbols, which are no type, too, and results in
4431 * better error messages. The typical cases are misspelled type
4432 * names and missing includes. */
4434 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4444 /* update function type */
4445 type_t *new_type = duplicate_type(type);
4447 function_parameter_t *parameters = NULL;
4448 function_parameter_t **anchor = ¶meters;
4450 /* did we have an earlier prototype? */
4451 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4452 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4455 function_parameter_t *proto_parameter = NULL;
4456 if (proto_type != NULL) {
4457 type_t *proto_type_type = proto_type->declaration.type;
4458 proto_parameter = proto_type_type->function.parameters;
4459 /* If a K&R function definition has a variadic prototype earlier, then
4460 * make the function definition variadic, too. This should conform to
4461 * §6.7.5.3:15 and §6.9.1:8. */
4462 new_type->function.variadic = proto_type_type->function.variadic;
4464 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4466 new_type->function.unspecified_parameters = true;
4469 bool need_incompatible_warning = false;
4470 parameter = entity->function.parameters.entities;
4471 for (; parameter != NULL; parameter = parameter->base.next,
4473 proto_parameter == NULL ? NULL : proto_parameter->next) {
4474 if (parameter->kind != ENTITY_PARAMETER)
4477 type_t *parameter_type = parameter->declaration.type;
4478 if (parameter_type == NULL) {
4479 source_position_t const* const pos = ¶meter->base.source_position;
4481 errorf(pos, "no type specified for function '%N'", parameter);
4482 parameter_type = type_error_type;
4484 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4485 parameter_type = type_int;
4487 parameter->declaration.type = parameter_type;
4490 semantic_parameter_incomplete(parameter);
4492 /* we need the default promoted types for the function type */
4493 type_t *not_promoted = parameter_type;
4494 parameter_type = get_default_promoted_type(parameter_type);
4496 /* gcc special: if the type of the prototype matches the unpromoted
4497 * type don't promote */
4498 if (!strict_mode && proto_parameter != NULL) {
4499 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4500 type_t *promo_skip = skip_typeref(parameter_type);
4501 type_t *param_skip = skip_typeref(not_promoted);
4502 if (!types_compatible(proto_p_type, promo_skip)
4503 && types_compatible(proto_p_type, param_skip)) {
4505 need_incompatible_warning = true;
4506 parameter_type = not_promoted;
4509 function_parameter_t *const function_parameter
4510 = allocate_parameter(parameter_type);
4512 *anchor = function_parameter;
4513 anchor = &function_parameter->next;
4516 new_type->function.parameters = parameters;
4517 new_type = identify_new_type(new_type);
4519 if (need_incompatible_warning) {
4520 symbol_t const *const sym = entity->base.symbol;
4521 source_position_t const *const pos = &entity->base.source_position;
4522 source_position_t const *const ppos = &proto_type->base.source_position;
4523 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4525 entity->declaration.type = new_type;
4527 rem_anchor_token('{');
4530 static bool first_err = true;
4533 * When called with first_err set, prints the name of the current function,
4536 static void print_in_function(void)
4540 char const *const file = current_function->base.base.source_position.input_name;
4541 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4546 * Check if all labels are defined in the current function.
4547 * Check if all labels are used in the current function.
4549 static void check_labels(void)
4551 for (const goto_statement_t *goto_statement = goto_first;
4552 goto_statement != NULL;
4553 goto_statement = goto_statement->next) {
4554 label_t *label = goto_statement->label;
4555 if (label->base.source_position.input_name == NULL) {
4556 print_in_function();
4557 source_position_t const *const pos = &goto_statement->base.source_position;
4558 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4562 if (is_warn_on(WARN_UNUSED_LABEL)) {
4563 for (const label_statement_t *label_statement = label_first;
4564 label_statement != NULL;
4565 label_statement = label_statement->next) {
4566 label_t *label = label_statement->label;
4568 if (! label->used) {
4569 print_in_function();
4570 source_position_t const *const pos = &label_statement->base.source_position;
4571 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4577 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4579 entity_t const *const end = last != NULL ? last->base.next : NULL;
4580 for (; entity != end; entity = entity->base.next) {
4581 if (!is_declaration(entity))
4584 declaration_t *declaration = &entity->declaration;
4585 if (declaration->implicit)
4588 if (!declaration->used) {
4589 print_in_function();
4590 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4591 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4592 print_in_function();
4593 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4598 static void check_unused_variables(statement_t *const stmt, void *const env)
4602 switch (stmt->kind) {
4603 case STATEMENT_DECLARATION: {
4604 declaration_statement_t const *const decls = &stmt->declaration;
4605 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4610 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4619 * Check declarations of current_function for unused entities.
4621 static void check_declarations(void)
4623 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4624 const scope_t *scope = ¤t_function->parameters;
4625 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4627 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4628 walk_statements(current_function->statement, check_unused_variables,
4633 static int determine_truth(expression_t const* const cond)
4636 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4637 fold_constant_to_bool(cond) ? 1 :
4641 static void check_reachable(statement_t *);
4642 static bool reaches_end;
4644 static bool expression_returns(expression_t const *const expr)
4646 switch (expr->kind) {
4648 expression_t const *const func = expr->call.function;
4649 type_t const *const type = skip_typeref(func->base.type);
4650 if (type->kind == TYPE_POINTER) {
4651 type_t const *const points_to
4652 = skip_typeref(type->pointer.points_to);
4653 if (points_to->kind == TYPE_FUNCTION
4654 && points_to->function.modifiers & DM_NORETURN)
4658 if (!expression_returns(func))
4661 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4662 if (!expression_returns(arg->expression))
4669 case EXPR_REFERENCE:
4670 case EXPR_ENUM_CONSTANT:
4671 case EXPR_LITERAL_CASES:
4672 case EXPR_STRING_LITERAL:
4673 case EXPR_WIDE_STRING_LITERAL:
4674 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4675 case EXPR_LABEL_ADDRESS:
4676 case EXPR_CLASSIFY_TYPE:
4677 case EXPR_SIZEOF: // TODO handle obscure VLA case
4680 case EXPR_BUILTIN_CONSTANT_P:
4681 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4686 case EXPR_STATEMENT: {
4687 bool old_reaches_end = reaches_end;
4688 reaches_end = false;
4689 check_reachable(expr->statement.statement);
4690 bool returns = reaches_end;
4691 reaches_end = old_reaches_end;
4695 case EXPR_CONDITIONAL:
4696 // TODO handle constant expression
4698 if (!expression_returns(expr->conditional.condition))
4701 if (expr->conditional.true_expression != NULL
4702 && expression_returns(expr->conditional.true_expression))
4705 return expression_returns(expr->conditional.false_expression);
4708 return expression_returns(expr->select.compound);
4710 case EXPR_ARRAY_ACCESS:
4712 expression_returns(expr->array_access.array_ref) &&
4713 expression_returns(expr->array_access.index);
4716 return expression_returns(expr->va_starte.ap);
4719 return expression_returns(expr->va_arge.ap);
4722 return expression_returns(expr->va_copye.src);
4724 case EXPR_UNARY_CASES_MANDATORY:
4725 return expression_returns(expr->unary.value);
4727 case EXPR_UNARY_THROW:
4730 case EXPR_BINARY_CASES:
4731 // TODO handle constant lhs of && and ||
4733 expression_returns(expr->binary.left) &&
4734 expression_returns(expr->binary.right);
4737 panic("unhandled expression");
4740 static bool initializer_returns(initializer_t const *const init)
4742 switch (init->kind) {
4743 case INITIALIZER_VALUE:
4744 return expression_returns(init->value.value);
4746 case INITIALIZER_LIST: {
4747 initializer_t * const* i = init->list.initializers;
4748 initializer_t * const* const end = i + init->list.len;
4749 bool returns = true;
4750 for (; i != end; ++i) {
4751 if (!initializer_returns(*i))
4757 case INITIALIZER_STRING:
4758 case INITIALIZER_WIDE_STRING:
4759 case INITIALIZER_DESIGNATOR: // designators have no payload
4762 panic("unhandled initializer");
4765 static bool noreturn_candidate;
4767 static void check_reachable(statement_t *const stmt)
4769 if (stmt->base.reachable)
4771 if (stmt->kind != STATEMENT_DO_WHILE)
4772 stmt->base.reachable = true;
4774 statement_t *last = stmt;
4776 switch (stmt->kind) {
4777 case STATEMENT_ERROR:
4778 case STATEMENT_EMPTY:
4780 next = stmt->base.next;
4783 case STATEMENT_DECLARATION: {
4784 declaration_statement_t const *const decl = &stmt->declaration;
4785 entity_t const * ent = decl->declarations_begin;
4786 entity_t const *const last_decl = decl->declarations_end;
4788 for (;; ent = ent->base.next) {
4789 if (ent->kind == ENTITY_VARIABLE &&
4790 ent->variable.initializer != NULL &&
4791 !initializer_returns(ent->variable.initializer)) {
4794 if (ent == last_decl)
4798 next = stmt->base.next;
4802 case STATEMENT_COMPOUND:
4803 next = stmt->compound.statements;
4805 next = stmt->base.next;
4808 case STATEMENT_RETURN: {
4809 expression_t const *const val = stmt->returns.value;
4810 if (val == NULL || expression_returns(val))
4811 noreturn_candidate = false;
4815 case STATEMENT_IF: {
4816 if_statement_t const *const ifs = &stmt->ifs;
4817 expression_t const *const cond = ifs->condition;
4819 if (!expression_returns(cond))
4822 int const val = determine_truth(cond);
4825 check_reachable(ifs->true_statement);
4830 if (ifs->false_statement != NULL) {
4831 check_reachable(ifs->false_statement);
4835 next = stmt->base.next;
4839 case STATEMENT_SWITCH: {
4840 switch_statement_t const *const switchs = &stmt->switchs;
4841 expression_t const *const expr = switchs->expression;
4843 if (!expression_returns(expr))
4846 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4847 long const val = fold_constant_to_int(expr);
4848 case_label_statement_t * defaults = NULL;
4849 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4850 if (i->expression == NULL) {
4855 if (i->first_case <= val && val <= i->last_case) {
4856 check_reachable((statement_t*)i);
4861 if (defaults != NULL) {
4862 check_reachable((statement_t*)defaults);
4866 bool has_default = false;
4867 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4868 if (i->expression == NULL)
4871 check_reachable((statement_t*)i);
4878 next = stmt->base.next;
4882 case STATEMENT_EXPRESSION: {
4883 /* Check for noreturn function call */
4884 expression_t const *const expr = stmt->expression.expression;
4885 if (!expression_returns(expr))
4888 next = stmt->base.next;
4892 case STATEMENT_CONTINUE:
4893 for (statement_t *parent = stmt;;) {
4894 parent = parent->base.parent;
4895 if (parent == NULL) /* continue not within loop */
4899 switch (parent->kind) {
4900 case STATEMENT_WHILE: goto continue_while;
4901 case STATEMENT_DO_WHILE: goto continue_do_while;
4902 case STATEMENT_FOR: goto continue_for;
4908 case STATEMENT_BREAK:
4909 for (statement_t *parent = stmt;;) {
4910 parent = parent->base.parent;
4911 if (parent == NULL) /* break not within loop/switch */
4914 switch (parent->kind) {
4915 case STATEMENT_SWITCH:
4916 case STATEMENT_WHILE:
4917 case STATEMENT_DO_WHILE:
4920 next = parent->base.next;
4921 goto found_break_parent;
4929 case STATEMENT_COMPUTED_GOTO: {
4930 if (!expression_returns(stmt->computed_goto.expression))
4933 statement_t *parent = stmt->base.parent;
4934 if (parent == NULL) /* top level goto */
4940 case STATEMENT_GOTO:
4941 next = stmt->gotos.label->statement;
4942 if (next == NULL) /* missing label */
4946 case STATEMENT_LABEL:
4947 next = stmt->label.statement;
4950 case STATEMENT_CASE_LABEL:
4951 next = stmt->case_label.statement;
4954 case STATEMENT_WHILE: {
4955 while_statement_t const *const whiles = &stmt->whiles;
4956 expression_t const *const cond = whiles->condition;
4958 if (!expression_returns(cond))
4961 int const val = determine_truth(cond);
4964 check_reachable(whiles->body);
4969 next = stmt->base.next;
4973 case STATEMENT_DO_WHILE:
4974 next = stmt->do_while.body;
4977 case STATEMENT_FOR: {
4978 for_statement_t *const fors = &stmt->fors;
4980 if (fors->condition_reachable)
4982 fors->condition_reachable = true;
4984 expression_t const *const cond = fors->condition;
4989 } else if (expression_returns(cond)) {
4990 val = determine_truth(cond);
4996 check_reachable(fors->body);
5001 next = stmt->base.next;
5005 case STATEMENT_MS_TRY: {
5006 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5007 check_reachable(ms_try->try_statement);
5008 next = ms_try->final_statement;
5012 case STATEMENT_LEAVE: {
5013 statement_t *parent = stmt;
5015 parent = parent->base.parent;
5016 if (parent == NULL) /* __leave not within __try */
5019 if (parent->kind == STATEMENT_MS_TRY) {
5021 next = parent->ms_try.final_statement;
5029 panic("invalid statement kind");
5032 while (next == NULL) {
5033 next = last->base.parent;
5035 noreturn_candidate = false;
5037 type_t *const type = skip_typeref(current_function->base.type);
5038 assert(is_type_function(type));
5039 type_t *const ret = skip_typeref(type->function.return_type);
5040 if (!is_type_void(ret) &&
5041 is_type_valid(ret) &&
5042 !is_sym_main(current_function->base.base.symbol)) {
5043 source_position_t const *const pos = &stmt->base.source_position;
5044 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5049 switch (next->kind) {
5050 case STATEMENT_ERROR:
5051 case STATEMENT_EMPTY:
5052 case STATEMENT_DECLARATION:
5053 case STATEMENT_EXPRESSION:
5055 case STATEMENT_RETURN:
5056 case STATEMENT_CONTINUE:
5057 case STATEMENT_BREAK:
5058 case STATEMENT_COMPUTED_GOTO:
5059 case STATEMENT_GOTO:
5060 case STATEMENT_LEAVE:
5061 panic("invalid control flow in function");
5063 case STATEMENT_COMPOUND:
5064 if (next->compound.stmt_expr) {
5070 case STATEMENT_SWITCH:
5071 case STATEMENT_LABEL:
5072 case STATEMENT_CASE_LABEL:
5074 next = next->base.next;
5077 case STATEMENT_WHILE: {
5079 if (next->base.reachable)
5081 next->base.reachable = true;
5083 while_statement_t const *const whiles = &next->whiles;
5084 expression_t const *const cond = whiles->condition;
5086 if (!expression_returns(cond))
5089 int const val = determine_truth(cond);
5092 check_reachable(whiles->body);
5098 next = next->base.next;
5102 case STATEMENT_DO_WHILE: {
5104 if (next->base.reachable)
5106 next->base.reachable = true;
5108 do_while_statement_t const *const dw = &next->do_while;
5109 expression_t const *const cond = dw->condition;
5111 if (!expression_returns(cond))
5114 int const val = determine_truth(cond);
5117 check_reachable(dw->body);
5123 next = next->base.next;
5127 case STATEMENT_FOR: {
5129 for_statement_t *const fors = &next->fors;
5131 fors->step_reachable = true;
5133 if (fors->condition_reachable)
5135 fors->condition_reachable = true;
5137 expression_t const *const cond = fors->condition;
5142 } else if (expression_returns(cond)) {
5143 val = determine_truth(cond);
5149 check_reachable(fors->body);
5155 next = next->base.next;
5159 case STATEMENT_MS_TRY:
5161 next = next->ms_try.final_statement;
5166 check_reachable(next);
5169 static void check_unreachable(statement_t* const stmt, void *const env)
5173 switch (stmt->kind) {
5174 case STATEMENT_DO_WHILE:
5175 if (!stmt->base.reachable) {
5176 expression_t const *const cond = stmt->do_while.condition;
5177 if (determine_truth(cond) >= 0) {
5178 source_position_t const *const pos = &cond->base.source_position;
5179 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5184 case STATEMENT_FOR: {
5185 for_statement_t const* const fors = &stmt->fors;
5187 // if init and step are unreachable, cond is unreachable, too
5188 if (!stmt->base.reachable && !fors->step_reachable) {
5189 goto warn_unreachable;
5191 if (!stmt->base.reachable && fors->initialisation != NULL) {
5192 source_position_t const *const pos = &fors->initialisation->base.source_position;
5193 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5196 if (!fors->condition_reachable && fors->condition != NULL) {
5197 source_position_t const *const pos = &fors->condition->base.source_position;
5198 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5201 if (!fors->step_reachable && fors->step != NULL) {
5202 source_position_t const *const pos = &fors->step->base.source_position;
5203 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5209 case STATEMENT_COMPOUND:
5210 if (stmt->compound.statements != NULL)
5212 goto warn_unreachable;
5214 case STATEMENT_DECLARATION: {
5215 /* Only warn if there is at least one declarator with an initializer.
5216 * This typically occurs in switch statements. */
5217 declaration_statement_t const *const decl = &stmt->declaration;
5218 entity_t const * ent = decl->declarations_begin;
5219 entity_t const *const last = decl->declarations_end;
5221 for (;; ent = ent->base.next) {
5222 if (ent->kind == ENTITY_VARIABLE &&
5223 ent->variable.initializer != NULL) {
5224 goto warn_unreachable;
5234 if (!stmt->base.reachable) {
5235 source_position_t const *const pos = &stmt->base.source_position;
5236 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5242 static bool is_main(entity_t *entity)
5244 static symbol_t *sym_main = NULL;
5245 if (sym_main == NULL) {
5246 sym_main = symbol_table_insert("main");
5249 if (entity->base.symbol != sym_main)
5251 /* must be in outermost scope */
5252 if (entity->base.parent_scope != file_scope)
5258 static void prepare_main_collect2(entity_t*);
5260 static void parse_external_declaration(void)
5262 /* function-definitions and declarations both start with declaration
5264 add_anchor_token(';');
5265 declaration_specifiers_t specifiers;
5266 parse_declaration_specifiers(&specifiers);
5267 rem_anchor_token(';');
5269 /* must be a declaration */
5270 if (token.kind == ';') {
5271 parse_anonymous_declaration_rest(&specifiers);
5275 add_anchor_token(',');
5276 add_anchor_token('=');
5277 add_anchor_token(';');
5278 add_anchor_token('{');
5280 /* declarator is common to both function-definitions and declarations */
5281 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5283 rem_anchor_token('{');
5284 rem_anchor_token(';');
5285 rem_anchor_token('=');
5286 rem_anchor_token(',');
5288 /* must be a declaration */
5289 switch (token.kind) {
5293 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5298 /* must be a function definition */
5299 parse_kr_declaration_list(ndeclaration);
5301 if (token.kind != '{') {
5302 parse_error_expected("while parsing function definition", '{', NULL);
5303 eat_until_matching_token(';');
5307 assert(is_declaration(ndeclaration));
5308 type_t *const orig_type = ndeclaration->declaration.type;
5309 type_t * type = skip_typeref(orig_type);
5311 if (!is_type_function(type)) {
5312 if (is_type_valid(type)) {
5313 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5319 source_position_t const *const pos = &ndeclaration->base.source_position;
5320 if (is_typeref(orig_type)) {
5322 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5325 if (is_type_compound(skip_typeref(type->function.return_type))) {
5326 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5328 if (type->function.unspecified_parameters) {
5329 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5331 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5334 /* §6.7.5.3:14 a function definition with () means no
5335 * parameters (and not unspecified parameters) */
5336 if (type->function.unspecified_parameters &&
5337 type->function.parameters == NULL) {
5338 type_t *copy = duplicate_type(type);
5339 copy->function.unspecified_parameters = false;
5340 type = identify_new_type(copy);
5342 ndeclaration->declaration.type = type;
5345 entity_t *const entity = record_entity(ndeclaration, true);
5346 assert(entity->kind == ENTITY_FUNCTION);
5347 assert(ndeclaration->kind == ENTITY_FUNCTION);
5349 function_t *const function = &entity->function;
5350 if (ndeclaration != entity) {
5351 function->parameters = ndeclaration->function.parameters;
5354 PUSH_SCOPE(&function->parameters);
5356 entity_t *parameter = function->parameters.entities;
5357 for (; parameter != NULL; parameter = parameter->base.next) {
5358 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5359 parameter->base.parent_scope = current_scope;
5361 assert(parameter->base.parent_scope == NULL
5362 || parameter->base.parent_scope == current_scope);
5363 parameter->base.parent_scope = current_scope;
5364 if (parameter->base.symbol == NULL) {
5365 errorf(¶meter->base.source_position, "parameter name omitted");
5368 environment_push(parameter);
5371 if (function->statement != NULL) {
5372 parser_error_multiple_definition(entity, HERE);
5375 /* parse function body */
5376 int label_stack_top = label_top();
5377 function_t *old_current_function = current_function;
5378 current_function = function;
5379 PUSH_CURRENT_ENTITY(entity);
5383 goto_anchor = &goto_first;
5385 label_anchor = &label_first;
5387 statement_t *const body = parse_compound_statement(false);
5388 function->statement = body;
5391 check_declarations();
5392 if (is_warn_on(WARN_RETURN_TYPE) ||
5393 is_warn_on(WARN_UNREACHABLE_CODE) ||
5394 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5395 noreturn_candidate = true;
5396 check_reachable(body);
5397 if (is_warn_on(WARN_UNREACHABLE_CODE))
5398 walk_statements(body, check_unreachable, NULL);
5399 if (noreturn_candidate &&
5400 !(function->base.modifiers & DM_NORETURN)) {
5401 source_position_t const *const pos = &body->base.source_position;
5402 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5406 if (is_main(entity) && enable_main_collect2_hack)
5407 prepare_main_collect2(entity);
5409 POP_CURRENT_ENTITY();
5411 assert(current_function == function);
5412 current_function = old_current_function;
5413 label_pop_to(label_stack_top);
5419 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5421 entity_t *iter = compound->members.entities;
5422 for (; iter != NULL; iter = iter->base.next) {
5423 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5426 if (iter->base.symbol == symbol) {
5428 } else if (iter->base.symbol == NULL) {
5429 /* search in anonymous structs and unions */
5430 type_t *type = skip_typeref(iter->declaration.type);
5431 if (is_type_compound(type)) {
5432 if (find_compound_entry(type->compound.compound, symbol)
5443 static void check_deprecated(const source_position_t *source_position,
5444 const entity_t *entity)
5446 if (!is_declaration(entity))
5448 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5451 source_position_t const *const epos = &entity->base.source_position;
5452 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5454 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5456 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5461 static expression_t *create_select(const source_position_t *pos,
5463 type_qualifiers_t qualifiers,
5466 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5468 check_deprecated(pos, entry);
5470 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5471 select->select.compound = addr;
5472 select->select.compound_entry = entry;
5474 type_t *entry_type = entry->declaration.type;
5475 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5477 /* bitfields need special treatment */
5478 if (entry->compound_member.bitfield) {
5479 unsigned bit_size = entry->compound_member.bit_size;
5480 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5481 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5482 res_type = type_int;
5486 /* we always do the auto-type conversions; the & and sizeof parser contains
5487 * code to revert this! */
5488 select->base.type = automatic_type_conversion(res_type);
5495 * Find entry with symbol in compound. Search anonymous structs and unions and
5496 * creates implicit select expressions for them.
5497 * Returns the adress for the innermost compound.
5499 static expression_t *find_create_select(const source_position_t *pos,
5501 type_qualifiers_t qualifiers,
5502 compound_t *compound, symbol_t *symbol)
5504 entity_t *iter = compound->members.entities;
5505 for (; iter != NULL; iter = iter->base.next) {
5506 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5509 symbol_t *iter_symbol = iter->base.symbol;
5510 if (iter_symbol == NULL) {
5511 type_t *type = iter->declaration.type;
5512 if (type->kind != TYPE_COMPOUND_STRUCT
5513 && type->kind != TYPE_COMPOUND_UNION)
5516 compound_t *sub_compound = type->compound.compound;
5518 if (find_compound_entry(sub_compound, symbol) == NULL)
5521 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5522 sub_addr->base.source_position = *pos;
5523 sub_addr->base.implicit = true;
5524 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5528 if (iter_symbol == symbol) {
5529 return create_select(pos, addr, qualifiers, iter);
5536 static void parse_bitfield_member(entity_t *entity)
5540 expression_t *size = parse_constant_expression();
5543 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5544 type_t *type = entity->declaration.type;
5545 if (!is_type_integer(skip_typeref(type))) {
5546 errorf(HERE, "bitfield base type '%T' is not an integer type",
5550 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5551 /* error already reported by parse_constant_expression */
5552 size_long = get_type_size(type) * 8;
5554 size_long = fold_constant_to_int(size);
5556 const symbol_t *symbol = entity->base.symbol;
5557 const symbol_t *user_symbol
5558 = symbol == NULL ? sym_anonymous : symbol;
5559 unsigned bit_size = get_type_size(type) * 8;
5560 if (size_long < 0) {
5561 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5562 } else if (size_long == 0 && symbol != NULL) {
5563 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5564 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5565 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5568 /* hope that people don't invent crazy types with more bits
5569 * than our struct can hold */
5571 (1 << sizeof(entity->compound_member.bit_size)*8));
5575 entity->compound_member.bitfield = true;
5576 entity->compound_member.bit_size = (unsigned char)size_long;
5579 static void parse_compound_declarators(compound_t *compound,
5580 const declaration_specifiers_t *specifiers)
5582 add_anchor_token(';');
5583 add_anchor_token(',');
5587 if (token.kind == ':') {
5588 /* anonymous bitfield */
5589 type_t *type = specifiers->type;
5590 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5591 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5592 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5593 entity->declaration.type = type;
5595 parse_bitfield_member(entity);
5597 attribute_t *attributes = parse_attributes(NULL);
5598 attribute_t **anchor = &attributes;
5599 while (*anchor != NULL)
5600 anchor = &(*anchor)->next;
5601 *anchor = specifiers->attributes;
5602 if (attributes != NULL) {
5603 handle_entity_attributes(attributes, entity);
5605 entity->declaration.attributes = attributes;
5607 append_entity(&compound->members, entity);
5609 entity = parse_declarator(specifiers,
5610 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5611 source_position_t const *const pos = &entity->base.source_position;
5612 if (entity->kind == ENTITY_TYPEDEF) {
5613 errorf(pos, "typedef not allowed as compound member");
5615 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5617 /* make sure we don't define a symbol multiple times */
5618 symbol_t *symbol = entity->base.symbol;
5619 if (symbol != NULL) {
5620 entity_t *prev = find_compound_entry(compound, symbol);
5622 source_position_t const *const ppos = &prev->base.source_position;
5623 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5627 if (token.kind == ':') {
5628 parse_bitfield_member(entity);
5630 attribute_t *attributes = parse_attributes(NULL);
5631 handle_entity_attributes(attributes, entity);
5633 type_t *orig_type = entity->declaration.type;
5634 type_t *type = skip_typeref(orig_type);
5635 if (is_type_function(type)) {
5636 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5637 } else if (is_type_incomplete(type)) {
5638 /* §6.7.2.1:16 flexible array member */
5639 if (!is_type_array(type) ||
5640 token.kind != ';' ||
5641 look_ahead(1)->kind != '}') {
5642 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5643 } else if (compound->members.entities == NULL) {
5644 errorf(pos, "flexible array member in otherwise empty struct");
5649 append_entity(&compound->members, entity);
5652 } while (next_if(','));
5653 rem_anchor_token(',');
5654 rem_anchor_token(';');
5657 anonymous_entity = NULL;
5660 static void parse_compound_type_entries(compound_t *compound)
5663 add_anchor_token('}');
5666 switch (token.kind) {
5668 case T___extension__:
5669 case T_IDENTIFIER: {
5671 declaration_specifiers_t specifiers;
5672 parse_declaration_specifiers(&specifiers);
5673 parse_compound_declarators(compound, &specifiers);
5679 rem_anchor_token('}');
5682 compound->complete = true;
5688 static type_t *parse_typename(void)
5690 declaration_specifiers_t specifiers;
5691 parse_declaration_specifiers(&specifiers);
5692 if (specifiers.storage_class != STORAGE_CLASS_NONE
5693 || specifiers.thread_local) {
5694 /* TODO: improve error message, user does probably not know what a
5695 * storage class is...
5697 errorf(&specifiers.source_position, "typename must not have a storage class");
5700 type_t *result = parse_abstract_declarator(specifiers.type);
5708 typedef expression_t* (*parse_expression_function)(void);
5709 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5711 typedef struct expression_parser_function_t expression_parser_function_t;
5712 struct expression_parser_function_t {
5713 parse_expression_function parser;
5714 precedence_t infix_precedence;
5715 parse_expression_infix_function infix_parser;
5718 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5720 static type_t *get_string_type(void)
5722 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5725 static type_t *get_wide_string_type(void)
5727 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5731 * Parse a string constant.
5733 static expression_t *parse_string_literal(void)
5735 source_position_t begin = token.base.source_position;
5736 string_t res = token.string.string;
5737 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5740 while (token.kind == T_STRING_LITERAL
5741 || token.kind == T_WIDE_STRING_LITERAL) {
5742 warn_string_concat(&token.base.source_position);
5743 res = concat_strings(&res, &token.string.string);
5745 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5748 expression_t *literal;
5750 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5751 literal->base.type = get_wide_string_type();
5753 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5754 literal->base.type = get_string_type();
5756 literal->base.source_position = begin;
5757 literal->literal.value = res;
5763 * Parse a boolean constant.
5765 static expression_t *parse_boolean_literal(bool value)
5767 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5768 literal->base.type = type_bool;
5769 literal->literal.value.begin = value ? "true" : "false";
5770 literal->literal.value.size = value ? 4 : 5;
5776 static void warn_traditional_suffix(void)
5778 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5779 &token.number.suffix);
5782 static void check_integer_suffix(void)
5784 const string_t *suffix = &token.number.suffix;
5785 if (suffix->size == 0)
5788 bool not_traditional = false;
5789 const char *c = suffix->begin;
5790 if (*c == 'l' || *c == 'L') {
5793 not_traditional = true;
5795 if (*c == 'u' || *c == 'U') {
5798 } else if (*c == 'u' || *c == 'U') {
5799 not_traditional = true;
5802 } else if (*c == 'u' || *c == 'U') {
5803 not_traditional = true;
5805 if (*c == 'l' || *c == 'L') {
5813 errorf(&token.base.source_position,
5814 "invalid suffix '%S' on integer constant", suffix);
5815 } else if (not_traditional) {
5816 warn_traditional_suffix();
5820 static type_t *check_floatingpoint_suffix(void)
5822 const string_t *suffix = &token.number.suffix;
5823 type_t *type = type_double;
5824 if (suffix->size == 0)
5827 bool not_traditional = false;
5828 const char *c = suffix->begin;
5829 if (*c == 'f' || *c == 'F') {
5832 } else if (*c == 'l' || *c == 'L') {
5834 type = type_long_double;
5837 errorf(&token.base.source_position,
5838 "invalid suffix '%S' on floatingpoint constant", suffix);
5839 } else if (not_traditional) {
5840 warn_traditional_suffix();
5847 * Parse an integer constant.
5849 static expression_t *parse_number_literal(void)
5851 expression_kind_t kind;
5854 switch (token.kind) {
5856 kind = EXPR_LITERAL_INTEGER;
5857 check_integer_suffix();
5860 case T_INTEGER_OCTAL:
5861 kind = EXPR_LITERAL_INTEGER_OCTAL;
5862 check_integer_suffix();
5865 case T_INTEGER_HEXADECIMAL:
5866 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5867 check_integer_suffix();
5870 case T_FLOATINGPOINT:
5871 kind = EXPR_LITERAL_FLOATINGPOINT;
5872 type = check_floatingpoint_suffix();
5874 case T_FLOATINGPOINT_HEXADECIMAL:
5875 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5876 type = check_floatingpoint_suffix();
5879 panic("unexpected token type in parse_number_literal");
5882 expression_t *literal = allocate_expression_zero(kind);
5883 literal->base.type = type;
5884 literal->literal.value = token.number.number;
5885 literal->literal.suffix = token.number.suffix;
5888 /* integer type depends on the size of the number and the size
5889 * representable by the types. The backend/codegeneration has to determine
5892 determine_literal_type(&literal->literal);
5897 * Parse a character constant.
5899 static expression_t *parse_character_constant(void)
5901 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5902 literal->base.type = c_mode & _CXX ? type_char : type_int;
5903 literal->literal.value = token.string.string;
5905 size_t len = literal->literal.value.size;
5907 if (!GNU_MODE && !(c_mode & _C99)) {
5908 errorf(HERE, "more than 1 character in character constant");
5910 literal->base.type = type_int;
5911 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5920 * Parse a wide character constant.
5922 static expression_t *parse_wide_character_constant(void)
5924 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5925 literal->base.type = type_int;
5926 literal->literal.value = token.string.string;
5928 size_t len = wstrlen(&literal->literal.value);
5930 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5937 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
5939 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
5940 ntype->function.return_type = type_int;
5941 ntype->function.unspecified_parameters = true;
5942 ntype->function.linkage = LINKAGE_C;
5943 type_t *type = identify_new_type(ntype);
5945 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
5946 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
5947 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
5948 entity->declaration.type = type;
5949 entity->declaration.implicit = true;
5951 if (current_scope != NULL)
5952 record_entity(entity, false);
5958 * Performs automatic type cast as described in §6.3.2.1.
5960 * @param orig_type the original type
5962 static type_t *automatic_type_conversion(type_t *orig_type)
5964 type_t *type = skip_typeref(orig_type);
5965 if (is_type_array(type)) {
5966 array_type_t *array_type = &type->array;
5967 type_t *element_type = array_type->element_type;
5968 unsigned qualifiers = array_type->base.qualifiers;
5970 return make_pointer_type(element_type, qualifiers);
5973 if (is_type_function(type)) {
5974 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
5981 * reverts the automatic casts of array to pointer types and function
5982 * to function-pointer types as defined §6.3.2.1
5984 type_t *revert_automatic_type_conversion(const expression_t *expression)
5986 switch (expression->kind) {
5987 case EXPR_REFERENCE: {
5988 entity_t *entity = expression->reference.entity;
5989 if (is_declaration(entity)) {
5990 return entity->declaration.type;
5991 } else if (entity->kind == ENTITY_ENUM_VALUE) {
5992 return entity->enum_value.enum_type;
5994 panic("no declaration or enum in reference");
5999 entity_t *entity = expression->select.compound_entry;
6000 assert(is_declaration(entity));
6001 type_t *type = entity->declaration.type;
6002 return get_qualified_type(type, expression->base.type->base.qualifiers);
6005 case EXPR_UNARY_DEREFERENCE: {
6006 const expression_t *const value = expression->unary.value;
6007 type_t *const type = skip_typeref(value->base.type);
6008 if (!is_type_pointer(type))
6009 return type_error_type;
6010 return type->pointer.points_to;
6013 case EXPR_ARRAY_ACCESS: {
6014 const expression_t *array_ref = expression->array_access.array_ref;
6015 type_t *type_left = skip_typeref(array_ref->base.type);
6016 if (!is_type_pointer(type_left))
6017 return type_error_type;
6018 return type_left->pointer.points_to;
6021 case EXPR_STRING_LITERAL: {
6022 size_t size = expression->string_literal.value.size;
6023 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6026 case EXPR_WIDE_STRING_LITERAL: {
6027 size_t size = wstrlen(&expression->string_literal.value);
6028 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6031 case EXPR_COMPOUND_LITERAL:
6032 return expression->compound_literal.type;
6037 return expression->base.type;
6041 * Find an entity matching a symbol in a scope.
6042 * Uses current scope if scope is NULL
6044 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6045 namespace_tag_t namespc)
6047 if (scope == NULL) {
6048 return get_entity(symbol, namespc);
6051 /* we should optimize here, if scope grows above a certain size we should
6052 construct a hashmap here... */
6053 entity_t *entity = scope->entities;
6054 for ( ; entity != NULL; entity = entity->base.next) {
6055 if (entity->base.symbol == symbol
6056 && (namespace_tag_t)entity->base.namespc == namespc)
6063 static entity_t *parse_qualified_identifier(void)
6065 /* namespace containing the symbol */
6067 source_position_t pos;
6068 const scope_t *lookup_scope = NULL;
6070 if (next_if(T_COLONCOLON))
6071 lookup_scope = &unit->scope;
6075 symbol = expect_identifier("while parsing identifier", &pos);
6077 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6080 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6082 if (!next_if(T_COLONCOLON))
6085 switch (entity->kind) {
6086 case ENTITY_NAMESPACE:
6087 lookup_scope = &entity->namespacee.members;
6092 lookup_scope = &entity->compound.members;
6095 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6096 symbol, get_entity_kind_name(entity->kind));
6098 /* skip further qualifications */
6099 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6101 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6105 if (entity == NULL) {
6106 if (!strict_mode && token.kind == '(') {
6107 /* an implicitly declared function */
6108 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6109 "implicit declaration of function '%Y'", symbol);
6110 entity = create_implicit_function(symbol, &pos);
6112 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6113 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6120 static expression_t *parse_reference(void)
6122 source_position_t const pos = token.base.source_position;
6123 entity_t *const entity = parse_qualified_identifier();
6126 if (is_declaration(entity)) {
6127 orig_type = entity->declaration.type;
6128 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6129 orig_type = entity->enum_value.enum_type;
6131 panic("expected declaration or enum value in reference");
6134 /* we always do the auto-type conversions; the & and sizeof parser contains
6135 * code to revert this! */
6136 type_t *type = automatic_type_conversion(orig_type);
6138 expression_kind_t kind = EXPR_REFERENCE;
6139 if (entity->kind == ENTITY_ENUM_VALUE)
6140 kind = EXPR_ENUM_CONSTANT;
6142 expression_t *expression = allocate_expression_zero(kind);
6143 expression->base.source_position = pos;
6144 expression->base.type = type;
6145 expression->reference.entity = entity;
6147 /* this declaration is used */
6148 if (is_declaration(entity)) {
6149 entity->declaration.used = true;
6152 if (entity->base.parent_scope != file_scope
6153 && (current_function != NULL
6154 && entity->base.parent_scope->depth < current_function->parameters.depth)
6155 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6156 if (entity->kind == ENTITY_VARIABLE) {
6157 /* access of a variable from an outer function */
6158 entity->variable.address_taken = true;
6159 } else if (entity->kind == ENTITY_PARAMETER) {
6160 entity->parameter.address_taken = true;
6162 current_function->need_closure = true;
6165 check_deprecated(&pos, entity);
6170 static bool semantic_cast(expression_t *cast)
6172 expression_t *expression = cast->unary.value;
6173 type_t *orig_dest_type = cast->base.type;
6174 type_t *orig_type_right = expression->base.type;
6175 type_t const *dst_type = skip_typeref(orig_dest_type);
6176 type_t const *src_type = skip_typeref(orig_type_right);
6177 source_position_t const *pos = &cast->base.source_position;
6179 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6180 if (is_type_void(dst_type))
6183 /* only integer and pointer can be casted to pointer */
6184 if (is_type_pointer(dst_type) &&
6185 !is_type_pointer(src_type) &&
6186 !is_type_integer(src_type) &&
6187 is_type_valid(src_type)) {
6188 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6192 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6193 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6197 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6198 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6202 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6203 type_t *src = skip_typeref(src_type->pointer.points_to);
6204 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6205 unsigned missing_qualifiers =
6206 src->base.qualifiers & ~dst->base.qualifiers;
6207 if (missing_qualifiers != 0) {
6208 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6214 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6216 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6217 expression->base.source_position = *pos;
6219 parse_initializer_env_t env;
6222 env.must_be_constant = false;
6223 initializer_t *initializer = parse_initializer(&env);
6226 expression->compound_literal.initializer = initializer;
6227 expression->compound_literal.type = type;
6228 expression->base.type = automatic_type_conversion(type);
6234 * Parse a cast expression.
6236 static expression_t *parse_cast(void)
6238 source_position_t const pos = *HERE;
6241 add_anchor_token(')');
6243 type_t *type = parse_typename();
6245 rem_anchor_token(')');
6248 if (token.kind == '{') {
6249 return parse_compound_literal(&pos, type);
6252 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6253 cast->base.source_position = pos;
6255 expression_t *value = parse_subexpression(PREC_CAST);
6256 cast->base.type = type;
6257 cast->unary.value = value;
6259 if (! semantic_cast(cast)) {
6260 /* TODO: record the error in the AST. else it is impossible to detect it */
6267 * Parse a statement expression.
6269 static expression_t *parse_statement_expression(void)
6271 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6274 add_anchor_token(')');
6276 statement_t *statement = parse_compound_statement(true);
6277 statement->compound.stmt_expr = true;
6278 expression->statement.statement = statement;
6280 /* find last statement and use its type */
6281 type_t *type = type_void;
6282 const statement_t *stmt = statement->compound.statements;
6284 while (stmt->base.next != NULL)
6285 stmt = stmt->base.next;
6287 if (stmt->kind == STATEMENT_EXPRESSION) {
6288 type = stmt->expression.expression->base.type;
6291 source_position_t const *const pos = &expression->base.source_position;
6292 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6294 expression->base.type = type;
6296 rem_anchor_token(')');
6302 * Parse a parenthesized expression.
6304 static expression_t *parse_parenthesized_expression(void)
6306 token_t const* const la1 = look_ahead(1);
6307 switch (la1->kind) {
6309 /* gcc extension: a statement expression */
6310 return parse_statement_expression();
6313 if (is_typedef_symbol(la1->identifier.symbol)) {
6315 return parse_cast();
6320 add_anchor_token(')');
6321 expression_t *result = parse_expression();
6322 result->base.parenthesized = true;
6323 rem_anchor_token(')');
6329 static expression_t *parse_function_keyword(void)
6333 if (current_function == NULL) {
6334 errorf(HERE, "'__func__' used outside of a function");
6337 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6338 expression->base.type = type_char_ptr;
6339 expression->funcname.kind = FUNCNAME_FUNCTION;
6346 static expression_t *parse_pretty_function_keyword(void)
6348 if (current_function == NULL) {
6349 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6352 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6353 expression->base.type = type_char_ptr;
6354 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6356 eat(T___PRETTY_FUNCTION__);
6361 static expression_t *parse_funcsig_keyword(void)
6363 if (current_function == NULL) {
6364 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6367 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6368 expression->base.type = type_char_ptr;
6369 expression->funcname.kind = FUNCNAME_FUNCSIG;
6376 static expression_t *parse_funcdname_keyword(void)
6378 if (current_function == NULL) {
6379 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6382 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6383 expression->base.type = type_char_ptr;
6384 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6386 eat(T___FUNCDNAME__);
6391 static designator_t *parse_designator(void)
6393 designator_t *const result = allocate_ast_zero(sizeof(result[0]));
6394 result->symbol = expect_identifier("while parsing member designator", &result->source_position);
6395 if (!result->symbol)
6398 designator_t *last_designator = result;
6401 designator_t *const designator = allocate_ast_zero(sizeof(result[0]));
6402 designator->symbol = expect_identifier("while parsing member designator", &designator->source_position);
6403 if (!designator->symbol)
6406 last_designator->next = designator;
6407 last_designator = designator;
6411 add_anchor_token(']');
6412 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6413 designator->source_position = *HERE;
6414 designator->array_index = parse_expression();
6415 rem_anchor_token(']');
6417 if (designator->array_index == NULL) {
6421 last_designator->next = designator;
6422 last_designator = designator;
6432 * Parse the __builtin_offsetof() expression.
6434 static expression_t *parse_offsetof(void)
6436 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6437 expression->base.type = type_size_t;
6439 eat(T___builtin_offsetof);
6442 add_anchor_token(')');
6443 add_anchor_token(',');
6444 type_t *type = parse_typename();
6445 rem_anchor_token(',');
6447 designator_t *designator = parse_designator();
6448 rem_anchor_token(')');
6451 expression->offsetofe.type = type;
6452 expression->offsetofe.designator = designator;
6455 memset(&path, 0, sizeof(path));
6456 path.top_type = type;
6457 path.path = NEW_ARR_F(type_path_entry_t, 0);
6459 descend_into_subtype(&path);
6461 if (!walk_designator(&path, designator, true)) {
6462 return create_error_expression();
6465 DEL_ARR_F(path.path);
6471 * Parses a _builtin_va_start() expression.
6473 static expression_t *parse_va_start(void)
6475 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6477 eat(T___builtin_va_start);
6480 add_anchor_token(')');
6481 add_anchor_token(',');
6482 expression->va_starte.ap = parse_assignment_expression();
6483 rem_anchor_token(',');
6485 expression_t *const expr = parse_assignment_expression();
6486 if (expr->kind == EXPR_REFERENCE) {
6487 entity_t *const entity = expr->reference.entity;
6488 if (!current_function->base.type->function.variadic) {
6489 errorf(&expr->base.source_position,
6490 "'va_start' used in non-variadic function");
6491 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6492 entity->base.next != NULL ||
6493 entity->kind != ENTITY_PARAMETER) {
6494 errorf(&expr->base.source_position,
6495 "second argument of 'va_start' must be last parameter of the current function");
6497 expression->va_starte.parameter = &entity->variable;
6500 expression = create_error_expression();
6502 rem_anchor_token(')');
6508 * Parses a __builtin_va_arg() expression.
6510 static expression_t *parse_va_arg(void)
6512 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6514 eat(T___builtin_va_arg);
6517 add_anchor_token(')');
6518 add_anchor_token(',');
6520 ap.expression = parse_assignment_expression();
6521 expression->va_arge.ap = ap.expression;
6522 check_call_argument(type_valist, &ap, 1);
6524 rem_anchor_token(',');
6526 expression->base.type = parse_typename();
6527 rem_anchor_token(')');
6534 * Parses a __builtin_va_copy() expression.
6536 static expression_t *parse_va_copy(void)
6538 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6540 eat(T___builtin_va_copy);
6543 add_anchor_token(')');
6544 add_anchor_token(',');
6545 expression_t *dst = parse_assignment_expression();
6546 assign_error_t error = semantic_assign(type_valist, dst);
6547 report_assign_error(error, type_valist, dst, "call argument 1",
6548 &dst->base.source_position);
6549 expression->va_copye.dst = dst;
6551 rem_anchor_token(',');
6554 call_argument_t src;
6555 src.expression = parse_assignment_expression();
6556 check_call_argument(type_valist, &src, 2);
6557 expression->va_copye.src = src.expression;
6558 rem_anchor_token(')');
6565 * Parses a __builtin_constant_p() expression.
6567 static expression_t *parse_builtin_constant(void)
6569 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6571 eat(T___builtin_constant_p);
6574 add_anchor_token(')');
6575 expression->builtin_constant.value = parse_assignment_expression();
6576 rem_anchor_token(')');
6578 expression->base.type = type_int;
6584 * Parses a __builtin_types_compatible_p() expression.
6586 static expression_t *parse_builtin_types_compatible(void)
6588 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6590 eat(T___builtin_types_compatible_p);
6593 add_anchor_token(')');
6594 add_anchor_token(',');
6595 expression->builtin_types_compatible.left = parse_typename();
6596 rem_anchor_token(',');
6598 expression->builtin_types_compatible.right = parse_typename();
6599 rem_anchor_token(')');
6601 expression->base.type = type_int;
6607 * Parses a __builtin_is_*() compare expression.
6609 static expression_t *parse_compare_builtin(void)
6611 expression_t *expression;
6613 switch (token.kind) {
6614 case T___builtin_isgreater:
6615 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6617 case T___builtin_isgreaterequal:
6618 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6620 case T___builtin_isless:
6621 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6623 case T___builtin_islessequal:
6624 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6626 case T___builtin_islessgreater:
6627 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6629 case T___builtin_isunordered:
6630 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6633 internal_errorf(HERE, "invalid compare builtin found");
6635 expression->base.source_position = *HERE;
6639 add_anchor_token(')');
6640 add_anchor_token(',');
6641 expression->binary.left = parse_assignment_expression();
6642 rem_anchor_token(',');
6644 expression->binary.right = parse_assignment_expression();
6645 rem_anchor_token(')');
6648 type_t *const orig_type_left = expression->binary.left->base.type;
6649 type_t *const orig_type_right = expression->binary.right->base.type;
6651 type_t *const type_left = skip_typeref(orig_type_left);
6652 type_t *const type_right = skip_typeref(orig_type_right);
6653 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6654 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6655 type_error_incompatible("invalid operands in comparison",
6656 &expression->base.source_position, orig_type_left, orig_type_right);
6659 semantic_comparison(&expression->binary);
6666 * Parses a MS assume() expression.
6668 static expression_t *parse_assume(void)
6670 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6675 add_anchor_token(')');
6676 expression->unary.value = parse_assignment_expression();
6677 rem_anchor_token(')');
6680 expression->base.type = type_void;
6685 * Return the label for the current symbol or create a new one.
6687 static label_t *get_label(void)
6689 assert(token.kind == T_IDENTIFIER);
6690 assert(current_function != NULL);
6692 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6693 /* If we find a local label, we already created the declaration. */
6694 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6695 if (label->base.parent_scope != current_scope) {
6696 assert(label->base.parent_scope->depth < current_scope->depth);
6697 current_function->goto_to_outer = true;
6699 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6700 /* There is no matching label in the same function, so create a new one. */
6701 source_position_t const nowhere = { NULL, 0, 0, false };
6702 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6707 return &label->label;
6711 * Parses a GNU && label address expression.
6713 static expression_t *parse_label_address(void)
6715 source_position_t source_position = token.base.source_position;
6717 if (token.kind != T_IDENTIFIER) {
6718 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6719 return create_error_expression();
6722 label_t *const label = get_label();
6724 label->address_taken = true;
6726 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6727 expression->base.source_position = source_position;
6729 /* label address is treated as a void pointer */
6730 expression->base.type = type_void_ptr;
6731 expression->label_address.label = label;
6736 * Parse a microsoft __noop expression.
6738 static expression_t *parse_noop_expression(void)
6740 /* the result is a (int)0 */
6741 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6742 literal->base.type = type_int;
6743 literal->literal.value.begin = "__noop";
6744 literal->literal.value.size = 6;
6748 if (token.kind == '(') {
6749 /* parse arguments */
6751 add_anchor_token(')');
6752 add_anchor_token(',');
6754 if (token.kind != ')') do {
6755 (void)parse_assignment_expression();
6756 } while (next_if(','));
6758 rem_anchor_token(',');
6759 rem_anchor_token(')');
6767 * Parses a primary expression.
6769 static expression_t *parse_primary_expression(void)
6771 switch (token.kind) {
6772 case T_false: return parse_boolean_literal(false);
6773 case T_true: return parse_boolean_literal(true);
6775 case T_INTEGER_OCTAL:
6776 case T_INTEGER_HEXADECIMAL:
6777 case T_FLOATINGPOINT:
6778 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6779 case T_CHARACTER_CONSTANT: return parse_character_constant();
6780 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6781 case T_STRING_LITERAL:
6782 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6783 case T___FUNCTION__:
6784 case T___func__: return parse_function_keyword();
6785 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6786 case T___FUNCSIG__: return parse_funcsig_keyword();
6787 case T___FUNCDNAME__: return parse_funcdname_keyword();
6788 case T___builtin_offsetof: return parse_offsetof();
6789 case T___builtin_va_start: return parse_va_start();
6790 case T___builtin_va_arg: return parse_va_arg();
6791 case T___builtin_va_copy: return parse_va_copy();
6792 case T___builtin_isgreater:
6793 case T___builtin_isgreaterequal:
6794 case T___builtin_isless:
6795 case T___builtin_islessequal:
6796 case T___builtin_islessgreater:
6797 case T___builtin_isunordered: return parse_compare_builtin();
6798 case T___builtin_constant_p: return parse_builtin_constant();
6799 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6800 case T__assume: return parse_assume();
6803 return parse_label_address();
6806 case '(': return parse_parenthesized_expression();
6807 case T___noop: return parse_noop_expression();
6809 /* Gracefully handle type names while parsing expressions. */
6811 return parse_reference();
6813 if (!is_typedef_symbol(token.identifier.symbol)) {
6814 return parse_reference();
6818 source_position_t const pos = *HERE;
6819 declaration_specifiers_t specifiers;
6820 parse_declaration_specifiers(&specifiers);
6821 type_t const *const type = parse_abstract_declarator(specifiers.type);
6822 errorf(&pos, "encountered type '%T' while parsing expression", type);
6823 return create_error_expression();
6827 errorf(HERE, "unexpected token %K, expected an expression", &token);
6829 return create_error_expression();
6832 static expression_t *parse_array_expression(expression_t *left)
6834 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6835 array_access_expression_t *const arr = &expr->array_access;
6838 add_anchor_token(']');
6840 expression_t *const inside = parse_expression();
6842 type_t *const orig_type_left = left->base.type;
6843 type_t *const orig_type_inside = inside->base.type;
6845 type_t *const type_left = skip_typeref(orig_type_left);
6846 type_t *const type_inside = skip_typeref(orig_type_inside);
6852 if (is_type_pointer(type_left)) {
6855 idx_type = type_inside;
6856 res_type = type_left->pointer.points_to;
6858 } else if (is_type_pointer(type_inside)) {
6859 arr->flipped = true;
6862 idx_type = type_left;
6863 res_type = type_inside->pointer.points_to;
6865 res_type = automatic_type_conversion(res_type);
6866 if (!is_type_integer(idx_type)) {
6867 errorf(&idx->base.source_position, "array subscript must have integer type");
6868 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6869 source_position_t const *const pos = &idx->base.source_position;
6870 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6873 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6874 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6876 res_type = type_error_type;
6881 arr->array_ref = ref;
6883 arr->base.type = res_type;
6885 rem_anchor_token(']');
6890 static bool is_bitfield(const expression_t *expression)
6892 return expression->kind == EXPR_SELECT
6893 && expression->select.compound_entry->compound_member.bitfield;
6896 static expression_t *parse_typeprop(expression_kind_t const kind)
6898 expression_t *tp_expression = allocate_expression_zero(kind);
6899 tp_expression->base.type = type_size_t;
6901 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6904 expression_t *expression;
6905 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6906 source_position_t const pos = *HERE;
6908 add_anchor_token(')');
6909 orig_type = parse_typename();
6910 rem_anchor_token(')');
6913 if (token.kind == '{') {
6914 /* It was not sizeof(type) after all. It is sizeof of an expression
6915 * starting with a compound literal */
6916 expression = parse_compound_literal(&pos, orig_type);
6917 goto typeprop_expression;
6920 expression = parse_subexpression(PREC_UNARY);
6922 typeprop_expression:
6923 if (is_bitfield(expression)) {
6924 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6925 errorf(&tp_expression->base.source_position,
6926 "operand of %s expression must not be a bitfield", what);
6929 tp_expression->typeprop.tp_expression = expression;
6931 orig_type = revert_automatic_type_conversion(expression);
6932 expression->base.type = orig_type;
6935 tp_expression->typeprop.type = orig_type;
6936 type_t const* const type = skip_typeref(orig_type);
6937 char const* wrong_type = NULL;
6938 if (is_type_incomplete(type)) {
6939 if (!is_type_void(type) || !GNU_MODE)
6940 wrong_type = "incomplete";
6941 } else if (type->kind == TYPE_FUNCTION) {
6943 /* function types are allowed (and return 1) */
6944 source_position_t const *const pos = &tp_expression->base.source_position;
6945 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6946 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
6948 wrong_type = "function";
6952 if (wrong_type != NULL) {
6953 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
6954 errorf(&tp_expression->base.source_position,
6955 "operand of %s expression must not be of %s type '%T'",
6956 what, wrong_type, orig_type);
6959 return tp_expression;
6962 static expression_t *parse_sizeof(void)
6964 return parse_typeprop(EXPR_SIZEOF);
6967 static expression_t *parse_alignof(void)
6969 return parse_typeprop(EXPR_ALIGNOF);
6972 static expression_t *parse_select_expression(expression_t *addr)
6974 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
6975 bool select_left_arrow = (token.kind == T_MINUSGREATER);
6976 source_position_t const pos = *HERE;
6979 symbol_t *const symbol = expect_identifier("while parsing select", NULL);
6981 return create_error_expression();
6983 type_t *const orig_type = addr->base.type;
6984 type_t *const type = skip_typeref(orig_type);
6987 bool saw_error = false;
6988 if (is_type_pointer(type)) {
6989 if (!select_left_arrow) {
6991 "request for member '%Y' in something not a struct or union, but '%T'",
6995 type_left = skip_typeref(type->pointer.points_to);
6997 if (select_left_arrow && is_type_valid(type)) {
6998 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7004 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7005 type_left->kind != TYPE_COMPOUND_UNION) {
7007 if (is_type_valid(type_left) && !saw_error) {
7009 "request for member '%Y' in something not a struct or union, but '%T'",
7012 return create_error_expression();
7015 compound_t *compound = type_left->compound.compound;
7016 if (!compound->complete) {
7017 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7019 return create_error_expression();
7022 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7023 expression_t *result =
7024 find_create_select(&pos, addr, qualifiers, compound, symbol);
7026 if (result == NULL) {
7027 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7028 return create_error_expression();
7034 static void check_call_argument(type_t *expected_type,
7035 call_argument_t *argument, unsigned pos)
7037 type_t *expected_type_skip = skip_typeref(expected_type);
7038 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7039 expression_t *arg_expr = argument->expression;
7040 type_t *arg_type = skip_typeref(arg_expr->base.type);
7042 /* handle transparent union gnu extension */
7043 if (is_type_union(expected_type_skip)
7044 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7045 compound_t *union_decl = expected_type_skip->compound.compound;
7046 type_t *best_type = NULL;
7047 entity_t *entry = union_decl->members.entities;
7048 for ( ; entry != NULL; entry = entry->base.next) {
7049 assert(is_declaration(entry));
7050 type_t *decl_type = entry->declaration.type;
7051 error = semantic_assign(decl_type, arg_expr);
7052 if (error == ASSIGN_ERROR_INCOMPATIBLE
7053 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7056 if (error == ASSIGN_SUCCESS) {
7057 best_type = decl_type;
7058 } else if (best_type == NULL) {
7059 best_type = decl_type;
7063 if (best_type != NULL) {
7064 expected_type = best_type;
7068 error = semantic_assign(expected_type, arg_expr);
7069 argument->expression = create_implicit_cast(arg_expr, expected_type);
7071 if (error != ASSIGN_SUCCESS) {
7072 /* report exact scope in error messages (like "in argument 3") */
7074 snprintf(buf, sizeof(buf), "call argument %u", pos);
7075 report_assign_error(error, expected_type, arg_expr, buf,
7076 &arg_expr->base.source_position);
7078 type_t *const promoted_type = get_default_promoted_type(arg_type);
7079 if (!types_compatible(expected_type_skip, promoted_type) &&
7080 !types_compatible(expected_type_skip, type_void_ptr) &&
7081 !types_compatible(type_void_ptr, promoted_type)) {
7082 /* Deliberately show the skipped types in this warning */
7083 source_position_t const *const apos = &arg_expr->base.source_position;
7084 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7090 * Handle the semantic restrictions of builtin calls
7092 static void handle_builtin_argument_restrictions(call_expression_t *call)
7094 entity_t *entity = call->function->reference.entity;
7095 switch (entity->function.btk) {
7097 switch (entity->function.b.firm_builtin_kind) {
7098 case ir_bk_return_address:
7099 case ir_bk_frame_address: {
7100 /* argument must be constant */
7101 call_argument_t *argument = call->arguments;
7103 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7104 errorf(&call->base.source_position,
7105 "argument of '%Y' must be a constant expression",
7106 call->function->reference.entity->base.symbol);
7110 case ir_bk_prefetch:
7111 /* second and third argument must be constant if existent */
7112 if (call->arguments == NULL)
7114 call_argument_t *rw = call->arguments->next;
7115 call_argument_t *locality = NULL;
7118 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7119 errorf(&call->base.source_position,
7120 "second argument of '%Y' must be a constant expression",
7121 call->function->reference.entity->base.symbol);
7123 locality = rw->next;
7125 if (locality != NULL) {
7126 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7127 errorf(&call->base.source_position,
7128 "third argument of '%Y' must be a constant expression",
7129 call->function->reference.entity->base.symbol);
7131 locality = rw->next;
7138 case BUILTIN_OBJECT_SIZE:
7139 if (call->arguments == NULL)
7142 call_argument_t *arg = call->arguments->next;
7143 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7144 errorf(&call->base.source_position,
7145 "second argument of '%Y' must be a constant expression",
7146 call->function->reference.entity->base.symbol);
7155 * Parse a call expression, ie. expression '( ... )'.
7157 * @param expression the function address
7159 static expression_t *parse_call_expression(expression_t *expression)
7161 expression_t *result = allocate_expression_zero(EXPR_CALL);
7162 call_expression_t *call = &result->call;
7163 call->function = expression;
7165 type_t *const orig_type = expression->base.type;
7166 type_t *const type = skip_typeref(orig_type);
7168 function_type_t *function_type = NULL;
7169 if (is_type_pointer(type)) {
7170 type_t *const to_type = skip_typeref(type->pointer.points_to);
7172 if (is_type_function(to_type)) {
7173 function_type = &to_type->function;
7174 call->base.type = function_type->return_type;
7178 if (function_type == NULL && is_type_valid(type)) {
7180 "called object '%E' (type '%T') is not a pointer to a function",
7181 expression, orig_type);
7184 /* parse arguments */
7186 add_anchor_token(')');
7187 add_anchor_token(',');
7189 if (token.kind != ')') {
7190 call_argument_t **anchor = &call->arguments;
7192 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7193 argument->expression = parse_assignment_expression();
7196 anchor = &argument->next;
7197 } while (next_if(','));
7199 rem_anchor_token(',');
7200 rem_anchor_token(')');
7203 if (function_type == NULL)
7206 /* check type and count of call arguments */
7207 function_parameter_t *parameter = function_type->parameters;
7208 call_argument_t *argument = call->arguments;
7209 if (!function_type->unspecified_parameters) {
7210 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7211 parameter = parameter->next, argument = argument->next) {
7212 check_call_argument(parameter->type, argument, ++pos);
7215 if (parameter != NULL) {
7216 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7217 } else if (argument != NULL && !function_type->variadic) {
7218 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7222 /* do default promotion for other arguments */
7223 for (; argument != NULL; argument = argument->next) {
7224 type_t *argument_type = argument->expression->base.type;
7225 if (!is_type_object(skip_typeref(argument_type))) {
7226 errorf(&argument->expression->base.source_position,
7227 "call argument '%E' must not be void", argument->expression);
7230 argument_type = get_default_promoted_type(argument_type);
7232 argument->expression
7233 = create_implicit_cast(argument->expression, argument_type);
7238 if (is_type_compound(skip_typeref(function_type->return_type))) {
7239 source_position_t const *const pos = &expression->base.source_position;
7240 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7243 if (expression->kind == EXPR_REFERENCE) {
7244 reference_expression_t *reference = &expression->reference;
7245 if (reference->entity->kind == ENTITY_FUNCTION &&
7246 reference->entity->function.btk != BUILTIN_NONE)
7247 handle_builtin_argument_restrictions(call);
7253 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7255 static bool same_compound_type(const type_t *type1, const type_t *type2)
7258 is_type_compound(type1) &&
7259 type1->kind == type2->kind &&
7260 type1->compound.compound == type2->compound.compound;
7263 static expression_t const *get_reference_address(expression_t const *expr)
7265 bool regular_take_address = true;
7267 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7268 expr = expr->unary.value;
7270 regular_take_address = false;
7273 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7276 expr = expr->unary.value;
7279 if (expr->kind != EXPR_REFERENCE)
7282 /* special case for functions which are automatically converted to a
7283 * pointer to function without an extra TAKE_ADDRESS operation */
7284 if (!regular_take_address &&
7285 expr->reference.entity->kind != ENTITY_FUNCTION) {
7292 static void warn_reference_address_as_bool(expression_t const* expr)
7294 expr = get_reference_address(expr);
7296 source_position_t const *const pos = &expr->base.source_position;
7297 entity_t const *const ent = expr->reference.entity;
7298 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7302 static void warn_assignment_in_condition(const expression_t *const expr)
7304 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7306 if (expr->base.parenthesized)
7308 source_position_t const *const pos = &expr->base.source_position;
7309 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7312 static void semantic_condition(expression_t const *const expr,
7313 char const *const context)
7315 type_t *const type = skip_typeref(expr->base.type);
7316 if (is_type_scalar(type)) {
7317 warn_reference_address_as_bool(expr);
7318 warn_assignment_in_condition(expr);
7319 } else if (is_type_valid(type)) {
7320 errorf(&expr->base.source_position,
7321 "%s must have scalar type", context);
7326 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7328 * @param expression the conditional expression
7330 static expression_t *parse_conditional_expression(expression_t *expression)
7332 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7334 conditional_expression_t *conditional = &result->conditional;
7335 conditional->condition = expression;
7338 add_anchor_token(':');
7340 /* §6.5.15:2 The first operand shall have scalar type. */
7341 semantic_condition(expression, "condition of conditional operator");
7343 expression_t *true_expression = expression;
7344 bool gnu_cond = false;
7345 if (GNU_MODE && token.kind == ':') {
7348 true_expression = parse_expression();
7350 rem_anchor_token(':');
7352 expression_t *false_expression =
7353 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7355 type_t *const orig_true_type = true_expression->base.type;
7356 type_t *const orig_false_type = false_expression->base.type;
7357 type_t *const true_type = skip_typeref(orig_true_type);
7358 type_t *const false_type = skip_typeref(orig_false_type);
7361 source_position_t const *const pos = &conditional->base.source_position;
7362 type_t *result_type;
7363 if (is_type_void(true_type) || is_type_void(false_type)) {
7364 /* ISO/IEC 14882:1998(E) §5.16:2 */
7365 if (true_expression->kind == EXPR_UNARY_THROW) {
7366 result_type = false_type;
7367 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7368 result_type = true_type;
7370 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7371 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7373 result_type = type_void;
7375 } else if (is_type_arithmetic(true_type)
7376 && is_type_arithmetic(false_type)) {
7377 result_type = semantic_arithmetic(true_type, false_type);
7378 } else if (same_compound_type(true_type, false_type)) {
7379 /* just take 1 of the 2 types */
7380 result_type = true_type;
7381 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7382 type_t *pointer_type;
7384 expression_t *other_expression;
7385 if (is_type_pointer(true_type) &&
7386 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7387 pointer_type = true_type;
7388 other_type = false_type;
7389 other_expression = false_expression;
7391 pointer_type = false_type;
7392 other_type = true_type;
7393 other_expression = true_expression;
7396 if (is_null_pointer_constant(other_expression)) {
7397 result_type = pointer_type;
7398 } else if (is_type_pointer(other_type)) {
7399 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7400 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7403 if (is_type_void(to1) || is_type_void(to2)) {
7405 } else if (types_compatible(get_unqualified_type(to1),
7406 get_unqualified_type(to2))) {
7409 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7413 type_t *const type =
7414 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7415 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7416 } else if (is_type_integer(other_type)) {
7417 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7418 result_type = pointer_type;
7420 goto types_incompatible;
7424 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7425 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7427 result_type = type_error_type;
7430 conditional->true_expression
7431 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7432 conditional->false_expression
7433 = create_implicit_cast(false_expression, result_type);
7434 conditional->base.type = result_type;
7439 * Parse an extension expression.
7441 static expression_t *parse_extension(void)
7444 expression_t *expression = parse_subexpression(PREC_UNARY);
7450 * Parse a __builtin_classify_type() expression.
7452 static expression_t *parse_builtin_classify_type(void)
7454 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7455 result->base.type = type_int;
7457 eat(T___builtin_classify_type);
7460 add_anchor_token(')');
7461 expression_t *expression = parse_expression();
7462 rem_anchor_token(')');
7464 result->classify_type.type_expression = expression;
7470 * Parse a delete expression
7471 * ISO/IEC 14882:1998(E) §5.3.5
7473 static expression_t *parse_delete(void)
7475 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7476 result->base.type = type_void;
7481 result->kind = EXPR_UNARY_DELETE_ARRAY;
7485 expression_t *const value = parse_subexpression(PREC_CAST);
7486 result->unary.value = value;
7488 type_t *const type = skip_typeref(value->base.type);
7489 if (!is_type_pointer(type)) {
7490 if (is_type_valid(type)) {
7491 errorf(&value->base.source_position,
7492 "operand of delete must have pointer type");
7494 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7495 source_position_t const *const pos = &value->base.source_position;
7496 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7503 * Parse a throw expression
7504 * ISO/IEC 14882:1998(E) §15:1
7506 static expression_t *parse_throw(void)
7508 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7509 result->base.type = type_void;
7513 expression_t *value = NULL;
7514 switch (token.kind) {
7516 value = parse_assignment_expression();
7517 /* ISO/IEC 14882:1998(E) §15.1:3 */
7518 type_t *const orig_type = value->base.type;
7519 type_t *const type = skip_typeref(orig_type);
7520 if (is_type_incomplete(type)) {
7521 errorf(&value->base.source_position,
7522 "cannot throw object of incomplete type '%T'", orig_type);
7523 } else if (is_type_pointer(type)) {
7524 type_t *const points_to = skip_typeref(type->pointer.points_to);
7525 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7526 errorf(&value->base.source_position,
7527 "cannot throw pointer to incomplete type '%T'", orig_type);
7535 result->unary.value = value;
7540 static bool check_pointer_arithmetic(const source_position_t *source_position,
7541 type_t *pointer_type,
7542 type_t *orig_pointer_type)
7544 type_t *points_to = pointer_type->pointer.points_to;
7545 points_to = skip_typeref(points_to);
7547 if (is_type_incomplete(points_to)) {
7548 if (!GNU_MODE || !is_type_void(points_to)) {
7549 errorf(source_position,
7550 "arithmetic with pointer to incomplete type '%T' not allowed",
7554 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7556 } else if (is_type_function(points_to)) {
7558 errorf(source_position,
7559 "arithmetic with pointer to function type '%T' not allowed",
7563 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7569 static bool is_lvalue(const expression_t *expression)
7571 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7572 switch (expression->kind) {
7573 case EXPR_ARRAY_ACCESS:
7574 case EXPR_COMPOUND_LITERAL:
7575 case EXPR_REFERENCE:
7577 case EXPR_UNARY_DEREFERENCE:
7581 type_t *type = skip_typeref(expression->base.type);
7583 /* ISO/IEC 14882:1998(E) §3.10:3 */
7584 is_type_reference(type) ||
7585 /* Claim it is an lvalue, if the type is invalid. There was a parse
7586 * error before, which maybe prevented properly recognizing it as
7588 !is_type_valid(type);
7593 static void semantic_incdec(unary_expression_t *expression)
7595 type_t *const orig_type = expression->value->base.type;
7596 type_t *const type = skip_typeref(orig_type);
7597 if (is_type_pointer(type)) {
7598 if (!check_pointer_arithmetic(&expression->base.source_position,
7602 } else if (!is_type_real(type) && is_type_valid(type)) {
7603 /* TODO: improve error message */
7604 errorf(&expression->base.source_position,
7605 "operation needs an arithmetic or pointer type");
7608 if (!is_lvalue(expression->value)) {
7609 /* TODO: improve error message */
7610 errorf(&expression->base.source_position, "lvalue required as operand");
7612 expression->base.type = orig_type;
7615 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7617 type_t *const res_type = promote_integer(type);
7618 expr->base.type = res_type;
7619 expr->value = create_implicit_cast(expr->value, res_type);
7622 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7624 type_t *const orig_type = expression->value->base.type;
7625 type_t *const type = skip_typeref(orig_type);
7626 if (!is_type_arithmetic(type)) {
7627 if (is_type_valid(type)) {
7628 /* TODO: improve error message */
7629 errorf(&expression->base.source_position,
7630 "operation needs an arithmetic type");
7633 } else if (is_type_integer(type)) {
7634 promote_unary_int_expr(expression, type);
7636 expression->base.type = orig_type;
7640 static void semantic_unexpr_plus(unary_expression_t *expression)
7642 semantic_unexpr_arithmetic(expression);
7643 source_position_t const *const pos = &expression->base.source_position;
7644 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7647 static void semantic_not(unary_expression_t *expression)
7649 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7650 semantic_condition(expression->value, "operand of !");
7651 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7654 static void semantic_unexpr_integer(unary_expression_t *expression)
7656 type_t *const orig_type = expression->value->base.type;
7657 type_t *const type = skip_typeref(orig_type);
7658 if (!is_type_integer(type)) {
7659 if (is_type_valid(type)) {
7660 errorf(&expression->base.source_position,
7661 "operand of ~ must be of integer type");
7666 promote_unary_int_expr(expression, type);
7669 static void semantic_dereference(unary_expression_t *expression)
7671 type_t *const orig_type = expression->value->base.type;
7672 type_t *const type = skip_typeref(orig_type);
7673 if (!is_type_pointer(type)) {
7674 if (is_type_valid(type)) {
7675 errorf(&expression->base.source_position,
7676 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7681 type_t *result_type = type->pointer.points_to;
7682 result_type = automatic_type_conversion(result_type);
7683 expression->base.type = result_type;
7687 * Record that an address is taken (expression represents an lvalue).
7689 * @param expression the expression
7690 * @param may_be_register if true, the expression might be an register
7692 static void set_address_taken(expression_t *expression, bool may_be_register)
7694 if (expression->kind != EXPR_REFERENCE)
7697 entity_t *const entity = expression->reference.entity;
7699 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7702 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7703 && !may_be_register) {
7704 source_position_t const *const pos = &expression->base.source_position;
7705 errorf(pos, "address of register '%N' requested", entity);
7708 if (entity->kind == ENTITY_VARIABLE) {
7709 entity->variable.address_taken = true;
7711 assert(entity->kind == ENTITY_PARAMETER);
7712 entity->parameter.address_taken = true;
7717 * Check the semantic of the address taken expression.
7719 static void semantic_take_addr(unary_expression_t *expression)
7721 expression_t *value = expression->value;
7722 value->base.type = revert_automatic_type_conversion(value);
7724 type_t *orig_type = value->base.type;
7725 type_t *type = skip_typeref(orig_type);
7726 if (!is_type_valid(type))
7730 if (!is_lvalue(value)) {
7731 errorf(&expression->base.source_position, "'&' requires an lvalue");
7733 if (is_bitfield(value)) {
7734 errorf(&expression->base.source_position,
7735 "'&' not allowed on bitfield");
7738 set_address_taken(value, false);
7740 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7743 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7744 static expression_t *parse_##unexpression_type(void) \
7746 expression_t *unary_expression \
7747 = allocate_expression_zero(unexpression_type); \
7749 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7751 sfunc(&unary_expression->unary); \
7753 return unary_expression; \
7756 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7757 semantic_unexpr_arithmetic)
7758 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7759 semantic_unexpr_plus)
7760 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7762 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7763 semantic_dereference)
7764 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7766 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7767 semantic_unexpr_integer)
7768 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7770 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7773 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7775 static expression_t *parse_##unexpression_type(expression_t *left) \
7777 expression_t *unary_expression \
7778 = allocate_expression_zero(unexpression_type); \
7780 unary_expression->unary.value = left; \
7782 sfunc(&unary_expression->unary); \
7784 return unary_expression; \
7787 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7788 EXPR_UNARY_POSTFIX_INCREMENT,
7790 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7791 EXPR_UNARY_POSTFIX_DECREMENT,
7794 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7796 /* TODO: handle complex + imaginary types */
7798 type_left = get_unqualified_type(type_left);
7799 type_right = get_unqualified_type(type_right);
7801 /* §6.3.1.8 Usual arithmetic conversions */
7802 if (type_left == type_long_double || type_right == type_long_double) {
7803 return type_long_double;
7804 } else if (type_left == type_double || type_right == type_double) {
7806 } else if (type_left == type_float || type_right == type_float) {
7810 type_left = promote_integer(type_left);
7811 type_right = promote_integer(type_right);
7813 if (type_left == type_right)
7816 bool const signed_left = is_type_signed(type_left);
7817 bool const signed_right = is_type_signed(type_right);
7818 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7819 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7821 if (signed_left == signed_right)
7822 return rank_left >= rank_right ? type_left : type_right;
7826 atomic_type_kind_t s_akind;
7827 atomic_type_kind_t u_akind;
7832 u_type = type_right;
7834 s_type = type_right;
7837 s_akind = get_akind(s_type);
7838 u_akind = get_akind(u_type);
7839 s_rank = get_akind_rank(s_akind);
7840 u_rank = get_akind_rank(u_akind);
7842 if (u_rank >= s_rank)
7845 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7849 case ATOMIC_TYPE_INT: return type_unsigned_int;
7850 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7851 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7853 default: panic("invalid atomic type");
7858 * Check the semantic restrictions for a binary expression.
7860 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7862 expression_t *const left = expression->left;
7863 expression_t *const right = expression->right;
7864 type_t *const orig_type_left = left->base.type;
7865 type_t *const orig_type_right = right->base.type;
7866 type_t *const type_left = skip_typeref(orig_type_left);
7867 type_t *const type_right = skip_typeref(orig_type_right);
7869 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7870 /* TODO: improve error message */
7871 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7872 errorf(&expression->base.source_position,
7873 "operation needs arithmetic types");
7878 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7879 expression->left = create_implicit_cast(left, arithmetic_type);
7880 expression->right = create_implicit_cast(right, arithmetic_type);
7881 expression->base.type = arithmetic_type;
7884 static void semantic_binexpr_integer(binary_expression_t *const expression)
7886 expression_t *const left = expression->left;
7887 expression_t *const right = expression->right;
7888 type_t *const orig_type_left = left->base.type;
7889 type_t *const orig_type_right = right->base.type;
7890 type_t *const type_left = skip_typeref(orig_type_left);
7891 type_t *const type_right = skip_typeref(orig_type_right);
7893 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7894 /* TODO: improve error message */
7895 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7896 errorf(&expression->base.source_position,
7897 "operation needs integer types");
7902 type_t *const result_type = semantic_arithmetic(type_left, type_right);
7903 expression->left = create_implicit_cast(left, result_type);
7904 expression->right = create_implicit_cast(right, result_type);
7905 expression->base.type = result_type;
7908 static void warn_div_by_zero(binary_expression_t const *const expression)
7910 if (!is_type_integer(expression->base.type))
7913 expression_t const *const right = expression->right;
7914 /* The type of the right operand can be different for /= */
7915 if (is_type_integer(right->base.type) &&
7916 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
7917 !fold_constant_to_bool(right)) {
7918 source_position_t const *const pos = &expression->base.source_position;
7919 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
7924 * Check the semantic restrictions for a div/mod expression.
7926 static void semantic_divmod_arithmetic(binary_expression_t *expression)
7928 semantic_binexpr_arithmetic(expression);
7929 warn_div_by_zero(expression);
7932 static void warn_addsub_in_shift(const expression_t *const expr)
7934 if (expr->base.parenthesized)
7938 switch (expr->kind) {
7939 case EXPR_BINARY_ADD: op = '+'; break;
7940 case EXPR_BINARY_SUB: op = '-'; break;
7944 source_position_t const *const pos = &expr->base.source_position;
7945 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
7948 static bool semantic_shift(binary_expression_t *expression)
7950 expression_t *const left = expression->left;
7951 expression_t *const right = expression->right;
7952 type_t *const orig_type_left = left->base.type;
7953 type_t *const orig_type_right = right->base.type;
7954 type_t * type_left = skip_typeref(orig_type_left);
7955 type_t * type_right = skip_typeref(orig_type_right);
7957 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7958 /* TODO: improve error message */
7959 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7960 errorf(&expression->base.source_position,
7961 "operands of shift operation must have integer types");
7966 type_left = promote_integer(type_left);
7968 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
7969 source_position_t const *const pos = &right->base.source_position;
7970 long const count = fold_constant_to_int(right);
7972 warningf(WARN_OTHER, pos, "shift count must be non-negative");
7973 } else if ((unsigned long)count >=
7974 get_atomic_type_size(type_left->atomic.akind) * 8) {
7975 warningf(WARN_OTHER, pos, "shift count must be less than type width");
7979 type_right = promote_integer(type_right);
7980 expression->right = create_implicit_cast(right, type_right);
7985 static void semantic_shift_op(binary_expression_t *expression)
7987 expression_t *const left = expression->left;
7988 expression_t *const right = expression->right;
7990 if (!semantic_shift(expression))
7993 warn_addsub_in_shift(left);
7994 warn_addsub_in_shift(right);
7996 type_t *const orig_type_left = left->base.type;
7997 type_t * type_left = skip_typeref(orig_type_left);
7999 type_left = promote_integer(type_left);
8000 expression->left = create_implicit_cast(left, type_left);
8001 expression->base.type = type_left;
8004 static void semantic_add(binary_expression_t *expression)
8006 expression_t *const left = expression->left;
8007 expression_t *const right = expression->right;
8008 type_t *const orig_type_left = left->base.type;
8009 type_t *const orig_type_right = right->base.type;
8010 type_t *const type_left = skip_typeref(orig_type_left);
8011 type_t *const type_right = skip_typeref(orig_type_right);
8014 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8015 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8016 expression->left = create_implicit_cast(left, arithmetic_type);
8017 expression->right = create_implicit_cast(right, arithmetic_type);
8018 expression->base.type = arithmetic_type;
8019 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8020 check_pointer_arithmetic(&expression->base.source_position,
8021 type_left, orig_type_left);
8022 expression->base.type = type_left;
8023 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8024 check_pointer_arithmetic(&expression->base.source_position,
8025 type_right, orig_type_right);
8026 expression->base.type = type_right;
8027 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8028 errorf(&expression->base.source_position,
8029 "invalid operands to binary + ('%T', '%T')",
8030 orig_type_left, orig_type_right);
8034 static void semantic_sub(binary_expression_t *expression)
8036 expression_t *const left = expression->left;
8037 expression_t *const right = expression->right;
8038 type_t *const orig_type_left = left->base.type;
8039 type_t *const orig_type_right = right->base.type;
8040 type_t *const type_left = skip_typeref(orig_type_left);
8041 type_t *const type_right = skip_typeref(orig_type_right);
8042 source_position_t const *const pos = &expression->base.source_position;
8045 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8046 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8047 expression->left = create_implicit_cast(left, arithmetic_type);
8048 expression->right = create_implicit_cast(right, arithmetic_type);
8049 expression->base.type = arithmetic_type;
8050 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8051 check_pointer_arithmetic(&expression->base.source_position,
8052 type_left, orig_type_left);
8053 expression->base.type = type_left;
8054 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8055 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8056 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8057 if (!types_compatible(unqual_left, unqual_right)) {
8059 "subtracting pointers to incompatible types '%T' and '%T'",
8060 orig_type_left, orig_type_right);
8061 } else if (!is_type_object(unqual_left)) {
8062 if (!is_type_void(unqual_left)) {
8063 errorf(pos, "subtracting pointers to non-object types '%T'",
8066 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8069 expression->base.type = type_ptrdiff_t;
8070 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8071 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8072 orig_type_left, orig_type_right);
8076 static void warn_string_literal_address(expression_t const* expr)
8078 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8079 expr = expr->unary.value;
8080 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8082 expr = expr->unary.value;
8085 if (expr->kind == EXPR_STRING_LITERAL
8086 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8087 source_position_t const *const pos = &expr->base.source_position;
8088 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8092 static bool maybe_negative(expression_t const *const expr)
8094 switch (is_constant_expression(expr)) {
8095 case EXPR_CLASS_ERROR: return false;
8096 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8097 default: return true;
8101 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8103 warn_string_literal_address(expr);
8105 expression_t const* const ref = get_reference_address(expr);
8106 if (ref != NULL && is_null_pointer_constant(other)) {
8107 entity_t const *const ent = ref->reference.entity;
8108 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8111 if (!expr->base.parenthesized) {
8112 switch (expr->base.kind) {
8113 case EXPR_BINARY_LESS:
8114 case EXPR_BINARY_GREATER:
8115 case EXPR_BINARY_LESSEQUAL:
8116 case EXPR_BINARY_GREATEREQUAL:
8117 case EXPR_BINARY_NOTEQUAL:
8118 case EXPR_BINARY_EQUAL:
8119 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8128 * Check the semantics of comparison expressions.
8130 * @param expression The expression to check.
8132 static void semantic_comparison(binary_expression_t *expression)
8134 source_position_t const *const pos = &expression->base.source_position;
8135 expression_t *const left = expression->left;
8136 expression_t *const right = expression->right;
8138 warn_comparison(pos, left, right);
8139 warn_comparison(pos, right, left);
8141 type_t *orig_type_left = left->base.type;
8142 type_t *orig_type_right = right->base.type;
8143 type_t *type_left = skip_typeref(orig_type_left);
8144 type_t *type_right = skip_typeref(orig_type_right);
8146 /* TODO non-arithmetic types */
8147 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8148 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8150 /* test for signed vs unsigned compares */
8151 if (is_type_integer(arithmetic_type)) {
8152 bool const signed_left = is_type_signed(type_left);
8153 bool const signed_right = is_type_signed(type_right);
8154 if (signed_left != signed_right) {
8155 /* FIXME long long needs better const folding magic */
8156 /* TODO check whether constant value can be represented by other type */
8157 if ((signed_left && maybe_negative(left)) ||
8158 (signed_right && maybe_negative(right))) {
8159 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8164 expression->left = create_implicit_cast(left, arithmetic_type);
8165 expression->right = create_implicit_cast(right, arithmetic_type);
8166 expression->base.type = arithmetic_type;
8167 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8168 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8169 is_type_float(arithmetic_type)) {
8170 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8172 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8173 /* TODO check compatibility */
8174 } else if (is_type_pointer(type_left)) {
8175 expression->right = create_implicit_cast(right, type_left);
8176 } else if (is_type_pointer(type_right)) {
8177 expression->left = create_implicit_cast(left, type_right);
8178 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8179 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8181 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8185 * Checks if a compound type has constant fields.
8187 static bool has_const_fields(const compound_type_t *type)
8189 compound_t *compound = type->compound;
8190 entity_t *entry = compound->members.entities;
8192 for (; entry != NULL; entry = entry->base.next) {
8193 if (!is_declaration(entry))
8196 const type_t *decl_type = skip_typeref(entry->declaration.type);
8197 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8204 static bool is_valid_assignment_lhs(expression_t const* const left)
8206 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8207 type_t *const type_left = skip_typeref(orig_type_left);
8209 if (!is_lvalue(left)) {
8210 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8215 if (left->kind == EXPR_REFERENCE
8216 && left->reference.entity->kind == ENTITY_FUNCTION) {
8217 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8221 if (is_type_array(type_left)) {
8222 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8225 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8226 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8230 if (is_type_incomplete(type_left)) {
8231 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8232 left, orig_type_left);
8235 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8236 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8237 left, orig_type_left);
8244 static void semantic_arithmetic_assign(binary_expression_t *expression)
8246 expression_t *left = expression->left;
8247 expression_t *right = expression->right;
8248 type_t *orig_type_left = left->base.type;
8249 type_t *orig_type_right = right->base.type;
8251 if (!is_valid_assignment_lhs(left))
8254 type_t *type_left = skip_typeref(orig_type_left);
8255 type_t *type_right = skip_typeref(orig_type_right);
8257 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8258 /* TODO: improve error message */
8259 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8260 errorf(&expression->base.source_position,
8261 "operation needs arithmetic types");
8266 /* combined instructions are tricky. We can't create an implicit cast on
8267 * the left side, because we need the uncasted form for the store.
8268 * The ast2firm pass has to know that left_type must be right_type
8269 * for the arithmetic operation and create a cast by itself */
8270 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8271 expression->right = create_implicit_cast(right, arithmetic_type);
8272 expression->base.type = type_left;
8275 static void semantic_divmod_assign(binary_expression_t *expression)
8277 semantic_arithmetic_assign(expression);
8278 warn_div_by_zero(expression);
8281 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8283 expression_t *const left = expression->left;
8284 expression_t *const right = expression->right;
8285 type_t *const orig_type_left = left->base.type;
8286 type_t *const orig_type_right = right->base.type;
8287 type_t *const type_left = skip_typeref(orig_type_left);
8288 type_t *const type_right = skip_typeref(orig_type_right);
8290 if (!is_valid_assignment_lhs(left))
8293 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8294 /* combined instructions are tricky. We can't create an implicit cast on
8295 * the left side, because we need the uncasted form for the store.
8296 * The ast2firm pass has to know that left_type must be right_type
8297 * for the arithmetic operation and create a cast by itself */
8298 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8299 expression->right = create_implicit_cast(right, arithmetic_type);
8300 expression->base.type = type_left;
8301 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8302 check_pointer_arithmetic(&expression->base.source_position,
8303 type_left, orig_type_left);
8304 expression->base.type = type_left;
8305 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8306 errorf(&expression->base.source_position,
8307 "incompatible types '%T' and '%T' in assignment",
8308 orig_type_left, orig_type_right);
8312 static void semantic_integer_assign(binary_expression_t *expression)
8314 expression_t *left = expression->left;
8315 expression_t *right = expression->right;
8316 type_t *orig_type_left = left->base.type;
8317 type_t *orig_type_right = right->base.type;
8319 if (!is_valid_assignment_lhs(left))
8322 type_t *type_left = skip_typeref(orig_type_left);
8323 type_t *type_right = skip_typeref(orig_type_right);
8325 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8326 /* TODO: improve error message */
8327 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8328 errorf(&expression->base.source_position,
8329 "operation needs integer types");
8334 /* combined instructions are tricky. We can't create an implicit cast on
8335 * the left side, because we need the uncasted form for the store.
8336 * The ast2firm pass has to know that left_type must be right_type
8337 * for the arithmetic operation and create a cast by itself */
8338 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8339 expression->right = create_implicit_cast(right, arithmetic_type);
8340 expression->base.type = type_left;
8343 static void semantic_shift_assign(binary_expression_t *expression)
8345 expression_t *left = expression->left;
8347 if (!is_valid_assignment_lhs(left))
8350 if (!semantic_shift(expression))
8353 expression->base.type = skip_typeref(left->base.type);
8356 static void warn_logical_and_within_or(const expression_t *const expr)
8358 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8360 if (expr->base.parenthesized)
8362 source_position_t const *const pos = &expr->base.source_position;
8363 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8367 * Check the semantic restrictions of a logical expression.
8369 static void semantic_logical_op(binary_expression_t *expression)
8371 /* §6.5.13:2 Each of the operands shall have scalar type.
8372 * §6.5.14:2 Each of the operands shall have scalar type. */
8373 semantic_condition(expression->left, "left operand of logical operator");
8374 semantic_condition(expression->right, "right operand of logical operator");
8375 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8376 warn_logical_and_within_or(expression->left);
8377 warn_logical_and_within_or(expression->right);
8379 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8383 * Check the semantic restrictions of a binary assign expression.
8385 static void semantic_binexpr_assign(binary_expression_t *expression)
8387 expression_t *left = expression->left;
8388 type_t *orig_type_left = left->base.type;
8390 if (!is_valid_assignment_lhs(left))
8393 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8394 report_assign_error(error, orig_type_left, expression->right,
8395 "assignment", &left->base.source_position);
8396 expression->right = create_implicit_cast(expression->right, orig_type_left);
8397 expression->base.type = orig_type_left;
8401 * Determine if the outermost operation (or parts thereof) of the given
8402 * expression has no effect in order to generate a warning about this fact.
8403 * Therefore in some cases this only examines some of the operands of the
8404 * expression (see comments in the function and examples below).
8406 * f() + 23; // warning, because + has no effect
8407 * x || f(); // no warning, because x controls execution of f()
8408 * x ? y : f(); // warning, because y has no effect
8409 * (void)x; // no warning to be able to suppress the warning
8410 * This function can NOT be used for an "expression has definitely no effect"-
8412 static bool expression_has_effect(const expression_t *const expr)
8414 switch (expr->kind) {
8415 case EXPR_ERROR: return true; /* do NOT warn */
8416 case EXPR_REFERENCE: return false;
8417 case EXPR_ENUM_CONSTANT: return false;
8418 case EXPR_LABEL_ADDRESS: return false;
8420 /* suppress the warning for microsoft __noop operations */
8421 case EXPR_LITERAL_MS_NOOP: return true;
8422 case EXPR_LITERAL_BOOLEAN:
8423 case EXPR_LITERAL_CHARACTER:
8424 case EXPR_LITERAL_WIDE_CHARACTER:
8425 case EXPR_LITERAL_INTEGER:
8426 case EXPR_LITERAL_INTEGER_OCTAL:
8427 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8428 case EXPR_LITERAL_FLOATINGPOINT:
8429 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8430 case EXPR_STRING_LITERAL: return false;
8431 case EXPR_WIDE_STRING_LITERAL: return false;
8434 const call_expression_t *const call = &expr->call;
8435 if (call->function->kind != EXPR_REFERENCE)
8438 switch (call->function->reference.entity->function.btk) {
8439 /* FIXME: which builtins have no effect? */
8440 default: return true;
8444 /* Generate the warning if either the left or right hand side of a
8445 * conditional expression has no effect */
8446 case EXPR_CONDITIONAL: {
8447 conditional_expression_t const *const cond = &expr->conditional;
8448 expression_t const *const t = cond->true_expression;
8450 (t == NULL || expression_has_effect(t)) &&
8451 expression_has_effect(cond->false_expression);
8454 case EXPR_SELECT: return false;
8455 case EXPR_ARRAY_ACCESS: return false;
8456 case EXPR_SIZEOF: return false;
8457 case EXPR_CLASSIFY_TYPE: return false;
8458 case EXPR_ALIGNOF: return false;
8460 case EXPR_FUNCNAME: return false;
8461 case EXPR_BUILTIN_CONSTANT_P: return false;
8462 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8463 case EXPR_OFFSETOF: return false;
8464 case EXPR_VA_START: return true;
8465 case EXPR_VA_ARG: return true;
8466 case EXPR_VA_COPY: return true;
8467 case EXPR_STATEMENT: return true; // TODO
8468 case EXPR_COMPOUND_LITERAL: return false;
8470 case EXPR_UNARY_NEGATE: return false;
8471 case EXPR_UNARY_PLUS: return false;
8472 case EXPR_UNARY_BITWISE_NEGATE: return false;
8473 case EXPR_UNARY_NOT: return false;
8474 case EXPR_UNARY_DEREFERENCE: return false;
8475 case EXPR_UNARY_TAKE_ADDRESS: return false;
8476 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8477 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8478 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8479 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8481 /* Treat void casts as if they have an effect in order to being able to
8482 * suppress the warning */
8483 case EXPR_UNARY_CAST: {
8484 type_t *const type = skip_typeref(expr->base.type);
8485 return is_type_void(type);
8488 case EXPR_UNARY_ASSUME: return true;
8489 case EXPR_UNARY_DELETE: return true;
8490 case EXPR_UNARY_DELETE_ARRAY: return true;
8491 case EXPR_UNARY_THROW: return true;
8493 case EXPR_BINARY_ADD: return false;
8494 case EXPR_BINARY_SUB: return false;
8495 case EXPR_BINARY_MUL: return false;
8496 case EXPR_BINARY_DIV: return false;
8497 case EXPR_BINARY_MOD: return false;
8498 case EXPR_BINARY_EQUAL: return false;
8499 case EXPR_BINARY_NOTEQUAL: return false;
8500 case EXPR_BINARY_LESS: return false;
8501 case EXPR_BINARY_LESSEQUAL: return false;
8502 case EXPR_BINARY_GREATER: return false;
8503 case EXPR_BINARY_GREATEREQUAL: return false;
8504 case EXPR_BINARY_BITWISE_AND: return false;
8505 case EXPR_BINARY_BITWISE_OR: return false;
8506 case EXPR_BINARY_BITWISE_XOR: return false;
8507 case EXPR_BINARY_SHIFTLEFT: return false;
8508 case EXPR_BINARY_SHIFTRIGHT: return false;
8509 case EXPR_BINARY_ASSIGN: return true;
8510 case EXPR_BINARY_MUL_ASSIGN: return true;
8511 case EXPR_BINARY_DIV_ASSIGN: return true;
8512 case EXPR_BINARY_MOD_ASSIGN: return true;
8513 case EXPR_BINARY_ADD_ASSIGN: return true;
8514 case EXPR_BINARY_SUB_ASSIGN: return true;
8515 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8516 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8517 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8518 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8519 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8521 /* Only examine the right hand side of && and ||, because the left hand
8522 * side already has the effect of controlling the execution of the right
8524 case EXPR_BINARY_LOGICAL_AND:
8525 case EXPR_BINARY_LOGICAL_OR:
8526 /* Only examine the right hand side of a comma expression, because the left
8527 * hand side has a separate warning */
8528 case EXPR_BINARY_COMMA:
8529 return expression_has_effect(expr->binary.right);
8531 case EXPR_BINARY_ISGREATER: return false;
8532 case EXPR_BINARY_ISGREATEREQUAL: return false;
8533 case EXPR_BINARY_ISLESS: return false;
8534 case EXPR_BINARY_ISLESSEQUAL: return false;
8535 case EXPR_BINARY_ISLESSGREATER: return false;
8536 case EXPR_BINARY_ISUNORDERED: return false;
8539 internal_errorf(HERE, "unexpected expression");
8542 static void semantic_comma(binary_expression_t *expression)
8544 const expression_t *const left = expression->left;
8545 if (!expression_has_effect(left)) {
8546 source_position_t const *const pos = &left->base.source_position;
8547 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8549 expression->base.type = expression->right->base.type;
8553 * @param prec_r precedence of the right operand
8555 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8556 static expression_t *parse_##binexpression_type(expression_t *left) \
8558 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8559 binexpr->binary.left = left; \
8562 expression_t *right = parse_subexpression(prec_r); \
8564 binexpr->binary.right = right; \
8565 sfunc(&binexpr->binary); \
8570 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8571 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8572 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8573 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8574 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8575 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8576 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8577 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8578 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8579 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8580 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8581 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8582 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8583 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8584 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8585 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8586 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8587 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8588 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8589 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8590 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8591 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8592 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8593 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8594 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8595 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8596 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8597 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8598 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8599 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8602 static expression_t *parse_subexpression(precedence_t precedence)
8604 expression_parser_function_t *parser
8605 = &expression_parsers[token.kind];
8608 if (parser->parser != NULL) {
8609 left = parser->parser();
8611 left = parse_primary_expression();
8613 assert(left != NULL);
8616 parser = &expression_parsers[token.kind];
8617 if (parser->infix_parser == NULL)
8619 if (parser->infix_precedence < precedence)
8622 left = parser->infix_parser(left);
8624 assert(left != NULL);
8631 * Parse an expression.
8633 static expression_t *parse_expression(void)
8635 return parse_subexpression(PREC_EXPRESSION);
8639 * Register a parser for a prefix-like operator.
8641 * @param parser the parser function
8642 * @param token_kind the token type of the prefix token
8644 static void register_expression_parser(parse_expression_function parser,
8647 expression_parser_function_t *entry = &expression_parsers[token_kind];
8649 if (entry->parser != NULL) {
8650 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8651 panic("trying to register multiple expression parsers for a token");
8653 entry->parser = parser;
8657 * Register a parser for an infix operator with given precedence.
8659 * @param parser the parser function
8660 * @param token_kind the token type of the infix operator
8661 * @param precedence the precedence of the operator
8663 static void register_infix_parser(parse_expression_infix_function parser,
8664 int token_kind, precedence_t precedence)
8666 expression_parser_function_t *entry = &expression_parsers[token_kind];
8668 if (entry->infix_parser != NULL) {
8669 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8670 panic("trying to register multiple infix expression parsers for a "
8673 entry->infix_parser = parser;
8674 entry->infix_precedence = precedence;
8678 * Initialize the expression parsers.
8680 static void init_expression_parsers(void)
8682 memset(&expression_parsers, 0, sizeof(expression_parsers));
8684 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8685 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8686 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8687 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8688 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8689 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8690 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8691 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8692 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8693 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8694 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8695 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8696 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8697 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8698 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8699 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8700 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8701 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8702 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8703 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8704 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8705 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8706 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8707 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8708 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8709 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8710 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8711 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8712 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8713 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8714 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8715 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8716 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8717 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8718 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8719 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8720 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8722 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8723 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8724 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8725 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8726 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8727 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8728 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8729 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8730 register_expression_parser(parse_sizeof, T_sizeof);
8731 register_expression_parser(parse_alignof, T___alignof__);
8732 register_expression_parser(parse_extension, T___extension__);
8733 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8734 register_expression_parser(parse_delete, T_delete);
8735 register_expression_parser(parse_throw, T_throw);
8739 * Parse a asm statement arguments specification.
8741 static asm_argument_t *parse_asm_arguments(bool is_out)
8743 asm_argument_t *result = NULL;
8744 asm_argument_t **anchor = &result;
8746 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8747 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8750 add_anchor_token(']');
8751 argument->symbol = expect_identifier("while parsing asm argument", NULL);
8752 rem_anchor_token(']');
8754 if (!argument->symbol)
8758 argument->constraints = parse_string_literals();
8760 add_anchor_token(')');
8761 expression_t *expression = parse_expression();
8762 rem_anchor_token(')');
8764 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8765 * change size or type representation (e.g. int -> long is ok, but
8766 * int -> float is not) */
8767 if (expression->kind == EXPR_UNARY_CAST) {
8768 type_t *const type = expression->base.type;
8769 type_kind_t const kind = type->kind;
8770 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8773 if (kind == TYPE_ATOMIC) {
8774 atomic_type_kind_t const akind = type->atomic.akind;
8775 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8776 size = get_atomic_type_size(akind);
8778 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8779 size = get_type_size(type_void_ptr);
8783 expression_t *const value = expression->unary.value;
8784 type_t *const value_type = value->base.type;
8785 type_kind_t const value_kind = value_type->kind;
8787 unsigned value_flags;
8788 unsigned value_size;
8789 if (value_kind == TYPE_ATOMIC) {
8790 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8791 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8792 value_size = get_atomic_type_size(value_akind);
8793 } else if (value_kind == TYPE_POINTER) {
8794 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8795 value_size = get_type_size(type_void_ptr);
8800 if (value_flags != flags || value_size != size)
8804 } while (expression->kind == EXPR_UNARY_CAST);
8808 if (!is_lvalue(expression)) {
8809 errorf(&expression->base.source_position,
8810 "asm output argument is not an lvalue");
8813 if (argument->constraints.begin[0] == '=')
8814 determine_lhs_ent(expression, NULL);
8816 mark_vars_read(expression, NULL);
8818 mark_vars_read(expression, NULL);
8820 argument->expression = expression;
8823 set_address_taken(expression, true);
8826 anchor = &argument->next;
8836 * Parse a asm statement clobber specification.
8838 static asm_clobber_t *parse_asm_clobbers(void)
8840 asm_clobber_t *result = NULL;
8841 asm_clobber_t **anchor = &result;
8843 while (token.kind == T_STRING_LITERAL) {
8844 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8845 clobber->clobber = parse_string_literals();
8848 anchor = &clobber->next;
8858 * Parse an asm statement.
8860 static statement_t *parse_asm_statement(void)
8862 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8863 asm_statement_t *asm_statement = &statement->asms;
8867 if (next_if(T_volatile))
8868 asm_statement->is_volatile = true;
8871 add_anchor_token(')');
8872 if (token.kind != T_STRING_LITERAL) {
8873 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8876 asm_statement->asm_text = parse_string_literals();
8878 add_anchor_token(':');
8879 if (!next_if(':')) {
8880 rem_anchor_token(':');
8884 asm_statement->outputs = parse_asm_arguments(true);
8885 if (!next_if(':')) {
8886 rem_anchor_token(':');
8890 asm_statement->inputs = parse_asm_arguments(false);
8891 if (!next_if(':')) {
8892 rem_anchor_token(':');
8895 rem_anchor_token(':');
8897 asm_statement->clobbers = parse_asm_clobbers();
8900 rem_anchor_token(')');
8904 if (asm_statement->outputs == NULL) {
8905 /* GCC: An 'asm' instruction without any output operands will be treated
8906 * identically to a volatile 'asm' instruction. */
8907 asm_statement->is_volatile = true;
8913 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
8915 statement_t *inner_stmt;
8916 switch (token.kind) {
8918 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
8919 inner_stmt = create_error_statement();
8923 if (label->kind == STATEMENT_LABEL) {
8924 /* Eat an empty statement here, to avoid the warning about an empty
8925 * statement after a label. label:; is commonly used to have a label
8926 * before a closing brace. */
8927 inner_stmt = create_empty_statement();
8934 inner_stmt = parse_statement();
8935 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
8936 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
8937 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
8938 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
8946 * Parse a case statement.
8948 static statement_t *parse_case_statement(void)
8950 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
8951 source_position_t *const pos = &statement->base.source_position;
8954 add_anchor_token(':');
8956 expression_t *expression = parse_expression();
8957 type_t *expression_type = expression->base.type;
8958 type_t *skipped = skip_typeref(expression_type);
8959 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8960 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8961 expression, expression_type);
8964 type_t *type = expression_type;
8965 if (current_switch != NULL) {
8966 type_t *switch_type = current_switch->expression->base.type;
8967 if (is_type_valid(switch_type)) {
8968 expression = create_implicit_cast(expression, switch_type);
8972 statement->case_label.expression = expression;
8973 expression_classification_t const expr_class = is_constant_expression(expression);
8974 if (expr_class != EXPR_CLASS_CONSTANT) {
8975 if (expr_class != EXPR_CLASS_ERROR) {
8976 errorf(pos, "case label does not reduce to an integer constant");
8978 statement->case_label.is_bad = true;
8980 long const val = fold_constant_to_int(expression);
8981 statement->case_label.first_case = val;
8982 statement->case_label.last_case = val;
8986 if (next_if(T_DOTDOTDOT)) {
8987 expression_t *end_range = parse_expression();
8988 expression_type = expression->base.type;
8989 skipped = skip_typeref(expression_type);
8990 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
8991 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
8992 expression, expression_type);
8995 end_range = create_implicit_cast(end_range, type);
8996 statement->case_label.end_range = end_range;
8997 expression_classification_t const end_class = is_constant_expression(end_range);
8998 if (end_class != EXPR_CLASS_CONSTANT) {
8999 if (end_class != EXPR_CLASS_ERROR) {
9000 errorf(pos, "case range does not reduce to an integer constant");
9002 statement->case_label.is_bad = true;
9004 long const val = fold_constant_to_int(end_range);
9005 statement->case_label.last_case = val;
9007 if (val < statement->case_label.first_case) {
9008 statement->case_label.is_empty_range = true;
9009 warningf(WARN_OTHER, pos, "empty range specified");
9015 PUSH_PARENT(statement);
9017 rem_anchor_token(':');
9020 if (current_switch != NULL) {
9021 if (! statement->case_label.is_bad) {
9022 /* Check for duplicate case values */
9023 case_label_statement_t *c = &statement->case_label;
9024 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9025 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9028 if (c->last_case < l->first_case || c->first_case > l->last_case)
9031 errorf(pos, "duplicate case value (previously used %P)",
9032 &l->base.source_position);
9036 /* link all cases into the switch statement */
9037 if (current_switch->last_case == NULL) {
9038 current_switch->first_case = &statement->case_label;
9040 current_switch->last_case->next = &statement->case_label;
9042 current_switch->last_case = &statement->case_label;
9044 errorf(pos, "case label not within a switch statement");
9047 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9054 * Parse a default statement.
9056 static statement_t *parse_default_statement(void)
9058 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9062 PUSH_PARENT(statement);
9066 if (current_switch != NULL) {
9067 const case_label_statement_t *def_label = current_switch->default_label;
9068 if (def_label != NULL) {
9069 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9071 current_switch->default_label = &statement->case_label;
9073 /* link all cases into the switch statement */
9074 if (current_switch->last_case == NULL) {
9075 current_switch->first_case = &statement->case_label;
9077 current_switch->last_case->next = &statement->case_label;
9079 current_switch->last_case = &statement->case_label;
9082 errorf(&statement->base.source_position,
9083 "'default' label not within a switch statement");
9086 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9093 * Parse a label statement.
9095 static statement_t *parse_label_statement(void)
9097 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9098 label_t *const label = get_label();
9099 statement->label.label = label;
9101 PUSH_PARENT(statement);
9103 /* if statement is already set then the label is defined twice,
9104 * otherwise it was just mentioned in a goto/local label declaration so far
9106 source_position_t const* const pos = &statement->base.source_position;
9107 if (label->statement != NULL) {
9108 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9110 label->base.source_position = *pos;
9111 label->statement = statement;
9116 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9117 parse_attributes(NULL); // TODO process attributes
9120 statement->label.statement = parse_label_inner_statement(statement, "label");
9122 /* remember the labels in a list for later checking */
9123 *label_anchor = &statement->label;
9124 label_anchor = &statement->label.next;
9130 static statement_t *parse_inner_statement(void)
9132 statement_t *const stmt = parse_statement();
9133 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9134 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9135 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9136 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9142 * Parse an expression in parentheses and mark its variables as read.
9144 static expression_t *parse_condition(void)
9147 add_anchor_token(')');
9148 expression_t *const expr = parse_expression();
9149 mark_vars_read(expr, NULL);
9150 rem_anchor_token(')');
9156 * Parse an if statement.
9158 static statement_t *parse_if(void)
9160 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9164 PUSH_PARENT(statement);
9165 PUSH_SCOPE_STATEMENT(&statement->ifs.scope);
9167 add_anchor_token(T_else);
9169 expression_t *const expr = parse_condition();
9170 statement->ifs.condition = expr;
9171 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9173 semantic_condition(expr, "condition of 'if'-statment");
9175 statement_t *const true_stmt = parse_inner_statement();
9176 statement->ifs.true_statement = true_stmt;
9177 rem_anchor_token(T_else);
9179 if (true_stmt->kind == STATEMENT_EMPTY) {
9180 warningf(WARN_EMPTY_BODY, HERE,
9181 "suggest braces around empty body in an ‘if’ statement");
9184 if (next_if(T_else)) {
9185 statement->ifs.false_statement = parse_inner_statement();
9187 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9188 warningf(WARN_EMPTY_BODY, HERE,
9189 "suggest braces around empty body in an ‘if’ statement");
9191 } else if (true_stmt->kind == STATEMENT_IF &&
9192 true_stmt->ifs.false_statement != NULL) {
9193 source_position_t const *const pos = &true_stmt->base.source_position;
9194 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9203 * Check that all enums are handled in a switch.
9205 * @param statement the switch statement to check
9207 static void check_enum_cases(const switch_statement_t *statement)
9209 if (!is_warn_on(WARN_SWITCH_ENUM))
9211 const type_t *type = skip_typeref(statement->expression->base.type);
9212 if (! is_type_enum(type))
9214 const enum_type_t *enumt = &type->enumt;
9216 /* if we have a default, no warnings */
9217 if (statement->default_label != NULL)
9220 /* FIXME: calculation of value should be done while parsing */
9221 /* TODO: quadratic algorithm here. Change to an n log n one */
9222 long last_value = -1;
9223 const entity_t *entry = enumt->enume->base.next;
9224 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9225 entry = entry->base.next) {
9226 const expression_t *expression = entry->enum_value.value;
9227 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9229 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9230 if (l->expression == NULL)
9232 if (l->first_case <= value && value <= l->last_case) {
9238 source_position_t const *const pos = &statement->base.source_position;
9239 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9246 * Parse a switch statement.
9248 static statement_t *parse_switch(void)
9250 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9254 PUSH_PARENT(statement);
9255 PUSH_SCOPE_STATEMENT(&statement->switchs.scope);
9257 expression_t *const expr = parse_condition();
9258 type_t * type = skip_typeref(expr->base.type);
9259 if (is_type_integer(type)) {
9260 type = promote_integer(type);
9261 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9262 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9264 } else if (is_type_valid(type)) {
9265 errorf(&expr->base.source_position,
9266 "switch quantity is not an integer, but '%T'", type);
9267 type = type_error_type;
9269 statement->switchs.expression = create_implicit_cast(expr, type);
9271 switch_statement_t *rem = current_switch;
9272 current_switch = &statement->switchs;
9273 statement->switchs.body = parse_inner_statement();
9274 current_switch = rem;
9276 if (statement->switchs.default_label == NULL) {
9277 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9279 check_enum_cases(&statement->switchs);
9286 static statement_t *parse_loop_body(statement_t *const loop)
9288 statement_t *const rem = current_loop;
9289 current_loop = loop;
9291 statement_t *const body = parse_inner_statement();
9298 * Parse a while statement.
9300 static statement_t *parse_while(void)
9302 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9306 PUSH_PARENT(statement);
9307 PUSH_SCOPE_STATEMENT(&statement->whiles.scope);
9309 expression_t *const cond = parse_condition();
9310 statement->whiles.condition = cond;
9311 /* §6.8.5:2 The controlling expression of an iteration statement shall
9312 * have scalar type. */
9313 semantic_condition(cond, "condition of 'while'-statement");
9315 statement->whiles.body = parse_loop_body(statement);
9323 * Parse a do statement.
9325 static statement_t *parse_do(void)
9327 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9331 PUSH_PARENT(statement);
9332 PUSH_SCOPE_STATEMENT(&statement->do_while.scope);
9334 add_anchor_token(T_while);
9335 statement->do_while.body = parse_loop_body(statement);
9336 rem_anchor_token(T_while);
9339 expression_t *const cond = parse_condition();
9340 statement->do_while.condition = cond;
9341 /* §6.8.5:2 The controlling expression of an iteration statement shall
9342 * have scalar type. */
9343 semantic_condition(cond, "condition of 'do-while'-statement");
9352 * Parse a for statement.
9354 static statement_t *parse_for(void)
9356 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9360 PUSH_PARENT(statement);
9361 PUSH_SCOPE_STATEMENT(&statement->fors.scope);
9364 add_anchor_token(')');
9369 } else if (is_declaration_specifier(&token)) {
9370 parse_declaration(record_entity, DECL_FLAGS_NONE);
9372 add_anchor_token(';');
9373 expression_t *const init = parse_expression();
9374 statement->fors.initialisation = init;
9375 mark_vars_read(init, ENT_ANY);
9376 if (!expression_has_effect(init)) {
9377 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9379 rem_anchor_token(';');
9385 if (token.kind != ';') {
9386 add_anchor_token(';');
9387 expression_t *const cond = parse_expression();
9388 statement->fors.condition = cond;
9389 /* §6.8.5:2 The controlling expression of an iteration statement
9390 * shall have scalar type. */
9391 semantic_condition(cond, "condition of 'for'-statement");
9392 mark_vars_read(cond, NULL);
9393 rem_anchor_token(';');
9396 if (token.kind != ')') {
9397 expression_t *const step = parse_expression();
9398 statement->fors.step = step;
9399 mark_vars_read(step, ENT_ANY);
9400 if (!expression_has_effect(step)) {
9401 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9404 rem_anchor_token(')');
9406 statement->fors.body = parse_loop_body(statement);
9414 * Parse a goto statement.
9416 static statement_t *parse_goto(void)
9418 statement_t *statement;
9419 if (GNU_MODE && look_ahead(1)->kind == '*') {
9420 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9424 expression_t *expression = parse_expression();
9425 mark_vars_read(expression, NULL);
9427 /* Argh: although documentation says the expression must be of type void*,
9428 * gcc accepts anything that can be casted into void* without error */
9429 type_t *type = expression->base.type;
9431 if (type != type_error_type) {
9432 if (!is_type_pointer(type) && !is_type_integer(type)) {
9433 errorf(&expression->base.source_position,
9434 "cannot convert to a pointer type");
9435 } else if (type != type_void_ptr) {
9436 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9438 expression = create_implicit_cast(expression, type_void_ptr);
9441 statement->computed_goto.expression = expression;
9443 statement = allocate_statement_zero(STATEMENT_GOTO);
9445 if (token.kind == T_IDENTIFIER) {
9446 label_t *const label = get_label();
9448 statement->gotos.label = label;
9450 /* remember the goto's in a list for later checking */
9451 *goto_anchor = &statement->gotos;
9452 goto_anchor = &statement->gotos.next;
9455 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9457 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9459 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9468 * Parse a continue statement.
9470 static statement_t *parse_continue(void)
9472 if (current_loop == NULL) {
9473 errorf(HERE, "continue statement not within loop");
9476 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9484 * Parse a break statement.
9486 static statement_t *parse_break(void)
9488 if (current_switch == NULL && current_loop == NULL) {
9489 errorf(HERE, "break statement not within loop or switch");
9492 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9500 * Parse a __leave statement.
9502 static statement_t *parse_leave_statement(void)
9504 if (current_try == NULL) {
9505 errorf(HERE, "__leave statement not within __try");
9508 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9516 * Check if a given entity represents a local variable.
9518 static bool is_local_variable(const entity_t *entity)
9520 if (entity->kind != ENTITY_VARIABLE)
9523 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9524 case STORAGE_CLASS_AUTO:
9525 case STORAGE_CLASS_REGISTER: {
9526 const type_t *type = skip_typeref(entity->declaration.type);
9527 if (is_type_function(type)) {
9539 * Check if a given expression represents a local variable.
9541 static bool expression_is_local_variable(const expression_t *expression)
9543 if (expression->base.kind != EXPR_REFERENCE) {
9546 const entity_t *entity = expression->reference.entity;
9547 return is_local_variable(entity);
9551 * Check if a given expression represents a local variable and
9552 * return its declaration then, else return NULL.
9554 entity_t *expression_is_variable(const expression_t *expression)
9556 if (expression->base.kind != EXPR_REFERENCE) {
9559 entity_t *entity = expression->reference.entity;
9560 if (entity->kind != ENTITY_VARIABLE)
9566 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9568 if (c_mode & _CXX || strict_mode) {
9571 warningf(WARN_OTHER, pos, msg);
9576 * Parse a return statement.
9578 static statement_t *parse_return(void)
9580 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9583 expression_t *return_value = NULL;
9584 if (token.kind != ';') {
9585 return_value = parse_expression();
9586 mark_vars_read(return_value, NULL);
9589 const type_t *const func_type = skip_typeref(current_function->base.type);
9590 assert(is_type_function(func_type));
9591 type_t *const return_type = skip_typeref(func_type->function.return_type);
9593 source_position_t const *const pos = &statement->base.source_position;
9594 if (return_value != NULL) {
9595 type_t *return_value_type = skip_typeref(return_value->base.type);
9597 if (is_type_void(return_type)) {
9598 if (!is_type_void(return_value_type)) {
9599 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9600 /* Only warn in C mode, because GCC does the same */
9601 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9602 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9603 /* Only warn in C mode, because GCC does the same */
9604 err_or_warn(pos, "'return' with expression in function returning 'void'");
9607 assign_error_t error = semantic_assign(return_type, return_value);
9608 report_assign_error(error, return_type, return_value, "'return'",
9611 return_value = create_implicit_cast(return_value, return_type);
9612 /* check for returning address of a local var */
9613 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9614 const expression_t *expression = return_value->unary.value;
9615 if (expression_is_local_variable(expression)) {
9616 warningf(WARN_OTHER, pos, "function returns address of local variable");
9619 } else if (!is_type_void(return_type)) {
9620 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9621 err_or_warn(pos, "'return' without value, in function returning non-void");
9623 statement->returns.value = return_value;
9630 * Parse a declaration statement.
9632 static statement_t *parse_declaration_statement(void)
9634 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9636 entity_t *before = current_scope->last_entity;
9638 parse_external_declaration();
9640 parse_declaration(record_entity, DECL_FLAGS_NONE);
9643 declaration_statement_t *const decl = &statement->declaration;
9644 entity_t *const begin =
9645 before != NULL ? before->base.next : current_scope->entities;
9646 decl->declarations_begin = begin;
9647 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9653 * Parse an expression statement, ie. expr ';'.
9655 static statement_t *parse_expression_statement(void)
9657 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9659 expression_t *const expr = parse_expression();
9660 statement->expression.expression = expr;
9661 mark_vars_read(expr, ENT_ANY);
9668 * Parse a microsoft __try { } __finally { } or
9669 * __try{ } __except() { }
9671 static statement_t *parse_ms_try_statment(void)
9673 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9676 PUSH_PARENT(statement);
9678 ms_try_statement_t *rem = current_try;
9679 current_try = &statement->ms_try;
9680 statement->ms_try.try_statement = parse_compound_statement(false);
9685 if (next_if(T___except)) {
9686 expression_t *const expr = parse_condition();
9687 type_t * type = skip_typeref(expr->base.type);
9688 if (is_type_integer(type)) {
9689 type = promote_integer(type);
9690 } else if (is_type_valid(type)) {
9691 errorf(&expr->base.source_position,
9692 "__expect expression is not an integer, but '%T'", type);
9693 type = type_error_type;
9695 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9696 } else if (!next_if(T__finally)) {
9697 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9699 statement->ms_try.final_statement = parse_compound_statement(false);
9703 static statement_t *parse_empty_statement(void)
9705 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9706 statement_t *const statement = create_empty_statement();
9711 static statement_t *parse_local_label_declaration(void)
9713 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9717 entity_t *begin = NULL;
9718 entity_t *end = NULL;
9719 entity_t **anchor = &begin;
9721 source_position_t pos;
9722 symbol_t *const symbol = expect_identifier("while parsing local label declaration", &pos);
9726 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9727 if (entity != NULL && entity->base.parent_scope == current_scope) {
9728 source_position_t const *const ppos = &entity->base.source_position;
9729 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9731 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, &pos);
9732 entity->base.parent_scope = current_scope;
9735 anchor = &entity->base.next;
9738 environment_push(entity);
9740 } while (next_if(','));
9743 statement->declaration.declarations_begin = begin;
9744 statement->declaration.declarations_end = end;
9748 static void parse_namespace_definition(void)
9752 entity_t *entity = NULL;
9753 symbol_t *symbol = NULL;
9755 if (token.kind == T_IDENTIFIER) {
9756 symbol = token.identifier.symbol;
9759 entity = get_entity(symbol, NAMESPACE_NORMAL);
9761 && entity->kind != ENTITY_NAMESPACE
9762 && entity->base.parent_scope == current_scope) {
9763 if (is_entity_valid(entity)) {
9764 error_redefined_as_different_kind(&token.base.source_position,
9765 entity, ENTITY_NAMESPACE);
9771 if (entity == NULL) {
9772 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9773 entity->base.parent_scope = current_scope;
9776 if (token.kind == '=') {
9777 /* TODO: parse namespace alias */
9778 panic("namespace alias definition not supported yet");
9781 environment_push(entity);
9782 append_entity(current_scope, entity);
9784 PUSH_SCOPE(&entity->namespacee.members);
9785 PUSH_CURRENT_ENTITY(entity);
9787 add_anchor_token('}');
9790 rem_anchor_token('}');
9793 POP_CURRENT_ENTITY();
9798 * Parse a statement.
9799 * There's also parse_statement() which additionally checks for
9800 * "statement has no effect" warnings
9802 static statement_t *intern_parse_statement(void)
9804 /* declaration or statement */
9805 statement_t *statement;
9806 switch (token.kind) {
9807 case T_IDENTIFIER: {
9808 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9809 if (la1_type == ':') {
9810 statement = parse_label_statement();
9811 } else if (is_typedef_symbol(token.identifier.symbol)) {
9812 statement = parse_declaration_statement();
9814 /* it's an identifier, the grammar says this must be an
9815 * expression statement. However it is common that users mistype
9816 * declaration types, so we guess a bit here to improve robustness
9817 * for incorrect programs */
9821 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9823 statement = parse_expression_statement();
9827 statement = parse_declaration_statement();
9835 case T___extension__: {
9836 /* This can be a prefix to a declaration or an expression statement.
9837 * We simply eat it now and parse the rest with tail recursion. */
9839 statement = intern_parse_statement();
9845 statement = parse_declaration_statement();
9849 statement = parse_local_label_declaration();
9852 case ';': statement = parse_empty_statement(); break;
9853 case '{': statement = parse_compound_statement(false); break;
9854 case T___leave: statement = parse_leave_statement(); break;
9855 case T___try: statement = parse_ms_try_statment(); break;
9856 case T_asm: statement = parse_asm_statement(); break;
9857 case T_break: statement = parse_break(); break;
9858 case T_case: statement = parse_case_statement(); break;
9859 case T_continue: statement = parse_continue(); break;
9860 case T_default: statement = parse_default_statement(); break;
9861 case T_do: statement = parse_do(); break;
9862 case T_for: statement = parse_for(); break;
9863 case T_goto: statement = parse_goto(); break;
9864 case T_if: statement = parse_if(); break;
9865 case T_return: statement = parse_return(); break;
9866 case T_switch: statement = parse_switch(); break;
9867 case T_while: statement = parse_while(); break;
9870 statement = parse_expression_statement();
9874 errorf(HERE, "unexpected token %K while parsing statement", &token);
9875 statement = create_error_statement();
9884 * parse a statement and emits "statement has no effect" warning if needed
9885 * (This is really a wrapper around intern_parse_statement with check for 1
9886 * single warning. It is needed, because for statement expressions we have
9887 * to avoid the warning on the last statement)
9889 static statement_t *parse_statement(void)
9891 statement_t *statement = intern_parse_statement();
9893 if (statement->kind == STATEMENT_EXPRESSION) {
9894 expression_t *expression = statement->expression.expression;
9895 if (!expression_has_effect(expression)) {
9896 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
9904 * Parse a compound statement.
9906 static statement_t *parse_compound_statement(bool inside_expression_statement)
9908 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
9910 PUSH_PARENT(statement);
9911 PUSH_SCOPE(&statement->compound.scope);
9914 add_anchor_token('}');
9915 /* tokens, which can start a statement */
9916 /* TODO MS, __builtin_FOO */
9917 add_anchor_token('!');
9918 add_anchor_token('&');
9919 add_anchor_token('(');
9920 add_anchor_token('*');
9921 add_anchor_token('+');
9922 add_anchor_token('-');
9923 add_anchor_token(';');
9924 add_anchor_token('{');
9925 add_anchor_token('~');
9926 add_anchor_token(T_CHARACTER_CONSTANT);
9927 add_anchor_token(T_COLONCOLON);
9928 add_anchor_token(T_FLOATINGPOINT);
9929 add_anchor_token(T_IDENTIFIER);
9930 add_anchor_token(T_INTEGER);
9931 add_anchor_token(T_MINUSMINUS);
9932 add_anchor_token(T_PLUSPLUS);
9933 add_anchor_token(T_STRING_LITERAL);
9934 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
9935 add_anchor_token(T_WIDE_STRING_LITERAL);
9936 add_anchor_token(T__Bool);
9937 add_anchor_token(T__Complex);
9938 add_anchor_token(T__Imaginary);
9939 add_anchor_token(T___FUNCTION__);
9940 add_anchor_token(T___PRETTY_FUNCTION__);
9941 add_anchor_token(T___alignof__);
9942 add_anchor_token(T___attribute__);
9943 add_anchor_token(T___builtin_va_start);
9944 add_anchor_token(T___extension__);
9945 add_anchor_token(T___func__);
9946 add_anchor_token(T___imag__);
9947 add_anchor_token(T___label__);
9948 add_anchor_token(T___real__);
9949 add_anchor_token(T___thread);
9950 add_anchor_token(T_asm);
9951 add_anchor_token(T_auto);
9952 add_anchor_token(T_bool);
9953 add_anchor_token(T_break);
9954 add_anchor_token(T_case);
9955 add_anchor_token(T_char);
9956 add_anchor_token(T_class);
9957 add_anchor_token(T_const);
9958 add_anchor_token(T_const_cast);
9959 add_anchor_token(T_continue);
9960 add_anchor_token(T_default);
9961 add_anchor_token(T_delete);
9962 add_anchor_token(T_double);
9963 add_anchor_token(T_do);
9964 add_anchor_token(T_dynamic_cast);
9965 add_anchor_token(T_enum);
9966 add_anchor_token(T_extern);
9967 add_anchor_token(T_false);
9968 add_anchor_token(T_float);
9969 add_anchor_token(T_for);
9970 add_anchor_token(T_goto);
9971 add_anchor_token(T_if);
9972 add_anchor_token(T_inline);
9973 add_anchor_token(T_int);
9974 add_anchor_token(T_long);
9975 add_anchor_token(T_new);
9976 add_anchor_token(T_operator);
9977 add_anchor_token(T_register);
9978 add_anchor_token(T_reinterpret_cast);
9979 add_anchor_token(T_restrict);
9980 add_anchor_token(T_return);
9981 add_anchor_token(T_short);
9982 add_anchor_token(T_signed);
9983 add_anchor_token(T_sizeof);
9984 add_anchor_token(T_static);
9985 add_anchor_token(T_static_cast);
9986 add_anchor_token(T_struct);
9987 add_anchor_token(T_switch);
9988 add_anchor_token(T_template);
9989 add_anchor_token(T_this);
9990 add_anchor_token(T_throw);
9991 add_anchor_token(T_true);
9992 add_anchor_token(T_try);
9993 add_anchor_token(T_typedef);
9994 add_anchor_token(T_typeid);
9995 add_anchor_token(T_typename);
9996 add_anchor_token(T_typeof);
9997 add_anchor_token(T_union);
9998 add_anchor_token(T_unsigned);
9999 add_anchor_token(T_using);
10000 add_anchor_token(T_void);
10001 add_anchor_token(T_volatile);
10002 add_anchor_token(T_wchar_t);
10003 add_anchor_token(T_while);
10005 statement_t **anchor = &statement->compound.statements;
10006 bool only_decls_so_far = true;
10007 while (token.kind != '}' && token.kind != T_EOF) {
10008 statement_t *sub_statement = intern_parse_statement();
10009 if (sub_statement->kind == STATEMENT_ERROR) {
10013 if (sub_statement->kind != STATEMENT_DECLARATION) {
10014 only_decls_so_far = false;
10015 } else if (!only_decls_so_far) {
10016 source_position_t const *const pos = &sub_statement->base.source_position;
10017 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10020 *anchor = sub_statement;
10021 anchor = &sub_statement->base.next;
10025 /* look over all statements again to produce no effect warnings */
10026 if (is_warn_on(WARN_UNUSED_VALUE)) {
10027 statement_t *sub_statement = statement->compound.statements;
10028 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10029 if (sub_statement->kind != STATEMENT_EXPRESSION)
10031 /* don't emit a warning for the last expression in an expression
10032 * statement as it has always an effect */
10033 if (inside_expression_statement && sub_statement->base.next == NULL)
10036 expression_t *expression = sub_statement->expression.expression;
10037 if (!expression_has_effect(expression)) {
10038 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10043 rem_anchor_token(T_while);
10044 rem_anchor_token(T_wchar_t);
10045 rem_anchor_token(T_volatile);
10046 rem_anchor_token(T_void);
10047 rem_anchor_token(T_using);
10048 rem_anchor_token(T_unsigned);
10049 rem_anchor_token(T_union);
10050 rem_anchor_token(T_typeof);
10051 rem_anchor_token(T_typename);
10052 rem_anchor_token(T_typeid);
10053 rem_anchor_token(T_typedef);
10054 rem_anchor_token(T_try);
10055 rem_anchor_token(T_true);
10056 rem_anchor_token(T_throw);
10057 rem_anchor_token(T_this);
10058 rem_anchor_token(T_template);
10059 rem_anchor_token(T_switch);
10060 rem_anchor_token(T_struct);
10061 rem_anchor_token(T_static_cast);
10062 rem_anchor_token(T_static);
10063 rem_anchor_token(T_sizeof);
10064 rem_anchor_token(T_signed);
10065 rem_anchor_token(T_short);
10066 rem_anchor_token(T_return);
10067 rem_anchor_token(T_restrict);
10068 rem_anchor_token(T_reinterpret_cast);
10069 rem_anchor_token(T_register);
10070 rem_anchor_token(T_operator);
10071 rem_anchor_token(T_new);
10072 rem_anchor_token(T_long);
10073 rem_anchor_token(T_int);
10074 rem_anchor_token(T_inline);
10075 rem_anchor_token(T_if);
10076 rem_anchor_token(T_goto);
10077 rem_anchor_token(T_for);
10078 rem_anchor_token(T_float);
10079 rem_anchor_token(T_false);
10080 rem_anchor_token(T_extern);
10081 rem_anchor_token(T_enum);
10082 rem_anchor_token(T_dynamic_cast);
10083 rem_anchor_token(T_do);
10084 rem_anchor_token(T_double);
10085 rem_anchor_token(T_delete);
10086 rem_anchor_token(T_default);
10087 rem_anchor_token(T_continue);
10088 rem_anchor_token(T_const_cast);
10089 rem_anchor_token(T_const);
10090 rem_anchor_token(T_class);
10091 rem_anchor_token(T_char);
10092 rem_anchor_token(T_case);
10093 rem_anchor_token(T_break);
10094 rem_anchor_token(T_bool);
10095 rem_anchor_token(T_auto);
10096 rem_anchor_token(T_asm);
10097 rem_anchor_token(T___thread);
10098 rem_anchor_token(T___real__);
10099 rem_anchor_token(T___label__);
10100 rem_anchor_token(T___imag__);
10101 rem_anchor_token(T___func__);
10102 rem_anchor_token(T___extension__);
10103 rem_anchor_token(T___builtin_va_start);
10104 rem_anchor_token(T___attribute__);
10105 rem_anchor_token(T___alignof__);
10106 rem_anchor_token(T___PRETTY_FUNCTION__);
10107 rem_anchor_token(T___FUNCTION__);
10108 rem_anchor_token(T__Imaginary);
10109 rem_anchor_token(T__Complex);
10110 rem_anchor_token(T__Bool);
10111 rem_anchor_token(T_WIDE_STRING_LITERAL);
10112 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10113 rem_anchor_token(T_STRING_LITERAL);
10114 rem_anchor_token(T_PLUSPLUS);
10115 rem_anchor_token(T_MINUSMINUS);
10116 rem_anchor_token(T_INTEGER);
10117 rem_anchor_token(T_IDENTIFIER);
10118 rem_anchor_token(T_FLOATINGPOINT);
10119 rem_anchor_token(T_COLONCOLON);
10120 rem_anchor_token(T_CHARACTER_CONSTANT);
10121 rem_anchor_token('~');
10122 rem_anchor_token('{');
10123 rem_anchor_token(';');
10124 rem_anchor_token('-');
10125 rem_anchor_token('+');
10126 rem_anchor_token('*');
10127 rem_anchor_token('(');
10128 rem_anchor_token('&');
10129 rem_anchor_token('!');
10130 rem_anchor_token('}');
10138 * Check for unused global static functions and variables
10140 static void check_unused_globals(void)
10142 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10145 for (const entity_t *entity = file_scope->entities; entity != NULL;
10146 entity = entity->base.next) {
10147 if (!is_declaration(entity))
10150 const declaration_t *declaration = &entity->declaration;
10151 if (declaration->used ||
10152 declaration->modifiers & DM_UNUSED ||
10153 declaration->modifiers & DM_USED ||
10154 declaration->storage_class != STORAGE_CLASS_STATIC)
10159 if (entity->kind == ENTITY_FUNCTION) {
10160 /* inhibit warning for static inline functions */
10161 if (entity->function.is_inline)
10164 why = WARN_UNUSED_FUNCTION;
10165 s = entity->function.statement != NULL ? "defined" : "declared";
10167 why = WARN_UNUSED_VARIABLE;
10171 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10175 static void parse_global_asm(void)
10177 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10180 add_anchor_token(';');
10181 add_anchor_token(')');
10182 add_anchor_token(T_STRING_LITERAL);
10185 rem_anchor_token(T_STRING_LITERAL);
10186 statement->asms.asm_text = parse_string_literals();
10187 statement->base.next = unit->global_asm;
10188 unit->global_asm = statement;
10190 rem_anchor_token(')');
10192 rem_anchor_token(';');
10196 static void parse_linkage_specification(void)
10200 source_position_t const pos = *HERE;
10201 char const *const linkage = parse_string_literals().begin;
10203 linkage_kind_t old_linkage = current_linkage;
10204 linkage_kind_t new_linkage;
10205 if (streq(linkage, "C")) {
10206 new_linkage = LINKAGE_C;
10207 } else if (streq(linkage, "C++")) {
10208 new_linkage = LINKAGE_CXX;
10210 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10211 new_linkage = LINKAGE_C;
10213 current_linkage = new_linkage;
10215 if (next_if('{')) {
10222 assert(current_linkage == new_linkage);
10223 current_linkage = old_linkage;
10226 static void parse_external(void)
10228 switch (token.kind) {
10230 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10231 parse_linkage_specification();
10233 DECLARATION_START_NO_EXTERN
10235 case T___extension__:
10236 /* tokens below are for implicit int */
10237 case '&': /* & x; -> int& x; (and error later, because C++ has no
10239 case '*': /* * x; -> int* x; */
10240 case '(': /* (x); -> int (x); */
10242 parse_external_declaration();
10248 parse_global_asm();
10252 parse_namespace_definition();
10256 if (!strict_mode) {
10257 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10264 errorf(HERE, "stray %K outside of function", &token);
10265 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10266 eat_until_matching_token(token.kind);
10272 static void parse_externals(void)
10274 add_anchor_token('}');
10275 add_anchor_token(T_EOF);
10278 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10279 unsigned short token_anchor_copy[T_LAST_TOKEN];
10280 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10283 while (token.kind != T_EOF && token.kind != '}') {
10285 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10286 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10288 /* the anchor set and its copy differs */
10289 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10292 if (in_gcc_extension) {
10293 /* an gcc extension scope was not closed */
10294 internal_errorf(HERE, "Leaked __extension__");
10301 rem_anchor_token(T_EOF);
10302 rem_anchor_token('}');
10306 * Parse a translation unit.
10308 static void parse_translation_unit(void)
10310 add_anchor_token(T_EOF);
10315 if (token.kind == T_EOF)
10318 errorf(HERE, "stray %K outside of function", &token);
10319 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10320 eat_until_matching_token(token.kind);
10325 void set_default_visibility(elf_visibility_tag_t visibility)
10327 default_visibility = visibility;
10333 * @return the translation unit or NULL if errors occurred.
10335 void start_parsing(void)
10337 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10338 label_stack = NEW_ARR_F(stack_entry_t, 0);
10339 diagnostic_count = 0;
10343 print_to_file(stderr);
10345 assert(unit == NULL);
10346 unit = allocate_ast_zero(sizeof(unit[0]));
10348 assert(file_scope == NULL);
10349 file_scope = &unit->scope;
10351 assert(current_scope == NULL);
10352 scope_push(&unit->scope);
10354 create_gnu_builtins();
10356 create_microsoft_intrinsics();
10359 translation_unit_t *finish_parsing(void)
10361 assert(current_scope == &unit->scope);
10364 assert(file_scope == &unit->scope);
10365 check_unused_globals();
10368 DEL_ARR_F(environment_stack);
10369 DEL_ARR_F(label_stack);
10371 translation_unit_t *result = unit;
10376 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10377 * are given length one. */
10378 static void complete_incomplete_arrays(void)
10380 size_t n = ARR_LEN(incomplete_arrays);
10381 for (size_t i = 0; i != n; ++i) {
10382 declaration_t *const decl = incomplete_arrays[i];
10383 type_t *const type = skip_typeref(decl->type);
10385 if (!is_type_incomplete(type))
10388 source_position_t const *const pos = &decl->base.source_position;
10389 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10391 type_t *const new_type = duplicate_type(type);
10392 new_type->array.size_constant = true;
10393 new_type->array.has_implicit_size = true;
10394 new_type->array.size = 1;
10396 type_t *const result = identify_new_type(new_type);
10398 decl->type = result;
10402 static void prepare_main_collect2(entity_t *const entity)
10404 PUSH_SCOPE(&entity->function.statement->compound.scope);
10406 // create call to __main
10407 symbol_t *symbol = symbol_table_insert("__main");
10408 entity_t *subsubmain_ent
10409 = create_implicit_function(symbol, &builtin_source_position);
10411 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10412 type_t *ftype = subsubmain_ent->declaration.type;
10413 ref->base.source_position = builtin_source_position;
10414 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10415 ref->reference.entity = subsubmain_ent;
10417 expression_t *call = allocate_expression_zero(EXPR_CALL);
10418 call->base.source_position = builtin_source_position;
10419 call->base.type = type_void;
10420 call->call.function = ref;
10422 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10423 expr_statement->base.source_position = builtin_source_position;
10424 expr_statement->expression.expression = call;
10426 statement_t *statement = entity->function.statement;
10427 assert(statement->kind == STATEMENT_COMPOUND);
10428 compound_statement_t *compounds = &statement->compound;
10430 expr_statement->base.next = compounds->statements;
10431 compounds->statements = expr_statement;
10438 lookahead_bufpos = 0;
10439 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10442 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10443 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10444 parse_translation_unit();
10445 complete_incomplete_arrays();
10446 DEL_ARR_F(incomplete_arrays);
10447 incomplete_arrays = NULL;
10451 * Initialize the parser.
10453 void init_parser(void)
10455 sym_anonymous = symbol_table_insert("<anonymous>");
10457 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10459 init_expression_parsers();
10460 obstack_init(&temp_obst);
10464 * Terminate the parser.
10466 void exit_parser(void)
10468 obstack_free(&temp_obst, NULL);