2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
41 #include "adt/bitfiddle.h"
42 #include "adt/error.h"
43 #include "adt/array.h"
45 //#define PRINT_TOKENS
46 #define MAX_LOOKAHEAD 1
51 entity_namespace_t namespc;
54 typedef struct declaration_specifiers_t declaration_specifiers_t;
55 struct declaration_specifiers_t {
56 source_position_t source_position;
57 storage_class_t storage_class;
58 unsigned char alignment; /**< Alignment, 0 if not set. */
60 bool thread_local : 1; /**< GCC __thread */
61 attribute_t *attributes; /**< list of attributes */
66 * An environment for parsing initializers (and compound literals).
68 typedef struct parse_initializer_env_t {
69 type_t *type; /**< the type of the initializer. In case of an
70 array type with unspecified size this gets
71 adjusted to the actual size. */
72 entity_t *entity; /**< the variable that is initialized if any */
73 bool must_be_constant;
74 } parse_initializer_env_t;
76 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
78 /** The current token. */
80 /** The lookahead ring-buffer. */
81 static token_t lookahead_buffer[MAX_LOOKAHEAD];
82 /** Position of the next token in the lookahead buffer. */
83 static size_t lookahead_bufpos;
84 static stack_entry_t *environment_stack = NULL;
85 static stack_entry_t *label_stack = NULL;
86 static scope_t *file_scope = NULL;
87 static scope_t *current_scope = NULL;
88 /** Point to the current function declaration if inside a function. */
89 static function_t *current_function = NULL;
90 static entity_t *current_init_decl = NULL;
91 static switch_statement_t *current_switch = NULL;
92 static statement_t *current_loop = NULL;
93 static statement_t *current_parent = NULL;
94 static ms_try_statement_t *current_try = NULL;
95 static linkage_kind_t current_linkage = LINKAGE_INVALID;
96 static goto_statement_t *goto_first = NULL;
97 static goto_statement_t **goto_anchor = NULL;
98 static label_statement_t *label_first = NULL;
99 static label_statement_t **label_anchor = NULL;
100 /** current translation unit. */
101 static translation_unit_t *unit = NULL;
102 /** true if we are in a type property context (evaluation only for type. */
103 static bool in_type_prop = false;
104 /** true in we are in a __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;
111 #define PUSH_PARENT(stmt) \
112 statement_t *const prev_parent = current_parent; \
113 ((void)(current_parent = (stmt)))
114 #define POP_PARENT ((void)(current_parent = prev_parent))
116 /** special symbol used for anonymous entities. */
117 static symbol_t *sym_anonymous = NULL;
119 /** The token anchor set */
120 static unsigned char token_anchor_set[T_LAST_TOKEN];
122 /** The current source position. */
123 #define HERE (&token.source_position)
125 /** true if we are in GCC mode. */
126 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
128 static statement_t *parse_compound_statement(bool inside_expression_statement);
129 static statement_t *parse_statement(void);
131 static expression_t *parse_sub_expression(precedence_t);
132 static expression_t *parse_expression(void);
133 static type_t *parse_typename(void);
134 static void parse_externals(void);
135 static void parse_external(void);
137 static void parse_compound_type_entries(compound_t *compound_declaration);
139 static void check_call_argument(type_t *expected_type,
140 call_argument_t *argument, unsigned pos);
142 typedef enum declarator_flags_t {
144 DECL_MAY_BE_ABSTRACT = 1U << 0,
145 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
146 DECL_IS_PARAMETER = 1U << 2
147 } declarator_flags_t;
149 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
150 declarator_flags_t flags);
152 static entity_t *record_entity(entity_t *entity, bool is_definition);
154 static void semantic_comparison(binary_expression_t *expression);
156 static void create_gnu_builtins(void);
157 static void create_microsoft_intrinsics(void);
159 #define STORAGE_CLASSES \
160 STORAGE_CLASSES_NO_EXTERN \
163 #define STORAGE_CLASSES_NO_EXTERN \
170 #define TYPE_QUALIFIERS \
175 case T__forceinline: \
176 case T___attribute__:
178 #define COMPLEX_SPECIFIERS \
180 #define IMAGINARY_SPECIFIERS \
183 #define TYPE_SPECIFIERS \
185 case T___builtin_va_list: \
210 #define DECLARATION_START \
215 #define DECLARATION_START_NO_EXTERN \
216 STORAGE_CLASSES_NO_EXTERN \
220 #define TYPENAME_START \
224 #define EXPRESSION_START \
233 case T_CHARACTER_CONSTANT: \
234 case T_FLOATINGPOINT: \
238 case T_STRING_LITERAL: \
239 case T_WIDE_CHARACTER_CONSTANT: \
240 case T_WIDE_STRING_LITERAL: \
241 case T___FUNCDNAME__: \
242 case T___FUNCSIG__: \
243 case T___FUNCTION__: \
244 case T___PRETTY_FUNCTION__: \
245 case T___alignof__: \
246 case T___builtin_classify_type: \
247 case T___builtin_constant_p: \
248 case T___builtin_isgreater: \
249 case T___builtin_isgreaterequal: \
250 case T___builtin_isless: \
251 case T___builtin_islessequal: \
252 case T___builtin_islessgreater: \
253 case T___builtin_isunordered: \
254 case T___builtin_offsetof: \
255 case T___builtin_va_arg: \
256 case T___builtin_va_start: \
257 case T___builtin_va_copy: \
268 * Allocate an AST node with given size and
269 * initialize all fields with zero.
271 static void *allocate_ast_zero(size_t size)
273 void *res = allocate_ast(size);
274 memset(res, 0, size);
279 * Returns the size of an entity node.
281 * @param kind the entity kind
283 static size_t get_entity_struct_size(entity_kind_t kind)
285 static const size_t sizes[] = {
286 [ENTITY_VARIABLE] = sizeof(variable_t),
287 [ENTITY_PARAMETER] = sizeof(parameter_t),
288 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
289 [ENTITY_FUNCTION] = sizeof(function_t),
290 [ENTITY_TYPEDEF] = sizeof(typedef_t),
291 [ENTITY_STRUCT] = sizeof(compound_t),
292 [ENTITY_UNION] = sizeof(compound_t),
293 [ENTITY_ENUM] = sizeof(enum_t),
294 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
295 [ENTITY_LABEL] = sizeof(label_t),
296 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
297 [ENTITY_NAMESPACE] = sizeof(namespace_t)
299 assert(kind < lengthof(sizes));
300 assert(sizes[kind] != 0);
305 * Allocate an entity of given kind and initialize all
308 * @param kind the kind of the entity to allocate
310 static entity_t *allocate_entity_zero(entity_kind_t kind)
312 size_t size = get_entity_struct_size(kind);
313 entity_t *entity = allocate_ast_zero(size);
319 * Returns the size of a statement node.
321 * @param kind the statement kind
323 static size_t get_statement_struct_size(statement_kind_t kind)
325 static const size_t sizes[] = {
326 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
327 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
328 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
329 [STATEMENT_RETURN] = sizeof(return_statement_t),
330 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
331 [STATEMENT_IF] = sizeof(if_statement_t),
332 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
333 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
334 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
335 [STATEMENT_BREAK] = sizeof(statement_base_t),
336 [STATEMENT_GOTO] = sizeof(goto_statement_t),
337 [STATEMENT_LABEL] = sizeof(label_statement_t),
338 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
339 [STATEMENT_WHILE] = sizeof(while_statement_t),
340 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
341 [STATEMENT_FOR] = sizeof(for_statement_t),
342 [STATEMENT_ASM] = sizeof(asm_statement_t),
343 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
344 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
346 assert(kind < lengthof(sizes));
347 assert(sizes[kind] != 0);
352 * Returns the size of an expression node.
354 * @param kind the expression kind
356 static size_t get_expression_struct_size(expression_kind_t kind)
358 static const size_t sizes[] = {
359 [EXPR_INVALID] = sizeof(expression_base_t),
360 [EXPR_REFERENCE] = sizeof(reference_expression_t),
361 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
362 [EXPR_CONST] = sizeof(const_expression_t),
363 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
364 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
365 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
366 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
367 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
368 [EXPR_CALL] = sizeof(call_expression_t),
369 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
370 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
371 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
372 [EXPR_SELECT] = sizeof(select_expression_t),
373 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
374 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
375 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
376 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
377 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
378 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
379 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
380 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
381 [EXPR_VA_START] = sizeof(va_start_expression_t),
382 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
383 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
384 [EXPR_STATEMENT] = sizeof(statement_expression_t),
385 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
387 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
388 return sizes[EXPR_UNARY_FIRST];
390 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
391 return sizes[EXPR_BINARY_FIRST];
393 assert(kind < lengthof(sizes));
394 assert(sizes[kind] != 0);
399 * Allocate a statement node of given kind and initialize all
400 * fields with zero. Sets its source position to the position
401 * of the current token.
403 static statement_t *allocate_statement_zero(statement_kind_t kind)
405 size_t size = get_statement_struct_size(kind);
406 statement_t *res = allocate_ast_zero(size);
408 res->base.kind = kind;
409 res->base.parent = current_parent;
410 res->base.source_position = token.source_position;
415 * Allocate an expression node of given kind and initialize all
418 * @param kind the kind of the expression to allocate
420 static expression_t *allocate_expression_zero(expression_kind_t kind)
422 size_t size = get_expression_struct_size(kind);
423 expression_t *res = allocate_ast_zero(size);
425 res->base.kind = kind;
426 res->base.type = type_error_type;
427 res->base.source_position = token.source_position;
432 * Creates a new invalid expression at the source position
433 * of the current token.
435 static expression_t *create_invalid_expression(void)
437 return allocate_expression_zero(EXPR_INVALID);
441 * Creates a new invalid statement.
443 static statement_t *create_invalid_statement(void)
445 return allocate_statement_zero(STATEMENT_INVALID);
449 * Allocate a new empty statement.
451 static statement_t *create_empty_statement(void)
453 return allocate_statement_zero(STATEMENT_EMPTY);
457 * Returns the size of a type node.
459 * @param kind the type kind
461 static size_t get_type_struct_size(type_kind_t kind)
463 static const size_t sizes[] = {
464 [TYPE_ATOMIC] = sizeof(atomic_type_t),
465 [TYPE_COMPLEX] = sizeof(complex_type_t),
466 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
467 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
468 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
469 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
470 [TYPE_ENUM] = sizeof(enum_type_t),
471 [TYPE_FUNCTION] = sizeof(function_type_t),
472 [TYPE_POINTER] = sizeof(pointer_type_t),
473 [TYPE_ARRAY] = sizeof(array_type_t),
474 [TYPE_BUILTIN] = sizeof(builtin_type_t),
475 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
476 [TYPE_TYPEOF] = sizeof(typeof_type_t),
478 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
479 assert(kind <= TYPE_TYPEOF);
480 assert(sizes[kind] != 0);
485 * Allocate a type node of given kind and initialize all
488 * @param kind type kind to allocate
490 static type_t *allocate_type_zero(type_kind_t kind)
492 size_t size = get_type_struct_size(kind);
493 type_t *res = obstack_alloc(type_obst, size);
494 memset(res, 0, size);
495 res->base.kind = kind;
500 static function_parameter_t *allocate_parameter(type_t *const type)
502 function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
503 memset(param, 0, sizeof(*param));
509 * Returns the size of an initializer node.
511 * @param kind the initializer kind
513 static size_t get_initializer_size(initializer_kind_t kind)
515 static const size_t sizes[] = {
516 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
517 [INITIALIZER_STRING] = sizeof(initializer_string_t),
518 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
519 [INITIALIZER_LIST] = sizeof(initializer_list_t),
520 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
522 assert(kind < lengthof(sizes));
523 assert(sizes[kind] != 0);
528 * Allocate an initializer node of given kind and initialize all
531 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
533 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
540 * Returns the index of the top element of the environment stack.
542 static size_t environment_top(void)
544 return ARR_LEN(environment_stack);
548 * Returns the index of the top element of the global label stack.
550 static size_t label_top(void)
552 return ARR_LEN(label_stack);
556 * Return the next token.
558 static inline void next_token(void)
560 token = lookahead_buffer[lookahead_bufpos];
561 lookahead_buffer[lookahead_bufpos] = lexer_token;
564 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
567 print_token(stderr, &token);
568 fprintf(stderr, "\n");
572 static inline bool next_if(int const type)
574 if (token.type == type) {
583 * Return the next token with a given lookahead.
585 static inline const token_t *look_ahead(size_t num)
587 assert(0 < num && num <= MAX_LOOKAHEAD);
588 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
589 return &lookahead_buffer[pos];
593 * Adds a token type to the token type anchor set (a multi-set).
595 static void add_anchor_token(int token_type)
597 assert(0 <= token_type && token_type < T_LAST_TOKEN);
598 ++token_anchor_set[token_type];
602 * Set the number of tokens types of the given type
603 * to zero and return the old count.
605 static int save_and_reset_anchor_state(int token_type)
607 assert(0 <= token_type && token_type < T_LAST_TOKEN);
608 int count = token_anchor_set[token_type];
609 token_anchor_set[token_type] = 0;
614 * Restore the number of token types to the given count.
616 static void restore_anchor_state(int token_type, int count)
618 assert(0 <= token_type && token_type < T_LAST_TOKEN);
619 token_anchor_set[token_type] = count;
623 * Remove a token type from the token type anchor set (a multi-set).
625 static void rem_anchor_token(int token_type)
627 assert(0 <= token_type && token_type < T_LAST_TOKEN);
628 assert(token_anchor_set[token_type] != 0);
629 --token_anchor_set[token_type];
633 * Return true if the token type of the current token is
636 static bool at_anchor(void)
640 return token_anchor_set[token.type];
644 * Eat tokens until a matching token type is found.
646 static void eat_until_matching_token(int type)
650 case '(': end_token = ')'; break;
651 case '{': end_token = '}'; break;
652 case '[': end_token = ']'; break;
653 default: end_token = type; break;
656 unsigned parenthesis_count = 0;
657 unsigned brace_count = 0;
658 unsigned bracket_count = 0;
659 while (token.type != end_token ||
660 parenthesis_count != 0 ||
662 bracket_count != 0) {
663 switch (token.type) {
665 case '(': ++parenthesis_count; break;
666 case '{': ++brace_count; break;
667 case '[': ++bracket_count; break;
670 if (parenthesis_count > 0)
680 if (bracket_count > 0)
683 if (token.type == end_token &&
684 parenthesis_count == 0 &&
698 * Eat input tokens until an anchor is found.
700 static void eat_until_anchor(void)
702 while (token_anchor_set[token.type] == 0) {
703 if (token.type == '(' || token.type == '{' || token.type == '[')
704 eat_until_matching_token(token.type);
710 * Eat a whole block from input tokens.
712 static void eat_block(void)
714 eat_until_matching_token('{');
718 #define eat(token_type) (assert(token.type == (token_type)), next_token())
721 * Report a parse error because an expected token was not found.
724 #if defined __GNUC__ && __GNUC__ >= 4
725 __attribute__((sentinel))
727 void parse_error_expected(const char *message, ...)
729 if (message != NULL) {
730 errorf(HERE, "%s", message);
733 va_start(ap, message);
734 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
739 * Report an incompatible type.
741 static void type_error_incompatible(const char *msg,
742 const source_position_t *source_position, type_t *type1, type_t *type2)
744 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
749 * Expect the current token is the expected token.
750 * If not, generate an error, eat the current statement,
751 * and goto the end_error label.
753 #define expect(expected, error_label) \
755 if (UNLIKELY(token.type != (expected))) { \
756 parse_error_expected(NULL, (expected), NULL); \
757 add_anchor_token(expected); \
758 eat_until_anchor(); \
759 next_if((expected)); \
760 rem_anchor_token(expected); \
767 * Push a given scope on the scope stack and make it the
770 static scope_t *scope_push(scope_t *new_scope)
772 if (current_scope != NULL) {
773 new_scope->depth = current_scope->depth + 1;
776 scope_t *old_scope = current_scope;
777 current_scope = new_scope;
782 * Pop the current scope from the scope stack.
784 static void scope_pop(scope_t *old_scope)
786 current_scope = old_scope;
790 * Search an entity by its symbol in a given namespace.
792 static entity_t *get_entity(const symbol_t *const symbol,
793 namespace_tag_t namespc)
795 entity_t *entity = symbol->entity;
796 for (; entity != NULL; entity = entity->base.symbol_next) {
797 if (entity->base.namespc == namespc)
804 /* §6.2.3:1 24) There is only one name space for tags even though three are
806 static entity_t *get_tag(symbol_t const *const symbol,
807 entity_kind_tag_t const kind)
809 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
810 if (entity != NULL && entity->kind != kind) {
812 "'%Y' defined as wrong kind of tag (previous definition %P)",
813 symbol, &entity->base.source_position);
820 * pushs an entity on the environment stack and links the corresponding symbol
823 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
825 symbol_t *symbol = entity->base.symbol;
826 entity_namespace_t namespc = entity->base.namespc;
827 assert(namespc != NAMESPACE_INVALID);
829 /* replace/add entity into entity list of the symbol */
832 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
837 /* replace an entry? */
838 if (iter->base.namespc == namespc) {
839 entity->base.symbol_next = iter->base.symbol_next;
845 /* remember old declaration */
847 entry.symbol = symbol;
848 entry.old_entity = iter;
849 entry.namespc = namespc;
850 ARR_APP1(stack_entry_t, *stack_ptr, entry);
854 * Push an entity on the environment stack.
856 static void environment_push(entity_t *entity)
858 assert(entity->base.source_position.input_name != NULL);
859 assert(entity->base.parent_scope != NULL);
860 stack_push(&environment_stack, entity);
864 * Push a declaration on the global label stack.
866 * @param declaration the declaration
868 static void label_push(entity_t *label)
870 /* we abuse the parameters scope as parent for the labels */
871 label->base.parent_scope = ¤t_function->parameters;
872 stack_push(&label_stack, label);
876 * pops symbols from the environment stack until @p new_top is the top element
878 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
880 stack_entry_t *stack = *stack_ptr;
881 size_t top = ARR_LEN(stack);
884 assert(new_top <= top);
888 for (i = top; i > new_top; --i) {
889 stack_entry_t *entry = &stack[i - 1];
891 entity_t *old_entity = entry->old_entity;
892 symbol_t *symbol = entry->symbol;
893 entity_namespace_t namespc = entry->namespc;
895 /* replace with old_entity/remove */
898 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
900 assert(iter != NULL);
901 /* replace an entry? */
902 if (iter->base.namespc == namespc)
906 /* restore definition from outer scopes (if there was one) */
907 if (old_entity != NULL) {
908 old_entity->base.symbol_next = iter->base.symbol_next;
909 *anchor = old_entity;
911 /* remove entry from list */
912 *anchor = iter->base.symbol_next;
916 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
920 * Pop all entries from the environment stack until the new_top
923 * @param new_top the new stack top
925 static void environment_pop_to(size_t new_top)
927 stack_pop_to(&environment_stack, new_top);
931 * Pop all entries from the global label stack until the new_top
934 * @param new_top the new stack top
936 static void label_pop_to(size_t new_top)
938 stack_pop_to(&label_stack, new_top);
941 static int get_akind_rank(atomic_type_kind_t akind)
947 * Return the type rank for an atomic type.
949 static int get_rank(const type_t *type)
951 assert(!is_typeref(type));
952 if (type->kind == TYPE_ENUM)
953 return get_akind_rank(type->enumt.akind);
955 assert(type->kind == TYPE_ATOMIC);
956 return get_akind_rank(type->atomic.akind);
960 * §6.3.1.1:2 Do integer promotion for a given type.
962 * @param type the type to promote
963 * @return the promoted type
965 static type_t *promote_integer(type_t *type)
967 if (type->kind == TYPE_BITFIELD)
968 type = type->bitfield.base_type;
970 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
977 * Create a cast expression.
979 * @param expression the expression to cast
980 * @param dest_type the destination type
982 static expression_t *create_cast_expression(expression_t *expression,
985 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
987 cast->unary.value = expression;
988 cast->base.type = dest_type;
994 * Check if a given expression represents a null pointer constant.
996 * @param expression the expression to check
998 static bool is_null_pointer_constant(const expression_t *expression)
1000 /* skip void* cast */
1001 if (expression->kind == EXPR_UNARY_CAST ||
1002 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1003 type_t *const type = skip_typeref(expression->base.type);
1004 if (types_compatible(type, type_void_ptr))
1005 expression = expression->unary.value;
1008 type_t *const type = skip_typeref(expression->base.type);
1010 is_type_integer(type) &&
1011 is_constant_expression(expression) &&
1012 !fold_constant_to_bool(expression);
1016 * Create an implicit cast expression.
1018 * @param expression the expression to cast
1019 * @param dest_type the destination type
1021 static expression_t *create_implicit_cast(expression_t *expression,
1024 type_t *const source_type = expression->base.type;
1026 if (source_type == dest_type)
1029 return create_cast_expression(expression, dest_type);
1032 typedef enum assign_error_t {
1034 ASSIGN_ERROR_INCOMPATIBLE,
1035 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1036 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1037 ASSIGN_WARNING_POINTER_FROM_INT,
1038 ASSIGN_WARNING_INT_FROM_POINTER
1041 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1042 const expression_t *const right,
1043 const char *context,
1044 const source_position_t *source_position)
1046 type_t *const orig_type_right = right->base.type;
1047 type_t *const type_left = skip_typeref(orig_type_left);
1048 type_t *const type_right = skip_typeref(orig_type_right);
1051 case ASSIGN_SUCCESS:
1053 case ASSIGN_ERROR_INCOMPATIBLE:
1054 errorf(source_position,
1055 "destination type '%T' in %s is incompatible with type '%T'",
1056 orig_type_left, context, orig_type_right);
1059 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1060 if (warning.other) {
1061 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1062 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1064 /* the left type has all qualifiers from the right type */
1065 unsigned missing_qualifiers
1066 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1067 warningf(source_position,
1068 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1069 orig_type_left, context, orig_type_right, missing_qualifiers);
1074 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1075 if (warning.other) {
1076 warningf(source_position,
1077 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1078 orig_type_left, context, right, orig_type_right);
1082 case ASSIGN_WARNING_POINTER_FROM_INT:
1083 if (warning.other) {
1084 warningf(source_position,
1085 "%s makes pointer '%T' from integer '%T' without a cast",
1086 context, orig_type_left, orig_type_right);
1090 case ASSIGN_WARNING_INT_FROM_POINTER:
1091 if (warning.other) {
1092 warningf(source_position,
1093 "%s makes integer '%T' from pointer '%T' without a cast",
1094 context, orig_type_left, orig_type_right);
1099 panic("invalid error value");
1103 /** Implements the rules from §6.5.16.1 */
1104 static assign_error_t semantic_assign(type_t *orig_type_left,
1105 const expression_t *const right)
1107 type_t *const orig_type_right = right->base.type;
1108 type_t *const type_left = skip_typeref(orig_type_left);
1109 type_t *const type_right = skip_typeref(orig_type_right);
1111 if (is_type_pointer(type_left)) {
1112 if (is_null_pointer_constant(right)) {
1113 return ASSIGN_SUCCESS;
1114 } else if (is_type_pointer(type_right)) {
1115 type_t *points_to_left
1116 = skip_typeref(type_left->pointer.points_to);
1117 type_t *points_to_right
1118 = skip_typeref(type_right->pointer.points_to);
1119 assign_error_t res = ASSIGN_SUCCESS;
1121 /* the left type has all qualifiers from the right type */
1122 unsigned missing_qualifiers
1123 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1124 if (missing_qualifiers != 0) {
1125 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1128 points_to_left = get_unqualified_type(points_to_left);
1129 points_to_right = get_unqualified_type(points_to_right);
1131 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1134 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1135 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1136 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1139 if (!types_compatible(points_to_left, points_to_right)) {
1140 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1144 } else if (is_type_integer(type_right)) {
1145 return ASSIGN_WARNING_POINTER_FROM_INT;
1147 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1148 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1149 && is_type_pointer(type_right))) {
1150 return ASSIGN_SUCCESS;
1151 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1152 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1153 type_t *const unqual_type_left = get_unqualified_type(type_left);
1154 type_t *const unqual_type_right = get_unqualified_type(type_right);
1155 if (types_compatible(unqual_type_left, unqual_type_right)) {
1156 return ASSIGN_SUCCESS;
1158 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1159 return ASSIGN_WARNING_INT_FROM_POINTER;
1162 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1163 return ASSIGN_SUCCESS;
1165 return ASSIGN_ERROR_INCOMPATIBLE;
1168 static expression_t *parse_constant_expression(void)
1170 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1172 if (!is_constant_expression(result)) {
1173 errorf(&result->base.source_position,
1174 "expression '%E' is not constant", result);
1180 static expression_t *parse_assignment_expression(void)
1182 return parse_sub_expression(PREC_ASSIGNMENT);
1185 static string_t parse_string_literals(void)
1187 assert(token.type == T_STRING_LITERAL);
1188 string_t result = token.v.string;
1192 while (token.type == T_STRING_LITERAL) {
1193 result = concat_strings(&result, &token.v.string);
1201 * compare two string, ignoring double underscores on the second.
1203 static int strcmp_underscore(const char *s1, const char *s2)
1205 if (s2[0] == '_' && s2[1] == '_') {
1206 size_t len2 = strlen(s2);
1207 size_t len1 = strlen(s1);
1208 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1209 return strncmp(s1, s2+2, len2-4);
1213 return strcmp(s1, s2);
1216 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1218 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1219 attribute->kind = kind;
1224 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1227 * __attribute__ ( ( attribute-list ) )
1231 * attribute_list , attrib
1236 * any-word ( identifier )
1237 * any-word ( identifier , nonempty-expr-list )
1238 * any-word ( expr-list )
1240 * where the "identifier" must not be declared as a type, and
1241 * "any-word" may be any identifier (including one declared as a
1242 * type), a reserved word storage class specifier, type specifier or
1243 * type qualifier. ??? This still leaves out most reserved keywords
1244 * (following the old parser), shouldn't we include them, and why not
1245 * allow identifiers declared as types to start the arguments?
1247 * Matze: this all looks confusing and little systematic, so we're even less
1248 * strict and parse any list of things which are identifiers or
1249 * (assignment-)expressions.
1251 static attribute_argument_t *parse_attribute_arguments(void)
1253 attribute_argument_t *first = NULL;
1254 attribute_argument_t **anchor = &first;
1255 if (token.type != ')') do {
1256 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1258 /* is it an identifier */
1259 if (token.type == T_IDENTIFIER
1260 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1261 symbol_t *symbol = token.v.symbol;
1262 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1263 argument->v.symbol = symbol;
1266 /* must be an expression */
1267 expression_t *expression = parse_assignment_expression();
1269 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1270 argument->v.expression = expression;
1273 /* append argument */
1275 anchor = &argument->next;
1276 } while (next_if(','));
1277 expect(')', end_error);
1286 static attribute_t *parse_attribute_asm(void)
1290 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1292 expect('(', end_error);
1293 attribute->a.arguments = parse_attribute_arguments();
1300 static symbol_t *get_symbol_from_token(void)
1302 switch(token.type) {
1304 return token.v.symbol;
1333 /* maybe we need more tokens ... add them on demand */
1334 return get_token_symbol(&token);
1340 static attribute_t *parse_attribute_gnu_single(void)
1342 /* parse "any-word" */
1343 symbol_t *symbol = get_symbol_from_token();
1344 if (symbol == NULL) {
1345 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1349 const char *name = symbol->string;
1352 attribute_kind_t kind;
1353 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1354 const char *attribute_name = get_attribute_name(kind);
1355 if (attribute_name != NULL
1356 && strcmp_underscore(attribute_name, name) == 0)
1360 if (kind >= ATTRIBUTE_GNU_LAST) {
1361 if (warning.attribute) {
1362 warningf(HERE, "unknown attribute '%s' ignored", name);
1364 /* TODO: we should still save the attribute in the list... */
1365 kind = ATTRIBUTE_UNKNOWN;
1368 attribute_t *attribute = allocate_attribute_zero(kind);
1370 /* parse arguments */
1372 attribute->a.arguments = parse_attribute_arguments();
1380 static attribute_t *parse_attribute_gnu(void)
1382 attribute_t *first = NULL;
1383 attribute_t **anchor = &first;
1385 eat(T___attribute__);
1386 expect('(', end_error);
1387 expect('(', end_error);
1389 if (token.type != ')') do {
1390 attribute_t *attribute = parse_attribute_gnu_single();
1391 if (attribute == NULL)
1394 *anchor = attribute;
1395 anchor = &attribute->next;
1396 } while (next_if(','));
1397 expect(')', end_error);
1398 expect(')', end_error);
1404 /** Parse attributes. */
1405 static attribute_t *parse_attributes(attribute_t *first)
1407 attribute_t **anchor = &first;
1409 while (*anchor != NULL)
1410 anchor = &(*anchor)->next;
1412 attribute_t *attribute;
1413 switch (token.type) {
1414 case T___attribute__:
1415 attribute = parse_attribute_gnu();
1419 attribute = parse_attribute_asm();
1424 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1429 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1432 case T__forceinline:
1434 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1439 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1444 /* TODO record modifier */
1446 warningf(HERE, "Ignoring declaration modifier %K", &token);
1447 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1454 *anchor = attribute;
1455 anchor = &attribute->next;
1459 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1461 static entity_t *determine_lhs_ent(expression_t *const expr,
1464 switch (expr->kind) {
1465 case EXPR_REFERENCE: {
1466 entity_t *const entity = expr->reference.entity;
1467 /* we should only find variables as lvalues... */
1468 if (entity->base.kind != ENTITY_VARIABLE
1469 && entity->base.kind != ENTITY_PARAMETER)
1475 case EXPR_ARRAY_ACCESS: {
1476 expression_t *const ref = expr->array_access.array_ref;
1477 entity_t * ent = NULL;
1478 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1479 ent = determine_lhs_ent(ref, lhs_ent);
1482 mark_vars_read(expr->select.compound, lhs_ent);
1484 mark_vars_read(expr->array_access.index, lhs_ent);
1489 if (is_type_compound(skip_typeref(expr->base.type))) {
1490 return determine_lhs_ent(expr->select.compound, lhs_ent);
1492 mark_vars_read(expr->select.compound, lhs_ent);
1497 case EXPR_UNARY_DEREFERENCE: {
1498 expression_t *const val = expr->unary.value;
1499 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1501 return determine_lhs_ent(val->unary.value, lhs_ent);
1503 mark_vars_read(val, NULL);
1509 mark_vars_read(expr, NULL);
1514 #define ENT_ANY ((entity_t*)-1)
1517 * Mark declarations, which are read. This is used to detect variables, which
1521 * x is not marked as "read", because it is only read to calculate its own new
1525 * x and y are not detected as "not read", because multiple variables are
1528 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1530 switch (expr->kind) {
1531 case EXPR_REFERENCE: {
1532 entity_t *const entity = expr->reference.entity;
1533 if (entity->kind != ENTITY_VARIABLE
1534 && entity->kind != ENTITY_PARAMETER)
1537 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1538 if (entity->kind == ENTITY_VARIABLE) {
1539 entity->variable.read = true;
1541 entity->parameter.read = true;
1548 // TODO respect pure/const
1549 mark_vars_read(expr->call.function, NULL);
1550 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1551 mark_vars_read(arg->expression, NULL);
1555 case EXPR_CONDITIONAL:
1556 // TODO lhs_decl should depend on whether true/false have an effect
1557 mark_vars_read(expr->conditional.condition, NULL);
1558 if (expr->conditional.true_expression != NULL)
1559 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1560 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1564 if (lhs_ent == ENT_ANY
1565 && !is_type_compound(skip_typeref(expr->base.type)))
1567 mark_vars_read(expr->select.compound, lhs_ent);
1570 case EXPR_ARRAY_ACCESS: {
1571 expression_t *const ref = expr->array_access.array_ref;
1572 mark_vars_read(ref, lhs_ent);
1573 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1574 mark_vars_read(expr->array_access.index, lhs_ent);
1579 mark_vars_read(expr->va_arge.ap, lhs_ent);
1583 mark_vars_read(expr->va_copye.src, lhs_ent);
1586 case EXPR_UNARY_CAST:
1587 /* Special case: Use void cast to mark a variable as "read" */
1588 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1593 case EXPR_UNARY_THROW:
1594 if (expr->unary.value == NULL)
1597 case EXPR_UNARY_DEREFERENCE:
1598 case EXPR_UNARY_DELETE:
1599 case EXPR_UNARY_DELETE_ARRAY:
1600 if (lhs_ent == ENT_ANY)
1604 case EXPR_UNARY_NEGATE:
1605 case EXPR_UNARY_PLUS:
1606 case EXPR_UNARY_BITWISE_NEGATE:
1607 case EXPR_UNARY_NOT:
1608 case EXPR_UNARY_TAKE_ADDRESS:
1609 case EXPR_UNARY_POSTFIX_INCREMENT:
1610 case EXPR_UNARY_POSTFIX_DECREMENT:
1611 case EXPR_UNARY_PREFIX_INCREMENT:
1612 case EXPR_UNARY_PREFIX_DECREMENT:
1613 case EXPR_UNARY_CAST_IMPLICIT:
1614 case EXPR_UNARY_ASSUME:
1616 mark_vars_read(expr->unary.value, lhs_ent);
1619 case EXPR_BINARY_ADD:
1620 case EXPR_BINARY_SUB:
1621 case EXPR_BINARY_MUL:
1622 case EXPR_BINARY_DIV:
1623 case EXPR_BINARY_MOD:
1624 case EXPR_BINARY_EQUAL:
1625 case EXPR_BINARY_NOTEQUAL:
1626 case EXPR_BINARY_LESS:
1627 case EXPR_BINARY_LESSEQUAL:
1628 case EXPR_BINARY_GREATER:
1629 case EXPR_BINARY_GREATEREQUAL:
1630 case EXPR_BINARY_BITWISE_AND:
1631 case EXPR_BINARY_BITWISE_OR:
1632 case EXPR_BINARY_BITWISE_XOR:
1633 case EXPR_BINARY_LOGICAL_AND:
1634 case EXPR_BINARY_LOGICAL_OR:
1635 case EXPR_BINARY_SHIFTLEFT:
1636 case EXPR_BINARY_SHIFTRIGHT:
1637 case EXPR_BINARY_COMMA:
1638 case EXPR_BINARY_ISGREATER:
1639 case EXPR_BINARY_ISGREATEREQUAL:
1640 case EXPR_BINARY_ISLESS:
1641 case EXPR_BINARY_ISLESSEQUAL:
1642 case EXPR_BINARY_ISLESSGREATER:
1643 case EXPR_BINARY_ISUNORDERED:
1644 mark_vars_read(expr->binary.left, lhs_ent);
1645 mark_vars_read(expr->binary.right, lhs_ent);
1648 case EXPR_BINARY_ASSIGN:
1649 case EXPR_BINARY_MUL_ASSIGN:
1650 case EXPR_BINARY_DIV_ASSIGN:
1651 case EXPR_BINARY_MOD_ASSIGN:
1652 case EXPR_BINARY_ADD_ASSIGN:
1653 case EXPR_BINARY_SUB_ASSIGN:
1654 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1655 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1656 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1657 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1658 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1659 if (lhs_ent == ENT_ANY)
1661 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1662 mark_vars_read(expr->binary.right, lhs_ent);
1667 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1673 case EXPR_CHARACTER_CONSTANT:
1674 case EXPR_WIDE_CHARACTER_CONSTANT:
1675 case EXPR_STRING_LITERAL:
1676 case EXPR_WIDE_STRING_LITERAL:
1677 case EXPR_COMPOUND_LITERAL: // TODO init?
1679 case EXPR_CLASSIFY_TYPE:
1682 case EXPR_BUILTIN_CONSTANT_P:
1683 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1685 case EXPR_STATEMENT: // TODO
1686 case EXPR_LABEL_ADDRESS:
1687 case EXPR_REFERENCE_ENUM_VALUE:
1691 panic("unhandled expression");
1694 static designator_t *parse_designation(void)
1696 designator_t *result = NULL;
1697 designator_t **anchor = &result;
1700 designator_t *designator;
1701 switch (token.type) {
1703 designator = allocate_ast_zero(sizeof(designator[0]));
1704 designator->source_position = token.source_position;
1706 add_anchor_token(']');
1707 designator->array_index = parse_constant_expression();
1708 rem_anchor_token(']');
1709 expect(']', end_error);
1712 designator = allocate_ast_zero(sizeof(designator[0]));
1713 designator->source_position = token.source_position;
1715 if (token.type != T_IDENTIFIER) {
1716 parse_error_expected("while parsing designator",
1717 T_IDENTIFIER, NULL);
1720 designator->symbol = token.v.symbol;
1724 expect('=', end_error);
1728 assert(designator != NULL);
1729 *anchor = designator;
1730 anchor = &designator->next;
1736 static initializer_t *initializer_from_string(array_type_t *type,
1737 const string_t *const string)
1739 /* TODO: check len vs. size of array type */
1742 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1743 initializer->string.string = *string;
1748 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1749 wide_string_t *const string)
1751 /* TODO: check len vs. size of array type */
1754 initializer_t *const initializer =
1755 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1756 initializer->wide_string.string = *string;
1762 * Build an initializer from a given expression.
1764 static initializer_t *initializer_from_expression(type_t *orig_type,
1765 expression_t *expression)
1767 /* TODO check that expression is a constant expression */
1769 /* §6.7.8.14/15 char array may be initialized by string literals */
1770 type_t *type = skip_typeref(orig_type);
1771 type_t *expr_type_orig = expression->base.type;
1772 type_t *expr_type = skip_typeref(expr_type_orig);
1773 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1774 array_type_t *const array_type = &type->array;
1775 type_t *const element_type = skip_typeref(array_type->element_type);
1777 if (element_type->kind == TYPE_ATOMIC) {
1778 atomic_type_kind_t akind = element_type->atomic.akind;
1779 switch (expression->kind) {
1780 case EXPR_STRING_LITERAL:
1781 if (akind == ATOMIC_TYPE_CHAR
1782 || akind == ATOMIC_TYPE_SCHAR
1783 || akind == ATOMIC_TYPE_UCHAR) {
1784 return initializer_from_string(array_type,
1785 &expression->string.value);
1789 case EXPR_WIDE_STRING_LITERAL: {
1790 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1791 if (get_unqualified_type(element_type) == bare_wchar_type) {
1792 return initializer_from_wide_string(array_type,
1793 &expression->wide_string.value);
1804 assign_error_t error = semantic_assign(type, expression);
1805 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1807 report_assign_error(error, type, expression, "initializer",
1808 &expression->base.source_position);
1810 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1811 result->value.value = create_implicit_cast(expression, type);
1817 * Checks if a given expression can be used as an constant initializer.
1819 static bool is_initializer_constant(const expression_t *expression)
1821 return is_constant_expression(expression)
1822 || is_address_constant(expression);
1826 * Parses an scalar initializer.
1828 * §6.7.8.11; eat {} without warning
1830 static initializer_t *parse_scalar_initializer(type_t *type,
1831 bool must_be_constant)
1833 /* there might be extra {} hierarchies */
1837 warningf(HERE, "extra curly braces around scalar initializer");
1840 } while (next_if('{'));
1843 expression_t *expression = parse_assignment_expression();
1844 mark_vars_read(expression, NULL);
1845 if (must_be_constant && !is_initializer_constant(expression)) {
1846 errorf(&expression->base.source_position,
1847 "initialisation expression '%E' is not constant",
1851 initializer_t *initializer = initializer_from_expression(type, expression);
1853 if (initializer == NULL) {
1854 errorf(&expression->base.source_position,
1855 "expression '%E' (type '%T') doesn't match expected type '%T'",
1856 expression, expression->base.type, type);
1861 bool additional_warning_displayed = false;
1862 while (braces > 0) {
1864 if (token.type != '}') {
1865 if (!additional_warning_displayed && warning.other) {
1866 warningf(HERE, "additional elements in scalar initializer");
1867 additional_warning_displayed = true;
1878 * An entry in the type path.
1880 typedef struct type_path_entry_t type_path_entry_t;
1881 struct type_path_entry_t {
1882 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1884 size_t index; /**< For array types: the current index. */
1885 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1890 * A type path expression a position inside compound or array types.
1892 typedef struct type_path_t type_path_t;
1893 struct type_path_t {
1894 type_path_entry_t *path; /**< An flexible array containing the current path. */
1895 type_t *top_type; /**< type of the element the path points */
1896 size_t max_index; /**< largest index in outermost array */
1900 * Prints a type path for debugging.
1902 static __attribute__((unused)) void debug_print_type_path(
1903 const type_path_t *path)
1905 size_t len = ARR_LEN(path->path);
1907 for (size_t i = 0; i < len; ++i) {
1908 const type_path_entry_t *entry = & path->path[i];
1910 type_t *type = skip_typeref(entry->type);
1911 if (is_type_compound(type)) {
1912 /* in gcc mode structs can have no members */
1913 if (entry->v.compound_entry == NULL) {
1917 fprintf(stderr, ".%s",
1918 entry->v.compound_entry->base.symbol->string);
1919 } else if (is_type_array(type)) {
1920 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1922 fprintf(stderr, "-INVALID-");
1925 if (path->top_type != NULL) {
1926 fprintf(stderr, " (");
1927 print_type(path->top_type);
1928 fprintf(stderr, ")");
1933 * Return the top type path entry, ie. in a path
1934 * (type).a.b returns the b.
1936 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1938 size_t len = ARR_LEN(path->path);
1940 return &path->path[len-1];
1944 * Enlarge the type path by an (empty) element.
1946 static type_path_entry_t *append_to_type_path(type_path_t *path)
1948 size_t len = ARR_LEN(path->path);
1949 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1951 type_path_entry_t *result = & path->path[len];
1952 memset(result, 0, sizeof(result[0]));
1957 * Descending into a sub-type. Enter the scope of the current top_type.
1959 static void descend_into_subtype(type_path_t *path)
1961 type_t *orig_top_type = path->top_type;
1962 type_t *top_type = skip_typeref(orig_top_type);
1964 type_path_entry_t *top = append_to_type_path(path);
1965 top->type = top_type;
1967 if (is_type_compound(top_type)) {
1968 compound_t *compound = top_type->compound.compound;
1969 entity_t *entry = compound->members.entities;
1971 if (entry != NULL) {
1972 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1973 top->v.compound_entry = &entry->declaration;
1974 path->top_type = entry->declaration.type;
1976 path->top_type = NULL;
1978 } else if (is_type_array(top_type)) {
1980 path->top_type = top_type->array.element_type;
1982 assert(!is_type_valid(top_type));
1987 * Pop an entry from the given type path, ie. returning from
1988 * (type).a.b to (type).a
1990 static void ascend_from_subtype(type_path_t *path)
1992 type_path_entry_t *top = get_type_path_top(path);
1994 path->top_type = top->type;
1996 size_t len = ARR_LEN(path->path);
1997 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2001 * Pop entries from the given type path until the given
2002 * path level is reached.
2004 static void ascend_to(type_path_t *path, size_t top_path_level)
2006 size_t len = ARR_LEN(path->path);
2008 while (len > top_path_level) {
2009 ascend_from_subtype(path);
2010 len = ARR_LEN(path->path);
2014 static bool walk_designator(type_path_t *path, const designator_t *designator,
2015 bool used_in_offsetof)
2017 for (; designator != NULL; designator = designator->next) {
2018 type_path_entry_t *top = get_type_path_top(path);
2019 type_t *orig_type = top->type;
2021 type_t *type = skip_typeref(orig_type);
2023 if (designator->symbol != NULL) {
2024 symbol_t *symbol = designator->symbol;
2025 if (!is_type_compound(type)) {
2026 if (is_type_valid(type)) {
2027 errorf(&designator->source_position,
2028 "'.%Y' designator used for non-compound type '%T'",
2032 top->type = type_error_type;
2033 top->v.compound_entry = NULL;
2034 orig_type = type_error_type;
2036 compound_t *compound = type->compound.compound;
2037 entity_t *iter = compound->members.entities;
2038 for (; iter != NULL; iter = iter->base.next) {
2039 if (iter->base.symbol == symbol) {
2044 errorf(&designator->source_position,
2045 "'%T' has no member named '%Y'", orig_type, symbol);
2048 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2049 if (used_in_offsetof) {
2050 type_t *real_type = skip_typeref(iter->declaration.type);
2051 if (real_type->kind == TYPE_BITFIELD) {
2052 errorf(&designator->source_position,
2053 "offsetof designator '%Y' may not specify bitfield",
2059 top->type = orig_type;
2060 top->v.compound_entry = &iter->declaration;
2061 orig_type = iter->declaration.type;
2064 expression_t *array_index = designator->array_index;
2065 assert(designator->array_index != NULL);
2067 if (!is_type_array(type)) {
2068 if (is_type_valid(type)) {
2069 errorf(&designator->source_position,
2070 "[%E] designator used for non-array type '%T'",
2071 array_index, orig_type);
2076 long index = fold_constant_to_int(array_index);
2077 if (!used_in_offsetof) {
2079 errorf(&designator->source_position,
2080 "array index [%E] must be positive", array_index);
2081 } else if (type->array.size_constant) {
2082 long array_size = type->array.size;
2083 if (index >= array_size) {
2084 errorf(&designator->source_position,
2085 "designator [%E] (%d) exceeds array size %d",
2086 array_index, index, array_size);
2091 top->type = orig_type;
2092 top->v.index = (size_t) index;
2093 orig_type = type->array.element_type;
2095 path->top_type = orig_type;
2097 if (designator->next != NULL) {
2098 descend_into_subtype(path);
2107 static void advance_current_object(type_path_t *path, size_t top_path_level)
2109 type_path_entry_t *top = get_type_path_top(path);
2111 type_t *type = skip_typeref(top->type);
2112 if (is_type_union(type)) {
2113 /* in unions only the first element is initialized */
2114 top->v.compound_entry = NULL;
2115 } else if (is_type_struct(type)) {
2116 declaration_t *entry = top->v.compound_entry;
2118 entity_t *next_entity = entry->base.next;
2119 if (next_entity != NULL) {
2120 assert(is_declaration(next_entity));
2121 entry = &next_entity->declaration;
2126 top->v.compound_entry = entry;
2127 if (entry != NULL) {
2128 path->top_type = entry->type;
2131 } else if (is_type_array(type)) {
2132 assert(is_type_array(type));
2136 if (!type->array.size_constant || top->v.index < type->array.size) {
2140 assert(!is_type_valid(type));
2144 /* we're past the last member of the current sub-aggregate, try if we
2145 * can ascend in the type hierarchy and continue with another subobject */
2146 size_t len = ARR_LEN(path->path);
2148 if (len > top_path_level) {
2149 ascend_from_subtype(path);
2150 advance_current_object(path, top_path_level);
2152 path->top_type = NULL;
2157 * skip any {...} blocks until a closing bracket is reached.
2159 static void skip_initializers(void)
2163 while (token.type != '}') {
2164 if (token.type == T_EOF)
2166 if (token.type == '{') {
2174 static initializer_t *create_empty_initializer(void)
2176 static initializer_t empty_initializer
2177 = { .list = { { INITIALIZER_LIST }, 0 } };
2178 return &empty_initializer;
2182 * Parse a part of an initialiser for a struct or union,
2184 static initializer_t *parse_sub_initializer(type_path_t *path,
2185 type_t *outer_type, size_t top_path_level,
2186 parse_initializer_env_t *env)
2188 if (token.type == '}') {
2189 /* empty initializer */
2190 return create_empty_initializer();
2193 type_t *orig_type = path->top_type;
2194 type_t *type = NULL;
2196 if (orig_type == NULL) {
2197 /* We are initializing an empty compound. */
2199 type = skip_typeref(orig_type);
2202 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2205 designator_t *designator = NULL;
2206 if (token.type == '.' || token.type == '[') {
2207 designator = parse_designation();
2208 goto finish_designator;
2209 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2210 /* GNU-style designator ("identifier: value") */
2211 designator = allocate_ast_zero(sizeof(designator[0]));
2212 designator->source_position = token.source_position;
2213 designator->symbol = token.v.symbol;
2218 /* reset path to toplevel, evaluate designator from there */
2219 ascend_to(path, top_path_level);
2220 if (!walk_designator(path, designator, false)) {
2221 /* can't continue after designation error */
2225 initializer_t *designator_initializer
2226 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2227 designator_initializer->designator.designator = designator;
2228 ARR_APP1(initializer_t*, initializers, designator_initializer);
2230 orig_type = path->top_type;
2231 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2236 if (token.type == '{') {
2237 if (type != NULL && is_type_scalar(type)) {
2238 sub = parse_scalar_initializer(type, env->must_be_constant);
2242 if (env->entity != NULL) {
2244 "extra brace group at end of initializer for '%Y'",
2245 env->entity->base.symbol);
2247 errorf(HERE, "extra brace group at end of initializer");
2250 descend_into_subtype(path);
2252 add_anchor_token('}');
2253 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2255 rem_anchor_token('}');
2258 ascend_from_subtype(path);
2259 expect('}', end_error);
2261 expect('}', end_error);
2262 goto error_parse_next;
2266 /* must be an expression */
2267 expression_t *expression = parse_assignment_expression();
2268 mark_vars_read(expression, NULL);
2270 if (env->must_be_constant && !is_initializer_constant(expression)) {
2271 errorf(&expression->base.source_position,
2272 "Initialisation expression '%E' is not constant",
2277 /* we are already outside, ... */
2278 if (outer_type == NULL)
2279 goto error_parse_next;
2280 type_t *const outer_type_skip = skip_typeref(outer_type);
2281 if (is_type_compound(outer_type_skip) &&
2282 !outer_type_skip->compound.compound->complete) {
2283 goto error_parse_next;
2288 /* handle { "string" } special case */
2289 if ((expression->kind == EXPR_STRING_LITERAL
2290 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2291 && outer_type != NULL) {
2292 sub = initializer_from_expression(outer_type, expression);
2295 if (token.type != '}' && warning.other) {
2296 warningf(HERE, "excessive elements in initializer for type '%T'",
2299 /* TODO: eat , ... */
2304 /* descend into subtypes until expression matches type */
2306 orig_type = path->top_type;
2307 type = skip_typeref(orig_type);
2309 sub = initializer_from_expression(orig_type, expression);
2313 if (!is_type_valid(type)) {
2316 if (is_type_scalar(type)) {
2317 errorf(&expression->base.source_position,
2318 "expression '%E' doesn't match expected type '%T'",
2319 expression, orig_type);
2323 descend_into_subtype(path);
2327 /* update largest index of top array */
2328 const type_path_entry_t *first = &path->path[0];
2329 type_t *first_type = first->type;
2330 first_type = skip_typeref(first_type);
2331 if (is_type_array(first_type)) {
2332 size_t index = first->v.index;
2333 if (index > path->max_index)
2334 path->max_index = index;
2338 /* append to initializers list */
2339 ARR_APP1(initializer_t*, initializers, sub);
2342 if (warning.other) {
2343 if (env->entity != NULL) {
2344 warningf(HERE, "excess elements in initializer for '%Y'",
2345 env->entity->base.symbol);
2347 warningf(HERE, "excess elements in initializer");
2353 if (token.type == '}') {
2356 expect(',', end_error);
2357 if (token.type == '}') {
2362 /* advance to the next declaration if we are not at the end */
2363 advance_current_object(path, top_path_level);
2364 orig_type = path->top_type;
2365 if (orig_type != NULL)
2366 type = skip_typeref(orig_type);
2372 size_t len = ARR_LEN(initializers);
2373 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2374 initializer_t *result = allocate_ast_zero(size);
2375 result->kind = INITIALIZER_LIST;
2376 result->list.len = len;
2377 memcpy(&result->list.initializers, initializers,
2378 len * sizeof(initializers[0]));
2380 DEL_ARR_F(initializers);
2381 ascend_to(path, top_path_level+1);
2386 skip_initializers();
2387 DEL_ARR_F(initializers);
2388 ascend_to(path, top_path_level+1);
2393 * Parses an initializer. Parsers either a compound literal
2394 * (env->declaration == NULL) or an initializer of a declaration.
2396 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2398 type_t *type = skip_typeref(env->type);
2399 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2400 initializer_t *result;
2402 if (is_type_scalar(type)) {
2403 result = parse_scalar_initializer(type, env->must_be_constant);
2404 } else if (token.type == '{') {
2408 memset(&path, 0, sizeof(path));
2409 path.top_type = env->type;
2410 path.path = NEW_ARR_F(type_path_entry_t, 0);
2412 descend_into_subtype(&path);
2414 add_anchor_token('}');
2415 result = parse_sub_initializer(&path, env->type, 1, env);
2416 rem_anchor_token('}');
2418 max_index = path.max_index;
2419 DEL_ARR_F(path.path);
2421 expect('}', end_error);
2423 /* parse_scalar_initializer() also works in this case: we simply
2424 * have an expression without {} around it */
2425 result = parse_scalar_initializer(type, env->must_be_constant);
2428 /* §6.7.8:22 array initializers for arrays with unknown size determine
2429 * the array type size */
2430 if (is_type_array(type) && type->array.size_expression == NULL
2431 && result != NULL) {
2433 switch (result->kind) {
2434 case INITIALIZER_LIST:
2435 assert(max_index != 0xdeadbeaf);
2436 size = max_index + 1;
2439 case INITIALIZER_STRING:
2440 size = result->string.string.size;
2443 case INITIALIZER_WIDE_STRING:
2444 size = result->wide_string.string.size;
2447 case INITIALIZER_DESIGNATOR:
2448 case INITIALIZER_VALUE:
2449 /* can happen for parse errors */
2454 internal_errorf(HERE, "invalid initializer type");
2457 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2458 cnst->base.type = type_size_t;
2459 cnst->conste.v.int_value = size;
2461 type_t *new_type = duplicate_type(type);
2463 new_type->array.size_expression = cnst;
2464 new_type->array.size_constant = true;
2465 new_type->array.has_implicit_size = true;
2466 new_type->array.size = size;
2467 env->type = new_type;
2475 static void append_entity(scope_t *scope, entity_t *entity)
2477 if (scope->last_entity != NULL) {
2478 scope->last_entity->base.next = entity;
2480 scope->entities = entity;
2482 scope->last_entity = entity;
2486 static compound_t *parse_compound_type_specifier(bool is_struct)
2488 eat(is_struct ? T_struct : T_union);
2490 symbol_t *symbol = NULL;
2491 compound_t *compound = NULL;
2492 attribute_t *attributes = NULL;
2494 if (token.type == T___attribute__) {
2495 attributes = parse_attributes(NULL);
2498 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2499 if (token.type == T_IDENTIFIER) {
2500 /* the compound has a name, check if we have seen it already */
2501 symbol = token.v.symbol;
2504 entity_t *entity = get_tag(symbol, kind);
2505 if (entity != NULL) {
2506 compound = &entity->compound;
2507 if (compound->base.parent_scope != current_scope &&
2508 (token.type == '{' || token.type == ';')) {
2509 /* we're in an inner scope and have a definition. Shadow
2510 * existing definition in outer scope */
2512 } else if (compound->complete && token.type == '{') {
2513 assert(symbol != NULL);
2514 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2515 is_struct ? "struct" : "union", symbol,
2516 &compound->base.source_position);
2517 /* clear members in the hope to avoid further errors */
2518 compound->members.entities = NULL;
2521 } else if (token.type != '{') {
2523 parse_error_expected("while parsing struct type specifier",
2524 T_IDENTIFIER, '{', NULL);
2526 parse_error_expected("while parsing union type specifier",
2527 T_IDENTIFIER, '{', NULL);
2533 if (compound == NULL) {
2534 entity_t *entity = allocate_entity_zero(kind);
2535 compound = &entity->compound;
2537 compound->alignment = 1;
2538 compound->base.namespc = NAMESPACE_TAG;
2539 compound->base.source_position = token.source_position;
2540 compound->base.symbol = symbol;
2541 compound->base.parent_scope = current_scope;
2542 if (symbol != NULL) {
2543 environment_push(entity);
2545 append_entity(current_scope, entity);
2548 if (token.type == '{') {
2549 parse_compound_type_entries(compound);
2551 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2552 if (symbol == NULL) {
2553 assert(anonymous_entity == NULL);
2554 anonymous_entity = (entity_t*)compound;
2558 if (attributes != NULL) {
2559 handle_entity_attributes(attributes, (entity_t*) compound);
2565 static void parse_enum_entries(type_t *const enum_type)
2569 if (token.type == '}') {
2570 errorf(HERE, "empty enum not allowed");
2575 add_anchor_token('}');
2577 if (token.type != T_IDENTIFIER) {
2578 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2580 rem_anchor_token('}');
2584 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2585 entity->enum_value.enum_type = enum_type;
2586 entity->base.symbol = token.v.symbol;
2587 entity->base.source_position = token.source_position;
2591 expression_t *value = parse_constant_expression();
2593 value = create_implicit_cast(value, enum_type);
2594 entity->enum_value.value = value;
2599 record_entity(entity, false);
2600 } while (next_if(',') && token.type != '}');
2601 rem_anchor_token('}');
2603 expect('}', end_error);
2609 static type_t *parse_enum_specifier(void)
2615 switch (token.type) {
2617 symbol = token.v.symbol;
2620 entity = get_tag(symbol, ENTITY_ENUM);
2621 if (entity != NULL) {
2622 if (entity->base.parent_scope != current_scope &&
2623 (token.type == '{' || token.type == ';')) {
2624 /* we're in an inner scope and have a definition. Shadow
2625 * existing definition in outer scope */
2627 } else if (entity->enume.complete && token.type == '{') {
2628 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2629 symbol, &entity->base.source_position);
2640 parse_error_expected("while parsing enum type specifier",
2641 T_IDENTIFIER, '{', NULL);
2645 if (entity == NULL) {
2646 entity = allocate_entity_zero(ENTITY_ENUM);
2647 entity->base.namespc = NAMESPACE_TAG;
2648 entity->base.source_position = token.source_position;
2649 entity->base.symbol = symbol;
2650 entity->base.parent_scope = current_scope;
2653 type_t *const type = allocate_type_zero(TYPE_ENUM);
2654 type->enumt.enume = &entity->enume;
2655 type->enumt.akind = ATOMIC_TYPE_INT;
2657 if (token.type == '{') {
2658 if (symbol != NULL) {
2659 environment_push(entity);
2661 append_entity(current_scope, entity);
2662 entity->enume.complete = true;
2664 parse_enum_entries(type);
2665 parse_attributes(NULL);
2667 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2668 if (symbol == NULL) {
2669 assert(anonymous_entity == NULL);
2670 anonymous_entity = entity;
2672 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2673 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2681 * if a symbol is a typedef to another type, return true
2683 static bool is_typedef_symbol(symbol_t *symbol)
2685 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2686 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2689 static type_t *parse_typeof(void)
2695 expect('(', end_error);
2696 add_anchor_token(')');
2698 expression_t *expression = NULL;
2700 bool old_type_prop = in_type_prop;
2701 bool old_gcc_extension = in_gcc_extension;
2702 in_type_prop = true;
2704 while (next_if(T___extension__)) {
2705 /* This can be a prefix to a typename or an expression. */
2706 in_gcc_extension = true;
2708 switch (token.type) {
2710 if (is_typedef_symbol(token.v.symbol)) {
2711 type = parse_typename();
2713 expression = parse_expression();
2714 type = revert_automatic_type_conversion(expression);
2719 type = parse_typename();
2723 expression = parse_expression();
2724 type = expression->base.type;
2727 in_type_prop = old_type_prop;
2728 in_gcc_extension = old_gcc_extension;
2730 rem_anchor_token(')');
2731 expect(')', end_error);
2733 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2734 typeof_type->typeoft.expression = expression;
2735 typeof_type->typeoft.typeof_type = type;
2742 typedef enum specifiers_t {
2743 SPECIFIER_SIGNED = 1 << 0,
2744 SPECIFIER_UNSIGNED = 1 << 1,
2745 SPECIFIER_LONG = 1 << 2,
2746 SPECIFIER_INT = 1 << 3,
2747 SPECIFIER_DOUBLE = 1 << 4,
2748 SPECIFIER_CHAR = 1 << 5,
2749 SPECIFIER_WCHAR_T = 1 << 6,
2750 SPECIFIER_SHORT = 1 << 7,
2751 SPECIFIER_LONG_LONG = 1 << 8,
2752 SPECIFIER_FLOAT = 1 << 9,
2753 SPECIFIER_BOOL = 1 << 10,
2754 SPECIFIER_VOID = 1 << 11,
2755 SPECIFIER_INT8 = 1 << 12,
2756 SPECIFIER_INT16 = 1 << 13,
2757 SPECIFIER_INT32 = 1 << 14,
2758 SPECIFIER_INT64 = 1 << 15,
2759 SPECIFIER_INT128 = 1 << 16,
2760 SPECIFIER_COMPLEX = 1 << 17,
2761 SPECIFIER_IMAGINARY = 1 << 18,
2764 static type_t *create_builtin_type(symbol_t *const symbol,
2765 type_t *const real_type)
2767 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2768 type->builtin.symbol = symbol;
2769 type->builtin.real_type = real_type;
2770 return identify_new_type(type);
2773 static type_t *get_typedef_type(symbol_t *symbol)
2775 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2776 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2779 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2780 type->typedeft.typedefe = &entity->typedefe;
2785 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2787 expect('(', end_error);
2789 attribute_property_argument_t *property
2790 = allocate_ast_zero(sizeof(*property));
2793 if (token.type != T_IDENTIFIER) {
2794 parse_error_expected("while parsing property declspec",
2795 T_IDENTIFIER, NULL);
2800 symbol_t *symbol = token.v.symbol;
2802 if (strcmp(symbol->string, "put") == 0) {
2804 } else if (strcmp(symbol->string, "get") == 0) {
2807 errorf(HERE, "expected put or get in property declspec");
2810 expect('=', end_error);
2811 if (token.type != T_IDENTIFIER) {
2812 parse_error_expected("while parsing property declspec",
2813 T_IDENTIFIER, NULL);
2817 property->put_symbol = token.v.symbol;
2819 property->get_symbol = token.v.symbol;
2822 } while (next_if(','));
2824 attribute->a.property = property;
2826 expect(')', end_error);
2832 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2834 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2835 if (next_if(T_restrict)) {
2836 kind = ATTRIBUTE_MS_RESTRICT;
2837 } else if (token.type == T_IDENTIFIER) {
2838 const char *name = token.v.symbol->string;
2840 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2842 const char *attribute_name = get_attribute_name(k);
2843 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2849 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2850 warningf(HERE, "unknown __declspec '%s' ignored", name);
2853 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2857 attribute_t *attribute = allocate_attribute_zero(kind);
2859 if (kind == ATTRIBUTE_MS_PROPERTY) {
2860 return parse_attribute_ms_property(attribute);
2863 /* parse arguments */
2865 attribute->a.arguments = parse_attribute_arguments();
2870 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2874 expect('(', end_error);
2879 add_anchor_token(')');
2881 attribute_t **anchor = &first;
2883 while (*anchor != NULL)
2884 anchor = &(*anchor)->next;
2886 attribute_t *attribute
2887 = parse_microsoft_extended_decl_modifier_single();
2888 if (attribute == NULL)
2891 *anchor = attribute;
2892 anchor = &attribute->next;
2893 } while (next_if(','));
2895 rem_anchor_token(')');
2896 expect(')', end_error);
2900 rem_anchor_token(')');
2904 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2906 entity_t *entity = allocate_entity_zero(kind);
2907 entity->base.source_position = *HERE;
2908 entity->base.symbol = symbol;
2909 if (is_declaration(entity)) {
2910 entity->declaration.type = type_error_type;
2911 entity->declaration.implicit = true;
2912 } else if (kind == ENTITY_TYPEDEF) {
2913 entity->typedefe.type = type_error_type;
2914 entity->typedefe.builtin = true;
2916 if (kind != ENTITY_COMPOUND_MEMBER)
2917 record_entity(entity, false);
2921 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2923 type_t *type = NULL;
2924 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2925 unsigned type_specifiers = 0;
2926 bool newtype = false;
2927 bool saw_error = false;
2928 bool old_gcc_extension = in_gcc_extension;
2930 specifiers->source_position = token.source_position;
2933 specifiers->attributes = parse_attributes(specifiers->attributes);
2935 switch (token.type) {
2937 #define MATCH_STORAGE_CLASS(token, class) \
2939 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2940 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2942 specifiers->storage_class = class; \
2943 if (specifiers->thread_local) \
2944 goto check_thread_storage_class; \
2948 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2949 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2950 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2951 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2952 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2955 specifiers->attributes
2956 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2960 if (specifiers->thread_local) {
2961 errorf(HERE, "duplicate '__thread'");
2963 specifiers->thread_local = true;
2964 check_thread_storage_class:
2965 switch (specifiers->storage_class) {
2966 case STORAGE_CLASS_EXTERN:
2967 case STORAGE_CLASS_NONE:
2968 case STORAGE_CLASS_STATIC:
2972 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2973 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2974 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2975 wrong_thread_stoarge_class:
2976 errorf(HERE, "'__thread' used with '%s'", wrong);
2983 /* type qualifiers */
2984 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2986 qualifiers |= qualifier; \
2990 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2991 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2992 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2993 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2994 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2995 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2996 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2997 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2999 case T___extension__:
3001 in_gcc_extension = true;
3004 /* type specifiers */
3005 #define MATCH_SPECIFIER(token, specifier, name) \
3007 if (type_specifiers & specifier) { \
3008 errorf(HERE, "multiple " name " type specifiers given"); \
3010 type_specifiers |= specifier; \
3015 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3016 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3017 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3018 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3019 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3020 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3021 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3022 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3023 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3024 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3025 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3026 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3027 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3028 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3029 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3030 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3031 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3032 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3036 specifiers->is_inline = true;
3040 case T__forceinline:
3042 specifiers->modifiers |= DM_FORCEINLINE;
3047 if (type_specifiers & SPECIFIER_LONG_LONG) {
3048 errorf(HERE, "multiple type specifiers given");
3049 } else if (type_specifiers & SPECIFIER_LONG) {
3050 type_specifiers |= SPECIFIER_LONG_LONG;
3052 type_specifiers |= SPECIFIER_LONG;
3057 #define CHECK_DOUBLE_TYPE() \
3058 if ( type != NULL) \
3059 errorf(HERE, "multiple data types in declaration specifiers");
3062 CHECK_DOUBLE_TYPE();
3063 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3065 type->compound.compound = parse_compound_type_specifier(true);
3068 CHECK_DOUBLE_TYPE();
3069 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3070 type->compound.compound = parse_compound_type_specifier(false);
3073 CHECK_DOUBLE_TYPE();
3074 type = parse_enum_specifier();
3077 CHECK_DOUBLE_TYPE();
3078 type = parse_typeof();
3080 case T___builtin_va_list:
3081 CHECK_DOUBLE_TYPE();
3082 type = duplicate_type(type_valist);
3086 case T_IDENTIFIER: {
3087 /* only parse identifier if we haven't found a type yet */
3088 if (type != NULL || type_specifiers != 0) {
3089 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3090 * declaration, so it doesn't generate errors about expecting '(' or
3092 switch (look_ahead(1)->type) {
3099 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3103 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3108 goto finish_specifiers;
3112 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3113 if (typedef_type == NULL) {
3114 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3115 * declaration, so it doesn't generate 'implicit int' followed by more
3116 * errors later on. */
3117 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3123 errorf(HERE, "%K does not name a type", &token);
3126 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3128 type = allocate_type_zero(TYPE_TYPEDEF);
3129 type->typedeft.typedefe = &entity->typedefe;
3133 if (la1_type == '&' || la1_type == '*')
3134 goto finish_specifiers;
3139 goto finish_specifiers;
3144 type = typedef_type;
3148 /* function specifier */
3150 goto finish_specifiers;
3155 specifiers->attributes = parse_attributes(specifiers->attributes);
3157 in_gcc_extension = old_gcc_extension;
3159 if (type == NULL || (saw_error && type_specifiers != 0)) {
3160 atomic_type_kind_t atomic_type;
3162 /* match valid basic types */
3163 switch (type_specifiers) {
3164 case SPECIFIER_VOID:
3165 atomic_type = ATOMIC_TYPE_VOID;
3167 case SPECIFIER_WCHAR_T:
3168 atomic_type = ATOMIC_TYPE_WCHAR_T;
3170 case SPECIFIER_CHAR:
3171 atomic_type = ATOMIC_TYPE_CHAR;
3173 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3174 atomic_type = ATOMIC_TYPE_SCHAR;
3176 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3177 atomic_type = ATOMIC_TYPE_UCHAR;
3179 case SPECIFIER_SHORT:
3180 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3181 case SPECIFIER_SHORT | SPECIFIER_INT:
3182 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3183 atomic_type = ATOMIC_TYPE_SHORT;
3185 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3186 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3187 atomic_type = ATOMIC_TYPE_USHORT;
3190 case SPECIFIER_SIGNED:
3191 case SPECIFIER_SIGNED | SPECIFIER_INT:
3192 atomic_type = ATOMIC_TYPE_INT;
3194 case SPECIFIER_UNSIGNED:
3195 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3196 atomic_type = ATOMIC_TYPE_UINT;
3198 case SPECIFIER_LONG:
3199 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3200 case SPECIFIER_LONG | SPECIFIER_INT:
3201 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3202 atomic_type = ATOMIC_TYPE_LONG;
3204 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3205 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3206 atomic_type = ATOMIC_TYPE_ULONG;
3209 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3210 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3211 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3212 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3214 atomic_type = ATOMIC_TYPE_LONGLONG;
3215 goto warn_about_long_long;
3217 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3218 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3220 atomic_type = ATOMIC_TYPE_ULONGLONG;
3221 warn_about_long_long:
3222 if (warning.long_long) {
3223 warningf(&specifiers->source_position,
3224 "ISO C90 does not support 'long long'");
3228 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3229 atomic_type = unsigned_int8_type_kind;
3232 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3233 atomic_type = unsigned_int16_type_kind;
3236 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3237 atomic_type = unsigned_int32_type_kind;
3240 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3241 atomic_type = unsigned_int64_type_kind;
3244 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3245 atomic_type = unsigned_int128_type_kind;
3248 case SPECIFIER_INT8:
3249 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3250 atomic_type = int8_type_kind;
3253 case SPECIFIER_INT16:
3254 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3255 atomic_type = int16_type_kind;
3258 case SPECIFIER_INT32:
3259 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3260 atomic_type = int32_type_kind;
3263 case SPECIFIER_INT64:
3264 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3265 atomic_type = int64_type_kind;
3268 case SPECIFIER_INT128:
3269 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3270 atomic_type = int128_type_kind;
3273 case SPECIFIER_FLOAT:
3274 atomic_type = ATOMIC_TYPE_FLOAT;
3276 case SPECIFIER_DOUBLE:
3277 atomic_type = ATOMIC_TYPE_DOUBLE;
3279 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3280 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3282 case SPECIFIER_BOOL:
3283 atomic_type = ATOMIC_TYPE_BOOL;
3285 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3286 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3287 atomic_type = ATOMIC_TYPE_FLOAT;
3289 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3290 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3291 atomic_type = ATOMIC_TYPE_DOUBLE;
3293 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3294 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3295 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3298 /* invalid specifier combination, give an error message */
3299 if (type_specifiers == 0) {
3303 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3304 if (!(c_mode & _CXX) && !strict_mode) {
3305 if (warning.implicit_int) {
3306 warningf(HERE, "no type specifiers in declaration, using 'int'");
3308 atomic_type = ATOMIC_TYPE_INT;
3311 errorf(HERE, "no type specifiers given in declaration");
3313 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3314 (type_specifiers & SPECIFIER_UNSIGNED)) {
3315 errorf(HERE, "signed and unsigned specifiers given");
3316 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3317 errorf(HERE, "only integer types can be signed or unsigned");
3319 errorf(HERE, "multiple datatypes in declaration");
3324 if (type_specifiers & SPECIFIER_COMPLEX) {
3325 type = allocate_type_zero(TYPE_COMPLEX);
3326 type->complex.akind = atomic_type;
3327 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3328 type = allocate_type_zero(TYPE_IMAGINARY);
3329 type->imaginary.akind = atomic_type;
3331 type = allocate_type_zero(TYPE_ATOMIC);
3332 type->atomic.akind = atomic_type;
3335 } else if (type_specifiers != 0) {
3336 errorf(HERE, "multiple datatypes in declaration");
3339 /* FIXME: check type qualifiers here */
3340 type->base.qualifiers = qualifiers;
3343 type = identify_new_type(type);
3345 type = typehash_insert(type);
3348 if (specifiers->attributes != NULL)
3349 type = handle_type_attributes(specifiers->attributes, type);
3350 specifiers->type = type;
3354 specifiers->type = type_error_type;
3357 static type_qualifiers_t parse_type_qualifiers(void)
3359 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3362 switch (token.type) {
3363 /* type qualifiers */
3364 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3365 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3366 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3367 /* microsoft extended type modifiers */
3368 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3369 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3370 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3371 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3372 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3381 * Parses an K&R identifier list
3383 static void parse_identifier_list(scope_t *scope)
3386 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3387 entity->base.source_position = token.source_position;
3388 entity->base.namespc = NAMESPACE_NORMAL;
3389 entity->base.symbol = token.v.symbol;
3390 /* a K&R parameter has no type, yet */
3394 append_entity(scope, entity);
3395 } while (next_if(',') && token.type == T_IDENTIFIER);
3398 static entity_t *parse_parameter(void)
3400 declaration_specifiers_t specifiers;
3401 memset(&specifiers, 0, sizeof(specifiers));
3403 parse_declaration_specifiers(&specifiers);
3405 entity_t *entity = parse_declarator(&specifiers,
3406 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3407 anonymous_entity = NULL;
3411 static void semantic_parameter_incomplete(const entity_t *entity)
3413 assert(entity->kind == ENTITY_PARAMETER);
3415 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3416 * list in a function declarator that is part of a
3417 * definition of that function shall not have
3418 * incomplete type. */
3419 type_t *type = skip_typeref(entity->declaration.type);
3420 if (is_type_incomplete(type)) {
3421 errorf(&entity->base.source_position,
3422 "parameter '%#T' has incomplete type",
3423 entity->declaration.type, entity->base.symbol);
3427 static bool has_parameters(void)
3429 /* func(void) is not a parameter */
3430 if (token.type == T_IDENTIFIER) {
3431 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3434 if (entity->kind != ENTITY_TYPEDEF)
3436 if (skip_typeref(entity->typedefe.type) != type_void)
3438 } else if (token.type != T_void) {
3441 if (look_ahead(1)->type != ')')
3448 * Parses function type parameters (and optionally creates variable_t entities
3449 * for them in a scope)
3451 static void parse_parameters(function_type_t *type, scope_t *scope)
3454 add_anchor_token(')');
3455 int saved_comma_state = save_and_reset_anchor_state(',');
3457 if (token.type == T_IDENTIFIER &&
3458 !is_typedef_symbol(token.v.symbol)) {
3459 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3460 if (la1_type == ',' || la1_type == ')') {
3461 type->kr_style_parameters = true;
3462 parse_identifier_list(scope);
3463 goto parameters_finished;
3467 if (token.type == ')') {
3468 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3469 if (!(c_mode & _CXX))
3470 type->unspecified_parameters = true;
3471 goto parameters_finished;
3474 if (has_parameters()) {
3475 function_parameter_t **anchor = &type->parameters;
3477 switch (token.type) {
3480 type->variadic = true;
3481 goto parameters_finished;
3484 case T___extension__:
3487 entity_t *entity = parse_parameter();
3488 if (entity->kind == ENTITY_TYPEDEF) {
3489 errorf(&entity->base.source_position,
3490 "typedef not allowed as function parameter");
3493 assert(is_declaration(entity));
3495 semantic_parameter_incomplete(entity);
3497 function_parameter_t *const parameter =
3498 allocate_parameter(entity->declaration.type);
3500 if (scope != NULL) {
3501 append_entity(scope, entity);
3504 *anchor = parameter;
3505 anchor = ¶meter->next;
3510 goto parameters_finished;
3512 } while (next_if(','));
3516 parameters_finished:
3517 rem_anchor_token(')');
3518 expect(')', end_error);
3521 restore_anchor_state(',', saved_comma_state);
3524 typedef enum construct_type_kind_t {
3527 CONSTRUCT_REFERENCE,
3530 } construct_type_kind_t;
3532 typedef union construct_type_t construct_type_t;
3534 typedef struct construct_type_base_t {
3535 construct_type_kind_t kind;
3536 construct_type_t *next;
3537 } construct_type_base_t;
3539 typedef struct parsed_pointer_t {
3540 construct_type_base_t base;
3541 type_qualifiers_t type_qualifiers;
3542 variable_t *base_variable; /**< MS __based extension. */
3545 typedef struct parsed_reference_t {
3546 construct_type_base_t base;
3547 } parsed_reference_t;
3549 typedef struct construct_function_type_t {
3550 construct_type_base_t base;
3551 type_t *function_type;
3552 } construct_function_type_t;
3554 typedef struct parsed_array_t {
3555 construct_type_base_t base;
3556 type_qualifiers_t type_qualifiers;
3562 union construct_type_t {
3563 construct_type_kind_t kind;
3564 construct_type_base_t base;
3565 parsed_pointer_t pointer;
3566 parsed_reference_t reference;
3567 construct_function_type_t function;
3568 parsed_array_t array;
3571 static construct_type_t *parse_pointer_declarator(void)
3575 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3576 memset(pointer, 0, sizeof(pointer[0]));
3577 pointer->base.kind = CONSTRUCT_POINTER;
3578 pointer->type_qualifiers = parse_type_qualifiers();
3579 //pointer->base_variable = base_variable;
3581 return (construct_type_t*) pointer;
3584 static construct_type_t *parse_reference_declarator(void)
3588 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3589 parsed_reference_t *reference = &cons->reference;
3590 memset(reference, 0, sizeof(*reference));
3591 cons->kind = CONSTRUCT_REFERENCE;
3596 static construct_type_t *parse_array_declarator(void)
3599 add_anchor_token(']');
3601 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3602 parsed_array_t *array = &cons->array;
3603 memset(array, 0, sizeof(*array));
3604 cons->kind = CONSTRUCT_ARRAY;
3606 if (next_if(T_static))
3607 array->is_static = true;
3609 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3610 if (type_qualifiers != 0 && next_if(T_static))
3611 array->is_static = true;
3612 array->type_qualifiers = type_qualifiers;
3614 if (token.type == '*' && look_ahead(1)->type == ']') {
3615 array->is_variable = true;
3617 } else if (token.type != ']') {
3618 expression_t *const size = parse_assignment_expression();
3620 /* §6.7.5.2:1 Array size must have integer type */
3621 type_t *const orig_type = size->base.type;
3622 type_t *const type = skip_typeref(orig_type);
3623 if (!is_type_integer(type) && is_type_valid(type)) {
3624 errorf(&size->base.source_position,
3625 "array size '%E' must have integer type but has type '%T'",
3630 mark_vars_read(size, NULL);
3633 rem_anchor_token(']');
3634 expect(']', end_error);
3640 static construct_type_t *parse_function_declarator(scope_t *scope)
3642 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3643 function_type_t *ftype = &type->function;
3645 ftype->linkage = current_linkage;
3646 ftype->calling_convention = CC_DEFAULT;
3648 parse_parameters(ftype, scope);
3650 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3651 construct_function_type_t *function = &cons->function;
3652 memset(function, 0, sizeof(*function));
3653 cons->kind = CONSTRUCT_FUNCTION;
3654 function->function_type = type;
3659 typedef struct parse_declarator_env_t {
3660 bool may_be_abstract : 1;
3661 bool must_be_abstract : 1;
3662 decl_modifiers_t modifiers;
3664 source_position_t source_position;
3666 attribute_t *attributes;
3667 } parse_declarator_env_t;
3669 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3671 /* construct a single linked list of construct_type_t's which describe
3672 * how to construct the final declarator type */
3673 construct_type_t *first = NULL;
3674 construct_type_t **anchor = &first;
3676 env->attributes = parse_attributes(env->attributes);
3679 construct_type_t *type;
3680 //variable_t *based = NULL; /* MS __based extension */
3681 switch (token.type) {
3683 if (!(c_mode & _CXX))
3684 errorf(HERE, "references are only available for C++");
3685 type = parse_reference_declarator();
3690 source_position_t const pos = *HERE;
3692 expect('(', end_error);
3693 add_anchor_token(')');
3694 based = parse_microsoft_based();
3695 rem_anchor_token(')');
3696 expect(')', end_error);
3697 if (token.type != '*') {
3698 if (token.type == T__based) {
3699 errorf(&pos, "__based type modifier specified more than once");
3700 } else if (warning.other) {
3702 "__based does not precede a pointer declarator, ignored");
3707 panic("based currently disabled");
3713 type = parse_pointer_declarator();
3717 goto ptr_operator_end;
3721 anchor = &type->base.next;
3723 /* TODO: find out if this is correct */
3724 env->attributes = parse_attributes(env->attributes);
3729 modifiers |= env->modifiers;
3730 env->modifiers = modifiers;
3733 construct_type_t *inner_types = NULL;
3735 switch (token.type) {
3737 if (env->must_be_abstract) {
3738 errorf(HERE, "no identifier expected in typename");
3740 env->symbol = token.v.symbol;
3741 env->source_position = token.source_position;
3746 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3747 * interpreted as ``function with no parameter specification'', rather
3748 * than redundant parentheses around the omitted identifier. */
3749 if (look_ahead(1)->type != ')') {
3751 add_anchor_token(')');
3752 inner_types = parse_inner_declarator(env);
3753 if (inner_types != NULL) {
3754 /* All later declarators only modify the return type */
3755 env->must_be_abstract = true;
3757 rem_anchor_token(')');
3758 expect(')', end_error);
3762 if (env->may_be_abstract)
3764 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3769 construct_type_t **const p = anchor;
3772 construct_type_t *type;
3773 switch (token.type) {
3775 scope_t *scope = NULL;
3776 if (!env->must_be_abstract) {
3777 scope = &env->parameters;
3780 type = parse_function_declarator(scope);
3784 type = parse_array_declarator();
3787 goto declarator_finished;
3790 /* insert in the middle of the list (at p) */
3791 type->base.next = *p;
3794 anchor = &type->base.next;
3797 declarator_finished:
3798 /* append inner_types at the end of the list, we don't to set anchor anymore
3799 * as it's not needed anymore */
3800 *anchor = inner_types;
3807 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3809 construct_type_t *iter = construct_list;
3810 for (; iter != NULL; iter = iter->base.next) {
3811 switch (iter->kind) {
3812 case CONSTRUCT_INVALID:
3814 case CONSTRUCT_FUNCTION: {
3815 construct_function_type_t *function = &iter->function;
3816 type_t *function_type = function->function_type;
3818 function_type->function.return_type = type;
3820 type_t *skipped_return_type = skip_typeref(type);
3822 if (is_type_function(skipped_return_type)) {
3823 errorf(HERE, "function returning function is not allowed");
3824 } else if (is_type_array(skipped_return_type)) {
3825 errorf(HERE, "function returning array is not allowed");
3827 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3829 "type qualifiers in return type of function type are meaningless");
3833 /* The function type was constructed earlier. Freeing it here will
3834 * destroy other types. */
3835 type = typehash_insert(function_type);
3839 case CONSTRUCT_POINTER: {
3840 if (is_type_reference(skip_typeref(type)))
3841 errorf(HERE, "cannot declare a pointer to reference");
3843 parsed_pointer_t *pointer = &iter->pointer;
3844 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3848 case CONSTRUCT_REFERENCE:
3849 if (is_type_reference(skip_typeref(type)))
3850 errorf(HERE, "cannot declare a reference to reference");
3852 type = make_reference_type(type);
3855 case CONSTRUCT_ARRAY: {
3856 if (is_type_reference(skip_typeref(type)))
3857 errorf(HERE, "cannot declare an array of references");
3859 parsed_array_t *array = &iter->array;
3860 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3862 expression_t *size_expression = array->size;
3863 if (size_expression != NULL) {
3865 = create_implicit_cast(size_expression, type_size_t);
3868 array_type->base.qualifiers = array->type_qualifiers;
3869 array_type->array.element_type = type;
3870 array_type->array.is_static = array->is_static;
3871 array_type->array.is_variable = array->is_variable;
3872 array_type->array.size_expression = size_expression;
3874 if (size_expression != NULL) {
3875 if (is_constant_expression(size_expression)) {
3877 = fold_constant_to_int(size_expression);
3878 array_type->array.size = size;
3879 array_type->array.size_constant = true;
3880 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3881 * have a value greater than zero. */
3883 if (size < 0 || !GNU_MODE) {
3884 errorf(&size_expression->base.source_position,
3885 "size of array must be greater than zero");
3886 } else if (warning.other) {
3887 warningf(&size_expression->base.source_position,
3888 "zero length arrays are a GCC extension");
3892 array_type->array.is_vla = true;
3896 type_t *skipped_type = skip_typeref(type);
3898 if (is_type_incomplete(skipped_type)) {
3899 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3900 } else if (is_type_function(skipped_type)) {
3901 errorf(HERE, "array of functions is not allowed");
3903 type = identify_new_type(array_type);
3907 internal_errorf(HERE, "invalid type construction found");
3913 static type_t *automatic_type_conversion(type_t *orig_type);
3915 static type_t *semantic_parameter(const source_position_t *pos,
3917 const declaration_specifiers_t *specifiers,
3920 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3921 * shall be adjusted to ``qualified pointer to type'',
3923 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3924 * type'' shall be adjusted to ``pointer to function
3925 * returning type'', as in 6.3.2.1. */
3926 type = automatic_type_conversion(type);
3928 if (specifiers->is_inline && is_type_valid(type)) {
3929 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3932 /* §6.9.1:6 The declarations in the declaration list shall contain
3933 * no storage-class specifier other than register and no
3934 * initializations. */
3935 if (specifiers->thread_local || (
3936 specifiers->storage_class != STORAGE_CLASS_NONE &&
3937 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3939 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3942 /* delay test for incomplete type, because we might have (void)
3943 * which is legal but incomplete... */
3948 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3949 declarator_flags_t flags)
3951 parse_declarator_env_t env;
3952 memset(&env, 0, sizeof(env));
3953 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3955 construct_type_t *construct_type = parse_inner_declarator(&env);
3957 construct_declarator_type(construct_type, specifiers->type);
3958 type_t *type = skip_typeref(orig_type);
3960 if (construct_type != NULL) {
3961 obstack_free(&temp_obst, construct_type);
3964 attribute_t *attributes = parse_attributes(env.attributes);
3965 /* append (shared) specifier attribute behind attributes of this
3967 attribute_t **anchor = &attributes;
3968 while (*anchor != NULL)
3969 anchor = &(*anchor)->next;
3970 *anchor = specifiers->attributes;
3973 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3974 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3975 entity->base.symbol = env.symbol;
3976 entity->base.source_position = env.source_position;
3977 entity->typedefe.type = orig_type;
3979 if (anonymous_entity != NULL) {
3980 if (is_type_compound(type)) {
3981 assert(anonymous_entity->compound.alias == NULL);
3982 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3983 anonymous_entity->kind == ENTITY_UNION);
3984 anonymous_entity->compound.alias = entity;
3985 anonymous_entity = NULL;
3986 } else if (is_type_enum(type)) {
3987 assert(anonymous_entity->enume.alias == NULL);
3988 assert(anonymous_entity->kind == ENTITY_ENUM);
3989 anonymous_entity->enume.alias = entity;
3990 anonymous_entity = NULL;
3994 /* create a declaration type entity */
3995 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3996 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3998 if (env.symbol != NULL) {
3999 if (specifiers->is_inline && is_type_valid(type)) {
4000 errorf(&env.source_position,
4001 "compound member '%Y' declared 'inline'", env.symbol);
4004 if (specifiers->thread_local ||
4005 specifiers->storage_class != STORAGE_CLASS_NONE) {
4006 errorf(&env.source_position,
4007 "compound member '%Y' must have no storage class",
4011 } else if (flags & DECL_IS_PARAMETER) {
4012 orig_type = semantic_parameter(&env.source_position, orig_type,
4013 specifiers, env.symbol);
4015 entity = allocate_entity_zero(ENTITY_PARAMETER);
4016 } else if (is_type_function(type)) {
4017 entity = allocate_entity_zero(ENTITY_FUNCTION);
4019 entity->function.is_inline = specifiers->is_inline;
4020 entity->function.parameters = env.parameters;
4022 if (env.symbol != NULL) {
4023 /* this needs fixes for C++ */
4024 bool in_function_scope = current_function != NULL;
4026 if (specifiers->thread_local || (
4027 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4028 specifiers->storage_class != STORAGE_CLASS_NONE &&
4029 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4031 errorf(&env.source_position,
4032 "invalid storage class for function '%Y'", env.symbol);
4036 entity = allocate_entity_zero(ENTITY_VARIABLE);
4038 entity->variable.thread_local = specifiers->thread_local;
4040 if (env.symbol != NULL) {
4041 if (specifiers->is_inline && is_type_valid(type)) {
4042 errorf(&env.source_position,
4043 "variable '%Y' declared 'inline'", env.symbol);
4046 bool invalid_storage_class = false;
4047 if (current_scope == file_scope) {
4048 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4049 specifiers->storage_class != STORAGE_CLASS_NONE &&
4050 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4051 invalid_storage_class = true;
4054 if (specifiers->thread_local &&
4055 specifiers->storage_class == STORAGE_CLASS_NONE) {
4056 invalid_storage_class = true;
4059 if (invalid_storage_class) {
4060 errorf(&env.source_position,
4061 "invalid storage class for variable '%Y'", env.symbol);
4066 if (env.symbol != NULL) {
4067 entity->base.symbol = env.symbol;
4068 entity->base.source_position = env.source_position;
4070 entity->base.source_position = specifiers->source_position;
4072 entity->base.namespc = NAMESPACE_NORMAL;
4073 entity->declaration.type = orig_type;
4074 entity->declaration.alignment = get_type_alignment(orig_type);
4075 entity->declaration.modifiers = env.modifiers;
4076 entity->declaration.attributes = attributes;
4078 storage_class_t storage_class = specifiers->storage_class;
4079 entity->declaration.declared_storage_class = storage_class;
4081 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4082 storage_class = STORAGE_CLASS_AUTO;
4083 entity->declaration.storage_class = storage_class;
4086 if (attributes != NULL) {
4087 handle_entity_attributes(attributes, entity);
4093 static type_t *parse_abstract_declarator(type_t *base_type)
4095 parse_declarator_env_t env;
4096 memset(&env, 0, sizeof(env));
4097 env.may_be_abstract = true;
4098 env.must_be_abstract = true;
4100 construct_type_t *construct_type = parse_inner_declarator(&env);
4102 type_t *result = construct_declarator_type(construct_type, base_type);
4103 if (construct_type != NULL) {
4104 obstack_free(&temp_obst, construct_type);
4106 result = handle_type_attributes(env.attributes, result);
4112 * Check if the declaration of main is suspicious. main should be a
4113 * function with external linkage, returning int, taking either zero
4114 * arguments, two, or three arguments of appropriate types, ie.
4116 * int main([ int argc, char **argv [, char **env ] ]).
4118 * @param decl the declaration to check
4119 * @param type the function type of the declaration
4121 static void check_main(const entity_t *entity)
4123 const source_position_t *pos = &entity->base.source_position;
4124 if (entity->kind != ENTITY_FUNCTION) {
4125 warningf(pos, "'main' is not a function");
4129 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4130 warningf(pos, "'main' is normally a non-static function");
4133 type_t *type = skip_typeref(entity->declaration.type);
4134 assert(is_type_function(type));
4136 function_type_t *func_type = &type->function;
4137 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4138 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4139 func_type->return_type);
4141 const function_parameter_t *parm = func_type->parameters;
4143 type_t *const first_type = parm->type;
4144 if (!types_compatible(skip_typeref(first_type), type_int)) {
4146 "first argument of 'main' should be 'int', but is '%T'",
4151 type_t *const second_type = parm->type;
4152 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4153 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4157 type_t *const third_type = parm->type;
4158 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4159 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4163 goto warn_arg_count;
4167 warningf(pos, "'main' takes only zero, two or three arguments");
4173 * Check if a symbol is the equal to "main".
4175 static bool is_sym_main(const symbol_t *const sym)
4177 return strcmp(sym->string, "main") == 0;
4180 static void error_redefined_as_different_kind(const source_position_t *pos,
4181 const entity_t *old, entity_kind_t new_kind)
4183 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4184 get_entity_kind_name(old->kind), old->base.symbol,
4185 get_entity_kind_name(new_kind), &old->base.source_position);
4188 static bool is_error_entity(entity_t *const ent)
4190 if (is_declaration(ent)) {
4191 return is_type_valid(skip_typeref(ent->declaration.type));
4192 } else if (ent->kind == ENTITY_TYPEDEF) {
4193 return is_type_valid(skip_typeref(ent->typedefe.type));
4198 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4200 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4201 if (attributes_equal(tattr, attr))
4208 * test wether new_list contains any attributes not included in old_list
4210 static bool has_new_attributes(const attribute_t *old_list,
4211 const attribute_t *new_list)
4213 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4214 if (!contains_attribute(old_list, attr))
4221 * Merge in attributes from an attribute list (probably from a previous
4222 * declaration with the same name). Warning: destroys the old structure
4223 * of the attribute list - don't reuse attributes after this call.
4225 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4228 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4230 if (contains_attribute(decl->attributes, attr))
4233 /* move attribute to new declarations attributes list */
4234 attr->next = decl->attributes;
4235 decl->attributes = attr;
4240 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4241 * for various problems that occur for multiple definitions
4243 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4245 const symbol_t *const symbol = entity->base.symbol;
4246 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4247 const source_position_t *pos = &entity->base.source_position;
4249 /* can happen in error cases */
4253 entity_t *const previous_entity = get_entity(symbol, namespc);
4254 /* pushing the same entity twice will break the stack structure */
4255 assert(previous_entity != entity);
4257 if (entity->kind == ENTITY_FUNCTION) {
4258 type_t *const orig_type = entity->declaration.type;
4259 type_t *const type = skip_typeref(orig_type);
4261 assert(is_type_function(type));
4262 if (type->function.unspecified_parameters &&
4263 warning.strict_prototypes &&
4264 previous_entity == NULL) {
4265 warningf(pos, "function declaration '%#T' is not a prototype",
4269 if (warning.main && current_scope == file_scope
4270 && is_sym_main(symbol)) {
4275 if (is_declaration(entity) &&
4276 warning.nested_externs &&
4277 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4278 current_scope != file_scope) {
4279 warningf(pos, "nested extern declaration of '%#T'",
4280 entity->declaration.type, symbol);
4283 if (previous_entity != NULL) {
4284 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4285 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4286 assert(previous_entity->kind == ENTITY_PARAMETER);
4288 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4289 entity->declaration.type, symbol,
4290 previous_entity->declaration.type, symbol,
4291 &previous_entity->base.source_position);
4295 if (previous_entity->base.parent_scope == current_scope) {
4296 if (previous_entity->kind != entity->kind) {
4297 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4298 error_redefined_as_different_kind(pos, previous_entity,
4303 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4304 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4305 symbol, &previous_entity->base.source_position);
4308 if (previous_entity->kind == ENTITY_TYPEDEF) {
4309 /* TODO: C++ allows this for exactly the same type */
4310 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4311 symbol, &previous_entity->base.source_position);
4315 /* at this point we should have only VARIABLES or FUNCTIONS */
4316 assert(is_declaration(previous_entity) && is_declaration(entity));
4318 declaration_t *const prev_decl = &previous_entity->declaration;
4319 declaration_t *const decl = &entity->declaration;
4321 /* can happen for K&R style declarations */
4322 if (prev_decl->type == NULL &&
4323 previous_entity->kind == ENTITY_PARAMETER &&
4324 entity->kind == ENTITY_PARAMETER) {
4325 prev_decl->type = decl->type;
4326 prev_decl->storage_class = decl->storage_class;
4327 prev_decl->declared_storage_class = decl->declared_storage_class;
4328 prev_decl->modifiers = decl->modifiers;
4329 return previous_entity;
4332 type_t *const orig_type = decl->type;
4333 assert(orig_type != NULL);
4334 type_t *const type = skip_typeref(orig_type);
4335 type_t *const prev_type = skip_typeref(prev_decl->type);
4337 if (!types_compatible(type, prev_type)) {
4339 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4340 orig_type, symbol, prev_decl->type, symbol,
4341 &previous_entity->base.source_position);
4343 unsigned old_storage_class = prev_decl->storage_class;
4345 if (warning.redundant_decls &&
4348 !(prev_decl->modifiers & DM_USED) &&
4349 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4350 warningf(&previous_entity->base.source_position,
4351 "unnecessary static forward declaration for '%#T'",
4352 prev_decl->type, symbol);
4355 storage_class_t new_storage_class = decl->storage_class;
4357 /* pretend no storage class means extern for function
4358 * declarations (except if the previous declaration is neither
4359 * none nor extern) */
4360 if (entity->kind == ENTITY_FUNCTION) {
4361 /* the previous declaration could have unspecified parameters or
4362 * be a typedef, so use the new type */
4363 if (prev_type->function.unspecified_parameters || is_definition)
4364 prev_decl->type = type;
4366 switch (old_storage_class) {
4367 case STORAGE_CLASS_NONE:
4368 old_storage_class = STORAGE_CLASS_EXTERN;
4371 case STORAGE_CLASS_EXTERN:
4372 if (is_definition) {
4373 if (warning.missing_prototypes &&
4374 prev_type->function.unspecified_parameters &&
4375 !is_sym_main(symbol)) {
4376 warningf(pos, "no previous prototype for '%#T'",
4379 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4380 new_storage_class = STORAGE_CLASS_EXTERN;
4387 } else if (is_type_incomplete(prev_type)) {
4388 prev_decl->type = type;
4391 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4392 new_storage_class == STORAGE_CLASS_EXTERN) {
4394 warn_redundant_declaration: ;
4396 = has_new_attributes(prev_decl->attributes,
4398 if (has_new_attrs) {
4399 merge_in_attributes(decl, prev_decl->attributes);
4400 } else if (!is_definition &&
4401 warning.redundant_decls &&
4402 is_type_valid(prev_type) &&
4403 strcmp(previous_entity->base.source_position.input_name,
4404 "<builtin>") != 0) {
4406 "redundant declaration for '%Y' (declared %P)",
4407 symbol, &previous_entity->base.source_position);
4409 } else if (current_function == NULL) {
4410 if (old_storage_class != STORAGE_CLASS_STATIC &&
4411 new_storage_class == STORAGE_CLASS_STATIC) {
4413 "static declaration of '%Y' follows non-static declaration (declared %P)",
4414 symbol, &previous_entity->base.source_position);
4415 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4416 prev_decl->storage_class = STORAGE_CLASS_NONE;
4417 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4419 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4421 goto error_redeclaration;
4422 goto warn_redundant_declaration;
4424 } else if (is_type_valid(prev_type)) {
4425 if (old_storage_class == new_storage_class) {
4426 error_redeclaration:
4427 errorf(pos, "redeclaration of '%Y' (declared %P)",
4428 symbol, &previous_entity->base.source_position);
4431 "redeclaration of '%Y' with different linkage (declared %P)",
4432 symbol, &previous_entity->base.source_position);
4437 prev_decl->modifiers |= decl->modifiers;
4438 if (entity->kind == ENTITY_FUNCTION) {
4439 previous_entity->function.is_inline |= entity->function.is_inline;
4441 return previous_entity;
4444 if (warning.shadow) {
4445 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4446 get_entity_kind_name(entity->kind), symbol,
4447 get_entity_kind_name(previous_entity->kind),
4448 &previous_entity->base.source_position);
4452 if (entity->kind == ENTITY_FUNCTION) {
4453 if (is_definition &&
4454 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4455 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4456 warningf(pos, "no previous prototype for '%#T'",
4457 entity->declaration.type, symbol);
4458 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4459 warningf(pos, "no previous declaration for '%#T'",
4460 entity->declaration.type, symbol);
4463 } else if (warning.missing_declarations &&
4464 entity->kind == ENTITY_VARIABLE &&
4465 current_scope == file_scope) {
4466 declaration_t *declaration = &entity->declaration;
4467 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4468 warningf(pos, "no previous declaration for '%#T'",
4469 declaration->type, symbol);
4474 assert(entity->base.parent_scope == NULL);
4475 assert(current_scope != NULL);
4477 entity->base.parent_scope = current_scope;
4478 entity->base.namespc = NAMESPACE_NORMAL;
4479 environment_push(entity);
4480 append_entity(current_scope, entity);
4485 static void parser_error_multiple_definition(entity_t *entity,
4486 const source_position_t *source_position)
4488 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4489 entity->base.symbol, &entity->base.source_position);
4492 static bool is_declaration_specifier(const token_t *token,
4493 bool only_specifiers_qualifiers)
4495 switch (token->type) {
4500 return is_typedef_symbol(token->v.symbol);
4502 case T___extension__:
4504 return !only_specifiers_qualifiers;
4511 static void parse_init_declarator_rest(entity_t *entity)
4513 assert(is_declaration(entity));
4514 declaration_t *const declaration = &entity->declaration;
4518 type_t *orig_type = declaration->type;
4519 type_t *type = skip_typeref(orig_type);
4521 if (entity->kind == ENTITY_VARIABLE
4522 && entity->variable.initializer != NULL) {
4523 parser_error_multiple_definition(entity, HERE);
4526 bool must_be_constant = false;
4527 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4528 entity->base.parent_scope == file_scope) {
4529 must_be_constant = true;
4532 if (is_type_function(type)) {
4533 errorf(&entity->base.source_position,
4534 "function '%#T' is initialized like a variable",
4535 orig_type, entity->base.symbol);
4536 orig_type = type_error_type;
4539 parse_initializer_env_t env;
4540 env.type = orig_type;
4541 env.must_be_constant = must_be_constant;
4542 env.entity = entity;
4543 current_init_decl = entity;
4545 initializer_t *initializer = parse_initializer(&env);
4546 current_init_decl = NULL;
4548 if (entity->kind == ENTITY_VARIABLE) {
4549 /* §6.7.5:22 array initializers for arrays with unknown size
4550 * determine the array type size */
4551 declaration->type = env.type;
4552 entity->variable.initializer = initializer;
4556 /* parse rest of a declaration without any declarator */
4557 static void parse_anonymous_declaration_rest(
4558 const declaration_specifiers_t *specifiers)
4561 anonymous_entity = NULL;
4563 if (warning.other) {
4564 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4565 specifiers->thread_local) {
4566 warningf(&specifiers->source_position,
4567 "useless storage class in empty declaration");
4570 type_t *type = specifiers->type;
4571 switch (type->kind) {
4572 case TYPE_COMPOUND_STRUCT:
4573 case TYPE_COMPOUND_UNION: {
4574 if (type->compound.compound->base.symbol == NULL) {
4575 warningf(&specifiers->source_position,
4576 "unnamed struct/union that defines no instances");
4585 warningf(&specifiers->source_position, "empty declaration");
4591 static void check_variable_type_complete(entity_t *ent)
4593 if (ent->kind != ENTITY_VARIABLE)
4596 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4597 * type for the object shall be complete [...] */
4598 declaration_t *decl = &ent->declaration;
4599 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4600 decl->storage_class == STORAGE_CLASS_STATIC)
4603 type_t *const orig_type = decl->type;
4604 type_t *const type = skip_typeref(orig_type);
4605 if (!is_type_incomplete(type))
4608 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4609 * are given length one. */
4610 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4611 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4615 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4616 orig_type, ent->base.symbol);
4620 static void parse_declaration_rest(entity_t *ndeclaration,
4621 const declaration_specifiers_t *specifiers,
4622 parsed_declaration_func finished_declaration,
4623 declarator_flags_t flags)
4625 add_anchor_token(';');
4626 add_anchor_token(',');
4628 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4630 if (token.type == '=') {
4631 parse_init_declarator_rest(entity);
4632 } else if (entity->kind == ENTITY_VARIABLE) {
4633 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4634 * [...] where the extern specifier is explicitly used. */
4635 declaration_t *decl = &entity->declaration;
4636 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4637 type_t *type = decl->type;
4638 if (is_type_reference(skip_typeref(type))) {
4639 errorf(&entity->base.source_position,
4640 "reference '%#T' must be initialized",
4641 type, entity->base.symbol);
4646 check_variable_type_complete(entity);
4651 add_anchor_token('=');
4652 ndeclaration = parse_declarator(specifiers, flags);
4653 rem_anchor_token('=');
4655 expect(';', end_error);
4658 anonymous_entity = NULL;
4659 rem_anchor_token(';');
4660 rem_anchor_token(',');
4663 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4665 symbol_t *symbol = entity->base.symbol;
4666 if (symbol == NULL) {
4667 errorf(HERE, "anonymous declaration not valid as function parameter");
4671 assert(entity->base.namespc == NAMESPACE_NORMAL);
4672 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4673 if (previous_entity == NULL
4674 || previous_entity->base.parent_scope != current_scope) {
4675 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4680 if (is_definition) {
4681 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4684 return record_entity(entity, false);
4687 static void parse_declaration(parsed_declaration_func finished_declaration,
4688 declarator_flags_t flags)
4690 declaration_specifiers_t specifiers;
4691 memset(&specifiers, 0, sizeof(specifiers));
4693 add_anchor_token(';');
4694 parse_declaration_specifiers(&specifiers);
4695 rem_anchor_token(';');
4697 if (token.type == ';') {
4698 parse_anonymous_declaration_rest(&specifiers);
4700 entity_t *entity = parse_declarator(&specifiers, flags);
4701 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4706 static type_t *get_default_promoted_type(type_t *orig_type)
4708 type_t *result = orig_type;
4710 type_t *type = skip_typeref(orig_type);
4711 if (is_type_integer(type)) {
4712 result = promote_integer(type);
4713 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4714 result = type_double;
4720 static void parse_kr_declaration_list(entity_t *entity)
4722 if (entity->kind != ENTITY_FUNCTION)
4725 type_t *type = skip_typeref(entity->declaration.type);
4726 assert(is_type_function(type));
4727 if (!type->function.kr_style_parameters)
4730 add_anchor_token('{');
4732 /* push function parameters */
4733 size_t const top = environment_top();
4734 scope_t *old_scope = scope_push(&entity->function.parameters);
4736 entity_t *parameter = entity->function.parameters.entities;
4737 for ( ; parameter != NULL; parameter = parameter->base.next) {
4738 assert(parameter->base.parent_scope == NULL);
4739 parameter->base.parent_scope = current_scope;
4740 environment_push(parameter);
4743 /* parse declaration list */
4745 switch (token.type) {
4747 case T___extension__:
4748 /* This covers symbols, which are no type, too, and results in
4749 * better error messages. The typical cases are misspelled type
4750 * names and missing includes. */
4752 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4760 /* pop function parameters */
4761 assert(current_scope == &entity->function.parameters);
4762 scope_pop(old_scope);
4763 environment_pop_to(top);
4765 /* update function type */
4766 type_t *new_type = duplicate_type(type);
4768 function_parameter_t *parameters = NULL;
4769 function_parameter_t **anchor = ¶meters;
4771 /* did we have an earlier prototype? */
4772 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4773 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4776 function_parameter_t *proto_parameter = NULL;
4777 if (proto_type != NULL) {
4778 type_t *proto_type_type = proto_type->declaration.type;
4779 proto_parameter = proto_type_type->function.parameters;
4780 /* If a K&R function definition has a variadic prototype earlier, then
4781 * make the function definition variadic, too. This should conform to
4782 * §6.7.5.3:15 and §6.9.1:8. */
4783 new_type->function.variadic = proto_type_type->function.variadic;
4785 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4787 new_type->function.unspecified_parameters = true;
4790 bool need_incompatible_warning = false;
4791 parameter = entity->function.parameters.entities;
4792 for (; parameter != NULL; parameter = parameter->base.next,
4794 proto_parameter == NULL ? NULL : proto_parameter->next) {
4795 if (parameter->kind != ENTITY_PARAMETER)
4798 type_t *parameter_type = parameter->declaration.type;
4799 if (parameter_type == NULL) {
4801 errorf(HERE, "no type specified for function parameter '%Y'",
4802 parameter->base.symbol);
4803 parameter_type = type_error_type;
4805 if (warning.implicit_int) {
4806 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4807 parameter->base.symbol);
4809 parameter_type = type_int;
4811 parameter->declaration.type = parameter_type;
4814 semantic_parameter_incomplete(parameter);
4816 /* we need the default promoted types for the function type */
4817 type_t *not_promoted = parameter_type;
4818 parameter_type = get_default_promoted_type(parameter_type);
4820 /* gcc special: if the type of the prototype matches the unpromoted
4821 * type don't promote */
4822 if (!strict_mode && proto_parameter != NULL) {
4823 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4824 type_t *promo_skip = skip_typeref(parameter_type);
4825 type_t *param_skip = skip_typeref(not_promoted);
4826 if (!types_compatible(proto_p_type, promo_skip)
4827 && types_compatible(proto_p_type, param_skip)) {
4829 need_incompatible_warning = true;
4830 parameter_type = not_promoted;
4833 function_parameter_t *const parameter
4834 = allocate_parameter(parameter_type);
4836 *anchor = parameter;
4837 anchor = ¶meter->next;
4840 new_type->function.parameters = parameters;
4841 new_type = identify_new_type(new_type);
4843 if (warning.other && need_incompatible_warning) {
4844 type_t *proto_type_type = proto_type->declaration.type;
4846 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4847 proto_type_type, proto_type->base.symbol,
4848 new_type, entity->base.symbol,
4849 &proto_type->base.source_position);
4852 entity->declaration.type = new_type;
4854 rem_anchor_token('{');
4857 static bool first_err = true;
4860 * When called with first_err set, prints the name of the current function,
4863 static void print_in_function(void)
4867 diagnosticf("%s: In function '%Y':\n",
4868 current_function->base.base.source_position.input_name,
4869 current_function->base.base.symbol);
4874 * Check if all labels are defined in the current function.
4875 * Check if all labels are used in the current function.
4877 static void check_labels(void)
4879 for (const goto_statement_t *goto_statement = goto_first;
4880 goto_statement != NULL;
4881 goto_statement = goto_statement->next) {
4882 /* skip computed gotos */
4883 if (goto_statement->expression != NULL)
4886 label_t *label = goto_statement->label;
4889 if (label->base.source_position.input_name == NULL) {
4890 print_in_function();
4891 errorf(&goto_statement->base.source_position,
4892 "label '%Y' used but not defined", label->base.symbol);
4896 if (warning.unused_label) {
4897 for (const label_statement_t *label_statement = label_first;
4898 label_statement != NULL;
4899 label_statement = label_statement->next) {
4900 label_t *label = label_statement->label;
4902 if (! label->used) {
4903 print_in_function();
4904 warningf(&label_statement->base.source_position,
4905 "label '%Y' defined but not used", label->base.symbol);
4911 static void warn_unused_entity(entity_t *entity, entity_t *last)
4913 entity_t const *const end = last != NULL ? last->base.next : NULL;
4914 for (; entity != end; entity = entity->base.next) {
4915 if (!is_declaration(entity))
4918 declaration_t *declaration = &entity->declaration;
4919 if (declaration->implicit)
4922 if (!declaration->used) {
4923 print_in_function();
4924 const char *what = get_entity_kind_name(entity->kind);
4925 warningf(&entity->base.source_position, "%s '%Y' is unused",
4926 what, entity->base.symbol);
4927 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4928 print_in_function();
4929 const char *what = get_entity_kind_name(entity->kind);
4930 warningf(&entity->base.source_position, "%s '%Y' is never read",
4931 what, entity->base.symbol);
4936 static void check_unused_variables(statement_t *const stmt, void *const env)
4940 switch (stmt->kind) {
4941 case STATEMENT_DECLARATION: {
4942 declaration_statement_t const *const decls = &stmt->declaration;
4943 warn_unused_entity(decls->declarations_begin,
4944 decls->declarations_end);
4949 warn_unused_entity(stmt->fors.scope.entities, NULL);
4958 * Check declarations of current_function for unused entities.
4960 static void check_declarations(void)
4962 if (warning.unused_parameter) {
4963 const scope_t *scope = ¤t_function->parameters;
4965 /* do not issue unused warnings for main */
4966 if (!is_sym_main(current_function->base.base.symbol)) {
4967 warn_unused_entity(scope->entities, NULL);
4970 if (warning.unused_variable) {
4971 walk_statements(current_function->statement, check_unused_variables,
4976 static int determine_truth(expression_t const* const cond)
4979 !is_constant_expression(cond) ? 0 :
4980 fold_constant_to_bool(cond) ? 1 :
4984 static void check_reachable(statement_t *);
4985 static bool reaches_end;
4987 static bool expression_returns(expression_t const *const expr)
4989 switch (expr->kind) {
4991 expression_t const *const func = expr->call.function;
4992 if (func->kind == EXPR_REFERENCE) {
4993 entity_t *entity = func->reference.entity;
4994 if (entity->kind == ENTITY_FUNCTION
4995 && entity->declaration.modifiers & DM_NORETURN)
4999 if (!expression_returns(func))
5002 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5003 if (!expression_returns(arg->expression))
5010 case EXPR_REFERENCE:
5011 case EXPR_REFERENCE_ENUM_VALUE:
5013 case EXPR_CHARACTER_CONSTANT:
5014 case EXPR_WIDE_CHARACTER_CONSTANT:
5015 case EXPR_STRING_LITERAL:
5016 case EXPR_WIDE_STRING_LITERAL:
5017 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5018 case EXPR_LABEL_ADDRESS:
5019 case EXPR_CLASSIFY_TYPE:
5020 case EXPR_SIZEOF: // TODO handle obscure VLA case
5023 case EXPR_BUILTIN_CONSTANT_P:
5024 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5029 case EXPR_STATEMENT: {
5030 bool old_reaches_end = reaches_end;
5031 reaches_end = false;
5032 check_reachable(expr->statement.statement);
5033 bool returns = reaches_end;
5034 reaches_end = old_reaches_end;
5038 case EXPR_CONDITIONAL:
5039 // TODO handle constant expression
5041 if (!expression_returns(expr->conditional.condition))
5044 if (expr->conditional.true_expression != NULL
5045 && expression_returns(expr->conditional.true_expression))
5048 return expression_returns(expr->conditional.false_expression);
5051 return expression_returns(expr->select.compound);
5053 case EXPR_ARRAY_ACCESS:
5055 expression_returns(expr->array_access.array_ref) &&
5056 expression_returns(expr->array_access.index);
5059 return expression_returns(expr->va_starte.ap);
5062 return expression_returns(expr->va_arge.ap);
5065 return expression_returns(expr->va_copye.src);
5067 EXPR_UNARY_CASES_MANDATORY
5068 return expression_returns(expr->unary.value);
5070 case EXPR_UNARY_THROW:
5074 // TODO handle constant lhs of && and ||
5076 expression_returns(expr->binary.left) &&
5077 expression_returns(expr->binary.right);
5083 panic("unhandled expression");
5086 static bool initializer_returns(initializer_t const *const init)
5088 switch (init->kind) {
5089 case INITIALIZER_VALUE:
5090 return expression_returns(init->value.value);
5092 case INITIALIZER_LIST: {
5093 initializer_t * const* i = init->list.initializers;
5094 initializer_t * const* const end = i + init->list.len;
5095 bool returns = true;
5096 for (; i != end; ++i) {
5097 if (!initializer_returns(*i))
5103 case INITIALIZER_STRING:
5104 case INITIALIZER_WIDE_STRING:
5105 case INITIALIZER_DESIGNATOR: // designators have no payload
5108 panic("unhandled initializer");
5111 static bool noreturn_candidate;
5113 static void check_reachable(statement_t *const stmt)
5115 if (stmt->base.reachable)
5117 if (stmt->kind != STATEMENT_DO_WHILE)
5118 stmt->base.reachable = true;
5120 statement_t *last = stmt;
5122 switch (stmt->kind) {
5123 case STATEMENT_INVALID:
5124 case STATEMENT_EMPTY:
5126 next = stmt->base.next;
5129 case STATEMENT_DECLARATION: {
5130 declaration_statement_t const *const decl = &stmt->declaration;
5131 entity_t const * ent = decl->declarations_begin;
5132 entity_t const *const last = decl->declarations_end;
5134 for (;; ent = ent->base.next) {
5135 if (ent->kind == ENTITY_VARIABLE &&
5136 ent->variable.initializer != NULL &&
5137 !initializer_returns(ent->variable.initializer)) {
5144 next = stmt->base.next;
5148 case STATEMENT_COMPOUND:
5149 next = stmt->compound.statements;
5151 next = stmt->base.next;
5154 case STATEMENT_RETURN: {
5155 expression_t const *const val = stmt->returns.value;
5156 if (val == NULL || expression_returns(val))
5157 noreturn_candidate = false;
5161 case STATEMENT_IF: {
5162 if_statement_t const *const ifs = &stmt->ifs;
5163 expression_t const *const cond = ifs->condition;
5165 if (!expression_returns(cond))
5168 int const val = determine_truth(cond);
5171 check_reachable(ifs->true_statement);
5176 if (ifs->false_statement != NULL) {
5177 check_reachable(ifs->false_statement);
5181 next = stmt->base.next;
5185 case STATEMENT_SWITCH: {
5186 switch_statement_t const *const switchs = &stmt->switchs;
5187 expression_t const *const expr = switchs->expression;
5189 if (!expression_returns(expr))
5192 if (is_constant_expression(expr)) {
5193 long const val = fold_constant_to_int(expr);
5194 case_label_statement_t * defaults = NULL;
5195 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5196 if (i->expression == NULL) {
5201 if (i->first_case <= val && val <= i->last_case) {
5202 check_reachable((statement_t*)i);
5207 if (defaults != NULL) {
5208 check_reachable((statement_t*)defaults);
5212 bool has_default = false;
5213 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5214 if (i->expression == NULL)
5217 check_reachable((statement_t*)i);
5224 next = stmt->base.next;
5228 case STATEMENT_EXPRESSION: {
5229 /* Check for noreturn function call */
5230 expression_t const *const expr = stmt->expression.expression;
5231 if (!expression_returns(expr))
5234 next = stmt->base.next;
5238 case STATEMENT_CONTINUE:
5239 for (statement_t *parent = stmt;;) {
5240 parent = parent->base.parent;
5241 if (parent == NULL) /* continue not within loop */
5245 switch (parent->kind) {
5246 case STATEMENT_WHILE: goto continue_while;
5247 case STATEMENT_DO_WHILE: goto continue_do_while;
5248 case STATEMENT_FOR: goto continue_for;
5254 case STATEMENT_BREAK:
5255 for (statement_t *parent = stmt;;) {
5256 parent = parent->base.parent;
5257 if (parent == NULL) /* break not within loop/switch */
5260 switch (parent->kind) {
5261 case STATEMENT_SWITCH:
5262 case STATEMENT_WHILE:
5263 case STATEMENT_DO_WHILE:
5266 next = parent->base.next;
5267 goto found_break_parent;
5275 case STATEMENT_GOTO:
5276 if (stmt->gotos.expression) {
5277 if (!expression_returns(stmt->gotos.expression))
5280 statement_t *parent = stmt->base.parent;
5281 if (parent == NULL) /* top level goto */
5285 next = stmt->gotos.label->statement;
5286 if (next == NULL) /* missing label */
5291 case STATEMENT_LABEL:
5292 next = stmt->label.statement;
5295 case STATEMENT_CASE_LABEL:
5296 next = stmt->case_label.statement;
5299 case STATEMENT_WHILE: {
5300 while_statement_t const *const whiles = &stmt->whiles;
5301 expression_t const *const cond = whiles->condition;
5303 if (!expression_returns(cond))
5306 int const val = determine_truth(cond);
5309 check_reachable(whiles->body);
5314 next = stmt->base.next;
5318 case STATEMENT_DO_WHILE:
5319 next = stmt->do_while.body;
5322 case STATEMENT_FOR: {
5323 for_statement_t *const fors = &stmt->fors;
5325 if (fors->condition_reachable)
5327 fors->condition_reachable = true;
5329 expression_t const *const cond = fors->condition;
5334 } else if (expression_returns(cond)) {
5335 val = determine_truth(cond);
5341 check_reachable(fors->body);
5346 next = stmt->base.next;
5350 case STATEMENT_MS_TRY: {
5351 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5352 check_reachable(ms_try->try_statement);
5353 next = ms_try->final_statement;
5357 case STATEMENT_LEAVE: {
5358 statement_t *parent = stmt;
5360 parent = parent->base.parent;
5361 if (parent == NULL) /* __leave not within __try */
5364 if (parent->kind == STATEMENT_MS_TRY) {
5366 next = parent->ms_try.final_statement;
5374 panic("invalid statement kind");
5377 while (next == NULL) {
5378 next = last->base.parent;
5380 noreturn_candidate = false;
5382 type_t *const type = skip_typeref(current_function->base.type);
5383 assert(is_type_function(type));
5384 type_t *const ret = skip_typeref(type->function.return_type);
5385 if (warning.return_type &&
5386 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5387 is_type_valid(ret) &&
5388 !is_sym_main(current_function->base.base.symbol)) {
5389 warningf(&stmt->base.source_position,
5390 "control reaches end of non-void function");
5395 switch (next->kind) {
5396 case STATEMENT_INVALID:
5397 case STATEMENT_EMPTY:
5398 case STATEMENT_DECLARATION:
5399 case STATEMENT_EXPRESSION:
5401 case STATEMENT_RETURN:
5402 case STATEMENT_CONTINUE:
5403 case STATEMENT_BREAK:
5404 case STATEMENT_GOTO:
5405 case STATEMENT_LEAVE:
5406 panic("invalid control flow in function");
5408 case STATEMENT_COMPOUND:
5409 if (next->compound.stmt_expr) {
5415 case STATEMENT_SWITCH:
5416 case STATEMENT_LABEL:
5417 case STATEMENT_CASE_LABEL:
5419 next = next->base.next;
5422 case STATEMENT_WHILE: {
5424 if (next->base.reachable)
5426 next->base.reachable = true;
5428 while_statement_t const *const whiles = &next->whiles;
5429 expression_t const *const cond = whiles->condition;
5431 if (!expression_returns(cond))
5434 int const val = determine_truth(cond);
5437 check_reachable(whiles->body);
5443 next = next->base.next;
5447 case STATEMENT_DO_WHILE: {
5449 if (next->base.reachable)
5451 next->base.reachable = true;
5453 do_while_statement_t const *const dw = &next->do_while;
5454 expression_t const *const cond = dw->condition;
5456 if (!expression_returns(cond))
5459 int const val = determine_truth(cond);
5462 check_reachable(dw->body);
5468 next = next->base.next;
5472 case STATEMENT_FOR: {
5474 for_statement_t *const fors = &next->fors;
5476 fors->step_reachable = true;
5478 if (fors->condition_reachable)
5480 fors->condition_reachable = true;
5482 expression_t const *const cond = fors->condition;
5487 } else if (expression_returns(cond)) {
5488 val = determine_truth(cond);
5494 check_reachable(fors->body);
5500 next = next->base.next;
5504 case STATEMENT_MS_TRY:
5506 next = next->ms_try.final_statement;
5511 check_reachable(next);
5514 static void check_unreachable(statement_t* const stmt, void *const env)
5518 switch (stmt->kind) {
5519 case STATEMENT_DO_WHILE:
5520 if (!stmt->base.reachable) {
5521 expression_t const *const cond = stmt->do_while.condition;
5522 if (determine_truth(cond) >= 0) {
5523 warningf(&cond->base.source_position,
5524 "condition of do-while-loop is unreachable");
5529 case STATEMENT_FOR: {
5530 for_statement_t const* const fors = &stmt->fors;
5532 // if init and step are unreachable, cond is unreachable, too
5533 if (!stmt->base.reachable && !fors->step_reachable) {
5534 warningf(&stmt->base.source_position, "statement is unreachable");
5536 if (!stmt->base.reachable && fors->initialisation != NULL) {
5537 warningf(&fors->initialisation->base.source_position,
5538 "initialisation of for-statement is unreachable");
5541 if (!fors->condition_reachable && fors->condition != NULL) {
5542 warningf(&fors->condition->base.source_position,
5543 "condition of for-statement is unreachable");
5546 if (!fors->step_reachable && fors->step != NULL) {
5547 warningf(&fors->step->base.source_position,
5548 "step of for-statement is unreachable");
5554 case STATEMENT_COMPOUND:
5555 if (stmt->compound.statements != NULL)
5557 goto warn_unreachable;
5559 case STATEMENT_DECLARATION: {
5560 /* Only warn if there is at least one declarator with an initializer.
5561 * This typically occurs in switch statements. */
5562 declaration_statement_t const *const decl = &stmt->declaration;
5563 entity_t const * ent = decl->declarations_begin;
5564 entity_t const *const last = decl->declarations_end;
5566 for (;; ent = ent->base.next) {
5567 if (ent->kind == ENTITY_VARIABLE &&
5568 ent->variable.initializer != NULL) {
5569 goto warn_unreachable;
5579 if (!stmt->base.reachable)
5580 warningf(&stmt->base.source_position, "statement is unreachable");
5585 static void parse_external_declaration(void)
5587 /* function-definitions and declarations both start with declaration
5589 declaration_specifiers_t specifiers;
5590 memset(&specifiers, 0, sizeof(specifiers));
5592 add_anchor_token(';');
5593 parse_declaration_specifiers(&specifiers);
5594 rem_anchor_token(';');
5596 /* must be a declaration */
5597 if (token.type == ';') {
5598 parse_anonymous_declaration_rest(&specifiers);
5602 add_anchor_token(',');
5603 add_anchor_token('=');
5604 add_anchor_token(';');
5605 add_anchor_token('{');
5607 /* declarator is common to both function-definitions and declarations */
5608 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5610 rem_anchor_token('{');
5611 rem_anchor_token(';');
5612 rem_anchor_token('=');
5613 rem_anchor_token(',');
5615 /* must be a declaration */
5616 switch (token.type) {
5620 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5625 /* must be a function definition */
5626 parse_kr_declaration_list(ndeclaration);
5628 if (token.type != '{') {
5629 parse_error_expected("while parsing function definition", '{', NULL);
5630 eat_until_matching_token(';');
5634 assert(is_declaration(ndeclaration));
5635 type_t *const orig_type = ndeclaration->declaration.type;
5636 type_t * type = skip_typeref(orig_type);
5638 if (!is_type_function(type)) {
5639 if (is_type_valid(type)) {
5640 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5641 type, ndeclaration->base.symbol);
5645 } else if (is_typeref(orig_type)) {
5647 errorf(&ndeclaration->base.source_position,
5648 "type of function definition '%#T' is a typedef",
5649 orig_type, ndeclaration->base.symbol);
5652 if (warning.aggregate_return &&
5653 is_type_compound(skip_typeref(type->function.return_type))) {
5654 warningf(HERE, "function '%Y' returns an aggregate",
5655 ndeclaration->base.symbol);
5657 if (warning.traditional && !type->function.unspecified_parameters) {
5658 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5659 ndeclaration->base.symbol);
5661 if (warning.old_style_definition && type->function.unspecified_parameters) {
5662 warningf(HERE, "old-style function definition '%Y'",
5663 ndeclaration->base.symbol);
5666 /* §6.7.5.3:14 a function definition with () means no
5667 * parameters (and not unspecified parameters) */
5668 if (type->function.unspecified_parameters &&
5669 type->function.parameters == NULL) {
5670 type_t *copy = duplicate_type(type);
5671 copy->function.unspecified_parameters = false;
5672 type = identify_new_type(copy);
5674 ndeclaration->declaration.type = type;
5677 entity_t *const entity = record_entity(ndeclaration, true);
5678 assert(entity->kind == ENTITY_FUNCTION);
5679 assert(ndeclaration->kind == ENTITY_FUNCTION);
5681 function_t *function = &entity->function;
5682 if (ndeclaration != entity) {
5683 function->parameters = ndeclaration->function.parameters;
5685 assert(is_declaration(entity));
5686 type = skip_typeref(entity->declaration.type);
5688 /* push function parameters and switch scope */
5689 size_t const top = environment_top();
5690 scope_t *old_scope = scope_push(&function->parameters);
5692 entity_t *parameter = function->parameters.entities;
5693 for (; parameter != NULL; parameter = parameter->base.next) {
5694 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5695 parameter->base.parent_scope = current_scope;
5697 assert(parameter->base.parent_scope == NULL
5698 || parameter->base.parent_scope == current_scope);
5699 parameter->base.parent_scope = current_scope;
5700 if (parameter->base.symbol == NULL) {
5701 errorf(¶meter->base.source_position, "parameter name omitted");
5704 environment_push(parameter);
5707 if (function->statement != NULL) {
5708 parser_error_multiple_definition(entity, HERE);
5711 /* parse function body */
5712 int label_stack_top = label_top();
5713 function_t *old_current_function = current_function;
5714 current_function = function;
5715 current_parent = NULL;
5718 goto_anchor = &goto_first;
5720 label_anchor = &label_first;
5722 statement_t *const body = parse_compound_statement(false);
5723 function->statement = body;
5726 check_declarations();
5727 if (warning.return_type ||
5728 warning.unreachable_code ||
5729 (warning.missing_noreturn
5730 && !(function->base.modifiers & DM_NORETURN))) {
5731 noreturn_candidate = true;
5732 check_reachable(body);
5733 if (warning.unreachable_code)
5734 walk_statements(body, check_unreachable, NULL);
5735 if (warning.missing_noreturn &&
5736 noreturn_candidate &&
5737 !(function->base.modifiers & DM_NORETURN)) {
5738 warningf(&body->base.source_position,
5739 "function '%#T' is candidate for attribute 'noreturn'",
5740 type, entity->base.symbol);
5744 assert(current_parent == NULL);
5745 assert(current_function == function);
5746 current_function = old_current_function;
5747 label_pop_to(label_stack_top);
5750 assert(current_scope == &function->parameters);
5751 scope_pop(old_scope);
5752 environment_pop_to(top);
5755 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5756 source_position_t *source_position,
5757 const symbol_t *symbol)
5759 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5761 type->bitfield.base_type = base_type;
5762 type->bitfield.size_expression = size;
5765 type_t *skipped_type = skip_typeref(base_type);
5766 if (!is_type_integer(skipped_type)) {
5767 errorf(HERE, "bitfield base type '%T' is not an integer type",
5771 bit_size = get_type_size(base_type) * 8;
5774 if (is_constant_expression(size)) {
5775 long v = fold_constant_to_int(size);
5776 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5779 errorf(source_position, "negative width in bit-field '%Y'",
5781 } else if (v == 0 && symbol != NULL) {
5782 errorf(source_position, "zero width for bit-field '%Y'",
5784 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5785 errorf(source_position, "width of '%Y' exceeds its type",
5788 type->bitfield.bit_size = v;
5795 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5797 entity_t *iter = compound->members.entities;
5798 for (; iter != NULL; iter = iter->base.next) {
5799 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5802 if (iter->base.symbol == symbol) {
5804 } else if (iter->base.symbol == NULL) {
5805 /* search in anonymous structs and unions */
5806 type_t *type = skip_typeref(iter->declaration.type);
5807 if (is_type_compound(type)) {
5808 if (find_compound_entry(type->compound.compound, symbol)
5819 static void check_deprecated(const source_position_t *source_position,
5820 const entity_t *entity)
5822 if (!warning.deprecated_declarations)
5824 if (!is_declaration(entity))
5826 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5829 char const *const prefix = get_entity_kind_name(entity->kind);
5830 const char *deprecated_string
5831 = get_deprecated_string(entity->declaration.attributes);
5832 if (deprecated_string != NULL) {
5833 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5834 prefix, entity->base.symbol, &entity->base.source_position,
5837 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5838 entity->base.symbol, &entity->base.source_position);
5843 static expression_t *create_select(const source_position_t *pos,
5845 type_qualifiers_t qualifiers,
5848 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5850 check_deprecated(pos, entry);
5852 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5853 select->select.compound = addr;
5854 select->select.compound_entry = entry;
5856 type_t *entry_type = entry->declaration.type;
5857 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5859 /* we always do the auto-type conversions; the & and sizeof parser contains
5860 * code to revert this! */
5861 select->base.type = automatic_type_conversion(res_type);
5862 if (res_type->kind == TYPE_BITFIELD) {
5863 select->base.type = res_type->bitfield.base_type;
5870 * Find entry with symbol in compound. Search anonymous structs and unions and
5871 * creates implicit select expressions for them.
5872 * Returns the adress for the innermost compound.
5874 static expression_t *find_create_select(const source_position_t *pos,
5876 type_qualifiers_t qualifiers,
5877 compound_t *compound, symbol_t *symbol)
5879 entity_t *iter = compound->members.entities;
5880 for (; iter != NULL; iter = iter->base.next) {
5881 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5884 symbol_t *iter_symbol = iter->base.symbol;
5885 if (iter_symbol == NULL) {
5886 type_t *type = iter->declaration.type;
5887 if (type->kind != TYPE_COMPOUND_STRUCT
5888 && type->kind != TYPE_COMPOUND_UNION)
5891 compound_t *sub_compound = type->compound.compound;
5893 if (find_compound_entry(sub_compound, symbol) == NULL)
5896 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5897 sub_addr->base.source_position = *pos;
5898 sub_addr->select.implicit = true;
5899 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5903 if (iter_symbol == symbol) {
5904 return create_select(pos, addr, qualifiers, iter);
5911 static void parse_compound_declarators(compound_t *compound,
5912 const declaration_specifiers_t *specifiers)
5917 if (token.type == ':') {
5918 source_position_t source_position = *HERE;
5921 type_t *base_type = specifiers->type;
5922 expression_t *size = parse_constant_expression();
5924 type_t *type = make_bitfield_type(base_type, size,
5925 &source_position, NULL);
5927 attribute_t *attributes = parse_attributes(NULL);
5928 attribute_t **anchor = &attributes;
5929 while (*anchor != NULL)
5930 anchor = &(*anchor)->next;
5931 *anchor = specifiers->attributes;
5933 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5934 entity->base.namespc = NAMESPACE_NORMAL;
5935 entity->base.source_position = source_position;
5936 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5937 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5938 entity->declaration.type = type;
5939 entity->declaration.attributes = attributes;
5941 if (attributes != NULL) {
5942 handle_entity_attributes(attributes, entity);
5944 append_entity(&compound->members, entity);
5946 entity = parse_declarator(specifiers,
5947 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5948 if (entity->kind == ENTITY_TYPEDEF) {
5949 errorf(&entity->base.source_position,
5950 "typedef not allowed as compound member");
5952 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5954 /* make sure we don't define a symbol multiple times */
5955 symbol_t *symbol = entity->base.symbol;
5956 if (symbol != NULL) {
5957 entity_t *prev = find_compound_entry(compound, symbol);
5959 errorf(&entity->base.source_position,
5960 "multiple declarations of symbol '%Y' (declared %P)",
5961 symbol, &prev->base.source_position);
5965 if (token.type == ':') {
5966 source_position_t source_position = *HERE;
5968 expression_t *size = parse_constant_expression();
5970 type_t *type = entity->declaration.type;
5971 type_t *bitfield_type = make_bitfield_type(type, size,
5972 &source_position, entity->base.symbol);
5974 attribute_t *attributes = parse_attributes(NULL);
5975 entity->declaration.type = bitfield_type;
5976 handle_entity_attributes(attributes, entity);
5978 type_t *orig_type = entity->declaration.type;
5979 type_t *type = skip_typeref(orig_type);
5980 if (is_type_function(type)) {
5981 errorf(&entity->base.source_position,
5982 "compound member '%Y' must not have function type '%T'",
5983 entity->base.symbol, orig_type);
5984 } else if (is_type_incomplete(type)) {
5985 /* §6.7.2.1:16 flexible array member */
5986 if (!is_type_array(type) ||
5987 token.type != ';' ||
5988 look_ahead(1)->type != '}') {
5989 errorf(&entity->base.source_position,
5990 "compound member '%Y' has incomplete type '%T'",
5991 entity->base.symbol, orig_type);
5996 append_entity(&compound->members, entity);
5999 } while (next_if(','));
6000 expect(';', end_error);
6003 anonymous_entity = NULL;
6006 static void parse_compound_type_entries(compound_t *compound)
6009 add_anchor_token('}');
6011 while (token.type != '}') {
6012 if (token.type == T_EOF) {
6013 errorf(HERE, "EOF while parsing struct");
6016 declaration_specifiers_t specifiers;
6017 memset(&specifiers, 0, sizeof(specifiers));
6018 parse_declaration_specifiers(&specifiers);
6020 parse_compound_declarators(compound, &specifiers);
6022 rem_anchor_token('}');
6026 compound->complete = true;
6029 static type_t *parse_typename(void)
6031 declaration_specifiers_t specifiers;
6032 memset(&specifiers, 0, sizeof(specifiers));
6033 parse_declaration_specifiers(&specifiers);
6034 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6035 specifiers.thread_local) {
6036 /* TODO: improve error message, user does probably not know what a
6037 * storage class is...
6039 errorf(HERE, "typename may not have a storage class");
6042 type_t *result = parse_abstract_declarator(specifiers.type);
6050 typedef expression_t* (*parse_expression_function)(void);
6051 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6053 typedef struct expression_parser_function_t expression_parser_function_t;
6054 struct expression_parser_function_t {
6055 parse_expression_function parser;
6056 precedence_t infix_precedence;
6057 parse_expression_infix_function infix_parser;
6060 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6063 * Prints an error message if an expression was expected but not read
6065 static expression_t *expected_expression_error(void)
6067 /* skip the error message if the error token was read */
6068 if (token.type != T_ERROR) {
6069 errorf(HERE, "expected expression, got token %K", &token);
6073 return create_invalid_expression();
6077 * Parse a string constant.
6079 static expression_t *parse_string_const(void)
6082 if (token.type == T_STRING_LITERAL) {
6083 string_t res = token.v.string;
6085 while (token.type == T_STRING_LITERAL) {
6086 res = concat_strings(&res, &token.v.string);
6089 if (token.type != T_WIDE_STRING_LITERAL) {
6090 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6091 /* note: that we use type_char_ptr here, which is already the
6092 * automatic converted type. revert_automatic_type_conversion
6093 * will construct the array type */
6094 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6095 cnst->string.value = res;
6099 wres = concat_string_wide_string(&res, &token.v.wide_string);
6101 wres = token.v.wide_string;
6106 switch (token.type) {
6107 case T_WIDE_STRING_LITERAL:
6108 wres = concat_wide_strings(&wres, &token.v.wide_string);
6111 case T_STRING_LITERAL:
6112 wres = concat_wide_string_string(&wres, &token.v.string);
6116 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6117 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6118 cnst->wide_string.value = wres;
6127 * Parse a boolean constant.
6129 static expression_t *parse_bool_const(bool value)
6131 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6132 cnst->base.type = type_bool;
6133 cnst->conste.v.int_value = value;
6141 * Parse an integer constant.
6143 static expression_t *parse_int_const(void)
6145 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6146 cnst->base.type = token.datatype;
6147 cnst->conste.v.int_value = token.v.intvalue;
6155 * Parse a character constant.
6157 static expression_t *parse_character_constant(void)
6159 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6160 cnst->base.type = token.datatype;
6161 cnst->conste.v.character = token.v.string;
6163 if (cnst->conste.v.character.size != 1) {
6165 errorf(HERE, "more than 1 character in character constant");
6166 } else if (warning.multichar) {
6167 warningf(HERE, "multi-character character constant");
6176 * Parse a wide character constant.
6178 static expression_t *parse_wide_character_constant(void)
6180 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6181 cnst->base.type = token.datatype;
6182 cnst->conste.v.wide_character = token.v.wide_string;
6184 if (cnst->conste.v.wide_character.size != 1) {
6186 errorf(HERE, "more than 1 character in character constant");
6187 } else if (warning.multichar) {
6188 warningf(HERE, "multi-character character constant");
6197 * Parse a float constant.
6199 static expression_t *parse_float_const(void)
6201 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6202 cnst->base.type = token.datatype;
6203 cnst->conste.v.float_value = token.v.floatvalue;
6210 static entity_t *create_implicit_function(symbol_t *symbol,
6211 const source_position_t *source_position)
6213 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6214 ntype->function.return_type = type_int;
6215 ntype->function.unspecified_parameters = true;
6216 ntype->function.linkage = LINKAGE_C;
6217 type_t *type = identify_new_type(ntype);
6219 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6220 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6221 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6222 entity->declaration.type = type;
6223 entity->declaration.implicit = true;
6224 entity->base.symbol = symbol;
6225 entity->base.source_position = *source_position;
6227 if (current_scope != NULL) {
6228 bool strict_prototypes_old = warning.strict_prototypes;
6229 warning.strict_prototypes = false;
6230 record_entity(entity, false);
6231 warning.strict_prototypes = strict_prototypes_old;
6238 * Creates a return_type (func)(argument_type) function type if not
6241 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6242 type_t *argument_type2)
6244 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6245 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6246 parameter1->next = parameter2;
6248 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6249 type->function.return_type = return_type;
6250 type->function.parameters = parameter1;
6252 return identify_new_type(type);
6256 * Creates a return_type (func)(argument_type) function type if not
6259 * @param return_type the return type
6260 * @param argument_type the argument type
6262 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6264 function_parameter_t *const parameter = allocate_parameter(argument_type);
6266 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6267 type->function.return_type = return_type;
6268 type->function.parameters = parameter;
6270 return identify_new_type(type);
6274 * Creates a return_type (func)(argument_type, ...) function type if not
6277 * @param return_type the return type
6278 * @param argument_type the argument type
6280 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6282 function_parameter_t *const parameter = allocate_parameter(argument_type);
6284 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6285 type->function.return_type = return_type;
6286 type->function.parameters = parameter;
6287 type->function.variadic = true;
6289 return identify_new_type(type);
6293 * Creates a return_type (func)(void) function type if not
6296 * @param return_type the return type
6298 static type_t *make_function_0_type(type_t *return_type)
6300 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6301 type->function.return_type = return_type;
6302 type->function.parameters = NULL;
6304 return identify_new_type(type);
6308 * Creates a NO_RETURN return_type (func)(void) function type if not
6311 * @param return_type the return type
6313 static type_t *make_function_0_type_noreturn(type_t *return_type)
6315 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6316 type->function.return_type = return_type;
6317 type->function.parameters = NULL;
6318 type->function.modifiers |= DM_NORETURN;
6319 return identify_new_type(type);
6323 * Performs automatic type cast as described in §6.3.2.1.
6325 * @param orig_type the original type
6327 static type_t *automatic_type_conversion(type_t *orig_type)
6329 type_t *type = skip_typeref(orig_type);
6330 if (is_type_array(type)) {
6331 array_type_t *array_type = &type->array;
6332 type_t *element_type = array_type->element_type;
6333 unsigned qualifiers = array_type->base.qualifiers;
6335 return make_pointer_type(element_type, qualifiers);
6338 if (is_type_function(type)) {
6339 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6346 * reverts the automatic casts of array to pointer types and function
6347 * to function-pointer types as defined §6.3.2.1
6349 type_t *revert_automatic_type_conversion(const expression_t *expression)
6351 switch (expression->kind) {
6352 case EXPR_REFERENCE: {
6353 entity_t *entity = expression->reference.entity;
6354 if (is_declaration(entity)) {
6355 return entity->declaration.type;
6356 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6357 return entity->enum_value.enum_type;
6359 panic("no declaration or enum in reference");
6364 entity_t *entity = expression->select.compound_entry;
6365 assert(is_declaration(entity));
6366 type_t *type = entity->declaration.type;
6367 return get_qualified_type(type,
6368 expression->base.type->base.qualifiers);
6371 case EXPR_UNARY_DEREFERENCE: {
6372 const expression_t *const value = expression->unary.value;
6373 type_t *const type = skip_typeref(value->base.type);
6374 if (!is_type_pointer(type))
6375 return type_error_type;
6376 return type->pointer.points_to;
6379 case EXPR_ARRAY_ACCESS: {
6380 const expression_t *array_ref = expression->array_access.array_ref;
6381 type_t *type_left = skip_typeref(array_ref->base.type);
6382 if (!is_type_pointer(type_left))
6383 return type_error_type;
6384 return type_left->pointer.points_to;
6387 case EXPR_STRING_LITERAL: {
6388 size_t size = expression->string.value.size;
6389 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6392 case EXPR_WIDE_STRING_LITERAL: {
6393 size_t size = expression->wide_string.value.size;
6394 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6397 case EXPR_COMPOUND_LITERAL:
6398 return expression->compound_literal.type;
6401 return expression->base.type;
6406 * Find an entity matching a symbol in a scope.
6407 * Uses current scope if scope is NULL
6409 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6410 namespace_tag_t namespc)
6412 if (scope == NULL) {
6413 return get_entity(symbol, namespc);
6416 /* we should optimize here, if scope grows above a certain size we should
6417 construct a hashmap here... */
6418 entity_t *entity = scope->entities;
6419 for ( ; entity != NULL; entity = entity->base.next) {
6420 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6427 static entity_t *parse_qualified_identifier(void)
6429 /* namespace containing the symbol */
6431 source_position_t pos;
6432 const scope_t *lookup_scope = NULL;
6434 if (next_if(T_COLONCOLON))
6435 lookup_scope = &unit->scope;
6439 if (token.type != T_IDENTIFIER) {
6440 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6441 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6443 symbol = token.v.symbol;
6448 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6450 if (!next_if(T_COLONCOLON))
6453 switch (entity->kind) {
6454 case ENTITY_NAMESPACE:
6455 lookup_scope = &entity->namespacee.members;
6460 lookup_scope = &entity->compound.members;
6463 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6464 symbol, get_entity_kind_name(entity->kind));
6469 if (entity == NULL) {
6470 if (!strict_mode && token.type == '(') {
6471 /* an implicitly declared function */
6472 if (warning.error_implicit_function_declaration) {
6473 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6474 } else if (warning.implicit_function_declaration) {
6475 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6478 entity = create_implicit_function(symbol, &pos);
6480 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6481 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6488 /* skip further qualifications */
6489 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6491 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6494 static expression_t *parse_reference(void)
6496 entity_t *entity = parse_qualified_identifier();
6499 if (is_declaration(entity)) {
6500 orig_type = entity->declaration.type;
6501 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6502 orig_type = entity->enum_value.enum_type;
6504 panic("expected declaration or enum value in reference");
6507 /* we always do the auto-type conversions; the & and sizeof parser contains
6508 * code to revert this! */
6509 type_t *type = automatic_type_conversion(orig_type);
6511 expression_kind_t kind = EXPR_REFERENCE;
6512 if (entity->kind == ENTITY_ENUM_VALUE)
6513 kind = EXPR_REFERENCE_ENUM_VALUE;
6515 expression_t *expression = allocate_expression_zero(kind);
6516 expression->reference.entity = entity;
6517 expression->base.type = type;
6519 /* this declaration is used */
6520 if (is_declaration(entity)) {
6521 entity->declaration.used = true;
6524 if (entity->base.parent_scope != file_scope
6525 && (current_function != NULL
6526 && entity->base.parent_scope->depth < current_function->parameters.depth)
6527 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6528 if (entity->kind == ENTITY_VARIABLE) {
6529 /* access of a variable from an outer function */
6530 entity->variable.address_taken = true;
6531 } else if (entity->kind == ENTITY_PARAMETER) {
6532 entity->parameter.address_taken = true;
6534 current_function->need_closure = true;
6537 check_deprecated(HERE, entity);
6539 if (warning.init_self && entity == current_init_decl && !in_type_prop
6540 && entity->kind == ENTITY_VARIABLE) {
6541 current_init_decl = NULL;
6542 warningf(HERE, "variable '%#T' is initialized by itself",
6543 entity->declaration.type, entity->base.symbol);
6549 static bool semantic_cast(expression_t *cast)
6551 expression_t *expression = cast->unary.value;
6552 type_t *orig_dest_type = cast->base.type;
6553 type_t *orig_type_right = expression->base.type;
6554 type_t const *dst_type = skip_typeref(orig_dest_type);
6555 type_t const *src_type = skip_typeref(orig_type_right);
6556 source_position_t const *pos = &cast->base.source_position;
6558 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6559 if (dst_type == type_void)
6562 /* only integer and pointer can be casted to pointer */
6563 if (is_type_pointer(dst_type) &&
6564 !is_type_pointer(src_type) &&
6565 !is_type_integer(src_type) &&
6566 is_type_valid(src_type)) {
6567 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6571 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6572 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6576 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6577 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6581 if (warning.cast_qual &&
6582 is_type_pointer(src_type) &&
6583 is_type_pointer(dst_type)) {
6584 type_t *src = skip_typeref(src_type->pointer.points_to);
6585 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6586 unsigned missing_qualifiers =
6587 src->base.qualifiers & ~dst->base.qualifiers;
6588 if (missing_qualifiers != 0) {
6590 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6591 missing_qualifiers, orig_type_right);
6597 static expression_t *parse_compound_literal(type_t *type)
6599 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6601 parse_initializer_env_t env;
6604 env.must_be_constant = false;
6605 initializer_t *initializer = parse_initializer(&env);
6608 expression->compound_literal.initializer = initializer;
6609 expression->compound_literal.type = type;
6610 expression->base.type = automatic_type_conversion(type);
6616 * Parse a cast expression.
6618 static expression_t *parse_cast(void)
6620 add_anchor_token(')');
6622 source_position_t source_position = token.source_position;
6624 type_t *type = parse_typename();
6626 rem_anchor_token(')');
6627 expect(')', end_error);
6629 if (token.type == '{') {
6630 return parse_compound_literal(type);
6633 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6634 cast->base.source_position = source_position;
6636 expression_t *value = parse_sub_expression(PREC_CAST);
6637 cast->base.type = type;
6638 cast->unary.value = value;
6640 if (! semantic_cast(cast)) {
6641 /* TODO: record the error in the AST. else it is impossible to detect it */
6646 return create_invalid_expression();
6650 * Parse a statement expression.
6652 static expression_t *parse_statement_expression(void)
6654 add_anchor_token(')');
6656 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6658 statement_t *statement = parse_compound_statement(true);
6659 statement->compound.stmt_expr = true;
6660 expression->statement.statement = statement;
6662 /* find last statement and use its type */
6663 type_t *type = type_void;
6664 const statement_t *stmt = statement->compound.statements;
6666 while (stmt->base.next != NULL)
6667 stmt = stmt->base.next;
6669 if (stmt->kind == STATEMENT_EXPRESSION) {
6670 type = stmt->expression.expression->base.type;
6672 } else if (warning.other) {
6673 warningf(&expression->base.source_position, "empty statement expression ({})");
6675 expression->base.type = type;
6677 rem_anchor_token(')');
6678 expect(')', end_error);
6685 * Parse a parenthesized expression.
6687 static expression_t *parse_parenthesized_expression(void)
6691 switch (token.type) {
6693 /* gcc extension: a statement expression */
6694 return parse_statement_expression();
6698 return parse_cast();
6700 if (is_typedef_symbol(token.v.symbol)) {
6701 return parse_cast();
6705 add_anchor_token(')');
6706 expression_t *result = parse_expression();
6707 result->base.parenthesized = true;
6708 rem_anchor_token(')');
6709 expect(')', end_error);
6715 static expression_t *parse_function_keyword(void)
6719 if (current_function == NULL) {
6720 errorf(HERE, "'__func__' used outside of a function");
6723 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6724 expression->base.type = type_char_ptr;
6725 expression->funcname.kind = FUNCNAME_FUNCTION;
6732 static expression_t *parse_pretty_function_keyword(void)
6734 if (current_function == NULL) {
6735 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6738 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6739 expression->base.type = type_char_ptr;
6740 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6742 eat(T___PRETTY_FUNCTION__);
6747 static expression_t *parse_funcsig_keyword(void)
6749 if (current_function == NULL) {
6750 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6753 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6754 expression->base.type = type_char_ptr;
6755 expression->funcname.kind = FUNCNAME_FUNCSIG;
6762 static expression_t *parse_funcdname_keyword(void)
6764 if (current_function == NULL) {
6765 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6768 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6769 expression->base.type = type_char_ptr;
6770 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6772 eat(T___FUNCDNAME__);
6777 static designator_t *parse_designator(void)
6779 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6780 result->source_position = *HERE;
6782 if (token.type != T_IDENTIFIER) {
6783 parse_error_expected("while parsing member designator",
6784 T_IDENTIFIER, NULL);
6787 result->symbol = token.v.symbol;
6790 designator_t *last_designator = result;
6793 if (token.type != T_IDENTIFIER) {
6794 parse_error_expected("while parsing member designator",
6795 T_IDENTIFIER, NULL);
6798 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6799 designator->source_position = *HERE;
6800 designator->symbol = token.v.symbol;
6803 last_designator->next = designator;
6804 last_designator = designator;
6808 add_anchor_token(']');
6809 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6810 designator->source_position = *HERE;
6811 designator->array_index = parse_expression();
6812 rem_anchor_token(']');
6813 expect(']', end_error);
6814 if (designator->array_index == NULL) {
6818 last_designator->next = designator;
6819 last_designator = designator;
6831 * Parse the __builtin_offsetof() expression.
6833 static expression_t *parse_offsetof(void)
6835 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6836 expression->base.type = type_size_t;
6838 eat(T___builtin_offsetof);
6840 expect('(', end_error);
6841 add_anchor_token(',');
6842 type_t *type = parse_typename();
6843 rem_anchor_token(',');
6844 expect(',', end_error);
6845 add_anchor_token(')');
6846 designator_t *designator = parse_designator();
6847 rem_anchor_token(')');
6848 expect(')', end_error);
6850 expression->offsetofe.type = type;
6851 expression->offsetofe.designator = designator;
6854 memset(&path, 0, sizeof(path));
6855 path.top_type = type;
6856 path.path = NEW_ARR_F(type_path_entry_t, 0);
6858 descend_into_subtype(&path);
6860 if (!walk_designator(&path, designator, true)) {
6861 return create_invalid_expression();
6864 DEL_ARR_F(path.path);
6868 return create_invalid_expression();
6872 * Parses a _builtin_va_start() expression.
6874 static expression_t *parse_va_start(void)
6876 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6878 eat(T___builtin_va_start);
6880 expect('(', end_error);
6881 add_anchor_token(',');
6882 expression->va_starte.ap = parse_assignment_expression();
6883 rem_anchor_token(',');
6884 expect(',', end_error);
6885 expression_t *const expr = parse_assignment_expression();
6886 if (expr->kind == EXPR_REFERENCE) {
6887 entity_t *const entity = expr->reference.entity;
6888 if (!current_function->base.type->function.variadic) {
6889 errorf(&expr->base.source_position,
6890 "'va_start' used in non-variadic function");
6891 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6892 entity->base.next != NULL ||
6893 entity->kind != ENTITY_PARAMETER) {
6894 errorf(&expr->base.source_position,
6895 "second argument of 'va_start' must be last parameter of the current function");
6897 expression->va_starte.parameter = &entity->variable;
6899 expect(')', end_error);
6902 expect(')', end_error);
6904 return create_invalid_expression();
6908 * Parses a __builtin_va_arg() expression.
6910 static expression_t *parse_va_arg(void)
6912 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6914 eat(T___builtin_va_arg);
6916 expect('(', end_error);
6918 ap.expression = parse_assignment_expression();
6919 expression->va_arge.ap = ap.expression;
6920 check_call_argument(type_valist, &ap, 1);
6922 expect(',', end_error);
6923 expression->base.type = parse_typename();
6924 expect(')', end_error);
6928 return create_invalid_expression();
6932 * Parses a __builtin_va_copy() expression.
6934 static expression_t *parse_va_copy(void)
6936 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6938 eat(T___builtin_va_copy);
6940 expect('(', end_error);
6941 expression_t *dst = parse_assignment_expression();
6942 assign_error_t error = semantic_assign(type_valist, dst);
6943 report_assign_error(error, type_valist, dst, "call argument 1",
6944 &dst->base.source_position);
6945 expression->va_copye.dst = dst;
6947 expect(',', end_error);
6949 call_argument_t src;
6950 src.expression = parse_assignment_expression();
6951 check_call_argument(type_valist, &src, 2);
6952 expression->va_copye.src = src.expression;
6953 expect(')', end_error);
6957 return create_invalid_expression();
6961 * Parses a __builtin_constant_p() expression.
6963 static expression_t *parse_builtin_constant(void)
6965 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6967 eat(T___builtin_constant_p);
6969 expect('(', end_error);
6970 add_anchor_token(')');
6971 expression->builtin_constant.value = parse_assignment_expression();
6972 rem_anchor_token(')');
6973 expect(')', end_error);
6974 expression->base.type = type_int;
6978 return create_invalid_expression();
6982 * Parses a __builtin_types_compatible_p() expression.
6984 static expression_t *parse_builtin_types_compatible(void)
6986 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6988 eat(T___builtin_types_compatible_p);
6990 expect('(', end_error);
6991 add_anchor_token(')');
6992 add_anchor_token(',');
6993 expression->builtin_types_compatible.left = parse_typename();
6994 rem_anchor_token(',');
6995 expect(',', end_error);
6996 expression->builtin_types_compatible.right = parse_typename();
6997 rem_anchor_token(')');
6998 expect(')', end_error);
6999 expression->base.type = type_int;
7003 return create_invalid_expression();
7007 * Parses a __builtin_is_*() compare expression.
7009 static expression_t *parse_compare_builtin(void)
7011 expression_t *expression;
7013 switch (token.type) {
7014 case T___builtin_isgreater:
7015 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7017 case T___builtin_isgreaterequal:
7018 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7020 case T___builtin_isless:
7021 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7023 case T___builtin_islessequal:
7024 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7026 case T___builtin_islessgreater:
7027 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7029 case T___builtin_isunordered:
7030 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7033 internal_errorf(HERE, "invalid compare builtin found");
7035 expression->base.source_position = *HERE;
7038 expect('(', end_error);
7039 expression->binary.left = parse_assignment_expression();
7040 expect(',', end_error);
7041 expression->binary.right = parse_assignment_expression();
7042 expect(')', end_error);
7044 type_t *const orig_type_left = expression->binary.left->base.type;
7045 type_t *const orig_type_right = expression->binary.right->base.type;
7047 type_t *const type_left = skip_typeref(orig_type_left);
7048 type_t *const type_right = skip_typeref(orig_type_right);
7049 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7050 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7051 type_error_incompatible("invalid operands in comparison",
7052 &expression->base.source_position, orig_type_left, orig_type_right);
7055 semantic_comparison(&expression->binary);
7060 return create_invalid_expression();
7064 * Parses a MS assume() expression.
7066 static expression_t *parse_assume(void)
7068 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7072 expect('(', end_error);
7073 add_anchor_token(')');
7074 expression->unary.value = parse_assignment_expression();
7075 rem_anchor_token(')');
7076 expect(')', end_error);
7078 expression->base.type = type_void;
7081 return create_invalid_expression();
7085 * Return the declaration for a given label symbol or create a new one.
7087 * @param symbol the symbol of the label
7089 static label_t *get_label(symbol_t *symbol)
7092 assert(current_function != NULL);
7094 label = get_entity(symbol, NAMESPACE_LABEL);
7095 /* if we found a local label, we already created the declaration */
7096 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7097 if (label->base.parent_scope != current_scope) {
7098 assert(label->base.parent_scope->depth < current_scope->depth);
7099 current_function->goto_to_outer = true;
7101 return &label->label;
7104 label = get_entity(symbol, NAMESPACE_LABEL);
7105 /* if we found a label in the same function, then we already created the
7108 && label->base.parent_scope == ¤t_function->parameters) {
7109 return &label->label;
7112 /* otherwise we need to create a new one */
7113 label = allocate_entity_zero(ENTITY_LABEL);
7114 label->base.namespc = NAMESPACE_LABEL;
7115 label->base.symbol = symbol;
7119 return &label->label;
7123 * Parses a GNU && label address expression.
7125 static expression_t *parse_label_address(void)
7127 source_position_t source_position = token.source_position;
7129 if (token.type != T_IDENTIFIER) {
7130 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7133 symbol_t *symbol = token.v.symbol;
7136 label_t *label = get_label(symbol);
7138 label->address_taken = true;
7140 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7141 expression->base.source_position = source_position;
7143 /* label address is threaten as a void pointer */
7144 expression->base.type = type_void_ptr;
7145 expression->label_address.label = label;
7148 return create_invalid_expression();
7152 * Parse a microsoft __noop expression.
7154 static expression_t *parse_noop_expression(void)
7156 /* the result is a (int)0 */
7157 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7158 cnst->base.type = type_int;
7159 cnst->conste.v.int_value = 0;
7160 cnst->conste.is_ms_noop = true;
7164 if (token.type == '(') {
7165 /* parse arguments */
7167 add_anchor_token(')');
7168 add_anchor_token(',');
7170 if (token.type != ')') do {
7171 (void)parse_assignment_expression();
7172 } while (next_if(','));
7174 rem_anchor_token(',');
7175 rem_anchor_token(')');
7176 expect(')', end_error);
7183 * Parses a primary expression.
7185 static expression_t *parse_primary_expression(void)
7187 switch (token.type) {
7188 case T_false: return parse_bool_const(false);
7189 case T_true: return parse_bool_const(true);
7190 case T_INTEGER: return parse_int_const();
7191 case T_CHARACTER_CONSTANT: return parse_character_constant();
7192 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7193 case T_FLOATINGPOINT: return parse_float_const();
7194 case T_STRING_LITERAL:
7195 case T_WIDE_STRING_LITERAL: return parse_string_const();
7196 case T___FUNCTION__:
7197 case T___func__: return parse_function_keyword();
7198 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7199 case T___FUNCSIG__: return parse_funcsig_keyword();
7200 case T___FUNCDNAME__: return parse_funcdname_keyword();
7201 case T___builtin_offsetof: return parse_offsetof();
7202 case T___builtin_va_start: return parse_va_start();
7203 case T___builtin_va_arg: return parse_va_arg();
7204 case T___builtin_va_copy: return parse_va_copy();
7205 case T___builtin_isgreater:
7206 case T___builtin_isgreaterequal:
7207 case T___builtin_isless:
7208 case T___builtin_islessequal:
7209 case T___builtin_islessgreater:
7210 case T___builtin_isunordered: return parse_compare_builtin();
7211 case T___builtin_constant_p: return parse_builtin_constant();
7212 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7213 case T__assume: return parse_assume();
7216 return parse_label_address();
7219 case '(': return parse_parenthesized_expression();
7220 case T___noop: return parse_noop_expression();
7222 /* Gracefully handle type names while parsing expressions. */
7224 return parse_reference();
7226 if (!is_typedef_symbol(token.v.symbol)) {
7227 return parse_reference();
7231 source_position_t const pos = *HERE;
7232 type_t const *const type = parse_typename();
7233 errorf(&pos, "encountered type '%T' while parsing expression", type);
7234 return create_invalid_expression();
7238 errorf(HERE, "unexpected token %K, expected an expression", &token);
7239 return create_invalid_expression();
7243 * Check if the expression has the character type and issue a warning then.
7245 static void check_for_char_index_type(const expression_t *expression)
7247 type_t *const type = expression->base.type;
7248 const type_t *const base_type = skip_typeref(type);
7250 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7251 warning.char_subscripts) {
7252 warningf(&expression->base.source_position,
7253 "array subscript has type '%T'", type);
7257 static expression_t *parse_array_expression(expression_t *left)
7259 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7262 add_anchor_token(']');
7264 expression_t *inside = parse_expression();
7266 type_t *const orig_type_left = left->base.type;
7267 type_t *const orig_type_inside = inside->base.type;
7269 type_t *const type_left = skip_typeref(orig_type_left);
7270 type_t *const type_inside = skip_typeref(orig_type_inside);
7272 type_t *return_type;
7273 array_access_expression_t *array_access = &expression->array_access;
7274 if (is_type_pointer(type_left)) {
7275 return_type = type_left->pointer.points_to;
7276 array_access->array_ref = left;
7277 array_access->index = inside;
7278 check_for_char_index_type(inside);
7279 } else if (is_type_pointer(type_inside)) {
7280 return_type = type_inside->pointer.points_to;
7281 array_access->array_ref = inside;
7282 array_access->index = left;
7283 array_access->flipped = true;
7284 check_for_char_index_type(left);
7286 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7288 "array access on object with non-pointer types '%T', '%T'",
7289 orig_type_left, orig_type_inside);
7291 return_type = type_error_type;
7292 array_access->array_ref = left;
7293 array_access->index = inside;
7296 expression->base.type = automatic_type_conversion(return_type);
7298 rem_anchor_token(']');
7299 expect(']', end_error);
7304 static expression_t *parse_typeprop(expression_kind_t const kind)
7306 expression_t *tp_expression = allocate_expression_zero(kind);
7307 tp_expression->base.type = type_size_t;
7309 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7311 /* we only refer to a type property, mark this case */
7312 bool old = in_type_prop;
7313 in_type_prop = true;
7316 expression_t *expression;
7317 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7319 add_anchor_token(')');
7320 orig_type = parse_typename();
7321 rem_anchor_token(')');
7322 expect(')', end_error);
7324 if (token.type == '{') {
7325 /* It was not sizeof(type) after all. It is sizeof of an expression
7326 * starting with a compound literal */
7327 expression = parse_compound_literal(orig_type);
7328 goto typeprop_expression;
7331 expression = parse_sub_expression(PREC_UNARY);
7333 typeprop_expression:
7334 tp_expression->typeprop.tp_expression = expression;
7336 orig_type = revert_automatic_type_conversion(expression);
7337 expression->base.type = orig_type;
7340 tp_expression->typeprop.type = orig_type;
7341 type_t const* const type = skip_typeref(orig_type);
7342 char const* const wrong_type =
7343 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7344 is_type_incomplete(type) ? "incomplete" :
7345 type->kind == TYPE_FUNCTION ? "function designator" :
7346 type->kind == TYPE_BITFIELD ? "bitfield" :
7348 if (wrong_type != NULL) {
7349 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7350 errorf(&tp_expression->base.source_position,
7351 "operand of %s expression must not be of %s type '%T'",
7352 what, wrong_type, orig_type);
7357 return tp_expression;
7360 static expression_t *parse_sizeof(void)
7362 return parse_typeprop(EXPR_SIZEOF);
7365 static expression_t *parse_alignof(void)
7367 return parse_typeprop(EXPR_ALIGNOF);
7370 static expression_t *parse_select_expression(expression_t *addr)
7372 assert(token.type == '.' || token.type == T_MINUSGREATER);
7373 bool select_left_arrow = (token.type == T_MINUSGREATER);
7376 if (token.type != T_IDENTIFIER) {
7377 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7378 return create_invalid_expression();
7380 symbol_t *symbol = token.v.symbol;
7383 type_t *const orig_type = addr->base.type;
7384 type_t *const type = skip_typeref(orig_type);
7387 bool saw_error = false;
7388 if (is_type_pointer(type)) {
7389 if (!select_left_arrow) {
7391 "request for member '%Y' in something not a struct or union, but '%T'",
7395 type_left = skip_typeref(type->pointer.points_to);
7397 if (select_left_arrow && is_type_valid(type)) {
7398 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7404 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7405 type_left->kind != TYPE_COMPOUND_UNION) {
7407 if (is_type_valid(type_left) && !saw_error) {
7409 "request for member '%Y' in something not a struct or union, but '%T'",
7412 return create_invalid_expression();
7415 compound_t *compound = type_left->compound.compound;
7416 if (!compound->complete) {
7417 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7419 return create_invalid_expression();
7422 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7423 expression_t *result
7424 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7426 if (result == NULL) {
7427 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7428 return create_invalid_expression();
7434 static void check_call_argument(type_t *expected_type,
7435 call_argument_t *argument, unsigned pos)
7437 type_t *expected_type_skip = skip_typeref(expected_type);
7438 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7439 expression_t *arg_expr = argument->expression;
7440 type_t *arg_type = skip_typeref(arg_expr->base.type);
7442 /* handle transparent union gnu extension */
7443 if (is_type_union(expected_type_skip)
7444 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7445 compound_t *union_decl = expected_type_skip->compound.compound;
7446 type_t *best_type = NULL;
7447 entity_t *entry = union_decl->members.entities;
7448 for ( ; entry != NULL; entry = entry->base.next) {
7449 assert(is_declaration(entry));
7450 type_t *decl_type = entry->declaration.type;
7451 error = semantic_assign(decl_type, arg_expr);
7452 if (error == ASSIGN_ERROR_INCOMPATIBLE
7453 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7456 if (error == ASSIGN_SUCCESS) {
7457 best_type = decl_type;
7458 } else if (best_type == NULL) {
7459 best_type = decl_type;
7463 if (best_type != NULL) {
7464 expected_type = best_type;
7468 error = semantic_assign(expected_type, arg_expr);
7469 argument->expression = create_implicit_cast(arg_expr, expected_type);
7471 if (error != ASSIGN_SUCCESS) {
7472 /* report exact scope in error messages (like "in argument 3") */
7474 snprintf(buf, sizeof(buf), "call argument %u", pos);
7475 report_assign_error(error, expected_type, arg_expr, buf,
7476 &arg_expr->base.source_position);
7477 } else if (warning.traditional || warning.conversion) {
7478 type_t *const promoted_type = get_default_promoted_type(arg_type);
7479 if (!types_compatible(expected_type_skip, promoted_type) &&
7480 !types_compatible(expected_type_skip, type_void_ptr) &&
7481 !types_compatible(type_void_ptr, promoted_type)) {
7482 /* Deliberately show the skipped types in this warning */
7483 warningf(&arg_expr->base.source_position,
7484 "passing call argument %u as '%T' rather than '%T' due to prototype",
7485 pos, expected_type_skip, promoted_type);
7491 * Handle the semantic restrictions of builtin calls
7493 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7494 switch (call->function->reference.entity->function.btk) {
7495 case bk_gnu_builtin_return_address:
7496 case bk_gnu_builtin_frame_address: {
7497 /* argument must be constant */
7498 call_argument_t *argument = call->arguments;
7500 if (! is_constant_expression(argument->expression)) {
7501 errorf(&call->base.source_position,
7502 "argument of '%Y' must be a constant expression",
7503 call->function->reference.entity->base.symbol);
7507 case bk_gnu_builtin_prefetch: {
7508 /* second and third argument must be constant if existent */
7509 call_argument_t *rw = call->arguments->next;
7510 call_argument_t *locality = NULL;
7513 if (! is_constant_expression(rw->expression)) {
7514 errorf(&call->base.source_position,
7515 "second argument of '%Y' must be a constant expression",
7516 call->function->reference.entity->base.symbol);
7518 locality = rw->next;
7520 if (locality != NULL) {
7521 if (! is_constant_expression(locality->expression)) {
7522 errorf(&call->base.source_position,
7523 "third argument of '%Y' must be a constant expression",
7524 call->function->reference.entity->base.symbol);
7526 locality = rw->next;
7536 * Parse a call expression, ie. expression '( ... )'.
7538 * @param expression the function address
7540 static expression_t *parse_call_expression(expression_t *expression)
7542 expression_t *result = allocate_expression_zero(EXPR_CALL);
7543 call_expression_t *call = &result->call;
7544 call->function = expression;
7546 type_t *const orig_type = expression->base.type;
7547 type_t *const type = skip_typeref(orig_type);
7549 function_type_t *function_type = NULL;
7550 if (is_type_pointer(type)) {
7551 type_t *const to_type = skip_typeref(type->pointer.points_to);
7553 if (is_type_function(to_type)) {
7554 function_type = &to_type->function;
7555 call->base.type = function_type->return_type;
7559 if (function_type == NULL && is_type_valid(type)) {
7561 "called object '%E' (type '%T') is not a pointer to a function",
7562 expression, orig_type);
7565 /* parse arguments */
7567 add_anchor_token(')');
7568 add_anchor_token(',');
7570 if (token.type != ')') {
7571 call_argument_t **anchor = &call->arguments;
7573 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7574 argument->expression = parse_assignment_expression();
7577 anchor = &argument->next;
7578 } while (next_if(','));
7580 rem_anchor_token(',');
7581 rem_anchor_token(')');
7582 expect(')', end_error);
7584 if (function_type == NULL)
7587 /* check type and count of call arguments */
7588 function_parameter_t *parameter = function_type->parameters;
7589 call_argument_t *argument = call->arguments;
7590 if (!function_type->unspecified_parameters) {
7591 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7592 parameter = parameter->next, argument = argument->next) {
7593 check_call_argument(parameter->type, argument, ++pos);
7596 if (parameter != NULL) {
7597 errorf(HERE, "too few arguments to function '%E'", expression);
7598 } else if (argument != NULL && !function_type->variadic) {
7599 errorf(HERE, "too many arguments to function '%E'", expression);
7603 /* do default promotion for other arguments */
7604 for (; argument != NULL; argument = argument->next) {
7605 type_t *type = argument->expression->base.type;
7607 type = get_default_promoted_type(type);
7609 argument->expression
7610 = create_implicit_cast(argument->expression, type);
7613 check_format(&result->call);
7615 if (warning.aggregate_return &&
7616 is_type_compound(skip_typeref(function_type->return_type))) {
7617 warningf(&result->base.source_position,
7618 "function call has aggregate value");
7621 if (call->function->kind == EXPR_REFERENCE) {
7622 reference_expression_t *reference = &call->function->reference;
7623 if (reference->entity->kind == ENTITY_FUNCTION &&
7624 reference->entity->function.btk != bk_none)
7625 handle_builtin_argument_restrictions(call);
7632 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7634 static bool same_compound_type(const type_t *type1, const type_t *type2)
7637 is_type_compound(type1) &&
7638 type1->kind == type2->kind &&
7639 type1->compound.compound == type2->compound.compound;
7642 static expression_t const *get_reference_address(expression_t const *expr)
7644 bool regular_take_address = true;
7646 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7647 expr = expr->unary.value;
7649 regular_take_address = false;
7652 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7655 expr = expr->unary.value;
7658 if (expr->kind != EXPR_REFERENCE)
7661 /* special case for functions which are automatically converted to a
7662 * pointer to function without an extra TAKE_ADDRESS operation */
7663 if (!regular_take_address &&
7664 expr->reference.entity->kind != ENTITY_FUNCTION) {
7671 static void warn_reference_address_as_bool(expression_t const* expr)
7673 if (!warning.address)
7676 expr = get_reference_address(expr);
7678 warningf(&expr->base.source_position,
7679 "the address of '%Y' will always evaluate as 'true'",
7680 expr->reference.entity->base.symbol);
7684 static void warn_assignment_in_condition(const expression_t *const expr)
7686 if (!warning.parentheses)
7688 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7690 if (expr->base.parenthesized)
7692 warningf(&expr->base.source_position,
7693 "suggest parentheses around assignment used as truth value");
7696 static void semantic_condition(expression_t const *const expr,
7697 char const *const context)
7699 type_t *const type = skip_typeref(expr->base.type);
7700 if (is_type_scalar(type)) {
7701 warn_reference_address_as_bool(expr);
7702 warn_assignment_in_condition(expr);
7703 } else if (is_type_valid(type)) {
7704 errorf(&expr->base.source_position,
7705 "%s must have scalar type", context);
7710 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7712 * @param expression the conditional expression
7714 static expression_t *parse_conditional_expression(expression_t *expression)
7716 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7718 conditional_expression_t *conditional = &result->conditional;
7719 conditional->condition = expression;
7722 add_anchor_token(':');
7724 /* §6.5.15:2 The first operand shall have scalar type. */
7725 semantic_condition(expression, "condition of conditional operator");
7727 expression_t *true_expression = expression;
7728 bool gnu_cond = false;
7729 if (GNU_MODE && token.type == ':') {
7732 true_expression = parse_expression();
7734 rem_anchor_token(':');
7735 expect(':', end_error);
7737 expression_t *false_expression =
7738 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7740 type_t *const orig_true_type = true_expression->base.type;
7741 type_t *const orig_false_type = false_expression->base.type;
7742 type_t *const true_type = skip_typeref(orig_true_type);
7743 type_t *const false_type = skip_typeref(orig_false_type);
7746 type_t *result_type;
7747 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7748 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7749 /* ISO/IEC 14882:1998(E) §5.16:2 */
7750 if (true_expression->kind == EXPR_UNARY_THROW) {
7751 result_type = false_type;
7752 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7753 result_type = true_type;
7755 if (warning.other && (
7756 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7757 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7759 warningf(&conditional->base.source_position,
7760 "ISO C forbids conditional expression with only one void side");
7762 result_type = type_void;
7764 } else if (is_type_arithmetic(true_type)
7765 && is_type_arithmetic(false_type)) {
7766 result_type = semantic_arithmetic(true_type, false_type);
7768 true_expression = create_implicit_cast(true_expression, result_type);
7769 false_expression = create_implicit_cast(false_expression, result_type);
7771 conditional->true_expression = true_expression;
7772 conditional->false_expression = false_expression;
7773 conditional->base.type = result_type;
7774 } else if (same_compound_type(true_type, false_type)) {
7775 /* just take 1 of the 2 types */
7776 result_type = true_type;
7777 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7778 type_t *pointer_type;
7780 expression_t *other_expression;
7781 if (is_type_pointer(true_type) &&
7782 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7783 pointer_type = true_type;
7784 other_type = false_type;
7785 other_expression = false_expression;
7787 pointer_type = false_type;
7788 other_type = true_type;
7789 other_expression = true_expression;
7792 if (is_null_pointer_constant(other_expression)) {
7793 result_type = pointer_type;
7794 } else if (is_type_pointer(other_type)) {
7795 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7796 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7799 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7800 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7802 } else if (types_compatible(get_unqualified_type(to1),
7803 get_unqualified_type(to2))) {
7806 if (warning.other) {
7807 warningf(&conditional->base.source_position,
7808 "pointer types '%T' and '%T' in conditional expression are incompatible",
7809 true_type, false_type);
7814 type_t *const type =
7815 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7816 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7817 } else if (is_type_integer(other_type)) {
7818 if (warning.other) {
7819 warningf(&conditional->base.source_position,
7820 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7822 result_type = pointer_type;
7824 if (is_type_valid(other_type)) {
7825 type_error_incompatible("while parsing conditional",
7826 &expression->base.source_position, true_type, false_type);
7828 result_type = type_error_type;
7831 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7832 type_error_incompatible("while parsing conditional",
7833 &conditional->base.source_position, true_type,
7836 result_type = type_error_type;
7839 conditional->true_expression
7840 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7841 conditional->false_expression
7842 = create_implicit_cast(false_expression, result_type);
7843 conditional->base.type = result_type;
7848 * Parse an extension expression.
7850 static expression_t *parse_extension(void)
7852 eat(T___extension__);
7854 bool old_gcc_extension = in_gcc_extension;
7855 in_gcc_extension = true;
7856 expression_t *expression = parse_sub_expression(PREC_UNARY);
7857 in_gcc_extension = old_gcc_extension;
7862 * Parse a __builtin_classify_type() expression.
7864 static expression_t *parse_builtin_classify_type(void)
7866 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7867 result->base.type = type_int;
7869 eat(T___builtin_classify_type);
7871 expect('(', end_error);
7872 add_anchor_token(')');
7873 expression_t *expression = parse_expression();
7874 rem_anchor_token(')');
7875 expect(')', end_error);
7876 result->classify_type.type_expression = expression;
7880 return create_invalid_expression();
7884 * Parse a delete expression
7885 * ISO/IEC 14882:1998(E) §5.3.5
7887 static expression_t *parse_delete(void)
7889 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7890 result->base.type = type_void;
7895 result->kind = EXPR_UNARY_DELETE_ARRAY;
7896 expect(']', end_error);
7900 expression_t *const value = parse_sub_expression(PREC_CAST);
7901 result->unary.value = value;
7903 type_t *const type = skip_typeref(value->base.type);
7904 if (!is_type_pointer(type)) {
7905 if (is_type_valid(type)) {
7906 errorf(&value->base.source_position,
7907 "operand of delete must have pointer type");
7909 } else if (warning.other &&
7910 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7911 warningf(&value->base.source_position,
7912 "deleting 'void*' is undefined");
7919 * Parse a throw expression
7920 * ISO/IEC 14882:1998(E) §15:1
7922 static expression_t *parse_throw(void)
7924 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7925 result->base.type = type_void;
7929 expression_t *value = NULL;
7930 switch (token.type) {
7932 value = parse_assignment_expression();
7933 /* ISO/IEC 14882:1998(E) §15.1:3 */
7934 type_t *const orig_type = value->base.type;
7935 type_t *const type = skip_typeref(orig_type);
7936 if (is_type_incomplete(type)) {
7937 errorf(&value->base.source_position,
7938 "cannot throw object of incomplete type '%T'", orig_type);
7939 } else if (is_type_pointer(type)) {
7940 type_t *const points_to = skip_typeref(type->pointer.points_to);
7941 if (is_type_incomplete(points_to) &&
7942 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7943 errorf(&value->base.source_position,
7944 "cannot throw pointer to incomplete type '%T'", orig_type);
7952 result->unary.value = value;
7957 static bool check_pointer_arithmetic(const source_position_t *source_position,
7958 type_t *pointer_type,
7959 type_t *orig_pointer_type)
7961 type_t *points_to = pointer_type->pointer.points_to;
7962 points_to = skip_typeref(points_to);
7964 if (is_type_incomplete(points_to)) {
7965 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7966 errorf(source_position,
7967 "arithmetic with pointer to incomplete type '%T' not allowed",
7970 } else if (warning.pointer_arith) {
7971 warningf(source_position,
7972 "pointer of type '%T' used in arithmetic",
7975 } else if (is_type_function(points_to)) {
7977 errorf(source_position,
7978 "arithmetic with pointer to function type '%T' not allowed",
7981 } else if (warning.pointer_arith) {
7982 warningf(source_position,
7983 "pointer to a function '%T' used in arithmetic",
7990 static bool is_lvalue(const expression_t *expression)
7992 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7993 switch (expression->kind) {
7994 case EXPR_ARRAY_ACCESS:
7995 case EXPR_COMPOUND_LITERAL:
7996 case EXPR_REFERENCE:
7998 case EXPR_UNARY_DEREFERENCE:
8002 type_t *type = skip_typeref(expression->base.type);
8004 /* ISO/IEC 14882:1998(E) §3.10:3 */
8005 is_type_reference(type) ||
8006 /* Claim it is an lvalue, if the type is invalid. There was a parse
8007 * error before, which maybe prevented properly recognizing it as
8009 !is_type_valid(type);
8014 static void semantic_incdec(unary_expression_t *expression)
8016 type_t *const orig_type = expression->value->base.type;
8017 type_t *const type = skip_typeref(orig_type);
8018 if (is_type_pointer(type)) {
8019 if (!check_pointer_arithmetic(&expression->base.source_position,
8023 } else if (!is_type_real(type) && is_type_valid(type)) {
8024 /* TODO: improve error message */
8025 errorf(&expression->base.source_position,
8026 "operation needs an arithmetic or pointer type");
8029 if (!is_lvalue(expression->value)) {
8030 /* TODO: improve error message */
8031 errorf(&expression->base.source_position, "lvalue required as operand");
8033 expression->base.type = orig_type;
8036 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8038 type_t *const orig_type = expression->value->base.type;
8039 type_t *const type = skip_typeref(orig_type);
8040 if (!is_type_arithmetic(type)) {
8041 if (is_type_valid(type)) {
8042 /* TODO: improve error message */
8043 errorf(&expression->base.source_position,
8044 "operation needs an arithmetic type");
8049 expression->base.type = orig_type;
8052 static void semantic_unexpr_plus(unary_expression_t *expression)
8054 semantic_unexpr_arithmetic(expression);
8055 if (warning.traditional)
8056 warningf(&expression->base.source_position,
8057 "traditional C rejects the unary plus operator");
8060 static void semantic_not(unary_expression_t *expression)
8062 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8063 semantic_condition(expression->value, "operand of !");
8064 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8067 static void semantic_unexpr_integer(unary_expression_t *expression)
8069 type_t *const orig_type = expression->value->base.type;
8070 type_t *const type = skip_typeref(orig_type);
8071 if (!is_type_integer(type)) {
8072 if (is_type_valid(type)) {
8073 errorf(&expression->base.source_position,
8074 "operand of ~ must be of integer type");
8079 expression->base.type = orig_type;
8082 static void semantic_dereference(unary_expression_t *expression)
8084 type_t *const orig_type = expression->value->base.type;
8085 type_t *const type = skip_typeref(orig_type);
8086 if (!is_type_pointer(type)) {
8087 if (is_type_valid(type)) {
8088 errorf(&expression->base.source_position,
8089 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8094 type_t *result_type = type->pointer.points_to;
8095 result_type = automatic_type_conversion(result_type);
8096 expression->base.type = result_type;
8100 * Record that an address is taken (expression represents an lvalue).
8102 * @param expression the expression
8103 * @param may_be_register if true, the expression might be an register
8105 static void set_address_taken(expression_t *expression, bool may_be_register)
8107 if (expression->kind != EXPR_REFERENCE)
8110 entity_t *const entity = expression->reference.entity;
8112 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8115 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8116 && !may_be_register) {
8117 errorf(&expression->base.source_position,
8118 "address of register %s '%Y' requested",
8119 get_entity_kind_name(entity->kind), entity->base.symbol);
8122 if (entity->kind == ENTITY_VARIABLE) {
8123 entity->variable.address_taken = true;
8125 assert(entity->kind == ENTITY_PARAMETER);
8126 entity->parameter.address_taken = true;
8131 * Check the semantic of the address taken expression.
8133 static void semantic_take_addr(unary_expression_t *expression)
8135 expression_t *value = expression->value;
8136 value->base.type = revert_automatic_type_conversion(value);
8138 type_t *orig_type = value->base.type;
8139 type_t *type = skip_typeref(orig_type);
8140 if (!is_type_valid(type))
8144 if (!is_lvalue(value)) {
8145 errorf(&expression->base.source_position, "'&' requires an lvalue");
8147 if (type->kind == TYPE_BITFIELD) {
8148 errorf(&expression->base.source_position,
8149 "'&' not allowed on object with bitfield type '%T'",
8153 set_address_taken(value, false);
8155 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8158 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8159 static expression_t *parse_##unexpression_type(void) \
8161 expression_t *unary_expression \
8162 = allocate_expression_zero(unexpression_type); \
8164 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8166 sfunc(&unary_expression->unary); \
8168 return unary_expression; \
8171 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8172 semantic_unexpr_arithmetic)
8173 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8174 semantic_unexpr_plus)
8175 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8177 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8178 semantic_dereference)
8179 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8181 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8182 semantic_unexpr_integer)
8183 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8185 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8188 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8190 static expression_t *parse_##unexpression_type(expression_t *left) \
8192 expression_t *unary_expression \
8193 = allocate_expression_zero(unexpression_type); \
8195 unary_expression->unary.value = left; \
8197 sfunc(&unary_expression->unary); \
8199 return unary_expression; \
8202 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8203 EXPR_UNARY_POSTFIX_INCREMENT,
8205 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8206 EXPR_UNARY_POSTFIX_DECREMENT,
8209 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8211 /* TODO: handle complex + imaginary types */
8213 type_left = get_unqualified_type(type_left);
8214 type_right = get_unqualified_type(type_right);
8216 /* §6.3.1.8 Usual arithmetic conversions */
8217 if (type_left == type_long_double || type_right == type_long_double) {
8218 return type_long_double;
8219 } else if (type_left == type_double || type_right == type_double) {
8221 } else if (type_left == type_float || type_right == type_float) {
8225 type_left = promote_integer(type_left);
8226 type_right = promote_integer(type_right);
8228 if (type_left == type_right)
8231 bool const signed_left = is_type_signed(type_left);
8232 bool const signed_right = is_type_signed(type_right);
8233 int const rank_left = get_rank(type_left);
8234 int const rank_right = get_rank(type_right);
8236 if (signed_left == signed_right)
8237 return rank_left >= rank_right ? type_left : type_right;
8246 u_rank = rank_right;
8247 u_type = type_right;
8249 s_rank = rank_right;
8250 s_type = type_right;
8255 if (u_rank >= s_rank)
8258 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8260 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8261 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8265 case ATOMIC_TYPE_INT: return type_unsigned_int;
8266 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8267 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8269 default: panic("invalid atomic type");
8274 * Check the semantic restrictions for a binary expression.
8276 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8278 expression_t *const left = expression->left;
8279 expression_t *const right = expression->right;
8280 type_t *const orig_type_left = left->base.type;
8281 type_t *const orig_type_right = right->base.type;
8282 type_t *const type_left = skip_typeref(orig_type_left);
8283 type_t *const type_right = skip_typeref(orig_type_right);
8285 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8286 /* TODO: improve error message */
8287 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8288 errorf(&expression->base.source_position,
8289 "operation needs arithmetic types");
8294 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8295 expression->left = create_implicit_cast(left, arithmetic_type);
8296 expression->right = create_implicit_cast(right, arithmetic_type);
8297 expression->base.type = arithmetic_type;
8300 static void warn_div_by_zero(binary_expression_t const *const expression)
8302 if (!warning.div_by_zero ||
8303 !is_type_integer(expression->base.type))
8306 expression_t const *const right = expression->right;
8307 /* The type of the right operand can be different for /= */
8308 if (is_type_integer(right->base.type) &&
8309 is_constant_expression(right) &&
8310 !fold_constant_to_bool(right)) {
8311 warningf(&expression->base.source_position, "division by zero");
8316 * Check the semantic restrictions for a div/mod expression.
8318 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8320 semantic_binexpr_arithmetic(expression);
8321 warn_div_by_zero(expression);
8324 static void warn_addsub_in_shift(const expression_t *const expr)
8326 if (expr->base.parenthesized)
8330 switch (expr->kind) {
8331 case EXPR_BINARY_ADD: op = '+'; break;
8332 case EXPR_BINARY_SUB: op = '-'; break;
8336 warningf(&expr->base.source_position,
8337 "suggest parentheses around '%c' inside shift", op);
8340 static bool semantic_shift(binary_expression_t *expression)
8342 expression_t *const left = expression->left;
8343 expression_t *const right = expression->right;
8344 type_t *const orig_type_left = left->base.type;
8345 type_t *const orig_type_right = right->base.type;
8346 type_t * type_left = skip_typeref(orig_type_left);
8347 type_t * type_right = skip_typeref(orig_type_right);
8349 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8350 /* TODO: improve error message */
8351 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8352 errorf(&expression->base.source_position,
8353 "operands of shift operation must have integer types");
8358 type_left = promote_integer(type_left);
8360 if (is_constant_expression(right)) {
8361 long count = fold_constant_to_int(right);
8363 warningf(&right->base.source_position,
8364 "shift count must be non-negative");
8365 } else if ((unsigned long)count >=
8366 get_atomic_type_size(type_left->atomic.akind) * 8) {
8367 warningf(&right->base.source_position,
8368 "shift count must be less than type width");
8372 type_right = promote_integer(type_right);
8373 expression->right = create_implicit_cast(right, type_right);
8378 static void semantic_shift_op(binary_expression_t *expression)
8380 expression_t *const left = expression->left;
8381 expression_t *const right = expression->right;
8383 if (!semantic_shift(expression))
8386 if (warning.parentheses) {
8387 warn_addsub_in_shift(left);
8388 warn_addsub_in_shift(right);
8391 type_t *const orig_type_left = left->base.type;
8392 type_t * type_left = skip_typeref(orig_type_left);
8394 type_left = promote_integer(type_left);
8395 expression->left = create_implicit_cast(left, type_left);
8396 expression->base.type = type_left;
8399 static void semantic_add(binary_expression_t *expression)
8401 expression_t *const left = expression->left;
8402 expression_t *const right = expression->right;
8403 type_t *const orig_type_left = left->base.type;
8404 type_t *const orig_type_right = right->base.type;
8405 type_t *const type_left = skip_typeref(orig_type_left);
8406 type_t *const type_right = skip_typeref(orig_type_right);
8409 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8410 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8411 expression->left = create_implicit_cast(left, arithmetic_type);
8412 expression->right = create_implicit_cast(right, arithmetic_type);
8413 expression->base.type = arithmetic_type;
8414 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8415 check_pointer_arithmetic(&expression->base.source_position,
8416 type_left, orig_type_left);
8417 expression->base.type = type_left;
8418 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8419 check_pointer_arithmetic(&expression->base.source_position,
8420 type_right, orig_type_right);
8421 expression->base.type = type_right;
8422 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8423 errorf(&expression->base.source_position,
8424 "invalid operands to binary + ('%T', '%T')",
8425 orig_type_left, orig_type_right);
8429 static void semantic_sub(binary_expression_t *expression)
8431 expression_t *const left = expression->left;
8432 expression_t *const right = expression->right;
8433 type_t *const orig_type_left = left->base.type;
8434 type_t *const orig_type_right = right->base.type;
8435 type_t *const type_left = skip_typeref(orig_type_left);
8436 type_t *const type_right = skip_typeref(orig_type_right);
8437 source_position_t const *const pos = &expression->base.source_position;
8440 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8441 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8442 expression->left = create_implicit_cast(left, arithmetic_type);
8443 expression->right = create_implicit_cast(right, arithmetic_type);
8444 expression->base.type = arithmetic_type;
8445 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8446 check_pointer_arithmetic(&expression->base.source_position,
8447 type_left, orig_type_left);
8448 expression->base.type = type_left;
8449 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8450 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8451 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8452 if (!types_compatible(unqual_left, unqual_right)) {
8454 "subtracting pointers to incompatible types '%T' and '%T'",
8455 orig_type_left, orig_type_right);
8456 } else if (!is_type_object(unqual_left)) {
8457 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8458 errorf(pos, "subtracting pointers to non-object types '%T'",
8460 } else if (warning.other) {
8461 warningf(pos, "subtracting pointers to void");
8464 expression->base.type = type_ptrdiff_t;
8465 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8466 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8467 orig_type_left, orig_type_right);
8471 static void warn_string_literal_address(expression_t const* expr)
8473 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8474 expr = expr->unary.value;
8475 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8477 expr = expr->unary.value;
8480 if (expr->kind == EXPR_STRING_LITERAL ||
8481 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8482 warningf(&expr->base.source_position,
8483 "comparison with string literal results in unspecified behaviour");
8487 static void warn_comparison_in_comparison(const expression_t *const expr)
8489 if (expr->base.parenthesized)
8491 switch (expr->base.kind) {
8492 case EXPR_BINARY_LESS:
8493 case EXPR_BINARY_GREATER:
8494 case EXPR_BINARY_LESSEQUAL:
8495 case EXPR_BINARY_GREATEREQUAL:
8496 case EXPR_BINARY_NOTEQUAL:
8497 case EXPR_BINARY_EQUAL:
8498 warningf(&expr->base.source_position,
8499 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8506 static bool maybe_negative(expression_t const *const expr)
8509 !is_constant_expression(expr) ||
8510 fold_constant_to_int(expr) < 0;
8514 * Check the semantics of comparison expressions.
8516 * @param expression The expression to check.
8518 static void semantic_comparison(binary_expression_t *expression)
8520 expression_t *left = expression->left;
8521 expression_t *right = expression->right;
8523 if (warning.address) {
8524 warn_string_literal_address(left);
8525 warn_string_literal_address(right);
8527 expression_t const* const func_left = get_reference_address(left);
8528 if (func_left != NULL && is_null_pointer_constant(right)) {
8529 warningf(&expression->base.source_position,
8530 "the address of '%Y' will never be NULL",
8531 func_left->reference.entity->base.symbol);
8534 expression_t const* const func_right = get_reference_address(right);
8535 if (func_right != NULL && is_null_pointer_constant(right)) {
8536 warningf(&expression->base.source_position,
8537 "the address of '%Y' will never be NULL",
8538 func_right->reference.entity->base.symbol);
8542 if (warning.parentheses) {
8543 warn_comparison_in_comparison(left);
8544 warn_comparison_in_comparison(right);
8547 type_t *orig_type_left = left->base.type;
8548 type_t *orig_type_right = right->base.type;
8549 type_t *type_left = skip_typeref(orig_type_left);
8550 type_t *type_right = skip_typeref(orig_type_right);
8552 /* TODO non-arithmetic types */
8553 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8554 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8556 /* test for signed vs unsigned compares */
8557 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8558 bool const signed_left = is_type_signed(type_left);
8559 bool const signed_right = is_type_signed(type_right);
8560 if (signed_left != signed_right) {
8561 /* FIXME long long needs better const folding magic */
8562 /* TODO check whether constant value can be represented by other type */
8563 if ((signed_left && maybe_negative(left)) ||
8564 (signed_right && maybe_negative(right))) {
8565 warningf(&expression->base.source_position,
8566 "comparison between signed and unsigned");
8571 expression->left = create_implicit_cast(left, arithmetic_type);
8572 expression->right = create_implicit_cast(right, arithmetic_type);
8573 expression->base.type = arithmetic_type;
8574 if (warning.float_equal &&
8575 (expression->base.kind == EXPR_BINARY_EQUAL ||
8576 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8577 is_type_float(arithmetic_type)) {
8578 warningf(&expression->base.source_position,
8579 "comparing floating point with == or != is unsafe");
8581 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8582 /* TODO check compatibility */
8583 } else if (is_type_pointer(type_left)) {
8584 expression->right = create_implicit_cast(right, type_left);
8585 } else if (is_type_pointer(type_right)) {
8586 expression->left = create_implicit_cast(left, type_right);
8587 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8588 type_error_incompatible("invalid operands in comparison",
8589 &expression->base.source_position,
8590 type_left, type_right);
8592 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8596 * Checks if a compound type has constant fields.
8598 static bool has_const_fields(const compound_type_t *type)
8600 compound_t *compound = type->compound;
8601 entity_t *entry = compound->members.entities;
8603 for (; entry != NULL; entry = entry->base.next) {
8604 if (!is_declaration(entry))
8607 const type_t *decl_type = skip_typeref(entry->declaration.type);
8608 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8615 static bool is_valid_assignment_lhs(expression_t const* const left)
8617 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8618 type_t *const type_left = skip_typeref(orig_type_left);
8620 if (!is_lvalue(left)) {
8621 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8626 if (left->kind == EXPR_REFERENCE
8627 && left->reference.entity->kind == ENTITY_FUNCTION) {
8628 errorf(HERE, "cannot assign to function '%E'", left);
8632 if (is_type_array(type_left)) {
8633 errorf(HERE, "cannot assign to array '%E'", left);
8636 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8637 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8641 if (is_type_incomplete(type_left)) {
8642 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8643 left, orig_type_left);
8646 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8647 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8648 left, orig_type_left);
8655 static void semantic_arithmetic_assign(binary_expression_t *expression)
8657 expression_t *left = expression->left;
8658 expression_t *right = expression->right;
8659 type_t *orig_type_left = left->base.type;
8660 type_t *orig_type_right = right->base.type;
8662 if (!is_valid_assignment_lhs(left))
8665 type_t *type_left = skip_typeref(orig_type_left);
8666 type_t *type_right = skip_typeref(orig_type_right);
8668 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8669 /* TODO: improve error message */
8670 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8671 errorf(&expression->base.source_position,
8672 "operation needs arithmetic types");
8677 /* combined instructions are tricky. We can't create an implicit cast on
8678 * the left side, because we need the uncasted form for the store.
8679 * The ast2firm pass has to know that left_type must be right_type
8680 * for the arithmetic operation and create a cast by itself */
8681 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8682 expression->right = create_implicit_cast(right, arithmetic_type);
8683 expression->base.type = type_left;
8686 static void semantic_divmod_assign(binary_expression_t *expression)
8688 semantic_arithmetic_assign(expression);
8689 warn_div_by_zero(expression);
8692 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8694 expression_t *const left = expression->left;
8695 expression_t *const right = expression->right;
8696 type_t *const orig_type_left = left->base.type;
8697 type_t *const orig_type_right = right->base.type;
8698 type_t *const type_left = skip_typeref(orig_type_left);
8699 type_t *const type_right = skip_typeref(orig_type_right);
8701 if (!is_valid_assignment_lhs(left))
8704 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8705 /* combined instructions are tricky. We can't create an implicit cast on
8706 * the left side, because we need the uncasted form for the store.
8707 * The ast2firm pass has to know that left_type must be right_type
8708 * for the arithmetic operation and create a cast by itself */
8709 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8710 expression->right = create_implicit_cast(right, arithmetic_type);
8711 expression->base.type = type_left;
8712 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8713 check_pointer_arithmetic(&expression->base.source_position,
8714 type_left, orig_type_left);
8715 expression->base.type = type_left;
8716 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8717 errorf(&expression->base.source_position,
8718 "incompatible types '%T' and '%T' in assignment",
8719 orig_type_left, orig_type_right);
8723 static void semantic_integer_assign(binary_expression_t *expression)
8725 expression_t *left = expression->left;
8726 expression_t *right = expression->right;
8727 type_t *orig_type_left = left->base.type;
8728 type_t *orig_type_right = right->base.type;
8730 if (!is_valid_assignment_lhs(left))
8733 type_t *type_left = skip_typeref(orig_type_left);
8734 type_t *type_right = skip_typeref(orig_type_right);
8736 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8737 /* TODO: improve error message */
8738 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8739 errorf(&expression->base.source_position,
8740 "operation needs integer types");
8745 /* combined instructions are tricky. We can't create an implicit cast on
8746 * the left side, because we need the uncasted form for the store.
8747 * The ast2firm pass has to know that left_type must be right_type
8748 * for the arithmetic operation and create a cast by itself */
8749 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8750 expression->right = create_implicit_cast(right, arithmetic_type);
8751 expression->base.type = type_left;
8754 static void semantic_shift_assign(binary_expression_t *expression)
8756 expression_t *left = expression->left;
8758 if (!is_valid_assignment_lhs(left))
8761 if (!semantic_shift(expression))
8764 expression->base.type = skip_typeref(left->base.type);
8767 static void warn_logical_and_within_or(const expression_t *const expr)
8769 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8771 if (expr->base.parenthesized)
8773 warningf(&expr->base.source_position,
8774 "suggest parentheses around && within ||");
8778 * Check the semantic restrictions of a logical expression.
8780 static void semantic_logical_op(binary_expression_t *expression)
8782 /* §6.5.13:2 Each of the operands shall have scalar type.
8783 * §6.5.14:2 Each of the operands shall have scalar type. */
8784 semantic_condition(expression->left, "left operand of logical operator");
8785 semantic_condition(expression->right, "right operand of logical operator");
8786 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8787 warning.parentheses) {
8788 warn_logical_and_within_or(expression->left);
8789 warn_logical_and_within_or(expression->right);
8791 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8795 * Check the semantic restrictions of a binary assign expression.
8797 static void semantic_binexpr_assign(binary_expression_t *expression)
8799 expression_t *left = expression->left;
8800 type_t *orig_type_left = left->base.type;
8802 if (!is_valid_assignment_lhs(left))
8805 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8806 report_assign_error(error, orig_type_left, expression->right,
8807 "assignment", &left->base.source_position);
8808 expression->right = create_implicit_cast(expression->right, orig_type_left);
8809 expression->base.type = orig_type_left;
8813 * Determine if the outermost operation (or parts thereof) of the given
8814 * expression has no effect in order to generate a warning about this fact.
8815 * Therefore in some cases this only examines some of the operands of the
8816 * expression (see comments in the function and examples below).
8818 * f() + 23; // warning, because + has no effect
8819 * x || f(); // no warning, because x controls execution of f()
8820 * x ? y : f(); // warning, because y has no effect
8821 * (void)x; // no warning to be able to suppress the warning
8822 * This function can NOT be used for an "expression has definitely no effect"-
8824 static bool expression_has_effect(const expression_t *const expr)
8826 switch (expr->kind) {
8827 case EXPR_UNKNOWN: break;
8828 case EXPR_INVALID: return true; /* do NOT warn */
8829 case EXPR_REFERENCE: return false;
8830 case EXPR_REFERENCE_ENUM_VALUE: return false;
8831 /* suppress the warning for microsoft __noop operations */
8832 case EXPR_CONST: return expr->conste.is_ms_noop;
8833 case EXPR_CHARACTER_CONSTANT: return false;
8834 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8835 case EXPR_STRING_LITERAL: return false;
8836 case EXPR_WIDE_STRING_LITERAL: return false;
8837 case EXPR_LABEL_ADDRESS: return false;
8840 const call_expression_t *const call = &expr->call;
8841 if (call->function->kind != EXPR_REFERENCE)
8844 switch (call->function->reference.entity->function.btk) {
8845 /* FIXME: which builtins have no effect? */
8846 default: return true;
8850 /* Generate the warning if either the left or right hand side of a
8851 * conditional expression has no effect */
8852 case EXPR_CONDITIONAL: {
8853 conditional_expression_t const *const cond = &expr->conditional;
8854 expression_t const *const t = cond->true_expression;
8856 (t == NULL || expression_has_effect(t)) &&
8857 expression_has_effect(cond->false_expression);
8860 case EXPR_SELECT: return false;
8861 case EXPR_ARRAY_ACCESS: return false;
8862 case EXPR_SIZEOF: return false;
8863 case EXPR_CLASSIFY_TYPE: return false;
8864 case EXPR_ALIGNOF: return false;
8866 case EXPR_FUNCNAME: return false;
8867 case EXPR_BUILTIN_CONSTANT_P: return false;
8868 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8869 case EXPR_OFFSETOF: return false;
8870 case EXPR_VA_START: return true;
8871 case EXPR_VA_ARG: return true;
8872 case EXPR_VA_COPY: return true;
8873 case EXPR_STATEMENT: return true; // TODO
8874 case EXPR_COMPOUND_LITERAL: return false;
8876 case EXPR_UNARY_NEGATE: return false;
8877 case EXPR_UNARY_PLUS: return false;
8878 case EXPR_UNARY_BITWISE_NEGATE: return false;
8879 case EXPR_UNARY_NOT: return false;
8880 case EXPR_UNARY_DEREFERENCE: return false;
8881 case EXPR_UNARY_TAKE_ADDRESS: return false;
8882 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8883 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8884 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8885 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8887 /* Treat void casts as if they have an effect in order to being able to
8888 * suppress the warning */
8889 case EXPR_UNARY_CAST: {
8890 type_t *const type = skip_typeref(expr->base.type);
8891 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8894 case EXPR_UNARY_CAST_IMPLICIT: return true;
8895 case EXPR_UNARY_ASSUME: return true;
8896 case EXPR_UNARY_DELETE: return true;
8897 case EXPR_UNARY_DELETE_ARRAY: return true;
8898 case EXPR_UNARY_THROW: return true;
8900 case EXPR_BINARY_ADD: return false;
8901 case EXPR_BINARY_SUB: return false;
8902 case EXPR_BINARY_MUL: return false;
8903 case EXPR_BINARY_DIV: return false;
8904 case EXPR_BINARY_MOD: return false;
8905 case EXPR_BINARY_EQUAL: return false;
8906 case EXPR_BINARY_NOTEQUAL: return false;
8907 case EXPR_BINARY_LESS: return false;
8908 case EXPR_BINARY_LESSEQUAL: return false;
8909 case EXPR_BINARY_GREATER: return false;
8910 case EXPR_BINARY_GREATEREQUAL: return false;
8911 case EXPR_BINARY_BITWISE_AND: return false;
8912 case EXPR_BINARY_BITWISE_OR: return false;
8913 case EXPR_BINARY_BITWISE_XOR: return false;
8914 case EXPR_BINARY_SHIFTLEFT: return false;
8915 case EXPR_BINARY_SHIFTRIGHT: return false;
8916 case EXPR_BINARY_ASSIGN: return true;
8917 case EXPR_BINARY_MUL_ASSIGN: return true;
8918 case EXPR_BINARY_DIV_ASSIGN: return true;
8919 case EXPR_BINARY_MOD_ASSIGN: return true;
8920 case EXPR_BINARY_ADD_ASSIGN: return true;
8921 case EXPR_BINARY_SUB_ASSIGN: return true;
8922 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8923 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8924 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8925 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8926 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8928 /* Only examine the right hand side of && and ||, because the left hand
8929 * side already has the effect of controlling the execution of the right
8931 case EXPR_BINARY_LOGICAL_AND:
8932 case EXPR_BINARY_LOGICAL_OR:
8933 /* Only examine the right hand side of a comma expression, because the left
8934 * hand side has a separate warning */
8935 case EXPR_BINARY_COMMA:
8936 return expression_has_effect(expr->binary.right);
8938 case EXPR_BINARY_ISGREATER: return false;
8939 case EXPR_BINARY_ISGREATEREQUAL: return false;
8940 case EXPR_BINARY_ISLESS: return false;
8941 case EXPR_BINARY_ISLESSEQUAL: return false;
8942 case EXPR_BINARY_ISLESSGREATER: return false;
8943 case EXPR_BINARY_ISUNORDERED: return false;
8946 internal_errorf(HERE, "unexpected expression");
8949 static void semantic_comma(binary_expression_t *expression)
8951 if (warning.unused_value) {
8952 const expression_t *const left = expression->left;
8953 if (!expression_has_effect(left)) {
8954 warningf(&left->base.source_position,
8955 "left-hand operand of comma expression has no effect");
8958 expression->base.type = expression->right->base.type;
8962 * @param prec_r precedence of the right operand
8964 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8965 static expression_t *parse_##binexpression_type(expression_t *left) \
8967 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8968 binexpr->binary.left = left; \
8971 expression_t *right = parse_sub_expression(prec_r); \
8973 binexpr->binary.right = right; \
8974 sfunc(&binexpr->binary); \
8979 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8980 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8981 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8982 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8983 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8984 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8985 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8986 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8987 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8988 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8989 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8990 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8991 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8992 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8993 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8994 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8995 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8996 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8997 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8998 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8999 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9000 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9001 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9002 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9003 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9004 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9005 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9006 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9007 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9008 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9011 static expression_t *parse_sub_expression(precedence_t precedence)
9013 if (token.type < 0) {
9014 return expected_expression_error();
9017 expression_parser_function_t *parser
9018 = &expression_parsers[token.type];
9019 source_position_t source_position = token.source_position;
9022 if (parser->parser != NULL) {
9023 left = parser->parser();
9025 left = parse_primary_expression();
9027 assert(left != NULL);
9028 left->base.source_position = source_position;
9031 if (token.type < 0) {
9032 return expected_expression_error();
9035 parser = &expression_parsers[token.type];
9036 if (parser->infix_parser == NULL)
9038 if (parser->infix_precedence < precedence)
9041 left = parser->infix_parser(left);
9043 assert(left != NULL);
9044 assert(left->kind != EXPR_UNKNOWN);
9045 left->base.source_position = source_position;
9052 * Parse an expression.
9054 static expression_t *parse_expression(void)
9056 return parse_sub_expression(PREC_EXPRESSION);
9060 * Register a parser for a prefix-like operator.
9062 * @param parser the parser function
9063 * @param token_type the token type of the prefix token
9065 static void register_expression_parser(parse_expression_function parser,
9068 expression_parser_function_t *entry = &expression_parsers[token_type];
9070 if (entry->parser != NULL) {
9071 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9072 panic("trying to register multiple expression parsers for a token");
9074 entry->parser = parser;
9078 * Register a parser for an infix operator with given precedence.
9080 * @param parser the parser function
9081 * @param token_type the token type of the infix operator
9082 * @param precedence the precedence of the operator
9084 static void register_infix_parser(parse_expression_infix_function parser,
9085 int token_type, precedence_t precedence)
9087 expression_parser_function_t *entry = &expression_parsers[token_type];
9089 if (entry->infix_parser != NULL) {
9090 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9091 panic("trying to register multiple infix expression parsers for a "
9094 entry->infix_parser = parser;
9095 entry->infix_precedence = precedence;
9099 * Initialize the expression parsers.
9101 static void init_expression_parsers(void)
9103 memset(&expression_parsers, 0, sizeof(expression_parsers));
9105 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9106 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9107 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9108 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9109 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9110 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9111 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9112 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9113 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9114 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9115 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9116 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9117 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9118 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9119 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9120 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9121 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9122 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9123 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9124 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9125 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9126 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9127 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9128 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9129 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9130 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9131 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9132 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9133 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9134 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9135 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9136 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9137 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9138 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9139 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9140 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9141 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9143 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9144 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9145 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9146 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9147 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9148 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9149 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9150 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9151 register_expression_parser(parse_sizeof, T_sizeof);
9152 register_expression_parser(parse_alignof, T___alignof__);
9153 register_expression_parser(parse_extension, T___extension__);
9154 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9155 register_expression_parser(parse_delete, T_delete);
9156 register_expression_parser(parse_throw, T_throw);
9160 * Parse a asm statement arguments specification.
9162 static asm_argument_t *parse_asm_arguments(bool is_out)
9164 asm_argument_t *result = NULL;
9165 asm_argument_t **anchor = &result;
9167 while (token.type == T_STRING_LITERAL || token.type == '[') {
9168 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9169 memset(argument, 0, sizeof(argument[0]));
9172 if (token.type != T_IDENTIFIER) {
9173 parse_error_expected("while parsing asm argument",
9174 T_IDENTIFIER, NULL);
9177 argument->symbol = token.v.symbol;
9179 expect(']', end_error);
9182 argument->constraints = parse_string_literals();
9183 expect('(', end_error);
9184 add_anchor_token(')');
9185 expression_t *expression = parse_expression();
9186 rem_anchor_token(')');
9188 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9189 * change size or type representation (e.g. int -> long is ok, but
9190 * int -> float is not) */
9191 if (expression->kind == EXPR_UNARY_CAST) {
9192 type_t *const type = expression->base.type;
9193 type_kind_t const kind = type->kind;
9194 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9197 if (kind == TYPE_ATOMIC) {
9198 atomic_type_kind_t const akind = type->atomic.akind;
9199 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9200 size = get_atomic_type_size(akind);
9202 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9203 size = get_atomic_type_size(get_intptr_kind());
9207 expression_t *const value = expression->unary.value;
9208 type_t *const value_type = value->base.type;
9209 type_kind_t const value_kind = value_type->kind;
9211 unsigned value_flags;
9212 unsigned value_size;
9213 if (value_kind == TYPE_ATOMIC) {
9214 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9215 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9216 value_size = get_atomic_type_size(value_akind);
9217 } else if (value_kind == TYPE_POINTER) {
9218 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9219 value_size = get_atomic_type_size(get_intptr_kind());
9224 if (value_flags != flags || value_size != size)
9228 } while (expression->kind == EXPR_UNARY_CAST);
9232 if (!is_lvalue(expression)) {
9233 errorf(&expression->base.source_position,
9234 "asm output argument is not an lvalue");
9237 if (argument->constraints.begin[0] == '+')
9238 mark_vars_read(expression, NULL);
9240 mark_vars_read(expression, NULL);
9242 argument->expression = expression;
9243 expect(')', end_error);
9245 set_address_taken(expression, true);
9248 anchor = &argument->next;
9260 * Parse a asm statement clobber specification.
9262 static asm_clobber_t *parse_asm_clobbers(void)
9264 asm_clobber_t *result = NULL;
9265 asm_clobber_t **anchor = &result;
9267 while (token.type == T_STRING_LITERAL) {
9268 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9269 clobber->clobber = parse_string_literals();
9272 anchor = &clobber->next;
9282 * Parse an asm statement.
9284 static statement_t *parse_asm_statement(void)
9286 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9287 asm_statement_t *asm_statement = &statement->asms;
9291 if (next_if(T_volatile))
9292 asm_statement->is_volatile = true;
9294 expect('(', end_error);
9295 add_anchor_token(')');
9296 add_anchor_token(':');
9297 asm_statement->asm_text = parse_string_literals();
9299 if (!next_if(':')) {
9300 rem_anchor_token(':');
9304 asm_statement->outputs = parse_asm_arguments(true);
9305 if (!next_if(':')) {
9306 rem_anchor_token(':');
9310 asm_statement->inputs = parse_asm_arguments(false);
9311 if (!next_if(':')) {
9312 rem_anchor_token(':');
9315 rem_anchor_token(':');
9317 asm_statement->clobbers = parse_asm_clobbers();
9320 rem_anchor_token(')');
9321 expect(')', end_error);
9322 expect(';', end_error);
9324 if (asm_statement->outputs == NULL) {
9325 /* GCC: An 'asm' instruction without any output operands will be treated
9326 * identically to a volatile 'asm' instruction. */
9327 asm_statement->is_volatile = true;
9332 return create_invalid_statement();
9336 * Parse a case statement.
9338 static statement_t *parse_case_statement(void)
9340 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9341 source_position_t *const pos = &statement->base.source_position;
9345 expression_t *const expression = parse_expression();
9346 statement->case_label.expression = expression;
9347 if (!is_constant_expression(expression)) {
9348 /* This check does not prevent the error message in all cases of an
9349 * prior error while parsing the expression. At least it catches the
9350 * common case of a mistyped enum entry. */
9351 if (is_type_valid(skip_typeref(expression->base.type))) {
9352 errorf(pos, "case label does not reduce to an integer constant");
9354 statement->case_label.is_bad = true;
9356 long const val = fold_constant_to_int(expression);
9357 statement->case_label.first_case = val;
9358 statement->case_label.last_case = val;
9362 if (next_if(T_DOTDOTDOT)) {
9363 expression_t *const end_range = parse_expression();
9364 statement->case_label.end_range = end_range;
9365 if (!is_constant_expression(end_range)) {
9366 /* This check does not prevent the error message in all cases of an
9367 * prior error while parsing the expression. At least it catches the
9368 * common case of a mistyped enum entry. */
9369 if (is_type_valid(skip_typeref(end_range->base.type))) {
9370 errorf(pos, "case range does not reduce to an integer constant");
9372 statement->case_label.is_bad = true;
9374 long const val = fold_constant_to_int(end_range);
9375 statement->case_label.last_case = val;
9377 if (warning.other && val < statement->case_label.first_case) {
9378 statement->case_label.is_empty_range = true;
9379 warningf(pos, "empty range specified");
9385 PUSH_PARENT(statement);
9387 expect(':', end_error);
9390 if (current_switch != NULL) {
9391 if (! statement->case_label.is_bad) {
9392 /* Check for duplicate case values */
9393 case_label_statement_t *c = &statement->case_label;
9394 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9395 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9398 if (c->last_case < l->first_case || c->first_case > l->last_case)
9401 errorf(pos, "duplicate case value (previously used %P)",
9402 &l->base.source_position);
9406 /* link all cases into the switch statement */
9407 if (current_switch->last_case == NULL) {
9408 current_switch->first_case = &statement->case_label;
9410 current_switch->last_case->next = &statement->case_label;
9412 current_switch->last_case = &statement->case_label;
9414 errorf(pos, "case label not within a switch statement");
9417 statement_t *const inner_stmt = parse_statement();
9418 statement->case_label.statement = inner_stmt;
9419 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9420 errorf(&inner_stmt->base.source_position, "declaration after case label");
9428 * Parse a default statement.
9430 static statement_t *parse_default_statement(void)
9432 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9436 PUSH_PARENT(statement);
9438 expect(':', end_error);
9439 if (current_switch != NULL) {
9440 const case_label_statement_t *def_label = current_switch->default_label;
9441 if (def_label != NULL) {
9442 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9443 &def_label->base.source_position);
9445 current_switch->default_label = &statement->case_label;
9447 /* link all cases into the switch statement */
9448 if (current_switch->last_case == NULL) {
9449 current_switch->first_case = &statement->case_label;
9451 current_switch->last_case->next = &statement->case_label;
9453 current_switch->last_case = &statement->case_label;
9456 errorf(&statement->base.source_position,
9457 "'default' label not within a switch statement");
9460 statement_t *const inner_stmt = parse_statement();
9461 statement->case_label.statement = inner_stmt;
9462 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9463 errorf(&inner_stmt->base.source_position, "declaration after default label");
9470 return create_invalid_statement();
9474 * Parse a label statement.
9476 static statement_t *parse_label_statement(void)
9478 assert(token.type == T_IDENTIFIER);
9479 symbol_t *symbol = token.v.symbol;
9480 label_t *label = get_label(symbol);
9482 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9483 statement->label.label = label;
9487 PUSH_PARENT(statement);
9489 /* if statement is already set then the label is defined twice,
9490 * otherwise it was just mentioned in a goto/local label declaration so far
9492 if (label->statement != NULL) {
9493 errorf(HERE, "duplicate label '%Y' (declared %P)",
9494 symbol, &label->base.source_position);
9496 label->base.source_position = token.source_position;
9497 label->statement = statement;
9502 if (token.type == '}') {
9503 /* TODO only warn? */
9504 if (warning.other && false) {
9505 warningf(HERE, "label at end of compound statement");
9506 statement->label.statement = create_empty_statement();
9508 errorf(HERE, "label at end of compound statement");
9509 statement->label.statement = create_invalid_statement();
9511 } else if (token.type == ';') {
9512 /* Eat an empty statement here, to avoid the warning about an empty
9513 * statement after a label. label:; is commonly used to have a label
9514 * before a closing brace. */
9515 statement->label.statement = create_empty_statement();
9518 statement_t *const inner_stmt = parse_statement();
9519 statement->label.statement = inner_stmt;
9520 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9521 errorf(&inner_stmt->base.source_position, "declaration after label");
9525 /* remember the labels in a list for later checking */
9526 *label_anchor = &statement->label;
9527 label_anchor = &statement->label.next;
9534 * Parse an if statement.
9536 static statement_t *parse_if(void)
9538 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9542 PUSH_PARENT(statement);
9544 add_anchor_token('{');
9546 expect('(', end_error);
9547 add_anchor_token(')');
9548 expression_t *const expr = parse_expression();
9549 statement->ifs.condition = expr;
9550 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9552 semantic_condition(expr, "condition of 'if'-statment");
9553 mark_vars_read(expr, NULL);
9554 rem_anchor_token(')');
9555 expect(')', end_error);
9558 rem_anchor_token('{');
9560 add_anchor_token(T_else);
9561 statement_t *const true_stmt = parse_statement();
9562 statement->ifs.true_statement = true_stmt;
9563 rem_anchor_token(T_else);
9565 if (next_if(T_else)) {
9566 statement->ifs.false_statement = parse_statement();
9567 } else if (warning.parentheses &&
9568 true_stmt->kind == STATEMENT_IF &&
9569 true_stmt->ifs.false_statement != NULL) {
9570 warningf(&true_stmt->base.source_position,
9571 "suggest explicit braces to avoid ambiguous 'else'");
9579 * Check that all enums are handled in a switch.
9581 * @param statement the switch statement to check
9583 static void check_enum_cases(const switch_statement_t *statement)
9585 const type_t *type = skip_typeref(statement->expression->base.type);
9586 if (! is_type_enum(type))
9588 const enum_type_t *enumt = &type->enumt;
9590 /* if we have a default, no warnings */
9591 if (statement->default_label != NULL)
9594 /* FIXME: calculation of value should be done while parsing */
9595 /* TODO: quadratic algorithm here. Change to an n log n one */
9596 long last_value = -1;
9597 const entity_t *entry = enumt->enume->base.next;
9598 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9599 entry = entry->base.next) {
9600 const expression_t *expression = entry->enum_value.value;
9601 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9603 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9604 if (l->expression == NULL)
9606 if (l->first_case <= value && value <= l->last_case) {
9612 warningf(&statement->base.source_position,
9613 "enumeration value '%Y' not handled in switch",
9614 entry->base.symbol);
9621 * Parse a switch statement.
9623 static statement_t *parse_switch(void)
9625 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9629 PUSH_PARENT(statement);
9631 expect('(', end_error);
9632 add_anchor_token(')');
9633 expression_t *const expr = parse_expression();
9634 mark_vars_read(expr, NULL);
9635 type_t * type = skip_typeref(expr->base.type);
9636 if (is_type_integer(type)) {
9637 type = promote_integer(type);
9638 if (warning.traditional) {
9639 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9640 warningf(&expr->base.source_position,
9641 "'%T' switch expression not converted to '%T' in ISO C",
9645 } else if (is_type_valid(type)) {
9646 errorf(&expr->base.source_position,
9647 "switch quantity is not an integer, but '%T'", type);
9648 type = type_error_type;
9650 statement->switchs.expression = create_implicit_cast(expr, type);
9651 expect(')', end_error);
9652 rem_anchor_token(')');
9654 switch_statement_t *rem = current_switch;
9655 current_switch = &statement->switchs;
9656 statement->switchs.body = parse_statement();
9657 current_switch = rem;
9659 if (warning.switch_default &&
9660 statement->switchs.default_label == NULL) {
9661 warningf(&statement->base.source_position, "switch has no default case");
9663 if (warning.switch_enum)
9664 check_enum_cases(&statement->switchs);
9670 return create_invalid_statement();
9673 static statement_t *parse_loop_body(statement_t *const loop)
9675 statement_t *const rem = current_loop;
9676 current_loop = loop;
9678 statement_t *const body = parse_statement();
9685 * Parse a while statement.
9687 static statement_t *parse_while(void)
9689 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9693 PUSH_PARENT(statement);
9695 expect('(', end_error);
9696 add_anchor_token(')');
9697 expression_t *const cond = parse_expression();
9698 statement->whiles.condition = cond;
9699 /* §6.8.5:2 The controlling expression of an iteration statement shall
9700 * have scalar type. */
9701 semantic_condition(cond, "condition of 'while'-statement");
9702 mark_vars_read(cond, NULL);
9703 rem_anchor_token(')');
9704 expect(')', end_error);
9706 statement->whiles.body = parse_loop_body(statement);
9712 return create_invalid_statement();
9716 * Parse a do statement.
9718 static statement_t *parse_do(void)
9720 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9724 PUSH_PARENT(statement);
9726 add_anchor_token(T_while);
9727 statement->do_while.body = parse_loop_body(statement);
9728 rem_anchor_token(T_while);
9730 expect(T_while, end_error);
9731 expect('(', end_error);
9732 add_anchor_token(')');
9733 expression_t *const cond = parse_expression();
9734 statement->do_while.condition = cond;
9735 /* §6.8.5:2 The controlling expression of an iteration statement shall
9736 * have scalar type. */
9737 semantic_condition(cond, "condition of 'do-while'-statement");
9738 mark_vars_read(cond, NULL);
9739 rem_anchor_token(')');
9740 expect(')', end_error);
9741 expect(';', end_error);
9747 return create_invalid_statement();
9751 * Parse a for statement.
9753 static statement_t *parse_for(void)
9755 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9759 expect('(', end_error1);
9760 add_anchor_token(')');
9762 PUSH_PARENT(statement);
9764 size_t const top = environment_top();
9765 scope_t *old_scope = scope_push(&statement->fors.scope);
9767 bool old_gcc_extension = in_gcc_extension;
9768 while (next_if(T___extension__)) {
9769 in_gcc_extension = true;
9773 } else if (is_declaration_specifier(&token, false)) {
9774 parse_declaration(record_entity, DECL_FLAGS_NONE);
9776 add_anchor_token(';');
9777 expression_t *const init = parse_expression();
9778 statement->fors.initialisation = init;
9779 mark_vars_read(init, ENT_ANY);
9780 if (warning.unused_value && !expression_has_effect(init)) {
9781 warningf(&init->base.source_position,
9782 "initialisation of 'for'-statement has no effect");
9784 rem_anchor_token(';');
9785 expect(';', end_error2);
9787 in_gcc_extension = old_gcc_extension;
9789 if (token.type != ';') {
9790 add_anchor_token(';');
9791 expression_t *const cond = parse_expression();
9792 statement->fors.condition = cond;
9793 /* §6.8.5:2 The controlling expression of an iteration statement
9794 * shall have scalar type. */
9795 semantic_condition(cond, "condition of 'for'-statement");
9796 mark_vars_read(cond, NULL);
9797 rem_anchor_token(';');
9799 expect(';', end_error2);
9800 if (token.type != ')') {
9801 expression_t *const step = parse_expression();
9802 statement->fors.step = step;
9803 mark_vars_read(step, ENT_ANY);
9804 if (warning.unused_value && !expression_has_effect(step)) {
9805 warningf(&step->base.source_position,
9806 "step of 'for'-statement has no effect");
9809 expect(')', end_error2);
9810 rem_anchor_token(')');
9811 statement->fors.body = parse_loop_body(statement);
9813 assert(current_scope == &statement->fors.scope);
9814 scope_pop(old_scope);
9815 environment_pop_to(top);
9822 rem_anchor_token(')');
9823 assert(current_scope == &statement->fors.scope);
9824 scope_pop(old_scope);
9825 environment_pop_to(top);
9829 return create_invalid_statement();
9833 * Parse a goto statement.
9835 static statement_t *parse_goto(void)
9837 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9840 if (GNU_MODE && next_if('*')) {
9841 expression_t *expression = parse_expression();
9842 mark_vars_read(expression, NULL);
9844 /* Argh: although documentation says the expression must be of type void*,
9845 * gcc accepts anything that can be casted into void* without error */
9846 type_t *type = expression->base.type;
9848 if (type != type_error_type) {
9849 if (!is_type_pointer(type) && !is_type_integer(type)) {
9850 errorf(&expression->base.source_position,
9851 "cannot convert to a pointer type");
9852 } else if (warning.other && type != type_void_ptr) {
9853 warningf(&expression->base.source_position,
9854 "type of computed goto expression should be 'void*' not '%T'", type);
9856 expression = create_implicit_cast(expression, type_void_ptr);
9859 statement->gotos.expression = expression;
9860 } else if (token.type == T_IDENTIFIER) {
9861 symbol_t *symbol = token.v.symbol;
9863 statement->gotos.label = get_label(symbol);
9866 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9868 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9873 /* remember the goto's in a list for later checking */
9874 *goto_anchor = &statement->gotos;
9875 goto_anchor = &statement->gotos.next;
9877 expect(';', end_error);
9881 return create_invalid_statement();
9885 * Parse a continue statement.
9887 static statement_t *parse_continue(void)
9889 if (current_loop == NULL) {
9890 errorf(HERE, "continue statement not within loop");
9893 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9896 expect(';', end_error);
9903 * Parse a break statement.
9905 static statement_t *parse_break(void)
9907 if (current_switch == NULL && current_loop == NULL) {
9908 errorf(HERE, "break statement not within loop or switch");
9911 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9914 expect(';', end_error);
9921 * Parse a __leave statement.
9923 static statement_t *parse_leave_statement(void)
9925 if (current_try == NULL) {
9926 errorf(HERE, "__leave statement not within __try");
9929 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9932 expect(';', end_error);
9939 * Check if a given entity represents a local variable.
9941 static bool is_local_variable(const entity_t *entity)
9943 if (entity->kind != ENTITY_VARIABLE)
9946 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9947 case STORAGE_CLASS_AUTO:
9948 case STORAGE_CLASS_REGISTER: {
9949 const type_t *type = skip_typeref(entity->declaration.type);
9950 if (is_type_function(type)) {
9962 * Check if a given expression represents a local variable.
9964 static bool expression_is_local_variable(const expression_t *expression)
9966 if (expression->base.kind != EXPR_REFERENCE) {
9969 const entity_t *entity = expression->reference.entity;
9970 return is_local_variable(entity);
9974 * Check if a given expression represents a local variable and
9975 * return its declaration then, else return NULL.
9977 entity_t *expression_is_variable(const expression_t *expression)
9979 if (expression->base.kind != EXPR_REFERENCE) {
9982 entity_t *entity = expression->reference.entity;
9983 if (entity->kind != ENTITY_VARIABLE)
9990 * Parse a return statement.
9992 static statement_t *parse_return(void)
9996 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9998 expression_t *return_value = NULL;
9999 if (token.type != ';') {
10000 return_value = parse_expression();
10001 mark_vars_read(return_value, NULL);
10004 const type_t *const func_type = skip_typeref(current_function->base.type);
10005 assert(is_type_function(func_type));
10006 type_t *const return_type = skip_typeref(func_type->function.return_type);
10008 source_position_t const *const pos = &statement->base.source_position;
10009 if (return_value != NULL) {
10010 type_t *return_value_type = skip_typeref(return_value->base.type);
10012 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10013 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10014 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10015 /* Only warn in C mode, because GCC does the same */
10016 if (c_mode & _CXX || strict_mode) {
10018 "'return' with a value, in function returning 'void'");
10019 } else if (warning.other) {
10021 "'return' with a value, in function returning 'void'");
10023 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10024 /* Only warn in C mode, because GCC does the same */
10027 "'return' with expression in function returning 'void'");
10028 } else if (warning.other) {
10030 "'return' with expression in function returning 'void'");
10034 assign_error_t error = semantic_assign(return_type, return_value);
10035 report_assign_error(error, return_type, return_value, "'return'",
10038 return_value = create_implicit_cast(return_value, return_type);
10039 /* check for returning address of a local var */
10040 if (warning.other && return_value != NULL
10041 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10042 const expression_t *expression = return_value->unary.value;
10043 if (expression_is_local_variable(expression)) {
10044 warningf(pos, "function returns address of local variable");
10047 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10048 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10049 if (c_mode & _CXX || strict_mode) {
10051 "'return' without value, in function returning non-void");
10054 "'return' without value, in function returning non-void");
10057 statement->returns.value = return_value;
10059 expect(';', end_error);
10066 * Parse a declaration statement.
10068 static statement_t *parse_declaration_statement(void)
10070 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10072 entity_t *before = current_scope->last_entity;
10074 parse_external_declaration();
10076 parse_declaration(record_entity, DECL_FLAGS_NONE);
10079 declaration_statement_t *const decl = &statement->declaration;
10080 entity_t *const begin =
10081 before != NULL ? before->base.next : current_scope->entities;
10082 decl->declarations_begin = begin;
10083 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10089 * Parse an expression statement, ie. expr ';'.
10091 static statement_t *parse_expression_statement(void)
10093 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10095 expression_t *const expr = parse_expression();
10096 statement->expression.expression = expr;
10097 mark_vars_read(expr, ENT_ANY);
10099 expect(';', end_error);
10106 * Parse a microsoft __try { } __finally { } or
10107 * __try{ } __except() { }
10109 static statement_t *parse_ms_try_statment(void)
10111 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10114 PUSH_PARENT(statement);
10116 ms_try_statement_t *rem = current_try;
10117 current_try = &statement->ms_try;
10118 statement->ms_try.try_statement = parse_compound_statement(false);
10123 if (next_if(T___except)) {
10124 expect('(', end_error);
10125 add_anchor_token(')');
10126 expression_t *const expr = parse_expression();
10127 mark_vars_read(expr, NULL);
10128 type_t * type = skip_typeref(expr->base.type);
10129 if (is_type_integer(type)) {
10130 type = promote_integer(type);
10131 } else if (is_type_valid(type)) {
10132 errorf(&expr->base.source_position,
10133 "__expect expression is not an integer, but '%T'", type);
10134 type = type_error_type;
10136 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10137 rem_anchor_token(')');
10138 expect(')', end_error);
10139 statement->ms_try.final_statement = parse_compound_statement(false);
10140 } else if (next_if(T__finally)) {
10141 statement->ms_try.final_statement = parse_compound_statement(false);
10143 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10144 return create_invalid_statement();
10148 return create_invalid_statement();
10151 static statement_t *parse_empty_statement(void)
10153 if (warning.empty_statement) {
10154 warningf(HERE, "statement is empty");
10156 statement_t *const statement = create_empty_statement();
10161 static statement_t *parse_local_label_declaration(void)
10163 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10167 entity_t *begin = NULL, *end = NULL;
10170 if (token.type != T_IDENTIFIER) {
10171 parse_error_expected("while parsing local label declaration",
10172 T_IDENTIFIER, NULL);
10175 symbol_t *symbol = token.v.symbol;
10176 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10177 if (entity != NULL && entity->base.parent_scope == current_scope) {
10178 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10179 symbol, &entity->base.source_position);
10181 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10183 entity->base.parent_scope = current_scope;
10184 entity->base.namespc = NAMESPACE_LABEL;
10185 entity->base.source_position = token.source_position;
10186 entity->base.symbol = symbol;
10189 end->base.next = entity;
10194 environment_push(entity);
10197 } while (next_if(','));
10200 statement->declaration.declarations_begin = begin;
10201 statement->declaration.declarations_end = end;
10205 static void parse_namespace_definition(void)
10209 entity_t *entity = NULL;
10210 symbol_t *symbol = NULL;
10212 if (token.type == T_IDENTIFIER) {
10213 symbol = token.v.symbol;
10216 entity = get_entity(symbol, NAMESPACE_NORMAL);
10217 if (entity != NULL &&
10218 entity->kind != ENTITY_NAMESPACE &&
10219 entity->base.parent_scope == current_scope) {
10220 if (!is_error_entity(entity)) {
10221 error_redefined_as_different_kind(&token.source_position,
10222 entity, ENTITY_NAMESPACE);
10228 if (entity == NULL) {
10229 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10230 entity->base.symbol = symbol;
10231 entity->base.source_position = token.source_position;
10232 entity->base.namespc = NAMESPACE_NORMAL;
10233 entity->base.parent_scope = current_scope;
10236 if (token.type == '=') {
10237 /* TODO: parse namespace alias */
10238 panic("namespace alias definition not supported yet");
10241 environment_push(entity);
10242 append_entity(current_scope, entity);
10244 size_t const top = environment_top();
10245 scope_t *old_scope = scope_push(&entity->namespacee.members);
10247 expect('{', end_error);
10249 expect('}', end_error);
10252 assert(current_scope == &entity->namespacee.members);
10253 scope_pop(old_scope);
10254 environment_pop_to(top);
10258 * Parse a statement.
10259 * There's also parse_statement() which additionally checks for
10260 * "statement has no effect" warnings
10262 static statement_t *intern_parse_statement(void)
10264 statement_t *statement = NULL;
10266 /* declaration or statement */
10267 add_anchor_token(';');
10268 switch (token.type) {
10269 case T_IDENTIFIER: {
10270 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10271 if (la1_type == ':') {
10272 statement = parse_label_statement();
10273 } else if (is_typedef_symbol(token.v.symbol)) {
10274 statement = parse_declaration_statement();
10276 /* it's an identifier, the grammar says this must be an
10277 * expression statement. However it is common that users mistype
10278 * declaration types, so we guess a bit here to improve robustness
10279 * for incorrect programs */
10280 switch (la1_type) {
10283 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10284 goto expression_statment;
10289 statement = parse_declaration_statement();
10293 expression_statment:
10294 statement = parse_expression_statement();
10301 case T___extension__:
10302 /* This can be a prefix to a declaration or an expression statement.
10303 * We simply eat it now and parse the rest with tail recursion. */
10304 while (next_if(T___extension__)) {}
10305 bool old_gcc_extension = in_gcc_extension;
10306 in_gcc_extension = true;
10307 statement = intern_parse_statement();
10308 in_gcc_extension = old_gcc_extension;
10312 statement = parse_declaration_statement();
10316 statement = parse_local_label_declaration();
10319 case ';': statement = parse_empty_statement(); break;
10320 case '{': statement = parse_compound_statement(false); break;
10321 case T___leave: statement = parse_leave_statement(); break;
10322 case T___try: statement = parse_ms_try_statment(); break;
10323 case T_asm: statement = parse_asm_statement(); break;
10324 case T_break: statement = parse_break(); break;
10325 case T_case: statement = parse_case_statement(); break;
10326 case T_continue: statement = parse_continue(); break;
10327 case T_default: statement = parse_default_statement(); break;
10328 case T_do: statement = parse_do(); break;
10329 case T_for: statement = parse_for(); break;
10330 case T_goto: statement = parse_goto(); break;
10331 case T_if: statement = parse_if(); break;
10332 case T_return: statement = parse_return(); break;
10333 case T_switch: statement = parse_switch(); break;
10334 case T_while: statement = parse_while(); break;
10337 statement = parse_expression_statement();
10341 errorf(HERE, "unexpected token %K while parsing statement", &token);
10342 statement = create_invalid_statement();
10347 rem_anchor_token(';');
10349 assert(statement != NULL
10350 && statement->base.source_position.input_name != NULL);
10356 * parse a statement and emits "statement has no effect" warning if needed
10357 * (This is really a wrapper around intern_parse_statement with check for 1
10358 * single warning. It is needed, because for statement expressions we have
10359 * to avoid the warning on the last statement)
10361 static statement_t *parse_statement(void)
10363 statement_t *statement = intern_parse_statement();
10365 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10366 expression_t *expression = statement->expression.expression;
10367 if (!expression_has_effect(expression)) {
10368 warningf(&expression->base.source_position,
10369 "statement has no effect");
10377 * Parse a compound statement.
10379 static statement_t *parse_compound_statement(bool inside_expression_statement)
10381 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10383 PUSH_PARENT(statement);
10386 add_anchor_token('}');
10387 /* tokens, which can start a statement */
10388 /* TODO MS, __builtin_FOO */
10389 add_anchor_token('!');
10390 add_anchor_token('&');
10391 add_anchor_token('(');
10392 add_anchor_token('*');
10393 add_anchor_token('+');
10394 add_anchor_token('-');
10395 add_anchor_token('{');
10396 add_anchor_token('~');
10397 add_anchor_token(T_CHARACTER_CONSTANT);
10398 add_anchor_token(T_COLONCOLON);
10399 add_anchor_token(T_FLOATINGPOINT);
10400 add_anchor_token(T_IDENTIFIER);
10401 add_anchor_token(T_INTEGER);
10402 add_anchor_token(T_MINUSMINUS);
10403 add_anchor_token(T_PLUSPLUS);
10404 add_anchor_token(T_STRING_LITERAL);
10405 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10406 add_anchor_token(T_WIDE_STRING_LITERAL);
10407 add_anchor_token(T__Bool);
10408 add_anchor_token(T__Complex);
10409 add_anchor_token(T__Imaginary);
10410 add_anchor_token(T___FUNCTION__);
10411 add_anchor_token(T___PRETTY_FUNCTION__);
10412 add_anchor_token(T___alignof__);
10413 add_anchor_token(T___attribute__);
10414 add_anchor_token(T___builtin_va_start);
10415 add_anchor_token(T___extension__);
10416 add_anchor_token(T___func__);
10417 add_anchor_token(T___imag__);
10418 add_anchor_token(T___label__);
10419 add_anchor_token(T___real__);
10420 add_anchor_token(T___thread);
10421 add_anchor_token(T_asm);
10422 add_anchor_token(T_auto);
10423 add_anchor_token(T_bool);
10424 add_anchor_token(T_break);
10425 add_anchor_token(T_case);
10426 add_anchor_token(T_char);
10427 add_anchor_token(T_class);
10428 add_anchor_token(T_const);
10429 add_anchor_token(T_const_cast);
10430 add_anchor_token(T_continue);
10431 add_anchor_token(T_default);
10432 add_anchor_token(T_delete);
10433 add_anchor_token(T_double);
10434 add_anchor_token(T_do);
10435 add_anchor_token(T_dynamic_cast);
10436 add_anchor_token(T_enum);
10437 add_anchor_token(T_extern);
10438 add_anchor_token(T_false);
10439 add_anchor_token(T_float);
10440 add_anchor_token(T_for);
10441 add_anchor_token(T_goto);
10442 add_anchor_token(T_if);
10443 add_anchor_token(T_inline);
10444 add_anchor_token(T_int);
10445 add_anchor_token(T_long);
10446 add_anchor_token(T_new);
10447 add_anchor_token(T_operator);
10448 add_anchor_token(T_register);
10449 add_anchor_token(T_reinterpret_cast);
10450 add_anchor_token(T_restrict);
10451 add_anchor_token(T_return);
10452 add_anchor_token(T_short);
10453 add_anchor_token(T_signed);
10454 add_anchor_token(T_sizeof);
10455 add_anchor_token(T_static);
10456 add_anchor_token(T_static_cast);
10457 add_anchor_token(T_struct);
10458 add_anchor_token(T_switch);
10459 add_anchor_token(T_template);
10460 add_anchor_token(T_this);
10461 add_anchor_token(T_throw);
10462 add_anchor_token(T_true);
10463 add_anchor_token(T_try);
10464 add_anchor_token(T_typedef);
10465 add_anchor_token(T_typeid);
10466 add_anchor_token(T_typename);
10467 add_anchor_token(T_typeof);
10468 add_anchor_token(T_union);
10469 add_anchor_token(T_unsigned);
10470 add_anchor_token(T_using);
10471 add_anchor_token(T_void);
10472 add_anchor_token(T_volatile);
10473 add_anchor_token(T_wchar_t);
10474 add_anchor_token(T_while);
10476 size_t const top = environment_top();
10477 scope_t *old_scope = scope_push(&statement->compound.scope);
10479 statement_t **anchor = &statement->compound.statements;
10480 bool only_decls_so_far = true;
10481 while (token.type != '}') {
10482 if (token.type == T_EOF) {
10483 errorf(&statement->base.source_position,
10484 "EOF while parsing compound statement");
10487 statement_t *sub_statement = intern_parse_statement();
10488 if (is_invalid_statement(sub_statement)) {
10489 /* an error occurred. if we are at an anchor, return */
10495 if (warning.declaration_after_statement) {
10496 if (sub_statement->kind != STATEMENT_DECLARATION) {
10497 only_decls_so_far = false;
10498 } else if (!only_decls_so_far) {
10499 warningf(&sub_statement->base.source_position,
10500 "ISO C90 forbids mixed declarations and code");
10504 *anchor = sub_statement;
10506 while (sub_statement->base.next != NULL)
10507 sub_statement = sub_statement->base.next;
10509 anchor = &sub_statement->base.next;
10513 /* look over all statements again to produce no effect warnings */
10514 if (warning.unused_value) {
10515 statement_t *sub_statement = statement->compound.statements;
10516 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10517 if (sub_statement->kind != STATEMENT_EXPRESSION)
10519 /* don't emit a warning for the last expression in an expression
10520 * statement as it has always an effect */
10521 if (inside_expression_statement && sub_statement->base.next == NULL)
10524 expression_t *expression = sub_statement->expression.expression;
10525 if (!expression_has_effect(expression)) {
10526 warningf(&expression->base.source_position,
10527 "statement has no effect");
10533 rem_anchor_token(T_while);
10534 rem_anchor_token(T_wchar_t);
10535 rem_anchor_token(T_volatile);
10536 rem_anchor_token(T_void);
10537 rem_anchor_token(T_using);
10538 rem_anchor_token(T_unsigned);
10539 rem_anchor_token(T_union);
10540 rem_anchor_token(T_typeof);
10541 rem_anchor_token(T_typename);
10542 rem_anchor_token(T_typeid);
10543 rem_anchor_token(T_typedef);
10544 rem_anchor_token(T_try);
10545 rem_anchor_token(T_true);
10546 rem_anchor_token(T_throw);
10547 rem_anchor_token(T_this);
10548 rem_anchor_token(T_template);
10549 rem_anchor_token(T_switch);
10550 rem_anchor_token(T_struct);
10551 rem_anchor_token(T_static_cast);
10552 rem_anchor_token(T_static);
10553 rem_anchor_token(T_sizeof);
10554 rem_anchor_token(T_signed);
10555 rem_anchor_token(T_short);
10556 rem_anchor_token(T_return);
10557 rem_anchor_token(T_restrict);
10558 rem_anchor_token(T_reinterpret_cast);
10559 rem_anchor_token(T_register);
10560 rem_anchor_token(T_operator);
10561 rem_anchor_token(T_new);
10562 rem_anchor_token(T_long);
10563 rem_anchor_token(T_int);
10564 rem_anchor_token(T_inline);
10565 rem_anchor_token(T_if);
10566 rem_anchor_token(T_goto);
10567 rem_anchor_token(T_for);
10568 rem_anchor_token(T_float);
10569 rem_anchor_token(T_false);
10570 rem_anchor_token(T_extern);
10571 rem_anchor_token(T_enum);
10572 rem_anchor_token(T_dynamic_cast);
10573 rem_anchor_token(T_do);
10574 rem_anchor_token(T_double);
10575 rem_anchor_token(T_delete);
10576 rem_anchor_token(T_default);
10577 rem_anchor_token(T_continue);
10578 rem_anchor_token(T_const_cast);
10579 rem_anchor_token(T_const);
10580 rem_anchor_token(T_class);
10581 rem_anchor_token(T_char);
10582 rem_anchor_token(T_case);
10583 rem_anchor_token(T_break);
10584 rem_anchor_token(T_bool);
10585 rem_anchor_token(T_auto);
10586 rem_anchor_token(T_asm);
10587 rem_anchor_token(T___thread);
10588 rem_anchor_token(T___real__);
10589 rem_anchor_token(T___label__);
10590 rem_anchor_token(T___imag__);
10591 rem_anchor_token(T___func__);
10592 rem_anchor_token(T___extension__);
10593 rem_anchor_token(T___builtin_va_start);
10594 rem_anchor_token(T___attribute__);
10595 rem_anchor_token(T___alignof__);
10596 rem_anchor_token(T___PRETTY_FUNCTION__);
10597 rem_anchor_token(T___FUNCTION__);
10598 rem_anchor_token(T__Imaginary);
10599 rem_anchor_token(T__Complex);
10600 rem_anchor_token(T__Bool);
10601 rem_anchor_token(T_WIDE_STRING_LITERAL);
10602 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10603 rem_anchor_token(T_STRING_LITERAL);
10604 rem_anchor_token(T_PLUSPLUS);
10605 rem_anchor_token(T_MINUSMINUS);
10606 rem_anchor_token(T_INTEGER);
10607 rem_anchor_token(T_IDENTIFIER);
10608 rem_anchor_token(T_FLOATINGPOINT);
10609 rem_anchor_token(T_COLONCOLON);
10610 rem_anchor_token(T_CHARACTER_CONSTANT);
10611 rem_anchor_token('~');
10612 rem_anchor_token('{');
10613 rem_anchor_token('-');
10614 rem_anchor_token('+');
10615 rem_anchor_token('*');
10616 rem_anchor_token('(');
10617 rem_anchor_token('&');
10618 rem_anchor_token('!');
10619 rem_anchor_token('}');
10620 assert(current_scope == &statement->compound.scope);
10621 scope_pop(old_scope);
10622 environment_pop_to(top);
10629 * Check for unused global static functions and variables
10631 static void check_unused_globals(void)
10633 if (!warning.unused_function && !warning.unused_variable)
10636 for (const entity_t *entity = file_scope->entities; entity != NULL;
10637 entity = entity->base.next) {
10638 if (!is_declaration(entity))
10641 const declaration_t *declaration = &entity->declaration;
10642 if (declaration->used ||
10643 declaration->modifiers & DM_UNUSED ||
10644 declaration->modifiers & DM_USED ||
10645 declaration->storage_class != STORAGE_CLASS_STATIC)
10648 type_t *const type = declaration->type;
10650 if (entity->kind == ENTITY_FUNCTION) {
10651 /* inhibit warning for static inline functions */
10652 if (entity->function.is_inline)
10655 s = entity->function.statement != NULL ? "defined" : "declared";
10660 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10661 type, declaration->base.symbol, s);
10665 static void parse_global_asm(void)
10667 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10670 expect('(', end_error);
10672 statement->asms.asm_text = parse_string_literals();
10673 statement->base.next = unit->global_asm;
10674 unit->global_asm = statement;
10676 expect(')', end_error);
10677 expect(';', end_error);
10682 static void parse_linkage_specification(void)
10685 assert(token.type == T_STRING_LITERAL);
10687 const char *linkage = parse_string_literals().begin;
10689 linkage_kind_t old_linkage = current_linkage;
10690 linkage_kind_t new_linkage;
10691 if (strcmp(linkage, "C") == 0) {
10692 new_linkage = LINKAGE_C;
10693 } else if (strcmp(linkage, "C++") == 0) {
10694 new_linkage = LINKAGE_CXX;
10696 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10697 new_linkage = LINKAGE_INVALID;
10699 current_linkage = new_linkage;
10701 if (next_if('{')) {
10703 expect('}', end_error);
10709 assert(current_linkage == new_linkage);
10710 current_linkage = old_linkage;
10713 static void parse_external(void)
10715 switch (token.type) {
10716 DECLARATION_START_NO_EXTERN
10718 case T___extension__:
10719 /* tokens below are for implicit int */
10720 case '&': /* & x; -> int& x; (and error later, because C++ has no
10722 case '*': /* * x; -> int* x; */
10723 case '(': /* (x); -> int (x); */
10724 parse_external_declaration();
10728 if (look_ahead(1)->type == T_STRING_LITERAL) {
10729 parse_linkage_specification();
10731 parse_external_declaration();
10736 parse_global_asm();
10740 parse_namespace_definition();
10744 if (!strict_mode) {
10746 warningf(HERE, "stray ';' outside of function");
10753 errorf(HERE, "stray %K outside of function", &token);
10754 if (token.type == '(' || token.type == '{' || token.type == '[')
10755 eat_until_matching_token(token.type);
10761 static void parse_externals(void)
10763 add_anchor_token('}');
10764 add_anchor_token(T_EOF);
10767 unsigned char token_anchor_copy[T_LAST_TOKEN];
10768 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10771 while (token.type != T_EOF && token.type != '}') {
10773 bool anchor_leak = false;
10774 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10775 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10777 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10778 anchor_leak = true;
10781 if (in_gcc_extension) {
10782 errorf(HERE, "Leaked __extension__");
10783 anchor_leak = true;
10793 rem_anchor_token(T_EOF);
10794 rem_anchor_token('}');
10798 * Parse a translation unit.
10800 static void parse_translation_unit(void)
10802 add_anchor_token(T_EOF);
10807 if (token.type == T_EOF)
10810 errorf(HERE, "stray %K outside of function", &token);
10811 if (token.type == '(' || token.type == '{' || token.type == '[')
10812 eat_until_matching_token(token.type);
10820 * @return the translation unit or NULL if errors occurred.
10822 void start_parsing(void)
10824 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10825 label_stack = NEW_ARR_F(stack_entry_t, 0);
10826 diagnostic_count = 0;
10830 type_set_output(stderr);
10831 ast_set_output(stderr);
10833 assert(unit == NULL);
10834 unit = allocate_ast_zero(sizeof(unit[0]));
10836 assert(file_scope == NULL);
10837 file_scope = &unit->scope;
10839 assert(current_scope == NULL);
10840 scope_push(&unit->scope);
10842 create_gnu_builtins();
10844 create_microsoft_intrinsics();
10847 translation_unit_t *finish_parsing(void)
10849 assert(current_scope == &unit->scope);
10852 assert(file_scope == &unit->scope);
10853 check_unused_globals();
10856 DEL_ARR_F(environment_stack);
10857 DEL_ARR_F(label_stack);
10859 translation_unit_t *result = unit;
10864 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10865 * are given length one. */
10866 static void complete_incomplete_arrays(void)
10868 size_t n = ARR_LEN(incomplete_arrays);
10869 for (size_t i = 0; i != n; ++i) {
10870 declaration_t *const decl = incomplete_arrays[i];
10871 type_t *const orig_type = decl->type;
10872 type_t *const type = skip_typeref(orig_type);
10874 if (!is_type_incomplete(type))
10877 if (warning.other) {
10878 warningf(&decl->base.source_position,
10879 "array '%#T' assumed to have one element",
10880 orig_type, decl->base.symbol);
10883 type_t *const new_type = duplicate_type(type);
10884 new_type->array.size_constant = true;
10885 new_type->array.has_implicit_size = true;
10886 new_type->array.size = 1;
10888 type_t *const result = identify_new_type(new_type);
10890 decl->type = result;
10894 void prepare_main_collect2(entity_t *entity)
10896 // create call to __main
10897 symbol_t *symbol = symbol_table_insert("__main");
10898 entity_t *subsubmain_ent
10899 = create_implicit_function(symbol, &builtin_source_position);
10901 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10902 type_t *ftype = subsubmain_ent->declaration.type;
10903 ref->base.source_position = builtin_source_position;
10904 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10905 ref->reference.entity = subsubmain_ent;
10907 expression_t *call = allocate_expression_zero(EXPR_CALL);
10908 call->base.source_position = builtin_source_position;
10909 call->base.type = type_void;
10910 call->call.function = ref;
10912 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10913 expr_statement->base.source_position = builtin_source_position;
10914 expr_statement->expression.expression = call;
10916 statement_t *statement = entity->function.statement;
10917 assert(statement->kind == STATEMENT_COMPOUND);
10918 compound_statement_t *compounds = &statement->compound;
10920 expr_statement->base.next = compounds->statements;
10921 compounds->statements = expr_statement;
10926 lookahead_bufpos = 0;
10927 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10930 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10931 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10932 parse_translation_unit();
10933 complete_incomplete_arrays();
10934 DEL_ARR_F(incomplete_arrays);
10935 incomplete_arrays = NULL;
10939 * create a builtin function.
10941 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10943 symbol_t *symbol = symbol_table_insert(name);
10944 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10945 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10946 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10947 entity->declaration.type = function_type;
10948 entity->declaration.implicit = true;
10949 entity->base.symbol = symbol;
10950 entity->base.source_position = builtin_source_position;
10952 entity->function.btk = kind;
10954 record_entity(entity, /*is_definition=*/false);
10960 * Create predefined gnu builtins.
10962 static void create_gnu_builtins(void)
10964 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10966 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10967 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10968 GNU_BUILTIN(inf, make_function_0_type(type_double));
10969 GNU_BUILTIN(inff, make_function_0_type(type_float));
10970 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
10971 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
10972 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
10973 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
10974 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
10975 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
10976 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10977 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10978 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
10979 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
10980 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
10981 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
10982 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
10983 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
10984 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
10990 * Create predefined MS intrinsics.
10992 static void create_microsoft_intrinsics(void)
10994 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
10996 /* intrinsics for all architectures */
10997 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10998 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10999 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11000 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11001 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11002 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11003 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11005 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11006 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11007 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11008 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11011 MS_BUILTIN(_enable, make_function_0_type(type_void));
11012 MS_BUILTIN(_disable, make_function_0_type(type_void));
11013 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11014 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11015 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11016 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11017 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11018 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11019 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11020 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11021 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11022 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11023 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11025 if (machine_size <= 32) {
11026 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11027 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11029 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11030 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11037 * Initialize the parser.
11039 void init_parser(void)
11041 sym_anonymous = symbol_table_insert("<anonymous>");
11043 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11045 init_expression_parsers();
11046 obstack_init(&temp_obst);
11048 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11049 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11053 * Terminate the parser.
11055 void exit_parser(void)
11057 obstack_free(&temp_obst, NULL);