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 *last = NULL;
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 */
1277 last->next = argument;
1280 } while (next_if(','));
1281 expect(')', end_error);
1290 static attribute_t *parse_attribute_asm(void)
1294 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1296 expect('(', end_error);
1297 attribute->a.arguments = parse_attribute_arguments();
1304 static symbol_t *get_symbol_from_token(void)
1306 switch(token.type) {
1308 return token.v.symbol;
1337 /* maybe we need more tokens ... add them on demand */
1338 return get_token_symbol(&token);
1344 static attribute_t *parse_attribute_gnu_single(void)
1346 /* parse "any-word" */
1347 symbol_t *symbol = get_symbol_from_token();
1348 if (symbol == NULL) {
1349 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1353 const char *name = symbol->string;
1356 attribute_kind_t kind;
1357 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1358 const char *attribute_name = get_attribute_name(kind);
1359 if (attribute_name != NULL
1360 && strcmp_underscore(attribute_name, name) == 0)
1364 if (kind >= ATTRIBUTE_GNU_LAST) {
1365 if (warning.attribute) {
1366 warningf(HERE, "unknown attribute '%s' ignored", name);
1368 /* TODO: we should still save the attribute in the list... */
1369 kind = ATTRIBUTE_UNKNOWN;
1372 attribute_t *attribute = allocate_attribute_zero(kind);
1374 /* parse arguments */
1376 attribute->a.arguments = parse_attribute_arguments();
1384 static attribute_t *parse_attribute_gnu(void)
1386 attribute_t *first = NULL;
1387 attribute_t *last = NULL;
1389 eat(T___attribute__);
1390 expect('(', end_error);
1391 expect('(', end_error);
1393 if (token.type != ')') do {
1394 attribute_t *attribute = parse_attribute_gnu_single();
1395 if (attribute == NULL)
1401 last->next = attribute;
1404 } while (next_if(','));
1405 expect(')', end_error);
1406 expect(')', end_error);
1412 /** Parse attributes. */
1413 static attribute_t *parse_attributes(attribute_t *first)
1415 attribute_t *last = first;
1418 while (last->next != NULL)
1422 attribute_t *attribute;
1423 switch (token.type) {
1424 case T___attribute__:
1425 attribute = parse_attribute_gnu();
1429 attribute = parse_attribute_asm();
1434 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1439 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1442 case T__forceinline:
1444 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1449 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1454 /* TODO record modifier */
1456 warningf(HERE, "Ignoring declaration modifier %K", &token);
1457 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1467 last->next = attribute;
1473 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1475 static entity_t *determine_lhs_ent(expression_t *const expr,
1478 switch (expr->kind) {
1479 case EXPR_REFERENCE: {
1480 entity_t *const entity = expr->reference.entity;
1481 /* we should only find variables as lvalues... */
1482 if (entity->base.kind != ENTITY_VARIABLE
1483 && entity->base.kind != ENTITY_PARAMETER)
1489 case EXPR_ARRAY_ACCESS: {
1490 expression_t *const ref = expr->array_access.array_ref;
1491 entity_t * ent = NULL;
1492 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1493 ent = determine_lhs_ent(ref, lhs_ent);
1496 mark_vars_read(expr->select.compound, lhs_ent);
1498 mark_vars_read(expr->array_access.index, lhs_ent);
1503 if (is_type_compound(skip_typeref(expr->base.type))) {
1504 return determine_lhs_ent(expr->select.compound, lhs_ent);
1506 mark_vars_read(expr->select.compound, lhs_ent);
1511 case EXPR_UNARY_DEREFERENCE: {
1512 expression_t *const val = expr->unary.value;
1513 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1515 return determine_lhs_ent(val->unary.value, lhs_ent);
1517 mark_vars_read(val, NULL);
1523 mark_vars_read(expr, NULL);
1528 #define ENT_ANY ((entity_t*)-1)
1531 * Mark declarations, which are read. This is used to detect variables, which
1535 * x is not marked as "read", because it is only read to calculate its own new
1539 * x and y are not detected as "not read", because multiple variables are
1542 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1544 switch (expr->kind) {
1545 case EXPR_REFERENCE: {
1546 entity_t *const entity = expr->reference.entity;
1547 if (entity->kind != ENTITY_VARIABLE
1548 && entity->kind != ENTITY_PARAMETER)
1551 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1552 if (entity->kind == ENTITY_VARIABLE) {
1553 entity->variable.read = true;
1555 entity->parameter.read = true;
1562 // TODO respect pure/const
1563 mark_vars_read(expr->call.function, NULL);
1564 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1565 mark_vars_read(arg->expression, NULL);
1569 case EXPR_CONDITIONAL:
1570 // TODO lhs_decl should depend on whether true/false have an effect
1571 mark_vars_read(expr->conditional.condition, NULL);
1572 if (expr->conditional.true_expression != NULL)
1573 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1574 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1578 if (lhs_ent == ENT_ANY
1579 && !is_type_compound(skip_typeref(expr->base.type)))
1581 mark_vars_read(expr->select.compound, lhs_ent);
1584 case EXPR_ARRAY_ACCESS: {
1585 expression_t *const ref = expr->array_access.array_ref;
1586 mark_vars_read(ref, lhs_ent);
1587 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1588 mark_vars_read(expr->array_access.index, lhs_ent);
1593 mark_vars_read(expr->va_arge.ap, lhs_ent);
1597 mark_vars_read(expr->va_copye.src, lhs_ent);
1600 case EXPR_UNARY_CAST:
1601 /* Special case: Use void cast to mark a variable as "read" */
1602 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1607 case EXPR_UNARY_THROW:
1608 if (expr->unary.value == NULL)
1611 case EXPR_UNARY_DEREFERENCE:
1612 case EXPR_UNARY_DELETE:
1613 case EXPR_UNARY_DELETE_ARRAY:
1614 if (lhs_ent == ENT_ANY)
1618 case EXPR_UNARY_NEGATE:
1619 case EXPR_UNARY_PLUS:
1620 case EXPR_UNARY_BITWISE_NEGATE:
1621 case EXPR_UNARY_NOT:
1622 case EXPR_UNARY_TAKE_ADDRESS:
1623 case EXPR_UNARY_POSTFIX_INCREMENT:
1624 case EXPR_UNARY_POSTFIX_DECREMENT:
1625 case EXPR_UNARY_PREFIX_INCREMENT:
1626 case EXPR_UNARY_PREFIX_DECREMENT:
1627 case EXPR_UNARY_CAST_IMPLICIT:
1628 case EXPR_UNARY_ASSUME:
1630 mark_vars_read(expr->unary.value, lhs_ent);
1633 case EXPR_BINARY_ADD:
1634 case EXPR_BINARY_SUB:
1635 case EXPR_BINARY_MUL:
1636 case EXPR_BINARY_DIV:
1637 case EXPR_BINARY_MOD:
1638 case EXPR_BINARY_EQUAL:
1639 case EXPR_BINARY_NOTEQUAL:
1640 case EXPR_BINARY_LESS:
1641 case EXPR_BINARY_LESSEQUAL:
1642 case EXPR_BINARY_GREATER:
1643 case EXPR_BINARY_GREATEREQUAL:
1644 case EXPR_BINARY_BITWISE_AND:
1645 case EXPR_BINARY_BITWISE_OR:
1646 case EXPR_BINARY_BITWISE_XOR:
1647 case EXPR_BINARY_LOGICAL_AND:
1648 case EXPR_BINARY_LOGICAL_OR:
1649 case EXPR_BINARY_SHIFTLEFT:
1650 case EXPR_BINARY_SHIFTRIGHT:
1651 case EXPR_BINARY_COMMA:
1652 case EXPR_BINARY_ISGREATER:
1653 case EXPR_BINARY_ISGREATEREQUAL:
1654 case EXPR_BINARY_ISLESS:
1655 case EXPR_BINARY_ISLESSEQUAL:
1656 case EXPR_BINARY_ISLESSGREATER:
1657 case EXPR_BINARY_ISUNORDERED:
1658 mark_vars_read(expr->binary.left, lhs_ent);
1659 mark_vars_read(expr->binary.right, lhs_ent);
1662 case EXPR_BINARY_ASSIGN:
1663 case EXPR_BINARY_MUL_ASSIGN:
1664 case EXPR_BINARY_DIV_ASSIGN:
1665 case EXPR_BINARY_MOD_ASSIGN:
1666 case EXPR_BINARY_ADD_ASSIGN:
1667 case EXPR_BINARY_SUB_ASSIGN:
1668 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1669 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1670 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1671 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1672 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1673 if (lhs_ent == ENT_ANY)
1675 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1676 mark_vars_read(expr->binary.right, lhs_ent);
1681 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1687 case EXPR_CHARACTER_CONSTANT:
1688 case EXPR_WIDE_CHARACTER_CONSTANT:
1689 case EXPR_STRING_LITERAL:
1690 case EXPR_WIDE_STRING_LITERAL:
1691 case EXPR_COMPOUND_LITERAL: // TODO init?
1693 case EXPR_CLASSIFY_TYPE:
1696 case EXPR_BUILTIN_CONSTANT_P:
1697 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1699 case EXPR_STATEMENT: // TODO
1700 case EXPR_LABEL_ADDRESS:
1701 case EXPR_REFERENCE_ENUM_VALUE:
1705 panic("unhandled expression");
1708 static designator_t *parse_designation(void)
1710 designator_t *result = NULL;
1711 designator_t *last = NULL;
1714 designator_t *designator;
1715 switch (token.type) {
1717 designator = allocate_ast_zero(sizeof(designator[0]));
1718 designator->source_position = token.source_position;
1720 add_anchor_token(']');
1721 designator->array_index = parse_constant_expression();
1722 rem_anchor_token(']');
1723 expect(']', end_error);
1726 designator = allocate_ast_zero(sizeof(designator[0]));
1727 designator->source_position = token.source_position;
1729 if (token.type != T_IDENTIFIER) {
1730 parse_error_expected("while parsing designator",
1731 T_IDENTIFIER, NULL);
1734 designator->symbol = token.v.symbol;
1738 expect('=', end_error);
1742 assert(designator != NULL);
1744 last->next = designator;
1746 result = designator;
1754 static initializer_t *initializer_from_string(array_type_t *type,
1755 const string_t *const string)
1757 /* TODO: check len vs. size of array type */
1760 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1761 initializer->string.string = *string;
1766 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1767 wide_string_t *const string)
1769 /* TODO: check len vs. size of array type */
1772 initializer_t *const initializer =
1773 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1774 initializer->wide_string.string = *string;
1780 * Build an initializer from a given expression.
1782 static initializer_t *initializer_from_expression(type_t *orig_type,
1783 expression_t *expression)
1785 /* TODO check that expression is a constant expression */
1787 /* §6.7.8.14/15 char array may be initialized by string literals */
1788 type_t *type = skip_typeref(orig_type);
1789 type_t *expr_type_orig = expression->base.type;
1790 type_t *expr_type = skip_typeref(expr_type_orig);
1791 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1792 array_type_t *const array_type = &type->array;
1793 type_t *const element_type = skip_typeref(array_type->element_type);
1795 if (element_type->kind == TYPE_ATOMIC) {
1796 atomic_type_kind_t akind = element_type->atomic.akind;
1797 switch (expression->kind) {
1798 case EXPR_STRING_LITERAL:
1799 if (akind == ATOMIC_TYPE_CHAR
1800 || akind == ATOMIC_TYPE_SCHAR
1801 || akind == ATOMIC_TYPE_UCHAR) {
1802 return initializer_from_string(array_type,
1803 &expression->string.value);
1807 case EXPR_WIDE_STRING_LITERAL: {
1808 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1809 if (get_unqualified_type(element_type) == bare_wchar_type) {
1810 return initializer_from_wide_string(array_type,
1811 &expression->wide_string.value);
1822 assign_error_t error = semantic_assign(type, expression);
1823 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1825 report_assign_error(error, type, expression, "initializer",
1826 &expression->base.source_position);
1828 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1829 result->value.value = create_implicit_cast(expression, type);
1835 * Checks if a given expression can be used as an constant initializer.
1837 static bool is_initializer_constant(const expression_t *expression)
1839 return is_constant_expression(expression)
1840 || is_address_constant(expression);
1844 * Parses an scalar initializer.
1846 * §6.7.8.11; eat {} without warning
1848 static initializer_t *parse_scalar_initializer(type_t *type,
1849 bool must_be_constant)
1851 /* there might be extra {} hierarchies */
1855 warningf(HERE, "extra curly braces around scalar initializer");
1858 } while (next_if('{'));
1861 expression_t *expression = parse_assignment_expression();
1862 mark_vars_read(expression, NULL);
1863 if (must_be_constant && !is_initializer_constant(expression)) {
1864 errorf(&expression->base.source_position,
1865 "initialisation expression '%E' is not constant",
1869 initializer_t *initializer = initializer_from_expression(type, expression);
1871 if (initializer == NULL) {
1872 errorf(&expression->base.source_position,
1873 "expression '%E' (type '%T') doesn't match expected type '%T'",
1874 expression, expression->base.type, type);
1879 bool additional_warning_displayed = false;
1880 while (braces > 0) {
1882 if (token.type != '}') {
1883 if (!additional_warning_displayed && warning.other) {
1884 warningf(HERE, "additional elements in scalar initializer");
1885 additional_warning_displayed = true;
1896 * An entry in the type path.
1898 typedef struct type_path_entry_t type_path_entry_t;
1899 struct type_path_entry_t {
1900 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1902 size_t index; /**< For array types: the current index. */
1903 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1908 * A type path expression a position inside compound or array types.
1910 typedef struct type_path_t type_path_t;
1911 struct type_path_t {
1912 type_path_entry_t *path; /**< An flexible array containing the current path. */
1913 type_t *top_type; /**< type of the element the path points */
1914 size_t max_index; /**< largest index in outermost array */
1918 * Prints a type path for debugging.
1920 static __attribute__((unused)) void debug_print_type_path(
1921 const type_path_t *path)
1923 size_t len = ARR_LEN(path->path);
1925 for (size_t i = 0; i < len; ++i) {
1926 const type_path_entry_t *entry = & path->path[i];
1928 type_t *type = skip_typeref(entry->type);
1929 if (is_type_compound(type)) {
1930 /* in gcc mode structs can have no members */
1931 if (entry->v.compound_entry == NULL) {
1935 fprintf(stderr, ".%s",
1936 entry->v.compound_entry->base.symbol->string);
1937 } else if (is_type_array(type)) {
1938 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1940 fprintf(stderr, "-INVALID-");
1943 if (path->top_type != NULL) {
1944 fprintf(stderr, " (");
1945 print_type(path->top_type);
1946 fprintf(stderr, ")");
1951 * Return the top type path entry, ie. in a path
1952 * (type).a.b returns the b.
1954 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1956 size_t len = ARR_LEN(path->path);
1958 return &path->path[len-1];
1962 * Enlarge the type path by an (empty) element.
1964 static type_path_entry_t *append_to_type_path(type_path_t *path)
1966 size_t len = ARR_LEN(path->path);
1967 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1969 type_path_entry_t *result = & path->path[len];
1970 memset(result, 0, sizeof(result[0]));
1975 * Descending into a sub-type. Enter the scope of the current top_type.
1977 static void descend_into_subtype(type_path_t *path)
1979 type_t *orig_top_type = path->top_type;
1980 type_t *top_type = skip_typeref(orig_top_type);
1982 type_path_entry_t *top = append_to_type_path(path);
1983 top->type = top_type;
1985 if (is_type_compound(top_type)) {
1986 compound_t *compound = top_type->compound.compound;
1987 entity_t *entry = compound->members.entities;
1989 if (entry != NULL) {
1990 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1991 top->v.compound_entry = &entry->declaration;
1992 path->top_type = entry->declaration.type;
1994 path->top_type = NULL;
1996 } else if (is_type_array(top_type)) {
1998 path->top_type = top_type->array.element_type;
2000 assert(!is_type_valid(top_type));
2005 * Pop an entry from the given type path, ie. returning from
2006 * (type).a.b to (type).a
2008 static void ascend_from_subtype(type_path_t *path)
2010 type_path_entry_t *top = get_type_path_top(path);
2012 path->top_type = top->type;
2014 size_t len = ARR_LEN(path->path);
2015 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2019 * Pop entries from the given type path until the given
2020 * path level is reached.
2022 static void ascend_to(type_path_t *path, size_t top_path_level)
2024 size_t len = ARR_LEN(path->path);
2026 while (len > top_path_level) {
2027 ascend_from_subtype(path);
2028 len = ARR_LEN(path->path);
2032 static bool walk_designator(type_path_t *path, const designator_t *designator,
2033 bool used_in_offsetof)
2035 for (; designator != NULL; designator = designator->next) {
2036 type_path_entry_t *top = get_type_path_top(path);
2037 type_t *orig_type = top->type;
2039 type_t *type = skip_typeref(orig_type);
2041 if (designator->symbol != NULL) {
2042 symbol_t *symbol = designator->symbol;
2043 if (!is_type_compound(type)) {
2044 if (is_type_valid(type)) {
2045 errorf(&designator->source_position,
2046 "'.%Y' designator used for non-compound type '%T'",
2050 top->type = type_error_type;
2051 top->v.compound_entry = NULL;
2052 orig_type = type_error_type;
2054 compound_t *compound = type->compound.compound;
2055 entity_t *iter = compound->members.entities;
2056 for (; iter != NULL; iter = iter->base.next) {
2057 if (iter->base.symbol == symbol) {
2062 errorf(&designator->source_position,
2063 "'%T' has no member named '%Y'", orig_type, symbol);
2066 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2067 if (used_in_offsetof) {
2068 type_t *real_type = skip_typeref(iter->declaration.type);
2069 if (real_type->kind == TYPE_BITFIELD) {
2070 errorf(&designator->source_position,
2071 "offsetof designator '%Y' may not specify bitfield",
2077 top->type = orig_type;
2078 top->v.compound_entry = &iter->declaration;
2079 orig_type = iter->declaration.type;
2082 expression_t *array_index = designator->array_index;
2083 assert(designator->array_index != NULL);
2085 if (!is_type_array(type)) {
2086 if (is_type_valid(type)) {
2087 errorf(&designator->source_position,
2088 "[%E] designator used for non-array type '%T'",
2089 array_index, orig_type);
2094 long index = fold_constant_to_int(array_index);
2095 if (!used_in_offsetof) {
2097 errorf(&designator->source_position,
2098 "array index [%E] must be positive", array_index);
2099 } else if (type->array.size_constant) {
2100 long array_size = type->array.size;
2101 if (index >= array_size) {
2102 errorf(&designator->source_position,
2103 "designator [%E] (%d) exceeds array size %d",
2104 array_index, index, array_size);
2109 top->type = orig_type;
2110 top->v.index = (size_t) index;
2111 orig_type = type->array.element_type;
2113 path->top_type = orig_type;
2115 if (designator->next != NULL) {
2116 descend_into_subtype(path);
2125 static void advance_current_object(type_path_t *path, size_t top_path_level)
2127 type_path_entry_t *top = get_type_path_top(path);
2129 type_t *type = skip_typeref(top->type);
2130 if (is_type_union(type)) {
2131 /* in unions only the first element is initialized */
2132 top->v.compound_entry = NULL;
2133 } else if (is_type_struct(type)) {
2134 declaration_t *entry = top->v.compound_entry;
2136 entity_t *next_entity = entry->base.next;
2137 if (next_entity != NULL) {
2138 assert(is_declaration(next_entity));
2139 entry = &next_entity->declaration;
2144 top->v.compound_entry = entry;
2145 if (entry != NULL) {
2146 path->top_type = entry->type;
2149 } else if (is_type_array(type)) {
2150 assert(is_type_array(type));
2154 if (!type->array.size_constant || top->v.index < type->array.size) {
2158 assert(!is_type_valid(type));
2162 /* we're past the last member of the current sub-aggregate, try if we
2163 * can ascend in the type hierarchy and continue with another subobject */
2164 size_t len = ARR_LEN(path->path);
2166 if (len > top_path_level) {
2167 ascend_from_subtype(path);
2168 advance_current_object(path, top_path_level);
2170 path->top_type = NULL;
2175 * skip any {...} blocks until a closing bracket is reached.
2177 static void skip_initializers(void)
2181 while (token.type != '}') {
2182 if (token.type == T_EOF)
2184 if (token.type == '{') {
2192 static initializer_t *create_empty_initializer(void)
2194 static initializer_t empty_initializer
2195 = { .list = { { INITIALIZER_LIST }, 0 } };
2196 return &empty_initializer;
2200 * Parse a part of an initialiser for a struct or union,
2202 static initializer_t *parse_sub_initializer(type_path_t *path,
2203 type_t *outer_type, size_t top_path_level,
2204 parse_initializer_env_t *env)
2206 if (token.type == '}') {
2207 /* empty initializer */
2208 return create_empty_initializer();
2211 type_t *orig_type = path->top_type;
2212 type_t *type = NULL;
2214 if (orig_type == NULL) {
2215 /* We are initializing an empty compound. */
2217 type = skip_typeref(orig_type);
2220 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2223 designator_t *designator = NULL;
2224 if (token.type == '.' || token.type == '[') {
2225 designator = parse_designation();
2226 goto finish_designator;
2227 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2228 /* GNU-style designator ("identifier: value") */
2229 designator = allocate_ast_zero(sizeof(designator[0]));
2230 designator->source_position = token.source_position;
2231 designator->symbol = token.v.symbol;
2236 /* reset path to toplevel, evaluate designator from there */
2237 ascend_to(path, top_path_level);
2238 if (!walk_designator(path, designator, false)) {
2239 /* can't continue after designation error */
2243 initializer_t *designator_initializer
2244 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2245 designator_initializer->designator.designator = designator;
2246 ARR_APP1(initializer_t*, initializers, designator_initializer);
2248 orig_type = path->top_type;
2249 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2254 if (token.type == '{') {
2255 if (type != NULL && is_type_scalar(type)) {
2256 sub = parse_scalar_initializer(type, env->must_be_constant);
2260 if (env->entity != NULL) {
2262 "extra brace group at end of initializer for '%Y'",
2263 env->entity->base.symbol);
2265 errorf(HERE, "extra brace group at end of initializer");
2268 descend_into_subtype(path);
2270 add_anchor_token('}');
2271 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2273 rem_anchor_token('}');
2276 ascend_from_subtype(path);
2277 expect('}', end_error);
2279 expect('}', end_error);
2280 goto error_parse_next;
2284 /* must be an expression */
2285 expression_t *expression = parse_assignment_expression();
2286 mark_vars_read(expression, NULL);
2288 if (env->must_be_constant && !is_initializer_constant(expression)) {
2289 errorf(&expression->base.source_position,
2290 "Initialisation expression '%E' is not constant",
2295 /* we are already outside, ... */
2296 if (outer_type == NULL)
2297 goto error_parse_next;
2298 type_t *const outer_type_skip = skip_typeref(outer_type);
2299 if (is_type_compound(outer_type_skip) &&
2300 !outer_type_skip->compound.compound->complete) {
2301 goto error_parse_next;
2306 /* handle { "string" } special case */
2307 if ((expression->kind == EXPR_STRING_LITERAL
2308 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2309 && outer_type != NULL) {
2310 sub = initializer_from_expression(outer_type, expression);
2313 if (token.type != '}' && warning.other) {
2314 warningf(HERE, "excessive elements in initializer for type '%T'",
2317 /* TODO: eat , ... */
2322 /* descend into subtypes until expression matches type */
2324 orig_type = path->top_type;
2325 type = skip_typeref(orig_type);
2327 sub = initializer_from_expression(orig_type, expression);
2331 if (!is_type_valid(type)) {
2334 if (is_type_scalar(type)) {
2335 errorf(&expression->base.source_position,
2336 "expression '%E' doesn't match expected type '%T'",
2337 expression, orig_type);
2341 descend_into_subtype(path);
2345 /* update largest index of top array */
2346 const type_path_entry_t *first = &path->path[0];
2347 type_t *first_type = first->type;
2348 first_type = skip_typeref(first_type);
2349 if (is_type_array(first_type)) {
2350 size_t index = first->v.index;
2351 if (index > path->max_index)
2352 path->max_index = index;
2356 /* append to initializers list */
2357 ARR_APP1(initializer_t*, initializers, sub);
2360 if (warning.other) {
2361 if (env->entity != NULL) {
2362 warningf(HERE, "excess elements in initializer for '%Y'",
2363 env->entity->base.symbol);
2365 warningf(HERE, "excess elements in initializer");
2371 if (token.type == '}') {
2374 expect(',', end_error);
2375 if (token.type == '}') {
2380 /* advance to the next declaration if we are not at the end */
2381 advance_current_object(path, top_path_level);
2382 orig_type = path->top_type;
2383 if (orig_type != NULL)
2384 type = skip_typeref(orig_type);
2390 size_t len = ARR_LEN(initializers);
2391 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2392 initializer_t *result = allocate_ast_zero(size);
2393 result->kind = INITIALIZER_LIST;
2394 result->list.len = len;
2395 memcpy(&result->list.initializers, initializers,
2396 len * sizeof(initializers[0]));
2398 DEL_ARR_F(initializers);
2399 ascend_to(path, top_path_level+1);
2404 skip_initializers();
2405 DEL_ARR_F(initializers);
2406 ascend_to(path, top_path_level+1);
2411 * Parses an initializer. Parsers either a compound literal
2412 * (env->declaration == NULL) or an initializer of a declaration.
2414 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2416 type_t *type = skip_typeref(env->type);
2417 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2418 initializer_t *result;
2420 if (is_type_scalar(type)) {
2421 result = parse_scalar_initializer(type, env->must_be_constant);
2422 } else if (token.type == '{') {
2426 memset(&path, 0, sizeof(path));
2427 path.top_type = env->type;
2428 path.path = NEW_ARR_F(type_path_entry_t, 0);
2430 descend_into_subtype(&path);
2432 add_anchor_token('}');
2433 result = parse_sub_initializer(&path, env->type, 1, env);
2434 rem_anchor_token('}');
2436 max_index = path.max_index;
2437 DEL_ARR_F(path.path);
2439 expect('}', end_error);
2441 /* parse_scalar_initializer() also works in this case: we simply
2442 * have an expression without {} around it */
2443 result = parse_scalar_initializer(type, env->must_be_constant);
2446 /* §6.7.8:22 array initializers for arrays with unknown size determine
2447 * the array type size */
2448 if (is_type_array(type) && type->array.size_expression == NULL
2449 && result != NULL) {
2451 switch (result->kind) {
2452 case INITIALIZER_LIST:
2453 assert(max_index != 0xdeadbeaf);
2454 size = max_index + 1;
2457 case INITIALIZER_STRING:
2458 size = result->string.string.size;
2461 case INITIALIZER_WIDE_STRING:
2462 size = result->wide_string.string.size;
2465 case INITIALIZER_DESIGNATOR:
2466 case INITIALIZER_VALUE:
2467 /* can happen for parse errors */
2472 internal_errorf(HERE, "invalid initializer type");
2475 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2476 cnst->base.type = type_size_t;
2477 cnst->conste.v.int_value = size;
2479 type_t *new_type = duplicate_type(type);
2481 new_type->array.size_expression = cnst;
2482 new_type->array.size_constant = true;
2483 new_type->array.has_implicit_size = true;
2484 new_type->array.size = size;
2485 env->type = new_type;
2493 static void append_entity(scope_t *scope, entity_t *entity)
2495 if (scope->last_entity != NULL) {
2496 scope->last_entity->base.next = entity;
2498 scope->entities = entity;
2500 scope->last_entity = entity;
2504 static compound_t *parse_compound_type_specifier(bool is_struct)
2506 eat(is_struct ? T_struct : T_union);
2508 symbol_t *symbol = NULL;
2509 compound_t *compound = NULL;
2510 attribute_t *attributes = NULL;
2512 if (token.type == T___attribute__) {
2513 attributes = parse_attributes(NULL);
2516 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2517 if (token.type == T_IDENTIFIER) {
2518 /* the compound has a name, check if we have seen it already */
2519 symbol = token.v.symbol;
2522 entity_t *entity = get_tag(symbol, kind);
2523 if (entity != NULL) {
2524 compound = &entity->compound;
2525 if (compound->base.parent_scope != current_scope &&
2526 (token.type == '{' || token.type == ';')) {
2527 /* we're in an inner scope and have a definition. Shadow
2528 * existing definition in outer scope */
2530 } else if (compound->complete && token.type == '{') {
2531 assert(symbol != NULL);
2532 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2533 is_struct ? "struct" : "union", symbol,
2534 &compound->base.source_position);
2535 /* clear members in the hope to avoid further errors */
2536 compound->members.entities = NULL;
2539 } else if (token.type != '{') {
2541 parse_error_expected("while parsing struct type specifier",
2542 T_IDENTIFIER, '{', NULL);
2544 parse_error_expected("while parsing union type specifier",
2545 T_IDENTIFIER, '{', NULL);
2551 if (compound == NULL) {
2552 entity_t *entity = allocate_entity_zero(kind);
2553 compound = &entity->compound;
2555 compound->alignment = 1;
2556 compound->base.namespc = NAMESPACE_TAG;
2557 compound->base.source_position = token.source_position;
2558 compound->base.symbol = symbol;
2559 compound->base.parent_scope = current_scope;
2560 if (symbol != NULL) {
2561 environment_push(entity);
2563 append_entity(current_scope, entity);
2566 if (token.type == '{') {
2567 parse_compound_type_entries(compound);
2569 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2570 if (symbol == NULL) {
2571 assert(anonymous_entity == NULL);
2572 anonymous_entity = (entity_t*)compound;
2576 if (attributes != NULL) {
2577 handle_entity_attributes(attributes, (entity_t*) compound);
2583 static void parse_enum_entries(type_t *const enum_type)
2587 if (token.type == '}') {
2588 errorf(HERE, "empty enum not allowed");
2593 add_anchor_token('}');
2595 if (token.type != T_IDENTIFIER) {
2596 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2598 rem_anchor_token('}');
2602 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2603 entity->enum_value.enum_type = enum_type;
2604 entity->base.symbol = token.v.symbol;
2605 entity->base.source_position = token.source_position;
2609 expression_t *value = parse_constant_expression();
2611 value = create_implicit_cast(value, enum_type);
2612 entity->enum_value.value = value;
2617 record_entity(entity, false);
2618 } while (next_if(',') && token.type != '}');
2619 rem_anchor_token('}');
2621 expect('}', end_error);
2627 static type_t *parse_enum_specifier(void)
2633 switch (token.type) {
2635 symbol = token.v.symbol;
2638 entity = get_tag(symbol, ENTITY_ENUM);
2639 if (entity != NULL) {
2640 if (entity->base.parent_scope != current_scope &&
2641 (token.type == '{' || token.type == ';')) {
2642 /* we're in an inner scope and have a definition. Shadow
2643 * existing definition in outer scope */
2645 } else if (entity->enume.complete && token.type == '{') {
2646 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2647 symbol, &entity->base.source_position);
2658 parse_error_expected("while parsing enum type specifier",
2659 T_IDENTIFIER, '{', NULL);
2663 if (entity == NULL) {
2664 entity = allocate_entity_zero(ENTITY_ENUM);
2665 entity->base.namespc = NAMESPACE_TAG;
2666 entity->base.source_position = token.source_position;
2667 entity->base.symbol = symbol;
2668 entity->base.parent_scope = current_scope;
2671 type_t *const type = allocate_type_zero(TYPE_ENUM);
2672 type->enumt.enume = &entity->enume;
2673 type->enumt.akind = ATOMIC_TYPE_INT;
2675 if (token.type == '{') {
2676 if (symbol != NULL) {
2677 environment_push(entity);
2679 append_entity(current_scope, entity);
2680 entity->enume.complete = true;
2682 parse_enum_entries(type);
2683 parse_attributes(NULL);
2685 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2686 if (symbol == NULL) {
2687 assert(anonymous_entity == NULL);
2688 anonymous_entity = entity;
2690 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2691 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2699 * if a symbol is a typedef to another type, return true
2701 static bool is_typedef_symbol(symbol_t *symbol)
2703 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2704 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2707 static type_t *parse_typeof(void)
2713 expect('(', end_error);
2714 add_anchor_token(')');
2716 expression_t *expression = NULL;
2718 bool old_type_prop = in_type_prop;
2719 bool old_gcc_extension = in_gcc_extension;
2720 in_type_prop = true;
2722 while (next_if(T___extension__)) {
2723 /* This can be a prefix to a typename or an expression. */
2724 in_gcc_extension = true;
2726 switch (token.type) {
2728 if (is_typedef_symbol(token.v.symbol)) {
2729 type = parse_typename();
2731 expression = parse_expression();
2732 type = revert_automatic_type_conversion(expression);
2737 type = parse_typename();
2741 expression = parse_expression();
2742 type = expression->base.type;
2745 in_type_prop = old_type_prop;
2746 in_gcc_extension = old_gcc_extension;
2748 rem_anchor_token(')');
2749 expect(')', end_error);
2751 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2752 typeof_type->typeoft.expression = expression;
2753 typeof_type->typeoft.typeof_type = type;
2760 typedef enum specifiers_t {
2761 SPECIFIER_SIGNED = 1 << 0,
2762 SPECIFIER_UNSIGNED = 1 << 1,
2763 SPECIFIER_LONG = 1 << 2,
2764 SPECIFIER_INT = 1 << 3,
2765 SPECIFIER_DOUBLE = 1 << 4,
2766 SPECIFIER_CHAR = 1 << 5,
2767 SPECIFIER_WCHAR_T = 1 << 6,
2768 SPECIFIER_SHORT = 1 << 7,
2769 SPECIFIER_LONG_LONG = 1 << 8,
2770 SPECIFIER_FLOAT = 1 << 9,
2771 SPECIFIER_BOOL = 1 << 10,
2772 SPECIFIER_VOID = 1 << 11,
2773 SPECIFIER_INT8 = 1 << 12,
2774 SPECIFIER_INT16 = 1 << 13,
2775 SPECIFIER_INT32 = 1 << 14,
2776 SPECIFIER_INT64 = 1 << 15,
2777 SPECIFIER_INT128 = 1 << 16,
2778 SPECIFIER_COMPLEX = 1 << 17,
2779 SPECIFIER_IMAGINARY = 1 << 18,
2782 static type_t *create_builtin_type(symbol_t *const symbol,
2783 type_t *const real_type)
2785 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2786 type->builtin.symbol = symbol;
2787 type->builtin.real_type = real_type;
2788 return identify_new_type(type);
2791 static type_t *get_typedef_type(symbol_t *symbol)
2793 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2794 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2797 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2798 type->typedeft.typedefe = &entity->typedefe;
2803 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2805 expect('(', end_error);
2807 attribute_property_argument_t *property
2808 = allocate_ast_zero(sizeof(*property));
2811 if (token.type != T_IDENTIFIER) {
2812 parse_error_expected("while parsing property declspec",
2813 T_IDENTIFIER, NULL);
2818 symbol_t *symbol = token.v.symbol;
2820 if (strcmp(symbol->string, "put") == 0) {
2822 } else if (strcmp(symbol->string, "get") == 0) {
2825 errorf(HERE, "expected put or get in property declspec");
2828 expect('=', end_error);
2829 if (token.type != T_IDENTIFIER) {
2830 parse_error_expected("while parsing property declspec",
2831 T_IDENTIFIER, NULL);
2835 property->put_symbol = token.v.symbol;
2837 property->get_symbol = token.v.symbol;
2840 } while (next_if(','));
2842 attribute->a.property = property;
2844 expect(')', end_error);
2850 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2852 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2853 if (next_if(T_restrict)) {
2854 kind = ATTRIBUTE_MS_RESTRICT;
2855 } else if (token.type == T_IDENTIFIER) {
2856 const char *name = token.v.symbol->string;
2858 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2860 const char *attribute_name = get_attribute_name(k);
2861 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2867 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2868 warningf(HERE, "unknown __declspec '%s' ignored", name);
2871 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2875 attribute_t *attribute = allocate_attribute_zero(kind);
2877 if (kind == ATTRIBUTE_MS_PROPERTY) {
2878 return parse_attribute_ms_property(attribute);
2881 /* parse arguments */
2883 attribute->a.arguments = parse_attribute_arguments();
2888 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2892 expect('(', end_error);
2897 add_anchor_token(')');
2899 attribute_t *last = first;
2902 while (last->next != NULL)
2906 attribute_t *attribute
2907 = parse_microsoft_extended_decl_modifier_single();
2908 if (attribute == NULL)
2914 last->next = attribute;
2917 } while (next_if(','));
2919 rem_anchor_token(')');
2920 expect(')', end_error);
2924 rem_anchor_token(')');
2928 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2930 entity_t *entity = allocate_entity_zero(kind);
2931 entity->base.source_position = *HERE;
2932 entity->base.symbol = symbol;
2933 if (is_declaration(entity)) {
2934 entity->declaration.type = type_error_type;
2935 entity->declaration.implicit = true;
2936 } else if (kind == ENTITY_TYPEDEF) {
2937 entity->typedefe.type = type_error_type;
2938 entity->typedefe.builtin = true;
2940 if (kind != ENTITY_COMPOUND_MEMBER)
2941 record_entity(entity, false);
2945 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2947 type_t *type = NULL;
2948 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2949 unsigned type_specifiers = 0;
2950 bool newtype = false;
2951 bool saw_error = false;
2952 bool old_gcc_extension = in_gcc_extension;
2954 specifiers->source_position = token.source_position;
2957 specifiers->attributes = parse_attributes(specifiers->attributes);
2959 switch (token.type) {
2961 #define MATCH_STORAGE_CLASS(token, class) \
2963 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2964 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2966 specifiers->storage_class = class; \
2967 if (specifiers->thread_local) \
2968 goto check_thread_storage_class; \
2972 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2973 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2974 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2975 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2976 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2979 specifiers->attributes
2980 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2984 if (specifiers->thread_local) {
2985 errorf(HERE, "duplicate '__thread'");
2987 specifiers->thread_local = true;
2988 check_thread_storage_class:
2989 switch (specifiers->storage_class) {
2990 case STORAGE_CLASS_EXTERN:
2991 case STORAGE_CLASS_NONE:
2992 case STORAGE_CLASS_STATIC:
2996 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2997 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2998 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2999 wrong_thread_stoarge_class:
3000 errorf(HERE, "'__thread' used with '%s'", wrong);
3007 /* type qualifiers */
3008 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3010 qualifiers |= qualifier; \
3014 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3015 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3016 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3017 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3018 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3019 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3020 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3021 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3023 case T___extension__:
3025 in_gcc_extension = true;
3028 /* type specifiers */
3029 #define MATCH_SPECIFIER(token, specifier, name) \
3031 if (type_specifiers & specifier) { \
3032 errorf(HERE, "multiple " name " type specifiers given"); \
3034 type_specifiers |= specifier; \
3039 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3040 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3041 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3042 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3043 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3044 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3045 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3046 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3047 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3048 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3049 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3050 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3051 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3052 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3053 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3054 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3055 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3056 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3060 specifiers->is_inline = true;
3064 case T__forceinline:
3066 specifiers->modifiers |= DM_FORCEINLINE;
3071 if (type_specifiers & SPECIFIER_LONG_LONG) {
3072 errorf(HERE, "multiple type specifiers given");
3073 } else if (type_specifiers & SPECIFIER_LONG) {
3074 type_specifiers |= SPECIFIER_LONG_LONG;
3076 type_specifiers |= SPECIFIER_LONG;
3081 #define CHECK_DOUBLE_TYPE() \
3082 if ( type != NULL) \
3083 errorf(HERE, "multiple data types in declaration specifiers");
3086 CHECK_DOUBLE_TYPE();
3087 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3089 type->compound.compound = parse_compound_type_specifier(true);
3092 CHECK_DOUBLE_TYPE();
3093 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3094 type->compound.compound = parse_compound_type_specifier(false);
3097 CHECK_DOUBLE_TYPE();
3098 type = parse_enum_specifier();
3101 CHECK_DOUBLE_TYPE();
3102 type = parse_typeof();
3104 case T___builtin_va_list:
3105 CHECK_DOUBLE_TYPE();
3106 type = duplicate_type(type_valist);
3110 case T_IDENTIFIER: {
3111 /* only parse identifier if we haven't found a type yet */
3112 if (type != NULL || type_specifiers != 0) {
3113 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3114 * declaration, so it doesn't generate errors about expecting '(' or
3116 switch (look_ahead(1)->type) {
3123 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3127 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3132 goto finish_specifiers;
3136 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3137 if (typedef_type == NULL) {
3138 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3139 * declaration, so it doesn't generate 'implicit int' followed by more
3140 * errors later on. */
3141 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3147 errorf(HERE, "%K does not name a type", &token);
3150 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3152 type = allocate_type_zero(TYPE_TYPEDEF);
3153 type->typedeft.typedefe = &entity->typedefe;
3157 if (la1_type == '&' || la1_type == '*')
3158 goto finish_specifiers;
3163 goto finish_specifiers;
3168 type = typedef_type;
3172 /* function specifier */
3174 goto finish_specifiers;
3179 specifiers->attributes = parse_attributes(specifiers->attributes);
3181 in_gcc_extension = old_gcc_extension;
3183 if (type == NULL || (saw_error && type_specifiers != 0)) {
3184 atomic_type_kind_t atomic_type;
3186 /* match valid basic types */
3187 switch (type_specifiers) {
3188 case SPECIFIER_VOID:
3189 atomic_type = ATOMIC_TYPE_VOID;
3191 case SPECIFIER_WCHAR_T:
3192 atomic_type = ATOMIC_TYPE_WCHAR_T;
3194 case SPECIFIER_CHAR:
3195 atomic_type = ATOMIC_TYPE_CHAR;
3197 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3198 atomic_type = ATOMIC_TYPE_SCHAR;
3200 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3201 atomic_type = ATOMIC_TYPE_UCHAR;
3203 case SPECIFIER_SHORT:
3204 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3205 case SPECIFIER_SHORT | SPECIFIER_INT:
3206 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3207 atomic_type = ATOMIC_TYPE_SHORT;
3209 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3210 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3211 atomic_type = ATOMIC_TYPE_USHORT;
3214 case SPECIFIER_SIGNED:
3215 case SPECIFIER_SIGNED | SPECIFIER_INT:
3216 atomic_type = ATOMIC_TYPE_INT;
3218 case SPECIFIER_UNSIGNED:
3219 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3220 atomic_type = ATOMIC_TYPE_UINT;
3222 case SPECIFIER_LONG:
3223 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3224 case SPECIFIER_LONG | SPECIFIER_INT:
3225 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3226 atomic_type = ATOMIC_TYPE_LONG;
3228 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3229 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3230 atomic_type = ATOMIC_TYPE_ULONG;
3233 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3234 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3235 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3236 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3238 atomic_type = ATOMIC_TYPE_LONGLONG;
3239 goto warn_about_long_long;
3241 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3242 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3244 atomic_type = ATOMIC_TYPE_ULONGLONG;
3245 warn_about_long_long:
3246 if (warning.long_long) {
3247 warningf(&specifiers->source_position,
3248 "ISO C90 does not support 'long long'");
3252 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3253 atomic_type = unsigned_int8_type_kind;
3256 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3257 atomic_type = unsigned_int16_type_kind;
3260 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3261 atomic_type = unsigned_int32_type_kind;
3264 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3265 atomic_type = unsigned_int64_type_kind;
3268 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3269 atomic_type = unsigned_int128_type_kind;
3272 case SPECIFIER_INT8:
3273 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3274 atomic_type = int8_type_kind;
3277 case SPECIFIER_INT16:
3278 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3279 atomic_type = int16_type_kind;
3282 case SPECIFIER_INT32:
3283 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3284 atomic_type = int32_type_kind;
3287 case SPECIFIER_INT64:
3288 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3289 atomic_type = int64_type_kind;
3292 case SPECIFIER_INT128:
3293 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3294 atomic_type = int128_type_kind;
3297 case SPECIFIER_FLOAT:
3298 atomic_type = ATOMIC_TYPE_FLOAT;
3300 case SPECIFIER_DOUBLE:
3301 atomic_type = ATOMIC_TYPE_DOUBLE;
3303 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3304 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3306 case SPECIFIER_BOOL:
3307 atomic_type = ATOMIC_TYPE_BOOL;
3309 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3310 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3311 atomic_type = ATOMIC_TYPE_FLOAT;
3313 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3314 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3315 atomic_type = ATOMIC_TYPE_DOUBLE;
3317 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3318 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3319 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3322 /* invalid specifier combination, give an error message */
3323 if (type_specifiers == 0) {
3327 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3328 if (!(c_mode & _CXX) && !strict_mode) {
3329 if (warning.implicit_int) {
3330 warningf(HERE, "no type specifiers in declaration, using 'int'");
3332 atomic_type = ATOMIC_TYPE_INT;
3335 errorf(HERE, "no type specifiers given in declaration");
3337 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3338 (type_specifiers & SPECIFIER_UNSIGNED)) {
3339 errorf(HERE, "signed and unsigned specifiers given");
3340 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3341 errorf(HERE, "only integer types can be signed or unsigned");
3343 errorf(HERE, "multiple datatypes in declaration");
3348 if (type_specifiers & SPECIFIER_COMPLEX) {
3349 type = allocate_type_zero(TYPE_COMPLEX);
3350 type->complex.akind = atomic_type;
3351 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3352 type = allocate_type_zero(TYPE_IMAGINARY);
3353 type->imaginary.akind = atomic_type;
3355 type = allocate_type_zero(TYPE_ATOMIC);
3356 type->atomic.akind = atomic_type;
3359 } else if (type_specifiers != 0) {
3360 errorf(HERE, "multiple datatypes in declaration");
3363 /* FIXME: check type qualifiers here */
3364 type->base.qualifiers = qualifiers;
3367 type = identify_new_type(type);
3369 type = typehash_insert(type);
3372 if (specifiers->attributes != NULL)
3373 type = handle_type_attributes(specifiers->attributes, type);
3374 specifiers->type = type;
3378 specifiers->type = type_error_type;
3381 static type_qualifiers_t parse_type_qualifiers(void)
3383 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3386 switch (token.type) {
3387 /* type qualifiers */
3388 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3389 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3390 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3391 /* microsoft extended type modifiers */
3392 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3393 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3394 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3395 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3396 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3405 * Parses an K&R identifier list
3407 static void parse_identifier_list(scope_t *scope)
3410 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3411 entity->base.source_position = token.source_position;
3412 entity->base.namespc = NAMESPACE_NORMAL;
3413 entity->base.symbol = token.v.symbol;
3414 /* a K&R parameter has no type, yet */
3418 append_entity(scope, entity);
3419 } while (next_if(',') && token.type == T_IDENTIFIER);
3422 static entity_t *parse_parameter(void)
3424 declaration_specifiers_t specifiers;
3425 memset(&specifiers, 0, sizeof(specifiers));
3427 parse_declaration_specifiers(&specifiers);
3429 entity_t *entity = parse_declarator(&specifiers,
3430 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3431 anonymous_entity = NULL;
3435 static void semantic_parameter_incomplete(const entity_t *entity)
3437 assert(entity->kind == ENTITY_PARAMETER);
3439 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3440 * list in a function declarator that is part of a
3441 * definition of that function shall not have
3442 * incomplete type. */
3443 type_t *type = skip_typeref(entity->declaration.type);
3444 if (is_type_incomplete(type)) {
3445 errorf(&entity->base.source_position,
3446 "parameter '%#T' has incomplete type",
3447 entity->declaration.type, entity->base.symbol);
3451 static bool has_parameters(void)
3453 /* func(void) is not a parameter */
3454 if (token.type == T_IDENTIFIER) {
3455 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3458 if (entity->kind != ENTITY_TYPEDEF)
3460 if (skip_typeref(entity->typedefe.type) != type_void)
3462 } else if (token.type != T_void) {
3465 if (look_ahead(1)->type != ')')
3472 * Parses function type parameters (and optionally creates variable_t entities
3473 * for them in a scope)
3475 static void parse_parameters(function_type_t *type, scope_t *scope)
3478 add_anchor_token(')');
3479 int saved_comma_state = save_and_reset_anchor_state(',');
3481 if (token.type == T_IDENTIFIER &&
3482 !is_typedef_symbol(token.v.symbol)) {
3483 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3484 if (la1_type == ',' || la1_type == ')') {
3485 type->kr_style_parameters = true;
3486 parse_identifier_list(scope);
3487 goto parameters_finished;
3491 if (token.type == ')') {
3492 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3493 if (!(c_mode & _CXX))
3494 type->unspecified_parameters = true;
3495 goto parameters_finished;
3498 if (has_parameters()) {
3499 function_parameter_t **anchor = &type->parameters;
3501 switch (token.type) {
3504 type->variadic = true;
3505 goto parameters_finished;
3508 case T___extension__:
3511 entity_t *entity = parse_parameter();
3512 if (entity->kind == ENTITY_TYPEDEF) {
3513 errorf(&entity->base.source_position,
3514 "typedef not allowed as function parameter");
3517 assert(is_declaration(entity));
3519 semantic_parameter_incomplete(entity);
3521 function_parameter_t *const parameter =
3522 allocate_parameter(entity->declaration.type);
3524 if (scope != NULL) {
3525 append_entity(scope, entity);
3528 *anchor = parameter;
3529 anchor = ¶meter->next;
3534 goto parameters_finished;
3536 } while (next_if(','));
3540 parameters_finished:
3541 rem_anchor_token(')');
3542 expect(')', end_error);
3545 restore_anchor_state(',', saved_comma_state);
3548 typedef enum construct_type_kind_t {
3551 CONSTRUCT_REFERENCE,
3554 } construct_type_kind_t;
3556 typedef union construct_type_t construct_type_t;
3558 typedef struct construct_type_base_t {
3559 construct_type_kind_t kind;
3560 construct_type_t *next;
3561 } construct_type_base_t;
3563 typedef struct parsed_pointer_t {
3564 construct_type_base_t base;
3565 type_qualifiers_t type_qualifiers;
3566 variable_t *base_variable; /**< MS __based extension. */
3569 typedef struct parsed_reference_t {
3570 construct_type_base_t base;
3571 } parsed_reference_t;
3573 typedef struct construct_function_type_t {
3574 construct_type_base_t base;
3575 type_t *function_type;
3576 } construct_function_type_t;
3578 typedef struct parsed_array_t {
3579 construct_type_base_t base;
3580 type_qualifiers_t type_qualifiers;
3586 union construct_type_t {
3587 construct_type_kind_t kind;
3588 construct_type_base_t base;
3589 parsed_pointer_t pointer;
3590 parsed_reference_t reference;
3591 construct_function_type_t function;
3592 parsed_array_t array;
3595 static construct_type_t *parse_pointer_declarator(void)
3599 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3600 memset(pointer, 0, sizeof(pointer[0]));
3601 pointer->base.kind = CONSTRUCT_POINTER;
3602 pointer->type_qualifiers = parse_type_qualifiers();
3603 //pointer->base_variable = base_variable;
3605 return (construct_type_t*) pointer;
3608 static construct_type_t *parse_reference_declarator(void)
3612 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3613 parsed_reference_t *reference = &cons->reference;
3614 memset(reference, 0, sizeof(*reference));
3615 cons->kind = CONSTRUCT_REFERENCE;
3620 static construct_type_t *parse_array_declarator(void)
3623 add_anchor_token(']');
3625 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3626 parsed_array_t *array = &cons->array;
3627 memset(array, 0, sizeof(*array));
3628 cons->kind = CONSTRUCT_ARRAY;
3630 if (next_if(T_static))
3631 array->is_static = true;
3633 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3634 if (type_qualifiers != 0 && next_if(T_static))
3635 array->is_static = true;
3636 array->type_qualifiers = type_qualifiers;
3638 if (token.type == '*' && look_ahead(1)->type == ']') {
3639 array->is_variable = true;
3641 } else if (token.type != ']') {
3642 expression_t *const size = parse_assignment_expression();
3644 /* §6.7.5.2:1 Array size must have integer type */
3645 type_t *const orig_type = size->base.type;
3646 type_t *const type = skip_typeref(orig_type);
3647 if (!is_type_integer(type) && is_type_valid(type)) {
3648 errorf(&size->base.source_position,
3649 "array size '%E' must have integer type but has type '%T'",
3654 mark_vars_read(size, NULL);
3657 rem_anchor_token(']');
3658 expect(']', end_error);
3664 static construct_type_t *parse_function_declarator(scope_t *scope)
3666 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3667 function_type_t *ftype = &type->function;
3669 ftype->linkage = current_linkage;
3670 ftype->calling_convention = CC_DEFAULT;
3672 parse_parameters(ftype, scope);
3674 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3675 construct_function_type_t *function = &cons->function;
3676 memset(function, 0, sizeof(*function));
3677 cons->kind = CONSTRUCT_FUNCTION;
3678 function->function_type = type;
3683 typedef struct parse_declarator_env_t {
3684 bool may_be_abstract : 1;
3685 bool must_be_abstract : 1;
3686 decl_modifiers_t modifiers;
3688 source_position_t source_position;
3690 attribute_t *attributes;
3691 } parse_declarator_env_t;
3693 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3695 /* construct a single linked list of construct_type_t's which describe
3696 * how to construct the final declarator type */
3697 construct_type_t *first = NULL;
3698 construct_type_t **anchor = &first;
3700 env->attributes = parse_attributes(env->attributes);
3703 construct_type_t *type;
3704 //variable_t *based = NULL; /* MS __based extension */
3705 switch (token.type) {
3707 if (!(c_mode & _CXX))
3708 errorf(HERE, "references are only available for C++");
3709 type = parse_reference_declarator();
3714 source_position_t const pos = *HERE;
3716 expect('(', end_error);
3717 add_anchor_token(')');
3718 based = parse_microsoft_based();
3719 rem_anchor_token(')');
3720 expect(')', end_error);
3721 if (token.type != '*') {
3722 if (token.type == T__based) {
3723 errorf(&pos, "__based type modifier specified more than once");
3724 } else if (warning.other) {
3726 "__based does not precede a pointer declarator, ignored");
3731 panic("based currently disabled");
3737 type = parse_pointer_declarator();
3741 goto ptr_operator_end;
3745 anchor = &type->base.next;
3747 /* TODO: find out if this is correct */
3748 env->attributes = parse_attributes(env->attributes);
3753 modifiers |= env->modifiers;
3754 env->modifiers = modifiers;
3757 construct_type_t *inner_types = NULL;
3759 switch (token.type) {
3761 if (env->must_be_abstract) {
3762 errorf(HERE, "no identifier expected in typename");
3764 env->symbol = token.v.symbol;
3765 env->source_position = token.source_position;
3770 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3771 * interpreted as ``function with no parameter specification'', rather
3772 * than redundant parentheses around the omitted identifier. */
3773 if (look_ahead(1)->type != ')') {
3775 add_anchor_token(')');
3776 inner_types = parse_inner_declarator(env);
3777 if (inner_types != NULL) {
3778 /* All later declarators only modify the return type */
3779 env->must_be_abstract = true;
3781 rem_anchor_token(')');
3782 expect(')', end_error);
3786 if (env->may_be_abstract)
3788 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3793 construct_type_t **const p = anchor;
3796 construct_type_t *type;
3797 switch (token.type) {
3799 scope_t *scope = NULL;
3800 if (!env->must_be_abstract) {
3801 scope = &env->parameters;
3804 type = parse_function_declarator(scope);
3808 type = parse_array_declarator();
3811 goto declarator_finished;
3814 /* insert in the middle of the list (at p) */
3815 type->base.next = *p;
3818 anchor = &type->base.next;
3821 declarator_finished:
3822 /* append inner_types at the end of the list, we don't to set anchor anymore
3823 * as it's not needed anymore */
3824 *anchor = inner_types;
3831 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3833 construct_type_t *iter = construct_list;
3834 for (; iter != NULL; iter = iter->base.next) {
3835 switch (iter->kind) {
3836 case CONSTRUCT_INVALID:
3838 case CONSTRUCT_FUNCTION: {
3839 construct_function_type_t *function = &iter->function;
3840 type_t *function_type = function->function_type;
3842 function_type->function.return_type = type;
3844 type_t *skipped_return_type = skip_typeref(type);
3846 if (is_type_function(skipped_return_type)) {
3847 errorf(HERE, "function returning function is not allowed");
3848 } else if (is_type_array(skipped_return_type)) {
3849 errorf(HERE, "function returning array is not allowed");
3851 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3853 "type qualifiers in return type of function type are meaningless");
3857 /* The function type was constructed earlier. Freeing it here will
3858 * destroy other types. */
3859 type = typehash_insert(function_type);
3863 case CONSTRUCT_POINTER: {
3864 if (is_type_reference(skip_typeref(type)))
3865 errorf(HERE, "cannot declare a pointer to reference");
3867 parsed_pointer_t *pointer = &iter->pointer;
3868 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3872 case CONSTRUCT_REFERENCE:
3873 if (is_type_reference(skip_typeref(type)))
3874 errorf(HERE, "cannot declare a reference to reference");
3876 type = make_reference_type(type);
3879 case CONSTRUCT_ARRAY: {
3880 if (is_type_reference(skip_typeref(type)))
3881 errorf(HERE, "cannot declare an array of references");
3883 parsed_array_t *array = &iter->array;
3884 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3886 expression_t *size_expression = array->size;
3887 if (size_expression != NULL) {
3889 = create_implicit_cast(size_expression, type_size_t);
3892 array_type->base.qualifiers = array->type_qualifiers;
3893 array_type->array.element_type = type;
3894 array_type->array.is_static = array->is_static;
3895 array_type->array.is_variable = array->is_variable;
3896 array_type->array.size_expression = size_expression;
3898 if (size_expression != NULL) {
3899 if (is_constant_expression(size_expression)) {
3901 = fold_constant_to_int(size_expression);
3902 array_type->array.size = size;
3903 array_type->array.size_constant = true;
3904 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3905 * have a value greater than zero. */
3907 if (size < 0 || !GNU_MODE) {
3908 errorf(&size_expression->base.source_position,
3909 "size of array must be greater than zero");
3910 } else if (warning.other) {
3911 warningf(&size_expression->base.source_position,
3912 "zero length arrays are a GCC extension");
3916 array_type->array.is_vla = true;
3920 type_t *skipped_type = skip_typeref(type);
3922 if (is_type_incomplete(skipped_type)) {
3923 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3924 } else if (is_type_function(skipped_type)) {
3925 errorf(HERE, "array of functions is not allowed");
3927 type = identify_new_type(array_type);
3931 internal_errorf(HERE, "invalid type construction found");
3937 static type_t *automatic_type_conversion(type_t *orig_type);
3939 static type_t *semantic_parameter(const source_position_t *pos,
3941 const declaration_specifiers_t *specifiers,
3944 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3945 * shall be adjusted to ``qualified pointer to type'',
3947 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3948 * type'' shall be adjusted to ``pointer to function
3949 * returning type'', as in 6.3.2.1. */
3950 type = automatic_type_conversion(type);
3952 if (specifiers->is_inline && is_type_valid(type)) {
3953 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3956 /* §6.9.1:6 The declarations in the declaration list shall contain
3957 * no storage-class specifier other than register and no
3958 * initializations. */
3959 if (specifiers->thread_local || (
3960 specifiers->storage_class != STORAGE_CLASS_NONE &&
3961 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3963 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3966 /* delay test for incomplete type, because we might have (void)
3967 * which is legal but incomplete... */
3972 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3973 declarator_flags_t flags)
3975 parse_declarator_env_t env;
3976 memset(&env, 0, sizeof(env));
3977 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3979 construct_type_t *construct_type = parse_inner_declarator(&env);
3981 construct_declarator_type(construct_type, specifiers->type);
3982 type_t *type = skip_typeref(orig_type);
3984 if (construct_type != NULL) {
3985 obstack_free(&temp_obst, construct_type);
3988 attribute_t *attributes = parse_attributes(env.attributes);
3989 /* append (shared) specifier attribute behind attributes of this
3991 if (attributes != NULL) {
3992 attribute_t *last = attributes;
3993 while (last->next != NULL)
3995 last->next = specifiers->attributes;
3997 attributes = specifiers->attributes;
4001 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4002 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4003 entity->base.symbol = env.symbol;
4004 entity->base.source_position = env.source_position;
4005 entity->typedefe.type = orig_type;
4007 if (anonymous_entity != NULL) {
4008 if (is_type_compound(type)) {
4009 assert(anonymous_entity->compound.alias == NULL);
4010 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4011 anonymous_entity->kind == ENTITY_UNION);
4012 anonymous_entity->compound.alias = entity;
4013 anonymous_entity = NULL;
4014 } else if (is_type_enum(type)) {
4015 assert(anonymous_entity->enume.alias == NULL);
4016 assert(anonymous_entity->kind == ENTITY_ENUM);
4017 anonymous_entity->enume.alias = entity;
4018 anonymous_entity = NULL;
4022 /* create a declaration type entity */
4023 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4024 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4026 if (env.symbol != NULL) {
4027 if (specifiers->is_inline && is_type_valid(type)) {
4028 errorf(&env.source_position,
4029 "compound member '%Y' declared 'inline'", env.symbol);
4032 if (specifiers->thread_local ||
4033 specifiers->storage_class != STORAGE_CLASS_NONE) {
4034 errorf(&env.source_position,
4035 "compound member '%Y' must have no storage class",
4039 } else if (flags & DECL_IS_PARAMETER) {
4040 orig_type = semantic_parameter(&env.source_position, orig_type,
4041 specifiers, env.symbol);
4043 entity = allocate_entity_zero(ENTITY_PARAMETER);
4044 } else if (is_type_function(type)) {
4045 entity = allocate_entity_zero(ENTITY_FUNCTION);
4047 entity->function.is_inline = specifiers->is_inline;
4048 entity->function.parameters = env.parameters;
4050 if (env.symbol != NULL) {
4051 /* this needs fixes for C++ */
4052 bool in_function_scope = current_function != NULL;
4054 if (specifiers->thread_local || (
4055 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4056 specifiers->storage_class != STORAGE_CLASS_NONE &&
4057 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4059 errorf(&env.source_position,
4060 "invalid storage class for function '%Y'", env.symbol);
4064 entity = allocate_entity_zero(ENTITY_VARIABLE);
4066 entity->variable.thread_local = specifiers->thread_local;
4068 if (env.symbol != NULL) {
4069 if (specifiers->is_inline && is_type_valid(type)) {
4070 errorf(&env.source_position,
4071 "variable '%Y' declared 'inline'", env.symbol);
4074 bool invalid_storage_class = false;
4075 if (current_scope == file_scope) {
4076 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4077 specifiers->storage_class != STORAGE_CLASS_NONE &&
4078 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4079 invalid_storage_class = true;
4082 if (specifiers->thread_local &&
4083 specifiers->storage_class == STORAGE_CLASS_NONE) {
4084 invalid_storage_class = true;
4087 if (invalid_storage_class) {
4088 errorf(&env.source_position,
4089 "invalid storage class for variable '%Y'", env.symbol);
4094 if (env.symbol != NULL) {
4095 entity->base.symbol = env.symbol;
4096 entity->base.source_position = env.source_position;
4098 entity->base.source_position = specifiers->source_position;
4100 entity->base.namespc = NAMESPACE_NORMAL;
4101 entity->declaration.type = orig_type;
4102 entity->declaration.alignment = get_type_alignment(orig_type);
4103 entity->declaration.modifiers = env.modifiers;
4104 entity->declaration.attributes = attributes;
4106 storage_class_t storage_class = specifiers->storage_class;
4107 entity->declaration.declared_storage_class = storage_class;
4109 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4110 storage_class = STORAGE_CLASS_AUTO;
4111 entity->declaration.storage_class = storage_class;
4114 if (attributes != NULL) {
4115 handle_entity_attributes(attributes, entity);
4121 static type_t *parse_abstract_declarator(type_t *base_type)
4123 parse_declarator_env_t env;
4124 memset(&env, 0, sizeof(env));
4125 env.may_be_abstract = true;
4126 env.must_be_abstract = true;
4128 construct_type_t *construct_type = parse_inner_declarator(&env);
4130 type_t *result = construct_declarator_type(construct_type, base_type);
4131 if (construct_type != NULL) {
4132 obstack_free(&temp_obst, construct_type);
4134 result = handle_type_attributes(env.attributes, result);
4140 * Check if the declaration of main is suspicious. main should be a
4141 * function with external linkage, returning int, taking either zero
4142 * arguments, two, or three arguments of appropriate types, ie.
4144 * int main([ int argc, char **argv [, char **env ] ]).
4146 * @param decl the declaration to check
4147 * @param type the function type of the declaration
4149 static void check_main(const entity_t *entity)
4151 const source_position_t *pos = &entity->base.source_position;
4152 if (entity->kind != ENTITY_FUNCTION) {
4153 warningf(pos, "'main' is not a function");
4157 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4158 warningf(pos, "'main' is normally a non-static function");
4161 type_t *type = skip_typeref(entity->declaration.type);
4162 assert(is_type_function(type));
4164 function_type_t *func_type = &type->function;
4165 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4166 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4167 func_type->return_type);
4169 const function_parameter_t *parm = func_type->parameters;
4171 type_t *const first_type = parm->type;
4172 if (!types_compatible(skip_typeref(first_type), type_int)) {
4174 "first argument of 'main' should be 'int', but is '%T'",
4179 type_t *const second_type = parm->type;
4180 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4181 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4185 type_t *const third_type = parm->type;
4186 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4187 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4191 goto warn_arg_count;
4195 warningf(pos, "'main' takes only zero, two or three arguments");
4201 * Check if a symbol is the equal to "main".
4203 static bool is_sym_main(const symbol_t *const sym)
4205 return strcmp(sym->string, "main") == 0;
4208 static void error_redefined_as_different_kind(const source_position_t *pos,
4209 const entity_t *old, entity_kind_t new_kind)
4211 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4212 get_entity_kind_name(old->kind), old->base.symbol,
4213 get_entity_kind_name(new_kind), &old->base.source_position);
4216 static bool is_error_entity(entity_t *const ent)
4218 if (is_declaration(ent)) {
4219 return is_type_valid(skip_typeref(ent->declaration.type));
4220 } else if (ent->kind == ENTITY_TYPEDEF) {
4221 return is_type_valid(skip_typeref(ent->typedefe.type));
4226 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4228 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4229 if (attributes_equal(tattr, attr))
4236 * test wether new_list contains any attributes not included in old_list
4238 static bool has_new_attributes(const attribute_t *old_list,
4239 const attribute_t *new_list)
4241 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4242 if (!contains_attribute(old_list, attr))
4249 * Merge in attributes from an attribute list (probably from a previous
4250 * declaration with the same name). Warning: destroys the old structure
4251 * of the attribute list - don't reuse attributes after this call.
4253 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4256 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4258 if (contains_attribute(decl->attributes, attr))
4261 /* move attribute to new declarations attributes list */
4262 attr->next = decl->attributes;
4263 decl->attributes = attr;
4268 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4269 * for various problems that occur for multiple definitions
4271 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4273 const symbol_t *const symbol = entity->base.symbol;
4274 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4275 const source_position_t *pos = &entity->base.source_position;
4277 /* can happen in error cases */
4281 entity_t *const previous_entity = get_entity(symbol, namespc);
4282 /* pushing the same entity twice will break the stack structure */
4283 assert(previous_entity != entity);
4285 if (entity->kind == ENTITY_FUNCTION) {
4286 type_t *const orig_type = entity->declaration.type;
4287 type_t *const type = skip_typeref(orig_type);
4289 assert(is_type_function(type));
4290 if (type->function.unspecified_parameters &&
4291 warning.strict_prototypes &&
4292 previous_entity == NULL) {
4293 warningf(pos, "function declaration '%#T' is not a prototype",
4297 if (warning.main && current_scope == file_scope
4298 && is_sym_main(symbol)) {
4303 if (is_declaration(entity) &&
4304 warning.nested_externs &&
4305 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4306 current_scope != file_scope) {
4307 warningf(pos, "nested extern declaration of '%#T'",
4308 entity->declaration.type, symbol);
4311 if (previous_entity != NULL) {
4312 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4313 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4314 assert(previous_entity->kind == ENTITY_PARAMETER);
4316 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4317 entity->declaration.type, symbol,
4318 previous_entity->declaration.type, symbol,
4319 &previous_entity->base.source_position);
4323 if (previous_entity->base.parent_scope == current_scope) {
4324 if (previous_entity->kind != entity->kind) {
4325 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4326 error_redefined_as_different_kind(pos, previous_entity,
4331 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4332 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4333 symbol, &previous_entity->base.source_position);
4336 if (previous_entity->kind == ENTITY_TYPEDEF) {
4337 /* TODO: C++ allows this for exactly the same type */
4338 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4339 symbol, &previous_entity->base.source_position);
4343 /* at this point we should have only VARIABLES or FUNCTIONS */
4344 assert(is_declaration(previous_entity) && is_declaration(entity));
4346 declaration_t *const prev_decl = &previous_entity->declaration;
4347 declaration_t *const decl = &entity->declaration;
4349 /* can happen for K&R style declarations */
4350 if (prev_decl->type == NULL &&
4351 previous_entity->kind == ENTITY_PARAMETER &&
4352 entity->kind == ENTITY_PARAMETER) {
4353 prev_decl->type = decl->type;
4354 prev_decl->storage_class = decl->storage_class;
4355 prev_decl->declared_storage_class = decl->declared_storage_class;
4356 prev_decl->modifiers = decl->modifiers;
4357 return previous_entity;
4360 type_t *const orig_type = decl->type;
4361 assert(orig_type != NULL);
4362 type_t *const type = skip_typeref(orig_type);
4363 type_t *const prev_type = skip_typeref(prev_decl->type);
4365 if (!types_compatible(type, prev_type)) {
4367 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4368 orig_type, symbol, prev_decl->type, symbol,
4369 &previous_entity->base.source_position);
4371 unsigned old_storage_class = prev_decl->storage_class;
4373 if (warning.redundant_decls &&
4376 !(prev_decl->modifiers & DM_USED) &&
4377 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4378 warningf(&previous_entity->base.source_position,
4379 "unnecessary static forward declaration for '%#T'",
4380 prev_decl->type, symbol);
4383 storage_class_t new_storage_class = decl->storage_class;
4385 /* pretend no storage class means extern for function
4386 * declarations (except if the previous declaration is neither
4387 * none nor extern) */
4388 if (entity->kind == ENTITY_FUNCTION) {
4389 /* the previous declaration could have unspecified parameters or
4390 * be a typedef, so use the new type */
4391 if (prev_type->function.unspecified_parameters || is_definition)
4392 prev_decl->type = type;
4394 switch (old_storage_class) {
4395 case STORAGE_CLASS_NONE:
4396 old_storage_class = STORAGE_CLASS_EXTERN;
4399 case STORAGE_CLASS_EXTERN:
4400 if (is_definition) {
4401 if (warning.missing_prototypes &&
4402 prev_type->function.unspecified_parameters &&
4403 !is_sym_main(symbol)) {
4404 warningf(pos, "no previous prototype for '%#T'",
4407 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4408 new_storage_class = STORAGE_CLASS_EXTERN;
4415 } else if (is_type_incomplete(prev_type)) {
4416 prev_decl->type = type;
4419 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4420 new_storage_class == STORAGE_CLASS_EXTERN) {
4422 warn_redundant_declaration: ;
4424 = has_new_attributes(prev_decl->attributes,
4426 if (has_new_attrs) {
4427 merge_in_attributes(decl, prev_decl->attributes);
4428 } else if (!is_definition &&
4429 warning.redundant_decls &&
4430 is_type_valid(prev_type) &&
4431 strcmp(previous_entity->base.source_position.input_name,
4432 "<builtin>") != 0) {
4434 "redundant declaration for '%Y' (declared %P)",
4435 symbol, &previous_entity->base.source_position);
4437 } else if (current_function == NULL) {
4438 if (old_storage_class != STORAGE_CLASS_STATIC &&
4439 new_storage_class == STORAGE_CLASS_STATIC) {
4441 "static declaration of '%Y' follows non-static declaration (declared %P)",
4442 symbol, &previous_entity->base.source_position);
4443 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4444 prev_decl->storage_class = STORAGE_CLASS_NONE;
4445 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4447 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4449 goto error_redeclaration;
4450 goto warn_redundant_declaration;
4452 } else if (is_type_valid(prev_type)) {
4453 if (old_storage_class == new_storage_class) {
4454 error_redeclaration:
4455 errorf(pos, "redeclaration of '%Y' (declared %P)",
4456 symbol, &previous_entity->base.source_position);
4459 "redeclaration of '%Y' with different linkage (declared %P)",
4460 symbol, &previous_entity->base.source_position);
4465 prev_decl->modifiers |= decl->modifiers;
4466 if (entity->kind == ENTITY_FUNCTION) {
4467 previous_entity->function.is_inline |= entity->function.is_inline;
4469 return previous_entity;
4472 if (warning.shadow) {
4473 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4474 get_entity_kind_name(entity->kind), symbol,
4475 get_entity_kind_name(previous_entity->kind),
4476 &previous_entity->base.source_position);
4480 if (entity->kind == ENTITY_FUNCTION) {
4481 if (is_definition &&
4482 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4483 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4484 warningf(pos, "no previous prototype for '%#T'",
4485 entity->declaration.type, symbol);
4486 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4487 warningf(pos, "no previous declaration for '%#T'",
4488 entity->declaration.type, symbol);
4491 } else if (warning.missing_declarations &&
4492 entity->kind == ENTITY_VARIABLE &&
4493 current_scope == file_scope) {
4494 declaration_t *declaration = &entity->declaration;
4495 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4496 warningf(pos, "no previous declaration for '%#T'",
4497 declaration->type, symbol);
4502 assert(entity->base.parent_scope == NULL);
4503 assert(current_scope != NULL);
4505 entity->base.parent_scope = current_scope;
4506 entity->base.namespc = NAMESPACE_NORMAL;
4507 environment_push(entity);
4508 append_entity(current_scope, entity);
4513 static void parser_error_multiple_definition(entity_t *entity,
4514 const source_position_t *source_position)
4516 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4517 entity->base.symbol, &entity->base.source_position);
4520 static bool is_declaration_specifier(const token_t *token,
4521 bool only_specifiers_qualifiers)
4523 switch (token->type) {
4528 return is_typedef_symbol(token->v.symbol);
4530 case T___extension__:
4532 return !only_specifiers_qualifiers;
4539 static void parse_init_declarator_rest(entity_t *entity)
4541 assert(is_declaration(entity));
4542 declaration_t *const declaration = &entity->declaration;
4546 type_t *orig_type = declaration->type;
4547 type_t *type = skip_typeref(orig_type);
4549 if (entity->kind == ENTITY_VARIABLE
4550 && entity->variable.initializer != NULL) {
4551 parser_error_multiple_definition(entity, HERE);
4554 bool must_be_constant = false;
4555 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4556 entity->base.parent_scope == file_scope) {
4557 must_be_constant = true;
4560 if (is_type_function(type)) {
4561 errorf(&entity->base.source_position,
4562 "function '%#T' is initialized like a variable",
4563 orig_type, entity->base.symbol);
4564 orig_type = type_error_type;
4567 parse_initializer_env_t env;
4568 env.type = orig_type;
4569 env.must_be_constant = must_be_constant;
4570 env.entity = entity;
4571 current_init_decl = entity;
4573 initializer_t *initializer = parse_initializer(&env);
4574 current_init_decl = NULL;
4576 if (entity->kind == ENTITY_VARIABLE) {
4577 /* §6.7.5:22 array initializers for arrays with unknown size
4578 * determine the array type size */
4579 declaration->type = env.type;
4580 entity->variable.initializer = initializer;
4584 /* parse rest of a declaration without any declarator */
4585 static void parse_anonymous_declaration_rest(
4586 const declaration_specifiers_t *specifiers)
4589 anonymous_entity = NULL;
4591 if (warning.other) {
4592 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4593 specifiers->thread_local) {
4594 warningf(&specifiers->source_position,
4595 "useless storage class in empty declaration");
4598 type_t *type = specifiers->type;
4599 switch (type->kind) {
4600 case TYPE_COMPOUND_STRUCT:
4601 case TYPE_COMPOUND_UNION: {
4602 if (type->compound.compound->base.symbol == NULL) {
4603 warningf(&specifiers->source_position,
4604 "unnamed struct/union that defines no instances");
4613 warningf(&specifiers->source_position, "empty declaration");
4619 static void check_variable_type_complete(entity_t *ent)
4621 if (ent->kind != ENTITY_VARIABLE)
4624 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4625 * type for the object shall be complete [...] */
4626 declaration_t *decl = &ent->declaration;
4627 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4628 decl->storage_class == STORAGE_CLASS_STATIC)
4631 type_t *const orig_type = decl->type;
4632 type_t *const type = skip_typeref(orig_type);
4633 if (!is_type_incomplete(type))
4636 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4637 * are given length one. */
4638 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4639 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4643 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4644 orig_type, ent->base.symbol);
4648 static void parse_declaration_rest(entity_t *ndeclaration,
4649 const declaration_specifiers_t *specifiers,
4650 parsed_declaration_func finished_declaration,
4651 declarator_flags_t flags)
4653 add_anchor_token(';');
4654 add_anchor_token(',');
4656 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4658 if (token.type == '=') {
4659 parse_init_declarator_rest(entity);
4660 } else if (entity->kind == ENTITY_VARIABLE) {
4661 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4662 * [...] where the extern specifier is explicitly used. */
4663 declaration_t *decl = &entity->declaration;
4664 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4665 type_t *type = decl->type;
4666 if (is_type_reference(skip_typeref(type))) {
4667 errorf(&entity->base.source_position,
4668 "reference '%#T' must be initialized",
4669 type, entity->base.symbol);
4674 check_variable_type_complete(entity);
4679 add_anchor_token('=');
4680 ndeclaration = parse_declarator(specifiers, flags);
4681 rem_anchor_token('=');
4683 expect(';', end_error);
4686 anonymous_entity = NULL;
4687 rem_anchor_token(';');
4688 rem_anchor_token(',');
4691 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4693 symbol_t *symbol = entity->base.symbol;
4694 if (symbol == NULL) {
4695 errorf(HERE, "anonymous declaration not valid as function parameter");
4699 assert(entity->base.namespc == NAMESPACE_NORMAL);
4700 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4701 if (previous_entity == NULL
4702 || previous_entity->base.parent_scope != current_scope) {
4703 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4708 if (is_definition) {
4709 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4712 return record_entity(entity, false);
4715 static void parse_declaration(parsed_declaration_func finished_declaration,
4716 declarator_flags_t flags)
4718 declaration_specifiers_t specifiers;
4719 memset(&specifiers, 0, sizeof(specifiers));
4721 add_anchor_token(';');
4722 parse_declaration_specifiers(&specifiers);
4723 rem_anchor_token(';');
4725 if (token.type == ';') {
4726 parse_anonymous_declaration_rest(&specifiers);
4728 entity_t *entity = parse_declarator(&specifiers, flags);
4729 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4734 static type_t *get_default_promoted_type(type_t *orig_type)
4736 type_t *result = orig_type;
4738 type_t *type = skip_typeref(orig_type);
4739 if (is_type_integer(type)) {
4740 result = promote_integer(type);
4741 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4742 result = type_double;
4748 static void parse_kr_declaration_list(entity_t *entity)
4750 if (entity->kind != ENTITY_FUNCTION)
4753 type_t *type = skip_typeref(entity->declaration.type);
4754 assert(is_type_function(type));
4755 if (!type->function.kr_style_parameters)
4758 add_anchor_token('{');
4760 /* push function parameters */
4761 size_t const top = environment_top();
4762 scope_t *old_scope = scope_push(&entity->function.parameters);
4764 entity_t *parameter = entity->function.parameters.entities;
4765 for ( ; parameter != NULL; parameter = parameter->base.next) {
4766 assert(parameter->base.parent_scope == NULL);
4767 parameter->base.parent_scope = current_scope;
4768 environment_push(parameter);
4771 /* parse declaration list */
4773 switch (token.type) {
4775 case T___extension__:
4776 /* This covers symbols, which are no type, too, and results in
4777 * better error messages. The typical cases are misspelled type
4778 * names and missing includes. */
4780 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4788 /* pop function parameters */
4789 assert(current_scope == &entity->function.parameters);
4790 scope_pop(old_scope);
4791 environment_pop_to(top);
4793 /* update function type */
4794 type_t *new_type = duplicate_type(type);
4796 function_parameter_t *parameters = NULL;
4797 function_parameter_t **anchor = ¶meters;
4799 /* did we have an earlier prototype? */
4800 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4801 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4804 function_parameter_t *proto_parameter = NULL;
4805 if (proto_type != NULL) {
4806 type_t *proto_type_type = proto_type->declaration.type;
4807 proto_parameter = proto_type_type->function.parameters;
4808 /* If a K&R function definition has a variadic prototype earlier, then
4809 * make the function definition variadic, too. This should conform to
4810 * §6.7.5.3:15 and §6.9.1:8. */
4811 new_type->function.variadic = proto_type_type->function.variadic;
4813 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4815 new_type->function.unspecified_parameters = true;
4818 bool need_incompatible_warning = false;
4819 parameter = entity->function.parameters.entities;
4820 for (; parameter != NULL; parameter = parameter->base.next,
4822 proto_parameter == NULL ? NULL : proto_parameter->next) {
4823 if (parameter->kind != ENTITY_PARAMETER)
4826 type_t *parameter_type = parameter->declaration.type;
4827 if (parameter_type == NULL) {
4829 errorf(HERE, "no type specified for function parameter '%Y'",
4830 parameter->base.symbol);
4831 parameter_type = type_error_type;
4833 if (warning.implicit_int) {
4834 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4835 parameter->base.symbol);
4837 parameter_type = type_int;
4839 parameter->declaration.type = parameter_type;
4842 semantic_parameter_incomplete(parameter);
4844 /* we need the default promoted types for the function type */
4845 type_t *not_promoted = parameter_type;
4846 parameter_type = get_default_promoted_type(parameter_type);
4848 /* gcc special: if the type of the prototype matches the unpromoted
4849 * type don't promote */
4850 if (!strict_mode && proto_parameter != NULL) {
4851 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4852 type_t *promo_skip = skip_typeref(parameter_type);
4853 type_t *param_skip = skip_typeref(not_promoted);
4854 if (!types_compatible(proto_p_type, promo_skip)
4855 && types_compatible(proto_p_type, param_skip)) {
4857 need_incompatible_warning = true;
4858 parameter_type = not_promoted;
4861 function_parameter_t *const parameter
4862 = allocate_parameter(parameter_type);
4864 *anchor = parameter;
4865 anchor = ¶meter->next;
4868 new_type->function.parameters = parameters;
4869 new_type = identify_new_type(new_type);
4871 if (warning.other && need_incompatible_warning) {
4872 type_t *proto_type_type = proto_type->declaration.type;
4874 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4875 proto_type_type, proto_type->base.symbol,
4876 new_type, entity->base.symbol,
4877 &proto_type->base.source_position);
4880 entity->declaration.type = new_type;
4882 rem_anchor_token('{');
4885 static bool first_err = true;
4888 * When called with first_err set, prints the name of the current function,
4891 static void print_in_function(void)
4895 diagnosticf("%s: In function '%Y':\n",
4896 current_function->base.base.source_position.input_name,
4897 current_function->base.base.symbol);
4902 * Check if all labels are defined in the current function.
4903 * Check if all labels are used in the current function.
4905 static void check_labels(void)
4907 for (const goto_statement_t *goto_statement = goto_first;
4908 goto_statement != NULL;
4909 goto_statement = goto_statement->next) {
4910 /* skip computed gotos */
4911 if (goto_statement->expression != NULL)
4914 label_t *label = goto_statement->label;
4917 if (label->base.source_position.input_name == NULL) {
4918 print_in_function();
4919 errorf(&goto_statement->base.source_position,
4920 "label '%Y' used but not defined", label->base.symbol);
4924 if (warning.unused_label) {
4925 for (const label_statement_t *label_statement = label_first;
4926 label_statement != NULL;
4927 label_statement = label_statement->next) {
4928 label_t *label = label_statement->label;
4930 if (! label->used) {
4931 print_in_function();
4932 warningf(&label_statement->base.source_position,
4933 "label '%Y' defined but not used", label->base.symbol);
4939 static void warn_unused_entity(entity_t *entity, entity_t *last)
4941 entity_t const *const end = last != NULL ? last->base.next : NULL;
4942 for (; entity != end; entity = entity->base.next) {
4943 if (!is_declaration(entity))
4946 declaration_t *declaration = &entity->declaration;
4947 if (declaration->implicit)
4950 if (!declaration->used) {
4951 print_in_function();
4952 const char *what = get_entity_kind_name(entity->kind);
4953 warningf(&entity->base.source_position, "%s '%Y' is unused",
4954 what, entity->base.symbol);
4955 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4956 print_in_function();
4957 const char *what = get_entity_kind_name(entity->kind);
4958 warningf(&entity->base.source_position, "%s '%Y' is never read",
4959 what, entity->base.symbol);
4964 static void check_unused_variables(statement_t *const stmt, void *const env)
4968 switch (stmt->kind) {
4969 case STATEMENT_DECLARATION: {
4970 declaration_statement_t const *const decls = &stmt->declaration;
4971 warn_unused_entity(decls->declarations_begin,
4972 decls->declarations_end);
4977 warn_unused_entity(stmt->fors.scope.entities, NULL);
4986 * Check declarations of current_function for unused entities.
4988 static void check_declarations(void)
4990 if (warning.unused_parameter) {
4991 const scope_t *scope = ¤t_function->parameters;
4993 /* do not issue unused warnings for main */
4994 if (!is_sym_main(current_function->base.base.symbol)) {
4995 warn_unused_entity(scope->entities, NULL);
4998 if (warning.unused_variable) {
4999 walk_statements(current_function->statement, check_unused_variables,
5004 static int determine_truth(expression_t const* const cond)
5007 !is_constant_expression(cond) ? 0 :
5008 fold_constant_to_bool(cond) ? 1 :
5012 static void check_reachable(statement_t *);
5013 static bool reaches_end;
5015 static bool expression_returns(expression_t const *const expr)
5017 switch (expr->kind) {
5019 expression_t const *const func = expr->call.function;
5020 if (func->kind == EXPR_REFERENCE) {
5021 entity_t *entity = func->reference.entity;
5022 if (entity->kind == ENTITY_FUNCTION
5023 && entity->declaration.modifiers & DM_NORETURN)
5027 if (!expression_returns(func))
5030 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5031 if (!expression_returns(arg->expression))
5038 case EXPR_REFERENCE:
5039 case EXPR_REFERENCE_ENUM_VALUE:
5041 case EXPR_CHARACTER_CONSTANT:
5042 case EXPR_WIDE_CHARACTER_CONSTANT:
5043 case EXPR_STRING_LITERAL:
5044 case EXPR_WIDE_STRING_LITERAL:
5045 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5046 case EXPR_LABEL_ADDRESS:
5047 case EXPR_CLASSIFY_TYPE:
5048 case EXPR_SIZEOF: // TODO handle obscure VLA case
5051 case EXPR_BUILTIN_CONSTANT_P:
5052 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5057 case EXPR_STATEMENT: {
5058 bool old_reaches_end = reaches_end;
5059 reaches_end = false;
5060 check_reachable(expr->statement.statement);
5061 bool returns = reaches_end;
5062 reaches_end = old_reaches_end;
5066 case EXPR_CONDITIONAL:
5067 // TODO handle constant expression
5069 if (!expression_returns(expr->conditional.condition))
5072 if (expr->conditional.true_expression != NULL
5073 && expression_returns(expr->conditional.true_expression))
5076 return expression_returns(expr->conditional.false_expression);
5079 return expression_returns(expr->select.compound);
5081 case EXPR_ARRAY_ACCESS:
5083 expression_returns(expr->array_access.array_ref) &&
5084 expression_returns(expr->array_access.index);
5087 return expression_returns(expr->va_starte.ap);
5090 return expression_returns(expr->va_arge.ap);
5093 return expression_returns(expr->va_copye.src);
5095 EXPR_UNARY_CASES_MANDATORY
5096 return expression_returns(expr->unary.value);
5098 case EXPR_UNARY_THROW:
5102 // TODO handle constant lhs of && and ||
5104 expression_returns(expr->binary.left) &&
5105 expression_returns(expr->binary.right);
5111 panic("unhandled expression");
5114 static bool initializer_returns(initializer_t const *const init)
5116 switch (init->kind) {
5117 case INITIALIZER_VALUE:
5118 return expression_returns(init->value.value);
5120 case INITIALIZER_LIST: {
5121 initializer_t * const* i = init->list.initializers;
5122 initializer_t * const* const end = i + init->list.len;
5123 bool returns = true;
5124 for (; i != end; ++i) {
5125 if (!initializer_returns(*i))
5131 case INITIALIZER_STRING:
5132 case INITIALIZER_WIDE_STRING:
5133 case INITIALIZER_DESIGNATOR: // designators have no payload
5136 panic("unhandled initializer");
5139 static bool noreturn_candidate;
5141 static void check_reachable(statement_t *const stmt)
5143 if (stmt->base.reachable)
5145 if (stmt->kind != STATEMENT_DO_WHILE)
5146 stmt->base.reachable = true;
5148 statement_t *last = stmt;
5150 switch (stmt->kind) {
5151 case STATEMENT_INVALID:
5152 case STATEMENT_EMPTY:
5154 next = stmt->base.next;
5157 case STATEMENT_DECLARATION: {
5158 declaration_statement_t const *const decl = &stmt->declaration;
5159 entity_t const * ent = decl->declarations_begin;
5160 entity_t const *const last = decl->declarations_end;
5162 for (;; ent = ent->base.next) {
5163 if (ent->kind == ENTITY_VARIABLE &&
5164 ent->variable.initializer != NULL &&
5165 !initializer_returns(ent->variable.initializer)) {
5172 next = stmt->base.next;
5176 case STATEMENT_COMPOUND:
5177 next = stmt->compound.statements;
5179 next = stmt->base.next;
5182 case STATEMENT_RETURN: {
5183 expression_t const *const val = stmt->returns.value;
5184 if (val == NULL || expression_returns(val))
5185 noreturn_candidate = false;
5189 case STATEMENT_IF: {
5190 if_statement_t const *const ifs = &stmt->ifs;
5191 expression_t const *const cond = ifs->condition;
5193 if (!expression_returns(cond))
5196 int const val = determine_truth(cond);
5199 check_reachable(ifs->true_statement);
5204 if (ifs->false_statement != NULL) {
5205 check_reachable(ifs->false_statement);
5209 next = stmt->base.next;
5213 case STATEMENT_SWITCH: {
5214 switch_statement_t const *const switchs = &stmt->switchs;
5215 expression_t const *const expr = switchs->expression;
5217 if (!expression_returns(expr))
5220 if (is_constant_expression(expr)) {
5221 long const val = fold_constant_to_int(expr);
5222 case_label_statement_t * defaults = NULL;
5223 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5224 if (i->expression == NULL) {
5229 if (i->first_case <= val && val <= i->last_case) {
5230 check_reachable((statement_t*)i);
5235 if (defaults != NULL) {
5236 check_reachable((statement_t*)defaults);
5240 bool has_default = false;
5241 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5242 if (i->expression == NULL)
5245 check_reachable((statement_t*)i);
5252 next = stmt->base.next;
5256 case STATEMENT_EXPRESSION: {
5257 /* Check for noreturn function call */
5258 expression_t const *const expr = stmt->expression.expression;
5259 if (!expression_returns(expr))
5262 next = stmt->base.next;
5266 case STATEMENT_CONTINUE:
5267 for (statement_t *parent = stmt;;) {
5268 parent = parent->base.parent;
5269 if (parent == NULL) /* continue not within loop */
5273 switch (parent->kind) {
5274 case STATEMENT_WHILE: goto continue_while;
5275 case STATEMENT_DO_WHILE: goto continue_do_while;
5276 case STATEMENT_FOR: goto continue_for;
5282 case STATEMENT_BREAK:
5283 for (statement_t *parent = stmt;;) {
5284 parent = parent->base.parent;
5285 if (parent == NULL) /* break not within loop/switch */
5288 switch (parent->kind) {
5289 case STATEMENT_SWITCH:
5290 case STATEMENT_WHILE:
5291 case STATEMENT_DO_WHILE:
5294 next = parent->base.next;
5295 goto found_break_parent;
5303 case STATEMENT_GOTO:
5304 if (stmt->gotos.expression) {
5305 if (!expression_returns(stmt->gotos.expression))
5308 statement_t *parent = stmt->base.parent;
5309 if (parent == NULL) /* top level goto */
5313 next = stmt->gotos.label->statement;
5314 if (next == NULL) /* missing label */
5319 case STATEMENT_LABEL:
5320 next = stmt->label.statement;
5323 case STATEMENT_CASE_LABEL:
5324 next = stmt->case_label.statement;
5327 case STATEMENT_WHILE: {
5328 while_statement_t const *const whiles = &stmt->whiles;
5329 expression_t const *const cond = whiles->condition;
5331 if (!expression_returns(cond))
5334 int const val = determine_truth(cond);
5337 check_reachable(whiles->body);
5342 next = stmt->base.next;
5346 case STATEMENT_DO_WHILE:
5347 next = stmt->do_while.body;
5350 case STATEMENT_FOR: {
5351 for_statement_t *const fors = &stmt->fors;
5353 if (fors->condition_reachable)
5355 fors->condition_reachable = true;
5357 expression_t const *const cond = fors->condition;
5362 } else if (expression_returns(cond)) {
5363 val = determine_truth(cond);
5369 check_reachable(fors->body);
5374 next = stmt->base.next;
5378 case STATEMENT_MS_TRY: {
5379 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5380 check_reachable(ms_try->try_statement);
5381 next = ms_try->final_statement;
5385 case STATEMENT_LEAVE: {
5386 statement_t *parent = stmt;
5388 parent = parent->base.parent;
5389 if (parent == NULL) /* __leave not within __try */
5392 if (parent->kind == STATEMENT_MS_TRY) {
5394 next = parent->ms_try.final_statement;
5402 panic("invalid statement kind");
5405 while (next == NULL) {
5406 next = last->base.parent;
5408 noreturn_candidate = false;
5410 type_t *const type = skip_typeref(current_function->base.type);
5411 assert(is_type_function(type));
5412 type_t *const ret = skip_typeref(type->function.return_type);
5413 if (warning.return_type &&
5414 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5415 is_type_valid(ret) &&
5416 !is_sym_main(current_function->base.base.symbol)) {
5417 warningf(&stmt->base.source_position,
5418 "control reaches end of non-void function");
5423 switch (next->kind) {
5424 case STATEMENT_INVALID:
5425 case STATEMENT_EMPTY:
5426 case STATEMENT_DECLARATION:
5427 case STATEMENT_EXPRESSION:
5429 case STATEMENT_RETURN:
5430 case STATEMENT_CONTINUE:
5431 case STATEMENT_BREAK:
5432 case STATEMENT_GOTO:
5433 case STATEMENT_LEAVE:
5434 panic("invalid control flow in function");
5436 case STATEMENT_COMPOUND:
5437 if (next->compound.stmt_expr) {
5443 case STATEMENT_SWITCH:
5444 case STATEMENT_LABEL:
5445 case STATEMENT_CASE_LABEL:
5447 next = next->base.next;
5450 case STATEMENT_WHILE: {
5452 if (next->base.reachable)
5454 next->base.reachable = true;
5456 while_statement_t const *const whiles = &next->whiles;
5457 expression_t const *const cond = whiles->condition;
5459 if (!expression_returns(cond))
5462 int const val = determine_truth(cond);
5465 check_reachable(whiles->body);
5471 next = next->base.next;
5475 case STATEMENT_DO_WHILE: {
5477 if (next->base.reachable)
5479 next->base.reachable = true;
5481 do_while_statement_t const *const dw = &next->do_while;
5482 expression_t const *const cond = dw->condition;
5484 if (!expression_returns(cond))
5487 int const val = determine_truth(cond);
5490 check_reachable(dw->body);
5496 next = next->base.next;
5500 case STATEMENT_FOR: {
5502 for_statement_t *const fors = &next->fors;
5504 fors->step_reachable = true;
5506 if (fors->condition_reachable)
5508 fors->condition_reachable = true;
5510 expression_t const *const cond = fors->condition;
5515 } else if (expression_returns(cond)) {
5516 val = determine_truth(cond);
5522 check_reachable(fors->body);
5528 next = next->base.next;
5532 case STATEMENT_MS_TRY:
5534 next = next->ms_try.final_statement;
5539 check_reachable(next);
5542 static void check_unreachable(statement_t* const stmt, void *const env)
5546 switch (stmt->kind) {
5547 case STATEMENT_DO_WHILE:
5548 if (!stmt->base.reachable) {
5549 expression_t const *const cond = stmt->do_while.condition;
5550 if (determine_truth(cond) >= 0) {
5551 warningf(&cond->base.source_position,
5552 "condition of do-while-loop is unreachable");
5557 case STATEMENT_FOR: {
5558 for_statement_t const* const fors = &stmt->fors;
5560 // if init and step are unreachable, cond is unreachable, too
5561 if (!stmt->base.reachable && !fors->step_reachable) {
5562 warningf(&stmt->base.source_position, "statement is unreachable");
5564 if (!stmt->base.reachable && fors->initialisation != NULL) {
5565 warningf(&fors->initialisation->base.source_position,
5566 "initialisation of for-statement is unreachable");
5569 if (!fors->condition_reachable && fors->condition != NULL) {
5570 warningf(&fors->condition->base.source_position,
5571 "condition of for-statement is unreachable");
5574 if (!fors->step_reachable && fors->step != NULL) {
5575 warningf(&fors->step->base.source_position,
5576 "step of for-statement is unreachable");
5582 case STATEMENT_COMPOUND:
5583 if (stmt->compound.statements != NULL)
5585 goto warn_unreachable;
5587 case STATEMENT_DECLARATION: {
5588 /* Only warn if there is at least one declarator with an initializer.
5589 * This typically occurs in switch statements. */
5590 declaration_statement_t const *const decl = &stmt->declaration;
5591 entity_t const * ent = decl->declarations_begin;
5592 entity_t const *const last = decl->declarations_end;
5594 for (;; ent = ent->base.next) {
5595 if (ent->kind == ENTITY_VARIABLE &&
5596 ent->variable.initializer != NULL) {
5597 goto warn_unreachable;
5607 if (!stmt->base.reachable)
5608 warningf(&stmt->base.source_position, "statement is unreachable");
5613 static void parse_external_declaration(void)
5615 /* function-definitions and declarations both start with declaration
5617 declaration_specifiers_t specifiers;
5618 memset(&specifiers, 0, sizeof(specifiers));
5620 add_anchor_token(';');
5621 parse_declaration_specifiers(&specifiers);
5622 rem_anchor_token(';');
5624 /* must be a declaration */
5625 if (token.type == ';') {
5626 parse_anonymous_declaration_rest(&specifiers);
5630 add_anchor_token(',');
5631 add_anchor_token('=');
5632 add_anchor_token(';');
5633 add_anchor_token('{');
5635 /* declarator is common to both function-definitions and declarations */
5636 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5638 rem_anchor_token('{');
5639 rem_anchor_token(';');
5640 rem_anchor_token('=');
5641 rem_anchor_token(',');
5643 /* must be a declaration */
5644 switch (token.type) {
5648 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5653 /* must be a function definition */
5654 parse_kr_declaration_list(ndeclaration);
5656 if (token.type != '{') {
5657 parse_error_expected("while parsing function definition", '{', NULL);
5658 eat_until_matching_token(';');
5662 assert(is_declaration(ndeclaration));
5663 type_t *const orig_type = ndeclaration->declaration.type;
5664 type_t * type = skip_typeref(orig_type);
5666 if (!is_type_function(type)) {
5667 if (is_type_valid(type)) {
5668 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5669 type, ndeclaration->base.symbol);
5673 } else if (is_typeref(orig_type)) {
5675 errorf(&ndeclaration->base.source_position,
5676 "type of function definition '%#T' is a typedef",
5677 orig_type, ndeclaration->base.symbol);
5680 if (warning.aggregate_return &&
5681 is_type_compound(skip_typeref(type->function.return_type))) {
5682 warningf(HERE, "function '%Y' returns an aggregate",
5683 ndeclaration->base.symbol);
5685 if (warning.traditional && !type->function.unspecified_parameters) {
5686 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5687 ndeclaration->base.symbol);
5689 if (warning.old_style_definition && type->function.unspecified_parameters) {
5690 warningf(HERE, "old-style function definition '%Y'",
5691 ndeclaration->base.symbol);
5694 /* §6.7.5.3:14 a function definition with () means no
5695 * parameters (and not unspecified parameters) */
5696 if (type->function.unspecified_parameters &&
5697 type->function.parameters == NULL) {
5698 type_t *copy = duplicate_type(type);
5699 copy->function.unspecified_parameters = false;
5700 type = identify_new_type(copy);
5702 ndeclaration->declaration.type = type;
5705 entity_t *const entity = record_entity(ndeclaration, true);
5706 assert(entity->kind == ENTITY_FUNCTION);
5707 assert(ndeclaration->kind == ENTITY_FUNCTION);
5709 function_t *function = &entity->function;
5710 if (ndeclaration != entity) {
5711 function->parameters = ndeclaration->function.parameters;
5713 assert(is_declaration(entity));
5714 type = skip_typeref(entity->declaration.type);
5716 /* push function parameters and switch scope */
5717 size_t const top = environment_top();
5718 scope_t *old_scope = scope_push(&function->parameters);
5720 entity_t *parameter = function->parameters.entities;
5721 for (; parameter != NULL; parameter = parameter->base.next) {
5722 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5723 parameter->base.parent_scope = current_scope;
5725 assert(parameter->base.parent_scope == NULL
5726 || parameter->base.parent_scope == current_scope);
5727 parameter->base.parent_scope = current_scope;
5728 if (parameter->base.symbol == NULL) {
5729 errorf(¶meter->base.source_position, "parameter name omitted");
5732 environment_push(parameter);
5735 if (function->statement != NULL) {
5736 parser_error_multiple_definition(entity, HERE);
5739 /* parse function body */
5740 int label_stack_top = label_top();
5741 function_t *old_current_function = current_function;
5742 current_function = function;
5743 current_parent = NULL;
5746 goto_anchor = &goto_first;
5748 label_anchor = &label_first;
5750 statement_t *const body = parse_compound_statement(false);
5751 function->statement = body;
5754 check_declarations();
5755 if (warning.return_type ||
5756 warning.unreachable_code ||
5757 (warning.missing_noreturn
5758 && !(function->base.modifiers & DM_NORETURN))) {
5759 noreturn_candidate = true;
5760 check_reachable(body);
5761 if (warning.unreachable_code)
5762 walk_statements(body, check_unreachable, NULL);
5763 if (warning.missing_noreturn &&
5764 noreturn_candidate &&
5765 !(function->base.modifiers & DM_NORETURN)) {
5766 warningf(&body->base.source_position,
5767 "function '%#T' is candidate for attribute 'noreturn'",
5768 type, entity->base.symbol);
5772 assert(current_parent == NULL);
5773 assert(current_function == function);
5774 current_function = old_current_function;
5775 label_pop_to(label_stack_top);
5778 assert(current_scope == &function->parameters);
5779 scope_pop(old_scope);
5780 environment_pop_to(top);
5783 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5784 source_position_t *source_position,
5785 const symbol_t *symbol)
5787 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5789 type->bitfield.base_type = base_type;
5790 type->bitfield.size_expression = size;
5793 type_t *skipped_type = skip_typeref(base_type);
5794 if (!is_type_integer(skipped_type)) {
5795 errorf(HERE, "bitfield base type '%T' is not an integer type",
5799 bit_size = get_type_size(base_type) * 8;
5802 if (is_constant_expression(size)) {
5803 long v = fold_constant_to_int(size);
5804 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5807 errorf(source_position, "negative width in bit-field '%Y'",
5809 } else if (v == 0 && symbol != NULL) {
5810 errorf(source_position, "zero width for bit-field '%Y'",
5812 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5813 errorf(source_position, "width of '%Y' exceeds its type",
5816 type->bitfield.bit_size = v;
5823 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5825 entity_t *iter = compound->members.entities;
5826 for (; iter != NULL; iter = iter->base.next) {
5827 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5830 if (iter->base.symbol == symbol) {
5832 } else if (iter->base.symbol == NULL) {
5833 /* search in anonymous structs and unions */
5834 type_t *type = skip_typeref(iter->declaration.type);
5835 if (is_type_compound(type)) {
5836 if (find_compound_entry(type->compound.compound, symbol)
5847 static void check_deprecated(const source_position_t *source_position,
5848 const entity_t *entity)
5850 if (!warning.deprecated_declarations)
5852 if (!is_declaration(entity))
5854 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5857 char const *const prefix = get_entity_kind_name(entity->kind);
5858 const char *deprecated_string
5859 = get_deprecated_string(entity->declaration.attributes);
5860 if (deprecated_string != NULL) {
5861 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5862 prefix, entity->base.symbol, &entity->base.source_position,
5865 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5866 entity->base.symbol, &entity->base.source_position);
5871 static expression_t *create_select(const source_position_t *pos,
5873 type_qualifiers_t qualifiers,
5876 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5878 check_deprecated(pos, entry);
5880 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5881 select->select.compound = addr;
5882 select->select.compound_entry = entry;
5884 type_t *entry_type = entry->declaration.type;
5885 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5887 /* we always do the auto-type conversions; the & and sizeof parser contains
5888 * code to revert this! */
5889 select->base.type = automatic_type_conversion(res_type);
5890 if (res_type->kind == TYPE_BITFIELD) {
5891 select->base.type = res_type->bitfield.base_type;
5898 * Find entry with symbol in compound. Search anonymous structs and unions and
5899 * creates implicit select expressions for them.
5900 * Returns the adress for the innermost compound.
5902 static expression_t *find_create_select(const source_position_t *pos,
5904 type_qualifiers_t qualifiers,
5905 compound_t *compound, symbol_t *symbol)
5907 entity_t *iter = compound->members.entities;
5908 for (; iter != NULL; iter = iter->base.next) {
5909 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5912 symbol_t *iter_symbol = iter->base.symbol;
5913 if (iter_symbol == NULL) {
5914 type_t *type = iter->declaration.type;
5915 if (type->kind != TYPE_COMPOUND_STRUCT
5916 && type->kind != TYPE_COMPOUND_UNION)
5919 compound_t *sub_compound = type->compound.compound;
5921 if (find_compound_entry(sub_compound, symbol) == NULL)
5924 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5925 sub_addr->base.source_position = *pos;
5926 sub_addr->select.implicit = true;
5927 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5931 if (iter_symbol == symbol) {
5932 return create_select(pos, addr, qualifiers, iter);
5939 static void parse_compound_declarators(compound_t *compound,
5940 const declaration_specifiers_t *specifiers)
5945 if (token.type == ':') {
5946 source_position_t source_position = *HERE;
5949 type_t *base_type = specifiers->type;
5950 expression_t *size = parse_constant_expression();
5952 type_t *type = make_bitfield_type(base_type, size,
5953 &source_position, NULL);
5955 attribute_t *attributes = parse_attributes(NULL);
5956 if (attributes != NULL) {
5957 attribute_t *last = attributes;
5958 while (last->next != NULL)
5960 last->next = specifiers->attributes;
5962 attributes = specifiers->attributes;
5965 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5966 entity->base.namespc = NAMESPACE_NORMAL;
5967 entity->base.source_position = source_position;
5968 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5969 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5970 entity->declaration.type = type;
5971 entity->declaration.attributes = attributes;
5973 if (attributes != NULL) {
5974 handle_entity_attributes(attributes, entity);
5976 append_entity(&compound->members, entity);
5978 entity = parse_declarator(specifiers,
5979 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5980 if (entity->kind == ENTITY_TYPEDEF) {
5981 errorf(&entity->base.source_position,
5982 "typedef not allowed as compound member");
5984 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5986 /* make sure we don't define a symbol multiple times */
5987 symbol_t *symbol = entity->base.symbol;
5988 if (symbol != NULL) {
5989 entity_t *prev = find_compound_entry(compound, symbol);
5991 errorf(&entity->base.source_position,
5992 "multiple declarations of symbol '%Y' (declared %P)",
5993 symbol, &prev->base.source_position);
5997 if (token.type == ':') {
5998 source_position_t source_position = *HERE;
6000 expression_t *size = parse_constant_expression();
6002 type_t *type = entity->declaration.type;
6003 type_t *bitfield_type = make_bitfield_type(type, size,
6004 &source_position, entity->base.symbol);
6006 attribute_t *attributes = parse_attributes(NULL);
6007 entity->declaration.type = bitfield_type;
6008 handle_entity_attributes(attributes, entity);
6010 type_t *orig_type = entity->declaration.type;
6011 type_t *type = skip_typeref(orig_type);
6012 if (is_type_function(type)) {
6013 errorf(&entity->base.source_position,
6014 "compound member '%Y' must not have function type '%T'",
6015 entity->base.symbol, orig_type);
6016 } else if (is_type_incomplete(type)) {
6017 /* §6.7.2.1:16 flexible array member */
6018 if (!is_type_array(type) ||
6019 token.type != ';' ||
6020 look_ahead(1)->type != '}') {
6021 errorf(&entity->base.source_position,
6022 "compound member '%Y' has incomplete type '%T'",
6023 entity->base.symbol, orig_type);
6028 append_entity(&compound->members, entity);
6031 } while (next_if(','));
6032 expect(';', end_error);
6035 anonymous_entity = NULL;
6038 static void parse_compound_type_entries(compound_t *compound)
6041 add_anchor_token('}');
6043 while (token.type != '}') {
6044 if (token.type == T_EOF) {
6045 errorf(HERE, "EOF while parsing struct");
6048 declaration_specifiers_t specifiers;
6049 memset(&specifiers, 0, sizeof(specifiers));
6050 parse_declaration_specifiers(&specifiers);
6052 parse_compound_declarators(compound, &specifiers);
6054 rem_anchor_token('}');
6058 compound->complete = true;
6061 static type_t *parse_typename(void)
6063 declaration_specifiers_t specifiers;
6064 memset(&specifiers, 0, sizeof(specifiers));
6065 parse_declaration_specifiers(&specifiers);
6066 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6067 specifiers.thread_local) {
6068 /* TODO: improve error message, user does probably not know what a
6069 * storage class is...
6071 errorf(HERE, "typename may not have a storage class");
6074 type_t *result = parse_abstract_declarator(specifiers.type);
6082 typedef expression_t* (*parse_expression_function)(void);
6083 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6085 typedef struct expression_parser_function_t expression_parser_function_t;
6086 struct expression_parser_function_t {
6087 parse_expression_function parser;
6088 precedence_t infix_precedence;
6089 parse_expression_infix_function infix_parser;
6092 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6095 * Prints an error message if an expression was expected but not read
6097 static expression_t *expected_expression_error(void)
6099 /* skip the error message if the error token was read */
6100 if (token.type != T_ERROR) {
6101 errorf(HERE, "expected expression, got token %K", &token);
6105 return create_invalid_expression();
6109 * Parse a string constant.
6111 static expression_t *parse_string_const(void)
6114 if (token.type == T_STRING_LITERAL) {
6115 string_t res = token.v.string;
6117 while (token.type == T_STRING_LITERAL) {
6118 res = concat_strings(&res, &token.v.string);
6121 if (token.type != T_WIDE_STRING_LITERAL) {
6122 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6123 /* note: that we use type_char_ptr here, which is already the
6124 * automatic converted type. revert_automatic_type_conversion
6125 * will construct the array type */
6126 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6127 cnst->string.value = res;
6131 wres = concat_string_wide_string(&res, &token.v.wide_string);
6133 wres = token.v.wide_string;
6138 switch (token.type) {
6139 case T_WIDE_STRING_LITERAL:
6140 wres = concat_wide_strings(&wres, &token.v.wide_string);
6143 case T_STRING_LITERAL:
6144 wres = concat_wide_string_string(&wres, &token.v.string);
6148 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6149 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6150 cnst->wide_string.value = wres;
6159 * Parse a boolean constant.
6161 static expression_t *parse_bool_const(bool value)
6163 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6164 cnst->base.type = type_bool;
6165 cnst->conste.v.int_value = value;
6173 * Parse an integer constant.
6175 static expression_t *parse_int_const(void)
6177 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6178 cnst->base.type = token.datatype;
6179 cnst->conste.v.int_value = token.v.intvalue;
6187 * Parse a character constant.
6189 static expression_t *parse_character_constant(void)
6191 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6192 cnst->base.type = token.datatype;
6193 cnst->conste.v.character = token.v.string;
6195 if (cnst->conste.v.character.size != 1) {
6197 errorf(HERE, "more than 1 character in character constant");
6198 } else if (warning.multichar) {
6199 warningf(HERE, "multi-character character constant");
6208 * Parse a wide character constant.
6210 static expression_t *parse_wide_character_constant(void)
6212 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6213 cnst->base.type = token.datatype;
6214 cnst->conste.v.wide_character = token.v.wide_string;
6216 if (cnst->conste.v.wide_character.size != 1) {
6218 errorf(HERE, "more than 1 character in character constant");
6219 } else if (warning.multichar) {
6220 warningf(HERE, "multi-character character constant");
6229 * Parse a float constant.
6231 static expression_t *parse_float_const(void)
6233 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6234 cnst->base.type = token.datatype;
6235 cnst->conste.v.float_value = token.v.floatvalue;
6242 static entity_t *create_implicit_function(symbol_t *symbol,
6243 const source_position_t *source_position)
6245 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6246 ntype->function.return_type = type_int;
6247 ntype->function.unspecified_parameters = true;
6248 ntype->function.linkage = LINKAGE_C;
6249 type_t *type = identify_new_type(ntype);
6251 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6252 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6253 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6254 entity->declaration.type = type;
6255 entity->declaration.implicit = true;
6256 entity->base.symbol = symbol;
6257 entity->base.source_position = *source_position;
6259 if (current_scope != NULL) {
6260 bool strict_prototypes_old = warning.strict_prototypes;
6261 warning.strict_prototypes = false;
6262 record_entity(entity, false);
6263 warning.strict_prototypes = strict_prototypes_old;
6270 * Creates a return_type (func)(argument_type) function type if not
6273 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6274 type_t *argument_type2)
6276 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6277 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6278 parameter1->next = parameter2;
6280 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6281 type->function.return_type = return_type;
6282 type->function.parameters = parameter1;
6284 return identify_new_type(type);
6288 * Creates a return_type (func)(argument_type) function type if not
6291 * @param return_type the return type
6292 * @param argument_type the argument type
6294 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6296 function_parameter_t *const parameter = allocate_parameter(argument_type);
6298 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6299 type->function.return_type = return_type;
6300 type->function.parameters = parameter;
6302 return identify_new_type(type);
6306 * Creates a return_type (func)(argument_type, ...) function type if not
6309 * @param return_type the return type
6310 * @param argument_type the argument type
6312 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6314 function_parameter_t *const parameter = allocate_parameter(argument_type);
6316 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6317 type->function.return_type = return_type;
6318 type->function.parameters = parameter;
6319 type->function.variadic = true;
6321 return identify_new_type(type);
6325 * Creates a return_type (func)(void) function type if not
6328 * @param return_type the return type
6330 static type_t *make_function_0_type(type_t *return_type)
6332 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6333 type->function.return_type = return_type;
6334 type->function.parameters = NULL;
6336 return identify_new_type(type);
6340 * Creates a NO_RETURN return_type (func)(void) function type if not
6343 * @param return_type the return type
6345 static type_t *make_function_0_type_noreturn(type_t *return_type)
6347 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6348 type->function.return_type = return_type;
6349 type->function.parameters = NULL;
6350 type->function.modifiers |= DM_NORETURN;
6351 return identify_new_type(type);
6355 * Performs automatic type cast as described in §6.3.2.1.
6357 * @param orig_type the original type
6359 static type_t *automatic_type_conversion(type_t *orig_type)
6361 type_t *type = skip_typeref(orig_type);
6362 if (is_type_array(type)) {
6363 array_type_t *array_type = &type->array;
6364 type_t *element_type = array_type->element_type;
6365 unsigned qualifiers = array_type->base.qualifiers;
6367 return make_pointer_type(element_type, qualifiers);
6370 if (is_type_function(type)) {
6371 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6378 * reverts the automatic casts of array to pointer types and function
6379 * to function-pointer types as defined §6.3.2.1
6381 type_t *revert_automatic_type_conversion(const expression_t *expression)
6383 switch (expression->kind) {
6384 case EXPR_REFERENCE: {
6385 entity_t *entity = expression->reference.entity;
6386 if (is_declaration(entity)) {
6387 return entity->declaration.type;
6388 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6389 return entity->enum_value.enum_type;
6391 panic("no declaration or enum in reference");
6396 entity_t *entity = expression->select.compound_entry;
6397 assert(is_declaration(entity));
6398 type_t *type = entity->declaration.type;
6399 return get_qualified_type(type,
6400 expression->base.type->base.qualifiers);
6403 case EXPR_UNARY_DEREFERENCE: {
6404 const expression_t *const value = expression->unary.value;
6405 type_t *const type = skip_typeref(value->base.type);
6406 if (!is_type_pointer(type))
6407 return type_error_type;
6408 return type->pointer.points_to;
6411 case EXPR_ARRAY_ACCESS: {
6412 const expression_t *array_ref = expression->array_access.array_ref;
6413 type_t *type_left = skip_typeref(array_ref->base.type);
6414 if (!is_type_pointer(type_left))
6415 return type_error_type;
6416 return type_left->pointer.points_to;
6419 case EXPR_STRING_LITERAL: {
6420 size_t size = expression->string.value.size;
6421 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6424 case EXPR_WIDE_STRING_LITERAL: {
6425 size_t size = expression->wide_string.value.size;
6426 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6429 case EXPR_COMPOUND_LITERAL:
6430 return expression->compound_literal.type;
6433 return expression->base.type;
6438 * Find an entity matching a symbol in a scope.
6439 * Uses current scope if scope is NULL
6441 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6442 namespace_tag_t namespc)
6444 if (scope == NULL) {
6445 return get_entity(symbol, namespc);
6448 /* we should optimize here, if scope grows above a certain size we should
6449 construct a hashmap here... */
6450 entity_t *entity = scope->entities;
6451 for ( ; entity != NULL; entity = entity->base.next) {
6452 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6459 static entity_t *parse_qualified_identifier(void)
6461 /* namespace containing the symbol */
6463 source_position_t pos;
6464 const scope_t *lookup_scope = NULL;
6466 if (next_if(T_COLONCOLON))
6467 lookup_scope = &unit->scope;
6471 if (token.type != T_IDENTIFIER) {
6472 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6473 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6475 symbol = token.v.symbol;
6480 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6482 if (!next_if(T_COLONCOLON))
6485 switch (entity->kind) {
6486 case ENTITY_NAMESPACE:
6487 lookup_scope = &entity->namespacee.members;
6492 lookup_scope = &entity->compound.members;
6495 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6496 symbol, get_entity_kind_name(entity->kind));
6501 if (entity == NULL) {
6502 if (!strict_mode && token.type == '(') {
6503 /* an implicitly declared function */
6504 if (warning.error_implicit_function_declaration) {
6505 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6506 } else if (warning.implicit_function_declaration) {
6507 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6510 entity = create_implicit_function(symbol, &pos);
6512 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6513 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6520 /* skip further qualifications */
6521 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6523 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6526 static expression_t *parse_reference(void)
6528 entity_t *entity = parse_qualified_identifier();
6531 if (is_declaration(entity)) {
6532 orig_type = entity->declaration.type;
6533 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6534 orig_type = entity->enum_value.enum_type;
6536 panic("expected declaration or enum value in reference");
6539 /* we always do the auto-type conversions; the & and sizeof parser contains
6540 * code to revert this! */
6541 type_t *type = automatic_type_conversion(orig_type);
6543 expression_kind_t kind = EXPR_REFERENCE;
6544 if (entity->kind == ENTITY_ENUM_VALUE)
6545 kind = EXPR_REFERENCE_ENUM_VALUE;
6547 expression_t *expression = allocate_expression_zero(kind);
6548 expression->reference.entity = entity;
6549 expression->base.type = type;
6551 /* this declaration is used */
6552 if (is_declaration(entity)) {
6553 entity->declaration.used = true;
6556 if (entity->base.parent_scope != file_scope
6557 && (current_function != NULL
6558 && entity->base.parent_scope->depth < current_function->parameters.depth)
6559 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6560 if (entity->kind == ENTITY_VARIABLE) {
6561 /* access of a variable from an outer function */
6562 entity->variable.address_taken = true;
6563 } else if (entity->kind == ENTITY_PARAMETER) {
6564 entity->parameter.address_taken = true;
6566 current_function->need_closure = true;
6569 check_deprecated(HERE, entity);
6571 if (warning.init_self && entity == current_init_decl && !in_type_prop
6572 && entity->kind == ENTITY_VARIABLE) {
6573 current_init_decl = NULL;
6574 warningf(HERE, "variable '%#T' is initialized by itself",
6575 entity->declaration.type, entity->base.symbol);
6581 static bool semantic_cast(expression_t *cast)
6583 expression_t *expression = cast->unary.value;
6584 type_t *orig_dest_type = cast->base.type;
6585 type_t *orig_type_right = expression->base.type;
6586 type_t const *dst_type = skip_typeref(orig_dest_type);
6587 type_t const *src_type = skip_typeref(orig_type_right);
6588 source_position_t const *pos = &cast->base.source_position;
6590 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6591 if (dst_type == type_void)
6594 /* only integer and pointer can be casted to pointer */
6595 if (is_type_pointer(dst_type) &&
6596 !is_type_pointer(src_type) &&
6597 !is_type_integer(src_type) &&
6598 is_type_valid(src_type)) {
6599 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6603 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6604 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6608 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6609 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6613 if (warning.cast_qual &&
6614 is_type_pointer(src_type) &&
6615 is_type_pointer(dst_type)) {
6616 type_t *src = skip_typeref(src_type->pointer.points_to);
6617 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6618 unsigned missing_qualifiers =
6619 src->base.qualifiers & ~dst->base.qualifiers;
6620 if (missing_qualifiers != 0) {
6622 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6623 missing_qualifiers, orig_type_right);
6629 static expression_t *parse_compound_literal(type_t *type)
6631 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6633 parse_initializer_env_t env;
6636 env.must_be_constant = false;
6637 initializer_t *initializer = parse_initializer(&env);
6640 expression->compound_literal.initializer = initializer;
6641 expression->compound_literal.type = type;
6642 expression->base.type = automatic_type_conversion(type);
6648 * Parse a cast expression.
6650 static expression_t *parse_cast(void)
6652 add_anchor_token(')');
6654 source_position_t source_position = token.source_position;
6656 type_t *type = parse_typename();
6658 rem_anchor_token(')');
6659 expect(')', end_error);
6661 if (token.type == '{') {
6662 return parse_compound_literal(type);
6665 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6666 cast->base.source_position = source_position;
6668 expression_t *value = parse_sub_expression(PREC_CAST);
6669 cast->base.type = type;
6670 cast->unary.value = value;
6672 if (! semantic_cast(cast)) {
6673 /* TODO: record the error in the AST. else it is impossible to detect it */
6678 return create_invalid_expression();
6682 * Parse a statement expression.
6684 static expression_t *parse_statement_expression(void)
6686 add_anchor_token(')');
6688 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6690 statement_t *statement = parse_compound_statement(true);
6691 statement->compound.stmt_expr = true;
6692 expression->statement.statement = statement;
6694 /* find last statement and use its type */
6695 type_t *type = type_void;
6696 const statement_t *stmt = statement->compound.statements;
6698 while (stmt->base.next != NULL)
6699 stmt = stmt->base.next;
6701 if (stmt->kind == STATEMENT_EXPRESSION) {
6702 type = stmt->expression.expression->base.type;
6704 } else if (warning.other) {
6705 warningf(&expression->base.source_position, "empty statement expression ({})");
6707 expression->base.type = type;
6709 rem_anchor_token(')');
6710 expect(')', end_error);
6717 * Parse a parenthesized expression.
6719 static expression_t *parse_parenthesized_expression(void)
6723 switch (token.type) {
6725 /* gcc extension: a statement expression */
6726 return parse_statement_expression();
6730 return parse_cast();
6732 if (is_typedef_symbol(token.v.symbol)) {
6733 return parse_cast();
6737 add_anchor_token(')');
6738 expression_t *result = parse_expression();
6739 result->base.parenthesized = true;
6740 rem_anchor_token(')');
6741 expect(')', end_error);
6747 static expression_t *parse_function_keyword(void)
6751 if (current_function == NULL) {
6752 errorf(HERE, "'__func__' used outside of a function");
6755 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6756 expression->base.type = type_char_ptr;
6757 expression->funcname.kind = FUNCNAME_FUNCTION;
6764 static expression_t *parse_pretty_function_keyword(void)
6766 if (current_function == NULL) {
6767 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6770 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6771 expression->base.type = type_char_ptr;
6772 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6774 eat(T___PRETTY_FUNCTION__);
6779 static expression_t *parse_funcsig_keyword(void)
6781 if (current_function == NULL) {
6782 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6785 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6786 expression->base.type = type_char_ptr;
6787 expression->funcname.kind = FUNCNAME_FUNCSIG;
6794 static expression_t *parse_funcdname_keyword(void)
6796 if (current_function == NULL) {
6797 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6800 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6801 expression->base.type = type_char_ptr;
6802 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6804 eat(T___FUNCDNAME__);
6809 static designator_t *parse_designator(void)
6811 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6812 result->source_position = *HERE;
6814 if (token.type != T_IDENTIFIER) {
6815 parse_error_expected("while parsing member designator",
6816 T_IDENTIFIER, NULL);
6819 result->symbol = token.v.symbol;
6822 designator_t *last_designator = result;
6825 if (token.type != T_IDENTIFIER) {
6826 parse_error_expected("while parsing member designator",
6827 T_IDENTIFIER, NULL);
6830 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6831 designator->source_position = *HERE;
6832 designator->symbol = token.v.symbol;
6835 last_designator->next = designator;
6836 last_designator = designator;
6840 add_anchor_token(']');
6841 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6842 designator->source_position = *HERE;
6843 designator->array_index = parse_expression();
6844 rem_anchor_token(']');
6845 expect(']', end_error);
6846 if (designator->array_index == NULL) {
6850 last_designator->next = designator;
6851 last_designator = designator;
6863 * Parse the __builtin_offsetof() expression.
6865 static expression_t *parse_offsetof(void)
6867 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6868 expression->base.type = type_size_t;
6870 eat(T___builtin_offsetof);
6872 expect('(', end_error);
6873 add_anchor_token(',');
6874 type_t *type = parse_typename();
6875 rem_anchor_token(',');
6876 expect(',', end_error);
6877 add_anchor_token(')');
6878 designator_t *designator = parse_designator();
6879 rem_anchor_token(')');
6880 expect(')', end_error);
6882 expression->offsetofe.type = type;
6883 expression->offsetofe.designator = designator;
6886 memset(&path, 0, sizeof(path));
6887 path.top_type = type;
6888 path.path = NEW_ARR_F(type_path_entry_t, 0);
6890 descend_into_subtype(&path);
6892 if (!walk_designator(&path, designator, true)) {
6893 return create_invalid_expression();
6896 DEL_ARR_F(path.path);
6900 return create_invalid_expression();
6904 * Parses a _builtin_va_start() expression.
6906 static expression_t *parse_va_start(void)
6908 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6910 eat(T___builtin_va_start);
6912 expect('(', end_error);
6913 add_anchor_token(',');
6914 expression->va_starte.ap = parse_assignment_expression();
6915 rem_anchor_token(',');
6916 expect(',', end_error);
6917 expression_t *const expr = parse_assignment_expression();
6918 if (expr->kind == EXPR_REFERENCE) {
6919 entity_t *const entity = expr->reference.entity;
6920 if (!current_function->base.type->function.variadic) {
6921 errorf(&expr->base.source_position,
6922 "'va_start' used in non-variadic function");
6923 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6924 entity->base.next != NULL ||
6925 entity->kind != ENTITY_PARAMETER) {
6926 errorf(&expr->base.source_position,
6927 "second argument of 'va_start' must be last parameter of the current function");
6929 expression->va_starte.parameter = &entity->variable;
6931 expect(')', end_error);
6934 expect(')', end_error);
6936 return create_invalid_expression();
6940 * Parses a __builtin_va_arg() expression.
6942 static expression_t *parse_va_arg(void)
6944 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6946 eat(T___builtin_va_arg);
6948 expect('(', end_error);
6950 ap.expression = parse_assignment_expression();
6951 expression->va_arge.ap = ap.expression;
6952 check_call_argument(type_valist, &ap, 1);
6954 expect(',', end_error);
6955 expression->base.type = parse_typename();
6956 expect(')', end_error);
6960 return create_invalid_expression();
6964 * Parses a __builtin_va_copy() expression.
6966 static expression_t *parse_va_copy(void)
6968 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6970 eat(T___builtin_va_copy);
6972 expect('(', end_error);
6973 expression_t *dst = parse_assignment_expression();
6974 assign_error_t error = semantic_assign(type_valist, dst);
6975 report_assign_error(error, type_valist, dst, "call argument 1",
6976 &dst->base.source_position);
6977 expression->va_copye.dst = dst;
6979 expect(',', end_error);
6981 call_argument_t src;
6982 src.expression = parse_assignment_expression();
6983 check_call_argument(type_valist, &src, 2);
6984 expression->va_copye.src = src.expression;
6985 expect(')', end_error);
6989 return create_invalid_expression();
6993 * Parses a __builtin_constant_p() expression.
6995 static expression_t *parse_builtin_constant(void)
6997 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6999 eat(T___builtin_constant_p);
7001 expect('(', end_error);
7002 add_anchor_token(')');
7003 expression->builtin_constant.value = parse_assignment_expression();
7004 rem_anchor_token(')');
7005 expect(')', end_error);
7006 expression->base.type = type_int;
7010 return create_invalid_expression();
7014 * Parses a __builtin_types_compatible_p() expression.
7016 static expression_t *parse_builtin_types_compatible(void)
7018 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7020 eat(T___builtin_types_compatible_p);
7022 expect('(', end_error);
7023 add_anchor_token(')');
7024 add_anchor_token(',');
7025 expression->builtin_types_compatible.left = parse_typename();
7026 rem_anchor_token(',');
7027 expect(',', end_error);
7028 expression->builtin_types_compatible.right = parse_typename();
7029 rem_anchor_token(')');
7030 expect(')', end_error);
7031 expression->base.type = type_int;
7035 return create_invalid_expression();
7039 * Parses a __builtin_is_*() compare expression.
7041 static expression_t *parse_compare_builtin(void)
7043 expression_t *expression;
7045 switch (token.type) {
7046 case T___builtin_isgreater:
7047 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7049 case T___builtin_isgreaterequal:
7050 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7052 case T___builtin_isless:
7053 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7055 case T___builtin_islessequal:
7056 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7058 case T___builtin_islessgreater:
7059 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7061 case T___builtin_isunordered:
7062 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7065 internal_errorf(HERE, "invalid compare builtin found");
7067 expression->base.source_position = *HERE;
7070 expect('(', end_error);
7071 expression->binary.left = parse_assignment_expression();
7072 expect(',', end_error);
7073 expression->binary.right = parse_assignment_expression();
7074 expect(')', end_error);
7076 type_t *const orig_type_left = expression->binary.left->base.type;
7077 type_t *const orig_type_right = expression->binary.right->base.type;
7079 type_t *const type_left = skip_typeref(orig_type_left);
7080 type_t *const type_right = skip_typeref(orig_type_right);
7081 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7082 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7083 type_error_incompatible("invalid operands in comparison",
7084 &expression->base.source_position, orig_type_left, orig_type_right);
7087 semantic_comparison(&expression->binary);
7092 return create_invalid_expression();
7096 * Parses a MS assume() expression.
7098 static expression_t *parse_assume(void)
7100 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7104 expect('(', end_error);
7105 add_anchor_token(')');
7106 expression->unary.value = parse_assignment_expression();
7107 rem_anchor_token(')');
7108 expect(')', end_error);
7110 expression->base.type = type_void;
7113 return create_invalid_expression();
7117 * Return the declaration for a given label symbol or create a new one.
7119 * @param symbol the symbol of the label
7121 static label_t *get_label(symbol_t *symbol)
7124 assert(current_function != NULL);
7126 label = get_entity(symbol, NAMESPACE_LABEL);
7127 /* if we found a local label, we already created the declaration */
7128 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7129 if (label->base.parent_scope != current_scope) {
7130 assert(label->base.parent_scope->depth < current_scope->depth);
7131 current_function->goto_to_outer = true;
7133 return &label->label;
7136 label = get_entity(symbol, NAMESPACE_LABEL);
7137 /* if we found a label in the same function, then we already created the
7140 && label->base.parent_scope == ¤t_function->parameters) {
7141 return &label->label;
7144 /* otherwise we need to create a new one */
7145 label = allocate_entity_zero(ENTITY_LABEL);
7146 label->base.namespc = NAMESPACE_LABEL;
7147 label->base.symbol = symbol;
7151 return &label->label;
7155 * Parses a GNU && label address expression.
7157 static expression_t *parse_label_address(void)
7159 source_position_t source_position = token.source_position;
7161 if (token.type != T_IDENTIFIER) {
7162 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7165 symbol_t *symbol = token.v.symbol;
7168 label_t *label = get_label(symbol);
7170 label->address_taken = true;
7172 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7173 expression->base.source_position = source_position;
7175 /* label address is threaten as a void pointer */
7176 expression->base.type = type_void_ptr;
7177 expression->label_address.label = label;
7180 return create_invalid_expression();
7184 * Parse a microsoft __noop expression.
7186 static expression_t *parse_noop_expression(void)
7188 /* the result is a (int)0 */
7189 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7190 cnst->base.type = type_int;
7191 cnst->conste.v.int_value = 0;
7192 cnst->conste.is_ms_noop = true;
7196 if (token.type == '(') {
7197 /* parse arguments */
7199 add_anchor_token(')');
7200 add_anchor_token(',');
7202 if (token.type != ')') do {
7203 (void)parse_assignment_expression();
7204 } while (next_if(','));
7206 rem_anchor_token(',');
7207 rem_anchor_token(')');
7208 expect(')', end_error);
7215 * Parses a primary expression.
7217 static expression_t *parse_primary_expression(void)
7219 switch (token.type) {
7220 case T_false: return parse_bool_const(false);
7221 case T_true: return parse_bool_const(true);
7222 case T_INTEGER: return parse_int_const();
7223 case T_CHARACTER_CONSTANT: return parse_character_constant();
7224 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7225 case T_FLOATINGPOINT: return parse_float_const();
7226 case T_STRING_LITERAL:
7227 case T_WIDE_STRING_LITERAL: return parse_string_const();
7228 case T___FUNCTION__:
7229 case T___func__: return parse_function_keyword();
7230 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7231 case T___FUNCSIG__: return parse_funcsig_keyword();
7232 case T___FUNCDNAME__: return parse_funcdname_keyword();
7233 case T___builtin_offsetof: return parse_offsetof();
7234 case T___builtin_va_start: return parse_va_start();
7235 case T___builtin_va_arg: return parse_va_arg();
7236 case T___builtin_va_copy: return parse_va_copy();
7237 case T___builtin_isgreater:
7238 case T___builtin_isgreaterequal:
7239 case T___builtin_isless:
7240 case T___builtin_islessequal:
7241 case T___builtin_islessgreater:
7242 case T___builtin_isunordered: return parse_compare_builtin();
7243 case T___builtin_constant_p: return parse_builtin_constant();
7244 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7245 case T__assume: return parse_assume();
7248 return parse_label_address();
7251 case '(': return parse_parenthesized_expression();
7252 case T___noop: return parse_noop_expression();
7254 /* Gracefully handle type names while parsing expressions. */
7256 return parse_reference();
7258 if (!is_typedef_symbol(token.v.symbol)) {
7259 return parse_reference();
7263 source_position_t const pos = *HERE;
7264 type_t const *const type = parse_typename();
7265 errorf(&pos, "encountered type '%T' while parsing expression", type);
7266 return create_invalid_expression();
7270 errorf(HERE, "unexpected token %K, expected an expression", &token);
7271 return create_invalid_expression();
7275 * Check if the expression has the character type and issue a warning then.
7277 static void check_for_char_index_type(const expression_t *expression)
7279 type_t *const type = expression->base.type;
7280 const type_t *const base_type = skip_typeref(type);
7282 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7283 warning.char_subscripts) {
7284 warningf(&expression->base.source_position,
7285 "array subscript has type '%T'", type);
7289 static expression_t *parse_array_expression(expression_t *left)
7291 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7294 add_anchor_token(']');
7296 expression_t *inside = parse_expression();
7298 type_t *const orig_type_left = left->base.type;
7299 type_t *const orig_type_inside = inside->base.type;
7301 type_t *const type_left = skip_typeref(orig_type_left);
7302 type_t *const type_inside = skip_typeref(orig_type_inside);
7304 type_t *return_type;
7305 array_access_expression_t *array_access = &expression->array_access;
7306 if (is_type_pointer(type_left)) {
7307 return_type = type_left->pointer.points_to;
7308 array_access->array_ref = left;
7309 array_access->index = inside;
7310 check_for_char_index_type(inside);
7311 } else if (is_type_pointer(type_inside)) {
7312 return_type = type_inside->pointer.points_to;
7313 array_access->array_ref = inside;
7314 array_access->index = left;
7315 array_access->flipped = true;
7316 check_for_char_index_type(left);
7318 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7320 "array access on object with non-pointer types '%T', '%T'",
7321 orig_type_left, orig_type_inside);
7323 return_type = type_error_type;
7324 array_access->array_ref = left;
7325 array_access->index = inside;
7328 expression->base.type = automatic_type_conversion(return_type);
7330 rem_anchor_token(']');
7331 expect(']', end_error);
7336 static expression_t *parse_typeprop(expression_kind_t const kind)
7338 expression_t *tp_expression = allocate_expression_zero(kind);
7339 tp_expression->base.type = type_size_t;
7341 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7343 /* we only refer to a type property, mark this case */
7344 bool old = in_type_prop;
7345 in_type_prop = true;
7348 expression_t *expression;
7349 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7351 add_anchor_token(')');
7352 orig_type = parse_typename();
7353 rem_anchor_token(')');
7354 expect(')', end_error);
7356 if (token.type == '{') {
7357 /* It was not sizeof(type) after all. It is sizeof of an expression
7358 * starting with a compound literal */
7359 expression = parse_compound_literal(orig_type);
7360 goto typeprop_expression;
7363 expression = parse_sub_expression(PREC_UNARY);
7365 typeprop_expression:
7366 tp_expression->typeprop.tp_expression = expression;
7368 orig_type = revert_automatic_type_conversion(expression);
7369 expression->base.type = orig_type;
7372 tp_expression->typeprop.type = orig_type;
7373 type_t const* const type = skip_typeref(orig_type);
7374 char const* const wrong_type =
7375 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7376 is_type_incomplete(type) ? "incomplete" :
7377 type->kind == TYPE_FUNCTION ? "function designator" :
7378 type->kind == TYPE_BITFIELD ? "bitfield" :
7380 if (wrong_type != NULL) {
7381 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7382 errorf(&tp_expression->base.source_position,
7383 "operand of %s expression must not be of %s type '%T'",
7384 what, wrong_type, orig_type);
7389 return tp_expression;
7392 static expression_t *parse_sizeof(void)
7394 return parse_typeprop(EXPR_SIZEOF);
7397 static expression_t *parse_alignof(void)
7399 return parse_typeprop(EXPR_ALIGNOF);
7402 static expression_t *parse_select_expression(expression_t *addr)
7404 assert(token.type == '.' || token.type == T_MINUSGREATER);
7405 bool select_left_arrow = (token.type == T_MINUSGREATER);
7408 if (token.type != T_IDENTIFIER) {
7409 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7410 return create_invalid_expression();
7412 symbol_t *symbol = token.v.symbol;
7415 type_t *const orig_type = addr->base.type;
7416 type_t *const type = skip_typeref(orig_type);
7419 bool saw_error = false;
7420 if (is_type_pointer(type)) {
7421 if (!select_left_arrow) {
7423 "request for member '%Y' in something not a struct or union, but '%T'",
7427 type_left = skip_typeref(type->pointer.points_to);
7429 if (select_left_arrow && is_type_valid(type)) {
7430 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7436 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7437 type_left->kind != TYPE_COMPOUND_UNION) {
7439 if (is_type_valid(type_left) && !saw_error) {
7441 "request for member '%Y' in something not a struct or union, but '%T'",
7444 return create_invalid_expression();
7447 compound_t *compound = type_left->compound.compound;
7448 if (!compound->complete) {
7449 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7451 return create_invalid_expression();
7454 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7455 expression_t *result
7456 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7458 if (result == NULL) {
7459 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7460 return create_invalid_expression();
7466 static void check_call_argument(type_t *expected_type,
7467 call_argument_t *argument, unsigned pos)
7469 type_t *expected_type_skip = skip_typeref(expected_type);
7470 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7471 expression_t *arg_expr = argument->expression;
7472 type_t *arg_type = skip_typeref(arg_expr->base.type);
7474 /* handle transparent union gnu extension */
7475 if (is_type_union(expected_type_skip)
7476 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7477 compound_t *union_decl = expected_type_skip->compound.compound;
7478 type_t *best_type = NULL;
7479 entity_t *entry = union_decl->members.entities;
7480 for ( ; entry != NULL; entry = entry->base.next) {
7481 assert(is_declaration(entry));
7482 type_t *decl_type = entry->declaration.type;
7483 error = semantic_assign(decl_type, arg_expr);
7484 if (error == ASSIGN_ERROR_INCOMPATIBLE
7485 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7488 if (error == ASSIGN_SUCCESS) {
7489 best_type = decl_type;
7490 } else if (best_type == NULL) {
7491 best_type = decl_type;
7495 if (best_type != NULL) {
7496 expected_type = best_type;
7500 error = semantic_assign(expected_type, arg_expr);
7501 argument->expression = create_implicit_cast(arg_expr, expected_type);
7503 if (error != ASSIGN_SUCCESS) {
7504 /* report exact scope in error messages (like "in argument 3") */
7506 snprintf(buf, sizeof(buf), "call argument %u", pos);
7507 report_assign_error(error, expected_type, arg_expr, buf,
7508 &arg_expr->base.source_position);
7509 } else if (warning.traditional || warning.conversion) {
7510 type_t *const promoted_type = get_default_promoted_type(arg_type);
7511 if (!types_compatible(expected_type_skip, promoted_type) &&
7512 !types_compatible(expected_type_skip, type_void_ptr) &&
7513 !types_compatible(type_void_ptr, promoted_type)) {
7514 /* Deliberately show the skipped types in this warning */
7515 warningf(&arg_expr->base.source_position,
7516 "passing call argument %u as '%T' rather than '%T' due to prototype",
7517 pos, expected_type_skip, promoted_type);
7523 * Handle the semantic restrictions of builtin calls
7525 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7526 switch (call->function->reference.entity->function.btk) {
7527 case bk_gnu_builtin_return_address:
7528 case bk_gnu_builtin_frame_address: {
7529 /* argument must be constant */
7530 call_argument_t *argument = call->arguments;
7532 if (! is_constant_expression(argument->expression)) {
7533 errorf(&call->base.source_position,
7534 "argument of '%Y' must be a constant expression",
7535 call->function->reference.entity->base.symbol);
7539 case bk_gnu_builtin_prefetch: {
7540 /* second and third argument must be constant if existent */
7541 call_argument_t *rw = call->arguments->next;
7542 call_argument_t *locality = NULL;
7545 if (! is_constant_expression(rw->expression)) {
7546 errorf(&call->base.source_position,
7547 "second argument of '%Y' must be a constant expression",
7548 call->function->reference.entity->base.symbol);
7550 locality = rw->next;
7552 if (locality != NULL) {
7553 if (! is_constant_expression(locality->expression)) {
7554 errorf(&call->base.source_position,
7555 "third argument of '%Y' must be a constant expression",
7556 call->function->reference.entity->base.symbol);
7558 locality = rw->next;
7568 * Parse a call expression, ie. expression '( ... )'.
7570 * @param expression the function address
7572 static expression_t *parse_call_expression(expression_t *expression)
7574 expression_t *result = allocate_expression_zero(EXPR_CALL);
7575 call_expression_t *call = &result->call;
7576 call->function = expression;
7578 type_t *const orig_type = expression->base.type;
7579 type_t *const type = skip_typeref(orig_type);
7581 function_type_t *function_type = NULL;
7582 if (is_type_pointer(type)) {
7583 type_t *const to_type = skip_typeref(type->pointer.points_to);
7585 if (is_type_function(to_type)) {
7586 function_type = &to_type->function;
7587 call->base.type = function_type->return_type;
7591 if (function_type == NULL && is_type_valid(type)) {
7593 "called object '%E' (type '%T') is not a pointer to a function",
7594 expression, orig_type);
7597 /* parse arguments */
7599 add_anchor_token(')');
7600 add_anchor_token(',');
7602 if (token.type != ')') {
7603 call_argument_t **anchor = &call->arguments;
7605 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7606 argument->expression = parse_assignment_expression();
7609 anchor = &argument->next;
7610 } while (next_if(','));
7612 rem_anchor_token(',');
7613 rem_anchor_token(')');
7614 expect(')', end_error);
7616 if (function_type == NULL)
7619 /* check type and count of call arguments */
7620 function_parameter_t *parameter = function_type->parameters;
7621 call_argument_t *argument = call->arguments;
7622 if (!function_type->unspecified_parameters) {
7623 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7624 parameter = parameter->next, argument = argument->next) {
7625 check_call_argument(parameter->type, argument, ++pos);
7628 if (parameter != NULL) {
7629 errorf(HERE, "too few arguments to function '%E'", expression);
7630 } else if (argument != NULL && !function_type->variadic) {
7631 errorf(HERE, "too many arguments to function '%E'", expression);
7635 /* do default promotion for other arguments */
7636 for (; argument != NULL; argument = argument->next) {
7637 type_t *type = argument->expression->base.type;
7639 type = get_default_promoted_type(type);
7641 argument->expression
7642 = create_implicit_cast(argument->expression, type);
7645 check_format(&result->call);
7647 if (warning.aggregate_return &&
7648 is_type_compound(skip_typeref(function_type->return_type))) {
7649 warningf(&result->base.source_position,
7650 "function call has aggregate value");
7653 if (call->function->kind == EXPR_REFERENCE) {
7654 reference_expression_t *reference = &call->function->reference;
7655 if (reference->entity->kind == ENTITY_FUNCTION &&
7656 reference->entity->function.btk != bk_none)
7657 handle_builtin_argument_restrictions(call);
7664 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7666 static bool same_compound_type(const type_t *type1, const type_t *type2)
7669 is_type_compound(type1) &&
7670 type1->kind == type2->kind &&
7671 type1->compound.compound == type2->compound.compound;
7674 static expression_t const *get_reference_address(expression_t const *expr)
7676 bool regular_take_address = true;
7678 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7679 expr = expr->unary.value;
7681 regular_take_address = false;
7684 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7687 expr = expr->unary.value;
7690 if (expr->kind != EXPR_REFERENCE)
7693 /* special case for functions which are automatically converted to a
7694 * pointer to function without an extra TAKE_ADDRESS operation */
7695 if (!regular_take_address &&
7696 expr->reference.entity->kind != ENTITY_FUNCTION) {
7703 static void warn_reference_address_as_bool(expression_t const* expr)
7705 if (!warning.address)
7708 expr = get_reference_address(expr);
7710 warningf(&expr->base.source_position,
7711 "the address of '%Y' will always evaluate as 'true'",
7712 expr->reference.entity->base.symbol);
7716 static void warn_assignment_in_condition(const expression_t *const expr)
7718 if (!warning.parentheses)
7720 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7722 if (expr->base.parenthesized)
7724 warningf(&expr->base.source_position,
7725 "suggest parentheses around assignment used as truth value");
7728 static void semantic_condition(expression_t const *const expr,
7729 char const *const context)
7731 type_t *const type = skip_typeref(expr->base.type);
7732 if (is_type_scalar(type)) {
7733 warn_reference_address_as_bool(expr);
7734 warn_assignment_in_condition(expr);
7735 } else if (is_type_valid(type)) {
7736 errorf(&expr->base.source_position,
7737 "%s must have scalar type", context);
7742 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7744 * @param expression the conditional expression
7746 static expression_t *parse_conditional_expression(expression_t *expression)
7748 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7750 conditional_expression_t *conditional = &result->conditional;
7751 conditional->condition = expression;
7754 add_anchor_token(':');
7756 /* §6.5.15:2 The first operand shall have scalar type. */
7757 semantic_condition(expression, "condition of conditional operator");
7759 expression_t *true_expression = expression;
7760 bool gnu_cond = false;
7761 if (GNU_MODE && token.type == ':') {
7764 true_expression = parse_expression();
7766 rem_anchor_token(':');
7767 expect(':', end_error);
7769 expression_t *false_expression =
7770 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7772 type_t *const orig_true_type = true_expression->base.type;
7773 type_t *const orig_false_type = false_expression->base.type;
7774 type_t *const true_type = skip_typeref(orig_true_type);
7775 type_t *const false_type = skip_typeref(orig_false_type);
7778 type_t *result_type;
7779 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7780 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7781 /* ISO/IEC 14882:1998(E) §5.16:2 */
7782 if (true_expression->kind == EXPR_UNARY_THROW) {
7783 result_type = false_type;
7784 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7785 result_type = true_type;
7787 if (warning.other && (
7788 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7789 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7791 warningf(&conditional->base.source_position,
7792 "ISO C forbids conditional expression with only one void side");
7794 result_type = type_void;
7796 } else if (is_type_arithmetic(true_type)
7797 && is_type_arithmetic(false_type)) {
7798 result_type = semantic_arithmetic(true_type, false_type);
7800 true_expression = create_implicit_cast(true_expression, result_type);
7801 false_expression = create_implicit_cast(false_expression, result_type);
7803 conditional->true_expression = true_expression;
7804 conditional->false_expression = false_expression;
7805 conditional->base.type = result_type;
7806 } else if (same_compound_type(true_type, false_type)) {
7807 /* just take 1 of the 2 types */
7808 result_type = true_type;
7809 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7810 type_t *pointer_type;
7812 expression_t *other_expression;
7813 if (is_type_pointer(true_type) &&
7814 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7815 pointer_type = true_type;
7816 other_type = false_type;
7817 other_expression = false_expression;
7819 pointer_type = false_type;
7820 other_type = true_type;
7821 other_expression = true_expression;
7824 if (is_null_pointer_constant(other_expression)) {
7825 result_type = pointer_type;
7826 } else if (is_type_pointer(other_type)) {
7827 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7828 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7831 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7832 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7834 } else if (types_compatible(get_unqualified_type(to1),
7835 get_unqualified_type(to2))) {
7838 if (warning.other) {
7839 warningf(&conditional->base.source_position,
7840 "pointer types '%T' and '%T' in conditional expression are incompatible",
7841 true_type, false_type);
7846 type_t *const type =
7847 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7848 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7849 } else if (is_type_integer(other_type)) {
7850 if (warning.other) {
7851 warningf(&conditional->base.source_position,
7852 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7854 result_type = pointer_type;
7856 if (is_type_valid(other_type)) {
7857 type_error_incompatible("while parsing conditional",
7858 &expression->base.source_position, true_type, false_type);
7860 result_type = type_error_type;
7863 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7864 type_error_incompatible("while parsing conditional",
7865 &conditional->base.source_position, true_type,
7868 result_type = type_error_type;
7871 conditional->true_expression
7872 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7873 conditional->false_expression
7874 = create_implicit_cast(false_expression, result_type);
7875 conditional->base.type = result_type;
7880 * Parse an extension expression.
7882 static expression_t *parse_extension(void)
7884 eat(T___extension__);
7886 bool old_gcc_extension = in_gcc_extension;
7887 in_gcc_extension = true;
7888 expression_t *expression = parse_sub_expression(PREC_UNARY);
7889 in_gcc_extension = old_gcc_extension;
7894 * Parse a __builtin_classify_type() expression.
7896 static expression_t *parse_builtin_classify_type(void)
7898 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7899 result->base.type = type_int;
7901 eat(T___builtin_classify_type);
7903 expect('(', end_error);
7904 add_anchor_token(')');
7905 expression_t *expression = parse_expression();
7906 rem_anchor_token(')');
7907 expect(')', end_error);
7908 result->classify_type.type_expression = expression;
7912 return create_invalid_expression();
7916 * Parse a delete expression
7917 * ISO/IEC 14882:1998(E) §5.3.5
7919 static expression_t *parse_delete(void)
7921 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7922 result->base.type = type_void;
7927 result->kind = EXPR_UNARY_DELETE_ARRAY;
7928 expect(']', end_error);
7932 expression_t *const value = parse_sub_expression(PREC_CAST);
7933 result->unary.value = value;
7935 type_t *const type = skip_typeref(value->base.type);
7936 if (!is_type_pointer(type)) {
7937 if (is_type_valid(type)) {
7938 errorf(&value->base.source_position,
7939 "operand of delete must have pointer type");
7941 } else if (warning.other &&
7942 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7943 warningf(&value->base.source_position,
7944 "deleting 'void*' is undefined");
7951 * Parse a throw expression
7952 * ISO/IEC 14882:1998(E) §15:1
7954 static expression_t *parse_throw(void)
7956 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7957 result->base.type = type_void;
7961 expression_t *value = NULL;
7962 switch (token.type) {
7964 value = parse_assignment_expression();
7965 /* ISO/IEC 14882:1998(E) §15.1:3 */
7966 type_t *const orig_type = value->base.type;
7967 type_t *const type = skip_typeref(orig_type);
7968 if (is_type_incomplete(type)) {
7969 errorf(&value->base.source_position,
7970 "cannot throw object of incomplete type '%T'", orig_type);
7971 } else if (is_type_pointer(type)) {
7972 type_t *const points_to = skip_typeref(type->pointer.points_to);
7973 if (is_type_incomplete(points_to) &&
7974 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7975 errorf(&value->base.source_position,
7976 "cannot throw pointer to incomplete type '%T'", orig_type);
7984 result->unary.value = value;
7989 static bool check_pointer_arithmetic(const source_position_t *source_position,
7990 type_t *pointer_type,
7991 type_t *orig_pointer_type)
7993 type_t *points_to = pointer_type->pointer.points_to;
7994 points_to = skip_typeref(points_to);
7996 if (is_type_incomplete(points_to)) {
7997 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7998 errorf(source_position,
7999 "arithmetic with pointer to incomplete type '%T' not allowed",
8002 } else if (warning.pointer_arith) {
8003 warningf(source_position,
8004 "pointer of type '%T' used in arithmetic",
8007 } else if (is_type_function(points_to)) {
8009 errorf(source_position,
8010 "arithmetic with pointer to function type '%T' not allowed",
8013 } else if (warning.pointer_arith) {
8014 warningf(source_position,
8015 "pointer to a function '%T' used in arithmetic",
8022 static bool is_lvalue(const expression_t *expression)
8024 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8025 switch (expression->kind) {
8026 case EXPR_ARRAY_ACCESS:
8027 case EXPR_COMPOUND_LITERAL:
8028 case EXPR_REFERENCE:
8030 case EXPR_UNARY_DEREFERENCE:
8034 type_t *type = skip_typeref(expression->base.type);
8036 /* ISO/IEC 14882:1998(E) §3.10:3 */
8037 is_type_reference(type) ||
8038 /* Claim it is an lvalue, if the type is invalid. There was a parse
8039 * error before, which maybe prevented properly recognizing it as
8041 !is_type_valid(type);
8046 static void semantic_incdec(unary_expression_t *expression)
8048 type_t *const orig_type = expression->value->base.type;
8049 type_t *const type = skip_typeref(orig_type);
8050 if (is_type_pointer(type)) {
8051 if (!check_pointer_arithmetic(&expression->base.source_position,
8055 } else if (!is_type_real(type) && is_type_valid(type)) {
8056 /* TODO: improve error message */
8057 errorf(&expression->base.source_position,
8058 "operation needs an arithmetic or pointer type");
8061 if (!is_lvalue(expression->value)) {
8062 /* TODO: improve error message */
8063 errorf(&expression->base.source_position, "lvalue required as operand");
8065 expression->base.type = orig_type;
8068 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8070 type_t *const orig_type = expression->value->base.type;
8071 type_t *const type = skip_typeref(orig_type);
8072 if (!is_type_arithmetic(type)) {
8073 if (is_type_valid(type)) {
8074 /* TODO: improve error message */
8075 errorf(&expression->base.source_position,
8076 "operation needs an arithmetic type");
8081 expression->base.type = orig_type;
8084 static void semantic_unexpr_plus(unary_expression_t *expression)
8086 semantic_unexpr_arithmetic(expression);
8087 if (warning.traditional)
8088 warningf(&expression->base.source_position,
8089 "traditional C rejects the unary plus operator");
8092 static void semantic_not(unary_expression_t *expression)
8094 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8095 semantic_condition(expression->value, "operand of !");
8096 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8099 static void semantic_unexpr_integer(unary_expression_t *expression)
8101 type_t *const orig_type = expression->value->base.type;
8102 type_t *const type = skip_typeref(orig_type);
8103 if (!is_type_integer(type)) {
8104 if (is_type_valid(type)) {
8105 errorf(&expression->base.source_position,
8106 "operand of ~ must be of integer type");
8111 expression->base.type = orig_type;
8114 static void semantic_dereference(unary_expression_t *expression)
8116 type_t *const orig_type = expression->value->base.type;
8117 type_t *const type = skip_typeref(orig_type);
8118 if (!is_type_pointer(type)) {
8119 if (is_type_valid(type)) {
8120 errorf(&expression->base.source_position,
8121 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8126 type_t *result_type = type->pointer.points_to;
8127 result_type = automatic_type_conversion(result_type);
8128 expression->base.type = result_type;
8132 * Record that an address is taken (expression represents an lvalue).
8134 * @param expression the expression
8135 * @param may_be_register if true, the expression might be an register
8137 static void set_address_taken(expression_t *expression, bool may_be_register)
8139 if (expression->kind != EXPR_REFERENCE)
8142 entity_t *const entity = expression->reference.entity;
8144 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8147 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8148 && !may_be_register) {
8149 errorf(&expression->base.source_position,
8150 "address of register %s '%Y' requested",
8151 get_entity_kind_name(entity->kind), entity->base.symbol);
8154 if (entity->kind == ENTITY_VARIABLE) {
8155 entity->variable.address_taken = true;
8157 assert(entity->kind == ENTITY_PARAMETER);
8158 entity->parameter.address_taken = true;
8163 * Check the semantic of the address taken expression.
8165 static void semantic_take_addr(unary_expression_t *expression)
8167 expression_t *value = expression->value;
8168 value->base.type = revert_automatic_type_conversion(value);
8170 type_t *orig_type = value->base.type;
8171 type_t *type = skip_typeref(orig_type);
8172 if (!is_type_valid(type))
8176 if (!is_lvalue(value)) {
8177 errorf(&expression->base.source_position, "'&' requires an lvalue");
8179 if (type->kind == TYPE_BITFIELD) {
8180 errorf(&expression->base.source_position,
8181 "'&' not allowed on object with bitfield type '%T'",
8185 set_address_taken(value, false);
8187 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8190 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8191 static expression_t *parse_##unexpression_type(void) \
8193 expression_t *unary_expression \
8194 = allocate_expression_zero(unexpression_type); \
8196 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8198 sfunc(&unary_expression->unary); \
8200 return unary_expression; \
8203 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8204 semantic_unexpr_arithmetic)
8205 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8206 semantic_unexpr_plus)
8207 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8209 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8210 semantic_dereference)
8211 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8213 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8214 semantic_unexpr_integer)
8215 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8217 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8220 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8222 static expression_t *parse_##unexpression_type(expression_t *left) \
8224 expression_t *unary_expression \
8225 = allocate_expression_zero(unexpression_type); \
8227 unary_expression->unary.value = left; \
8229 sfunc(&unary_expression->unary); \
8231 return unary_expression; \
8234 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8235 EXPR_UNARY_POSTFIX_INCREMENT,
8237 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8238 EXPR_UNARY_POSTFIX_DECREMENT,
8241 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8243 /* TODO: handle complex + imaginary types */
8245 type_left = get_unqualified_type(type_left);
8246 type_right = get_unqualified_type(type_right);
8248 /* §6.3.1.8 Usual arithmetic conversions */
8249 if (type_left == type_long_double || type_right == type_long_double) {
8250 return type_long_double;
8251 } else if (type_left == type_double || type_right == type_double) {
8253 } else if (type_left == type_float || type_right == type_float) {
8257 type_left = promote_integer(type_left);
8258 type_right = promote_integer(type_right);
8260 if (type_left == type_right)
8263 bool const signed_left = is_type_signed(type_left);
8264 bool const signed_right = is_type_signed(type_right);
8265 int const rank_left = get_rank(type_left);
8266 int const rank_right = get_rank(type_right);
8268 if (signed_left == signed_right)
8269 return rank_left >= rank_right ? type_left : type_right;
8278 u_rank = rank_right;
8279 u_type = type_right;
8281 s_rank = rank_right;
8282 s_type = type_right;
8287 if (u_rank >= s_rank)
8290 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8292 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8293 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8297 case ATOMIC_TYPE_INT: return type_unsigned_int;
8298 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8299 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8301 default: panic("invalid atomic type");
8306 * Check the semantic restrictions for a binary expression.
8308 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8310 expression_t *const left = expression->left;
8311 expression_t *const right = expression->right;
8312 type_t *const orig_type_left = left->base.type;
8313 type_t *const orig_type_right = right->base.type;
8314 type_t *const type_left = skip_typeref(orig_type_left);
8315 type_t *const type_right = skip_typeref(orig_type_right);
8317 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8318 /* TODO: improve error message */
8319 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8320 errorf(&expression->base.source_position,
8321 "operation needs arithmetic types");
8326 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8327 expression->left = create_implicit_cast(left, arithmetic_type);
8328 expression->right = create_implicit_cast(right, arithmetic_type);
8329 expression->base.type = arithmetic_type;
8332 static void warn_div_by_zero(binary_expression_t const *const expression)
8334 if (!warning.div_by_zero ||
8335 !is_type_integer(expression->base.type))
8338 expression_t const *const right = expression->right;
8339 /* The type of the right operand can be different for /= */
8340 if (is_type_integer(right->base.type) &&
8341 is_constant_expression(right) &&
8342 !fold_constant_to_bool(right)) {
8343 warningf(&expression->base.source_position, "division by zero");
8348 * Check the semantic restrictions for a div/mod expression.
8350 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8352 semantic_binexpr_arithmetic(expression);
8353 warn_div_by_zero(expression);
8356 static void warn_addsub_in_shift(const expression_t *const expr)
8358 if (expr->base.parenthesized)
8362 switch (expr->kind) {
8363 case EXPR_BINARY_ADD: op = '+'; break;
8364 case EXPR_BINARY_SUB: op = '-'; break;
8368 warningf(&expr->base.source_position,
8369 "suggest parentheses around '%c' inside shift", op);
8372 static bool semantic_shift(binary_expression_t *expression)
8374 expression_t *const left = expression->left;
8375 expression_t *const right = expression->right;
8376 type_t *const orig_type_left = left->base.type;
8377 type_t *const orig_type_right = right->base.type;
8378 type_t * type_left = skip_typeref(orig_type_left);
8379 type_t * type_right = skip_typeref(orig_type_right);
8381 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8382 /* TODO: improve error message */
8383 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8384 errorf(&expression->base.source_position,
8385 "operands of shift operation must have integer types");
8390 type_left = promote_integer(type_left);
8392 if (is_constant_expression(right)) {
8393 long count = fold_constant_to_int(right);
8395 warningf(&right->base.source_position,
8396 "shift count must be non-negative");
8397 } else if ((unsigned long)count >=
8398 get_atomic_type_size(type_left->atomic.akind) * 8) {
8399 warningf(&right->base.source_position,
8400 "shift count must be less than type width");
8404 type_right = promote_integer(type_right);
8405 expression->right = create_implicit_cast(right, type_right);
8410 static void semantic_shift_op(binary_expression_t *expression)
8412 expression_t *const left = expression->left;
8413 expression_t *const right = expression->right;
8415 if (!semantic_shift(expression))
8418 if (warning.parentheses) {
8419 warn_addsub_in_shift(left);
8420 warn_addsub_in_shift(right);
8423 type_t *const orig_type_left = left->base.type;
8424 type_t * type_left = skip_typeref(orig_type_left);
8426 type_left = promote_integer(type_left);
8427 expression->left = create_implicit_cast(left, type_left);
8428 expression->base.type = type_left;
8431 static void semantic_add(binary_expression_t *expression)
8433 expression_t *const left = expression->left;
8434 expression_t *const right = expression->right;
8435 type_t *const orig_type_left = left->base.type;
8436 type_t *const orig_type_right = right->base.type;
8437 type_t *const type_left = skip_typeref(orig_type_left);
8438 type_t *const type_right = skip_typeref(orig_type_right);
8441 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8442 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8443 expression->left = create_implicit_cast(left, arithmetic_type);
8444 expression->right = create_implicit_cast(right, arithmetic_type);
8445 expression->base.type = arithmetic_type;
8446 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8447 check_pointer_arithmetic(&expression->base.source_position,
8448 type_left, orig_type_left);
8449 expression->base.type = type_left;
8450 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8451 check_pointer_arithmetic(&expression->base.source_position,
8452 type_right, orig_type_right);
8453 expression->base.type = type_right;
8454 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8455 errorf(&expression->base.source_position,
8456 "invalid operands to binary + ('%T', '%T')",
8457 orig_type_left, orig_type_right);
8461 static void semantic_sub(binary_expression_t *expression)
8463 expression_t *const left = expression->left;
8464 expression_t *const right = expression->right;
8465 type_t *const orig_type_left = left->base.type;
8466 type_t *const orig_type_right = right->base.type;
8467 type_t *const type_left = skip_typeref(orig_type_left);
8468 type_t *const type_right = skip_typeref(orig_type_right);
8469 source_position_t const *const pos = &expression->base.source_position;
8472 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8473 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8474 expression->left = create_implicit_cast(left, arithmetic_type);
8475 expression->right = create_implicit_cast(right, arithmetic_type);
8476 expression->base.type = arithmetic_type;
8477 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8478 check_pointer_arithmetic(&expression->base.source_position,
8479 type_left, orig_type_left);
8480 expression->base.type = type_left;
8481 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8482 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8483 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8484 if (!types_compatible(unqual_left, unqual_right)) {
8486 "subtracting pointers to incompatible types '%T' and '%T'",
8487 orig_type_left, orig_type_right);
8488 } else if (!is_type_object(unqual_left)) {
8489 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8490 errorf(pos, "subtracting pointers to non-object types '%T'",
8492 } else if (warning.other) {
8493 warningf(pos, "subtracting pointers to void");
8496 expression->base.type = type_ptrdiff_t;
8497 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8498 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8499 orig_type_left, orig_type_right);
8503 static void warn_string_literal_address(expression_t const* expr)
8505 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8506 expr = expr->unary.value;
8507 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8509 expr = expr->unary.value;
8512 if (expr->kind == EXPR_STRING_LITERAL ||
8513 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8514 warningf(&expr->base.source_position,
8515 "comparison with string literal results in unspecified behaviour");
8519 static void warn_comparison_in_comparison(const expression_t *const expr)
8521 if (expr->base.parenthesized)
8523 switch (expr->base.kind) {
8524 case EXPR_BINARY_LESS:
8525 case EXPR_BINARY_GREATER:
8526 case EXPR_BINARY_LESSEQUAL:
8527 case EXPR_BINARY_GREATEREQUAL:
8528 case EXPR_BINARY_NOTEQUAL:
8529 case EXPR_BINARY_EQUAL:
8530 warningf(&expr->base.source_position,
8531 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8538 static bool maybe_negative(expression_t const *const expr)
8541 !is_constant_expression(expr) ||
8542 fold_constant_to_int(expr) < 0;
8546 * Check the semantics of comparison expressions.
8548 * @param expression The expression to check.
8550 static void semantic_comparison(binary_expression_t *expression)
8552 expression_t *left = expression->left;
8553 expression_t *right = expression->right;
8555 if (warning.address) {
8556 warn_string_literal_address(left);
8557 warn_string_literal_address(right);
8559 expression_t const* const func_left = get_reference_address(left);
8560 if (func_left != NULL && is_null_pointer_constant(right)) {
8561 warningf(&expression->base.source_position,
8562 "the address of '%Y' will never be NULL",
8563 func_left->reference.entity->base.symbol);
8566 expression_t const* const func_right = get_reference_address(right);
8567 if (func_right != NULL && is_null_pointer_constant(right)) {
8568 warningf(&expression->base.source_position,
8569 "the address of '%Y' will never be NULL",
8570 func_right->reference.entity->base.symbol);
8574 if (warning.parentheses) {
8575 warn_comparison_in_comparison(left);
8576 warn_comparison_in_comparison(right);
8579 type_t *orig_type_left = left->base.type;
8580 type_t *orig_type_right = right->base.type;
8581 type_t *type_left = skip_typeref(orig_type_left);
8582 type_t *type_right = skip_typeref(orig_type_right);
8584 /* TODO non-arithmetic types */
8585 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8586 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8588 /* test for signed vs unsigned compares */
8589 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8590 bool const signed_left = is_type_signed(type_left);
8591 bool const signed_right = is_type_signed(type_right);
8592 if (signed_left != signed_right) {
8593 /* FIXME long long needs better const folding magic */
8594 /* TODO check whether constant value can be represented by other type */
8595 if ((signed_left && maybe_negative(left)) ||
8596 (signed_right && maybe_negative(right))) {
8597 warningf(&expression->base.source_position,
8598 "comparison between signed and unsigned");
8603 expression->left = create_implicit_cast(left, arithmetic_type);
8604 expression->right = create_implicit_cast(right, arithmetic_type);
8605 expression->base.type = arithmetic_type;
8606 if (warning.float_equal &&
8607 (expression->base.kind == EXPR_BINARY_EQUAL ||
8608 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8609 is_type_float(arithmetic_type)) {
8610 warningf(&expression->base.source_position,
8611 "comparing floating point with == or != is unsafe");
8613 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8614 /* TODO check compatibility */
8615 } else if (is_type_pointer(type_left)) {
8616 expression->right = create_implicit_cast(right, type_left);
8617 } else if (is_type_pointer(type_right)) {
8618 expression->left = create_implicit_cast(left, type_right);
8619 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8620 type_error_incompatible("invalid operands in comparison",
8621 &expression->base.source_position,
8622 type_left, type_right);
8624 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8628 * Checks if a compound type has constant fields.
8630 static bool has_const_fields(const compound_type_t *type)
8632 compound_t *compound = type->compound;
8633 entity_t *entry = compound->members.entities;
8635 for (; entry != NULL; entry = entry->base.next) {
8636 if (!is_declaration(entry))
8639 const type_t *decl_type = skip_typeref(entry->declaration.type);
8640 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8647 static bool is_valid_assignment_lhs(expression_t const* const left)
8649 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8650 type_t *const type_left = skip_typeref(orig_type_left);
8652 if (!is_lvalue(left)) {
8653 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8658 if (left->kind == EXPR_REFERENCE
8659 && left->reference.entity->kind == ENTITY_FUNCTION) {
8660 errorf(HERE, "cannot assign to function '%E'", left);
8664 if (is_type_array(type_left)) {
8665 errorf(HERE, "cannot assign to array '%E'", left);
8668 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8669 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8673 if (is_type_incomplete(type_left)) {
8674 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8675 left, orig_type_left);
8678 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8679 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8680 left, orig_type_left);
8687 static void semantic_arithmetic_assign(binary_expression_t *expression)
8689 expression_t *left = expression->left;
8690 expression_t *right = expression->right;
8691 type_t *orig_type_left = left->base.type;
8692 type_t *orig_type_right = right->base.type;
8694 if (!is_valid_assignment_lhs(left))
8697 type_t *type_left = skip_typeref(orig_type_left);
8698 type_t *type_right = skip_typeref(orig_type_right);
8700 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8701 /* TODO: improve error message */
8702 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8703 errorf(&expression->base.source_position,
8704 "operation needs arithmetic types");
8709 /* combined instructions are tricky. We can't create an implicit cast on
8710 * the left side, because we need the uncasted form for the store.
8711 * The ast2firm pass has to know that left_type must be right_type
8712 * for the arithmetic operation and create a cast by itself */
8713 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8714 expression->right = create_implicit_cast(right, arithmetic_type);
8715 expression->base.type = type_left;
8718 static void semantic_divmod_assign(binary_expression_t *expression)
8720 semantic_arithmetic_assign(expression);
8721 warn_div_by_zero(expression);
8724 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8726 expression_t *const left = expression->left;
8727 expression_t *const right = expression->right;
8728 type_t *const orig_type_left = left->base.type;
8729 type_t *const orig_type_right = right->base.type;
8730 type_t *const type_left = skip_typeref(orig_type_left);
8731 type_t *const type_right = skip_typeref(orig_type_right);
8733 if (!is_valid_assignment_lhs(left))
8736 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8737 /* combined instructions are tricky. We can't create an implicit cast on
8738 * the left side, because we need the uncasted form for the store.
8739 * The ast2firm pass has to know that left_type must be right_type
8740 * for the arithmetic operation and create a cast by itself */
8741 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8742 expression->right = create_implicit_cast(right, arithmetic_type);
8743 expression->base.type = type_left;
8744 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8745 check_pointer_arithmetic(&expression->base.source_position,
8746 type_left, orig_type_left);
8747 expression->base.type = type_left;
8748 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8749 errorf(&expression->base.source_position,
8750 "incompatible types '%T' and '%T' in assignment",
8751 orig_type_left, orig_type_right);
8755 static void semantic_integer_assign(binary_expression_t *expression)
8757 expression_t *left = expression->left;
8758 expression_t *right = expression->right;
8759 type_t *orig_type_left = left->base.type;
8760 type_t *orig_type_right = right->base.type;
8762 if (!is_valid_assignment_lhs(left))
8765 type_t *type_left = skip_typeref(orig_type_left);
8766 type_t *type_right = skip_typeref(orig_type_right);
8768 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8769 /* TODO: improve error message */
8770 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8771 errorf(&expression->base.source_position,
8772 "operation needs integer types");
8777 /* combined instructions are tricky. We can't create an implicit cast on
8778 * the left side, because we need the uncasted form for the store.
8779 * The ast2firm pass has to know that left_type must be right_type
8780 * for the arithmetic operation and create a cast by itself */
8781 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8782 expression->right = create_implicit_cast(right, arithmetic_type);
8783 expression->base.type = type_left;
8786 static void semantic_shift_assign(binary_expression_t *expression)
8788 expression_t *left = expression->left;
8790 if (!is_valid_assignment_lhs(left))
8793 if (!semantic_shift(expression))
8796 expression->base.type = skip_typeref(left->base.type);
8799 static void warn_logical_and_within_or(const expression_t *const expr)
8801 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8803 if (expr->base.parenthesized)
8805 warningf(&expr->base.source_position,
8806 "suggest parentheses around && within ||");
8810 * Check the semantic restrictions of a logical expression.
8812 static void semantic_logical_op(binary_expression_t *expression)
8814 /* §6.5.13:2 Each of the operands shall have scalar type.
8815 * §6.5.14:2 Each of the operands shall have scalar type. */
8816 semantic_condition(expression->left, "left operand of logical operator");
8817 semantic_condition(expression->right, "right operand of logical operator");
8818 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8819 warning.parentheses) {
8820 warn_logical_and_within_or(expression->left);
8821 warn_logical_and_within_or(expression->right);
8823 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8827 * Check the semantic restrictions of a binary assign expression.
8829 static void semantic_binexpr_assign(binary_expression_t *expression)
8831 expression_t *left = expression->left;
8832 type_t *orig_type_left = left->base.type;
8834 if (!is_valid_assignment_lhs(left))
8837 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8838 report_assign_error(error, orig_type_left, expression->right,
8839 "assignment", &left->base.source_position);
8840 expression->right = create_implicit_cast(expression->right, orig_type_left);
8841 expression->base.type = orig_type_left;
8845 * Determine if the outermost operation (or parts thereof) of the given
8846 * expression has no effect in order to generate a warning about this fact.
8847 * Therefore in some cases this only examines some of the operands of the
8848 * expression (see comments in the function and examples below).
8850 * f() + 23; // warning, because + has no effect
8851 * x || f(); // no warning, because x controls execution of f()
8852 * x ? y : f(); // warning, because y has no effect
8853 * (void)x; // no warning to be able to suppress the warning
8854 * This function can NOT be used for an "expression has definitely no effect"-
8856 static bool expression_has_effect(const expression_t *const expr)
8858 switch (expr->kind) {
8859 case EXPR_UNKNOWN: break;
8860 case EXPR_INVALID: return true; /* do NOT warn */
8861 case EXPR_REFERENCE: return false;
8862 case EXPR_REFERENCE_ENUM_VALUE: return false;
8863 /* suppress the warning for microsoft __noop operations */
8864 case EXPR_CONST: return expr->conste.is_ms_noop;
8865 case EXPR_CHARACTER_CONSTANT: return false;
8866 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8867 case EXPR_STRING_LITERAL: return false;
8868 case EXPR_WIDE_STRING_LITERAL: return false;
8869 case EXPR_LABEL_ADDRESS: return false;
8872 const call_expression_t *const call = &expr->call;
8873 if (call->function->kind != EXPR_REFERENCE)
8876 switch (call->function->reference.entity->function.btk) {
8877 /* FIXME: which builtins have no effect? */
8878 default: return true;
8882 /* Generate the warning if either the left or right hand side of a
8883 * conditional expression has no effect */
8884 case EXPR_CONDITIONAL: {
8885 conditional_expression_t const *const cond = &expr->conditional;
8886 expression_t const *const t = cond->true_expression;
8888 (t == NULL || expression_has_effect(t)) &&
8889 expression_has_effect(cond->false_expression);
8892 case EXPR_SELECT: return false;
8893 case EXPR_ARRAY_ACCESS: return false;
8894 case EXPR_SIZEOF: return false;
8895 case EXPR_CLASSIFY_TYPE: return false;
8896 case EXPR_ALIGNOF: return false;
8898 case EXPR_FUNCNAME: return false;
8899 case EXPR_BUILTIN_CONSTANT_P: return false;
8900 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8901 case EXPR_OFFSETOF: return false;
8902 case EXPR_VA_START: return true;
8903 case EXPR_VA_ARG: return true;
8904 case EXPR_VA_COPY: return true;
8905 case EXPR_STATEMENT: return true; // TODO
8906 case EXPR_COMPOUND_LITERAL: return false;
8908 case EXPR_UNARY_NEGATE: return false;
8909 case EXPR_UNARY_PLUS: return false;
8910 case EXPR_UNARY_BITWISE_NEGATE: return false;
8911 case EXPR_UNARY_NOT: return false;
8912 case EXPR_UNARY_DEREFERENCE: return false;
8913 case EXPR_UNARY_TAKE_ADDRESS: return false;
8914 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8915 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8916 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8917 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8919 /* Treat void casts as if they have an effect in order to being able to
8920 * suppress the warning */
8921 case EXPR_UNARY_CAST: {
8922 type_t *const type = skip_typeref(expr->base.type);
8923 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8926 case EXPR_UNARY_CAST_IMPLICIT: return true;
8927 case EXPR_UNARY_ASSUME: return true;
8928 case EXPR_UNARY_DELETE: return true;
8929 case EXPR_UNARY_DELETE_ARRAY: return true;
8930 case EXPR_UNARY_THROW: return true;
8932 case EXPR_BINARY_ADD: return false;
8933 case EXPR_BINARY_SUB: return false;
8934 case EXPR_BINARY_MUL: return false;
8935 case EXPR_BINARY_DIV: return false;
8936 case EXPR_BINARY_MOD: return false;
8937 case EXPR_BINARY_EQUAL: return false;
8938 case EXPR_BINARY_NOTEQUAL: return false;
8939 case EXPR_BINARY_LESS: return false;
8940 case EXPR_BINARY_LESSEQUAL: return false;
8941 case EXPR_BINARY_GREATER: return false;
8942 case EXPR_BINARY_GREATEREQUAL: return false;
8943 case EXPR_BINARY_BITWISE_AND: return false;
8944 case EXPR_BINARY_BITWISE_OR: return false;
8945 case EXPR_BINARY_BITWISE_XOR: return false;
8946 case EXPR_BINARY_SHIFTLEFT: return false;
8947 case EXPR_BINARY_SHIFTRIGHT: return false;
8948 case EXPR_BINARY_ASSIGN: return true;
8949 case EXPR_BINARY_MUL_ASSIGN: return true;
8950 case EXPR_BINARY_DIV_ASSIGN: return true;
8951 case EXPR_BINARY_MOD_ASSIGN: return true;
8952 case EXPR_BINARY_ADD_ASSIGN: return true;
8953 case EXPR_BINARY_SUB_ASSIGN: return true;
8954 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8955 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8956 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8957 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8958 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8960 /* Only examine the right hand side of && and ||, because the left hand
8961 * side already has the effect of controlling the execution of the right
8963 case EXPR_BINARY_LOGICAL_AND:
8964 case EXPR_BINARY_LOGICAL_OR:
8965 /* Only examine the right hand side of a comma expression, because the left
8966 * hand side has a separate warning */
8967 case EXPR_BINARY_COMMA:
8968 return expression_has_effect(expr->binary.right);
8970 case EXPR_BINARY_ISGREATER: return false;
8971 case EXPR_BINARY_ISGREATEREQUAL: return false;
8972 case EXPR_BINARY_ISLESS: return false;
8973 case EXPR_BINARY_ISLESSEQUAL: return false;
8974 case EXPR_BINARY_ISLESSGREATER: return false;
8975 case EXPR_BINARY_ISUNORDERED: return false;
8978 internal_errorf(HERE, "unexpected expression");
8981 static void semantic_comma(binary_expression_t *expression)
8983 if (warning.unused_value) {
8984 const expression_t *const left = expression->left;
8985 if (!expression_has_effect(left)) {
8986 warningf(&left->base.source_position,
8987 "left-hand operand of comma expression has no effect");
8990 expression->base.type = expression->right->base.type;
8994 * @param prec_r precedence of the right operand
8996 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8997 static expression_t *parse_##binexpression_type(expression_t *left) \
8999 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9000 binexpr->binary.left = left; \
9003 expression_t *right = parse_sub_expression(prec_r); \
9005 binexpr->binary.right = right; \
9006 sfunc(&binexpr->binary); \
9011 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9012 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9013 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9014 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9015 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9016 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9017 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9018 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9019 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9020 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9021 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9022 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9023 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9024 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9025 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9026 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9027 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9028 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9029 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9030 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9031 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9032 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9033 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9034 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9035 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9036 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9037 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9038 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9039 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9040 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9043 static expression_t *parse_sub_expression(precedence_t precedence)
9045 if (token.type < 0) {
9046 return expected_expression_error();
9049 expression_parser_function_t *parser
9050 = &expression_parsers[token.type];
9051 source_position_t source_position = token.source_position;
9054 if (parser->parser != NULL) {
9055 left = parser->parser();
9057 left = parse_primary_expression();
9059 assert(left != NULL);
9060 left->base.source_position = source_position;
9063 if (token.type < 0) {
9064 return expected_expression_error();
9067 parser = &expression_parsers[token.type];
9068 if (parser->infix_parser == NULL)
9070 if (parser->infix_precedence < precedence)
9073 left = parser->infix_parser(left);
9075 assert(left != NULL);
9076 assert(left->kind != EXPR_UNKNOWN);
9077 left->base.source_position = source_position;
9084 * Parse an expression.
9086 static expression_t *parse_expression(void)
9088 return parse_sub_expression(PREC_EXPRESSION);
9092 * Register a parser for a prefix-like operator.
9094 * @param parser the parser function
9095 * @param token_type the token type of the prefix token
9097 static void register_expression_parser(parse_expression_function parser,
9100 expression_parser_function_t *entry = &expression_parsers[token_type];
9102 if (entry->parser != NULL) {
9103 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9104 panic("trying to register multiple expression parsers for a token");
9106 entry->parser = parser;
9110 * Register a parser for an infix operator with given precedence.
9112 * @param parser the parser function
9113 * @param token_type the token type of the infix operator
9114 * @param precedence the precedence of the operator
9116 static void register_infix_parser(parse_expression_infix_function parser,
9117 int token_type, precedence_t precedence)
9119 expression_parser_function_t *entry = &expression_parsers[token_type];
9121 if (entry->infix_parser != NULL) {
9122 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9123 panic("trying to register multiple infix expression parsers for a "
9126 entry->infix_parser = parser;
9127 entry->infix_precedence = precedence;
9131 * Initialize the expression parsers.
9133 static void init_expression_parsers(void)
9135 memset(&expression_parsers, 0, sizeof(expression_parsers));
9137 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9138 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9139 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9140 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9141 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9142 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9143 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9144 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9145 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9146 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9147 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9148 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9149 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9150 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9151 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9152 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9153 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9154 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9155 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9156 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9157 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9158 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9159 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9160 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9161 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9162 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9163 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9164 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9165 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9166 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9167 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9168 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9169 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9170 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9171 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9172 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9173 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9175 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9176 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9177 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9178 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9179 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9180 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9181 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9182 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9183 register_expression_parser(parse_sizeof, T_sizeof);
9184 register_expression_parser(parse_alignof, T___alignof__);
9185 register_expression_parser(parse_extension, T___extension__);
9186 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9187 register_expression_parser(parse_delete, T_delete);
9188 register_expression_parser(parse_throw, T_throw);
9192 * Parse a asm statement arguments specification.
9194 static asm_argument_t *parse_asm_arguments(bool is_out)
9196 asm_argument_t *result = NULL;
9197 asm_argument_t **anchor = &result;
9199 while (token.type == T_STRING_LITERAL || token.type == '[') {
9200 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9201 memset(argument, 0, sizeof(argument[0]));
9204 if (token.type != T_IDENTIFIER) {
9205 parse_error_expected("while parsing asm argument",
9206 T_IDENTIFIER, NULL);
9209 argument->symbol = token.v.symbol;
9211 expect(']', end_error);
9214 argument->constraints = parse_string_literals();
9215 expect('(', end_error);
9216 add_anchor_token(')');
9217 expression_t *expression = parse_expression();
9218 rem_anchor_token(')');
9220 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9221 * change size or type representation (e.g. int -> long is ok, but
9222 * int -> float is not) */
9223 if (expression->kind == EXPR_UNARY_CAST) {
9224 type_t *const type = expression->base.type;
9225 type_kind_t const kind = type->kind;
9226 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9229 if (kind == TYPE_ATOMIC) {
9230 atomic_type_kind_t const akind = type->atomic.akind;
9231 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9232 size = get_atomic_type_size(akind);
9234 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9235 size = get_atomic_type_size(get_intptr_kind());
9239 expression_t *const value = expression->unary.value;
9240 type_t *const value_type = value->base.type;
9241 type_kind_t const value_kind = value_type->kind;
9243 unsigned value_flags;
9244 unsigned value_size;
9245 if (value_kind == TYPE_ATOMIC) {
9246 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9247 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9248 value_size = get_atomic_type_size(value_akind);
9249 } else if (value_kind == TYPE_POINTER) {
9250 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9251 value_size = get_atomic_type_size(get_intptr_kind());
9256 if (value_flags != flags || value_size != size)
9260 } while (expression->kind == EXPR_UNARY_CAST);
9264 if (!is_lvalue(expression)) {
9265 errorf(&expression->base.source_position,
9266 "asm output argument is not an lvalue");
9269 if (argument->constraints.begin[0] == '+')
9270 mark_vars_read(expression, NULL);
9272 mark_vars_read(expression, NULL);
9274 argument->expression = expression;
9275 expect(')', end_error);
9277 set_address_taken(expression, true);
9280 anchor = &argument->next;
9292 * Parse a asm statement clobber specification.
9294 static asm_clobber_t *parse_asm_clobbers(void)
9296 asm_clobber_t *result = NULL;
9297 asm_clobber_t *last = NULL;
9299 while (token.type == T_STRING_LITERAL) {
9300 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9301 clobber->clobber = parse_string_literals();
9304 last->next = clobber;
9318 * Parse an asm statement.
9320 static statement_t *parse_asm_statement(void)
9322 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9323 asm_statement_t *asm_statement = &statement->asms;
9327 if (next_if(T_volatile))
9328 asm_statement->is_volatile = true;
9330 expect('(', end_error);
9331 add_anchor_token(')');
9332 add_anchor_token(':');
9333 asm_statement->asm_text = parse_string_literals();
9335 if (!next_if(':')) {
9336 rem_anchor_token(':');
9340 asm_statement->outputs = parse_asm_arguments(true);
9341 if (!next_if(':')) {
9342 rem_anchor_token(':');
9346 asm_statement->inputs = parse_asm_arguments(false);
9347 if (!next_if(':')) {
9348 rem_anchor_token(':');
9351 rem_anchor_token(':');
9353 asm_statement->clobbers = parse_asm_clobbers();
9356 rem_anchor_token(')');
9357 expect(')', end_error);
9358 expect(';', end_error);
9360 if (asm_statement->outputs == NULL) {
9361 /* GCC: An 'asm' instruction without any output operands will be treated
9362 * identically to a volatile 'asm' instruction. */
9363 asm_statement->is_volatile = true;
9368 return create_invalid_statement();
9372 * Parse a case statement.
9374 static statement_t *parse_case_statement(void)
9376 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9377 source_position_t *const pos = &statement->base.source_position;
9381 expression_t *const expression = parse_expression();
9382 statement->case_label.expression = expression;
9383 if (!is_constant_expression(expression)) {
9384 /* This check does not prevent the error message in all cases of an
9385 * prior error while parsing the expression. At least it catches the
9386 * common case of a mistyped enum entry. */
9387 if (is_type_valid(skip_typeref(expression->base.type))) {
9388 errorf(pos, "case label does not reduce to an integer constant");
9390 statement->case_label.is_bad = true;
9392 long const val = fold_constant_to_int(expression);
9393 statement->case_label.first_case = val;
9394 statement->case_label.last_case = val;
9398 if (next_if(T_DOTDOTDOT)) {
9399 expression_t *const end_range = parse_expression();
9400 statement->case_label.end_range = end_range;
9401 if (!is_constant_expression(end_range)) {
9402 /* This check does not prevent the error message in all cases of an
9403 * prior error while parsing the expression. At least it catches the
9404 * common case of a mistyped enum entry. */
9405 if (is_type_valid(skip_typeref(end_range->base.type))) {
9406 errorf(pos, "case range does not reduce to an integer constant");
9408 statement->case_label.is_bad = true;
9410 long const val = fold_constant_to_int(end_range);
9411 statement->case_label.last_case = val;
9413 if (warning.other && val < statement->case_label.first_case) {
9414 statement->case_label.is_empty_range = true;
9415 warningf(pos, "empty range specified");
9421 PUSH_PARENT(statement);
9423 expect(':', end_error);
9426 if (current_switch != NULL) {
9427 if (! statement->case_label.is_bad) {
9428 /* Check for duplicate case values */
9429 case_label_statement_t *c = &statement->case_label;
9430 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9431 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9434 if (c->last_case < l->first_case || c->first_case > l->last_case)
9437 errorf(pos, "duplicate case value (previously used %P)",
9438 &l->base.source_position);
9442 /* link all cases into the switch statement */
9443 if (current_switch->last_case == NULL) {
9444 current_switch->first_case = &statement->case_label;
9446 current_switch->last_case->next = &statement->case_label;
9448 current_switch->last_case = &statement->case_label;
9450 errorf(pos, "case label not within a switch statement");
9453 statement_t *const inner_stmt = parse_statement();
9454 statement->case_label.statement = inner_stmt;
9455 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9456 errorf(&inner_stmt->base.source_position, "declaration after case label");
9464 * Parse a default statement.
9466 static statement_t *parse_default_statement(void)
9468 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9472 PUSH_PARENT(statement);
9474 expect(':', end_error);
9475 if (current_switch != NULL) {
9476 const case_label_statement_t *def_label = current_switch->default_label;
9477 if (def_label != NULL) {
9478 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9479 &def_label->base.source_position);
9481 current_switch->default_label = &statement->case_label;
9483 /* link all cases into the switch statement */
9484 if (current_switch->last_case == NULL) {
9485 current_switch->first_case = &statement->case_label;
9487 current_switch->last_case->next = &statement->case_label;
9489 current_switch->last_case = &statement->case_label;
9492 errorf(&statement->base.source_position,
9493 "'default' label not within a switch statement");
9496 statement_t *const inner_stmt = parse_statement();
9497 statement->case_label.statement = inner_stmt;
9498 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9499 errorf(&inner_stmt->base.source_position, "declaration after default label");
9506 return create_invalid_statement();
9510 * Parse a label statement.
9512 static statement_t *parse_label_statement(void)
9514 assert(token.type == T_IDENTIFIER);
9515 symbol_t *symbol = token.v.symbol;
9516 label_t *label = get_label(symbol);
9518 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9519 statement->label.label = label;
9523 PUSH_PARENT(statement);
9525 /* if statement is already set then the label is defined twice,
9526 * otherwise it was just mentioned in a goto/local label declaration so far
9528 if (label->statement != NULL) {
9529 errorf(HERE, "duplicate label '%Y' (declared %P)",
9530 symbol, &label->base.source_position);
9532 label->base.source_position = token.source_position;
9533 label->statement = statement;
9538 if (token.type == '}') {
9539 /* TODO only warn? */
9540 if (warning.other && false) {
9541 warningf(HERE, "label at end of compound statement");
9542 statement->label.statement = create_empty_statement();
9544 errorf(HERE, "label at end of compound statement");
9545 statement->label.statement = create_invalid_statement();
9547 } else if (token.type == ';') {
9548 /* Eat an empty statement here, to avoid the warning about an empty
9549 * statement after a label. label:; is commonly used to have a label
9550 * before a closing brace. */
9551 statement->label.statement = create_empty_statement();
9554 statement_t *const inner_stmt = parse_statement();
9555 statement->label.statement = inner_stmt;
9556 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9557 errorf(&inner_stmt->base.source_position, "declaration after label");
9561 /* remember the labels in a list for later checking */
9562 *label_anchor = &statement->label;
9563 label_anchor = &statement->label.next;
9570 * Parse an if statement.
9572 static statement_t *parse_if(void)
9574 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9578 PUSH_PARENT(statement);
9580 add_anchor_token('{');
9582 expect('(', end_error);
9583 add_anchor_token(')');
9584 expression_t *const expr = parse_expression();
9585 statement->ifs.condition = expr;
9586 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9588 semantic_condition(expr, "condition of 'if'-statment");
9589 mark_vars_read(expr, NULL);
9590 rem_anchor_token(')');
9591 expect(')', end_error);
9594 rem_anchor_token('{');
9596 add_anchor_token(T_else);
9597 statement_t *const true_stmt = parse_statement();
9598 statement->ifs.true_statement = true_stmt;
9599 rem_anchor_token(T_else);
9601 if (next_if(T_else)) {
9602 statement->ifs.false_statement = parse_statement();
9603 } else if (warning.parentheses &&
9604 true_stmt->kind == STATEMENT_IF &&
9605 true_stmt->ifs.false_statement != NULL) {
9606 warningf(&true_stmt->base.source_position,
9607 "suggest explicit braces to avoid ambiguous 'else'");
9615 * Check that all enums are handled in a switch.
9617 * @param statement the switch statement to check
9619 static void check_enum_cases(const switch_statement_t *statement)
9621 const type_t *type = skip_typeref(statement->expression->base.type);
9622 if (! is_type_enum(type))
9624 const enum_type_t *enumt = &type->enumt;
9626 /* if we have a default, no warnings */
9627 if (statement->default_label != NULL)
9630 /* FIXME: calculation of value should be done while parsing */
9631 /* TODO: quadratic algorithm here. Change to an n log n one */
9632 long last_value = -1;
9633 const entity_t *entry = enumt->enume->base.next;
9634 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9635 entry = entry->base.next) {
9636 const expression_t *expression = entry->enum_value.value;
9637 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9639 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9640 if (l->expression == NULL)
9642 if (l->first_case <= value && value <= l->last_case) {
9648 warningf(&statement->base.source_position,
9649 "enumeration value '%Y' not handled in switch",
9650 entry->base.symbol);
9657 * Parse a switch statement.
9659 static statement_t *parse_switch(void)
9661 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9665 PUSH_PARENT(statement);
9667 expect('(', end_error);
9668 add_anchor_token(')');
9669 expression_t *const expr = parse_expression();
9670 mark_vars_read(expr, NULL);
9671 type_t * type = skip_typeref(expr->base.type);
9672 if (is_type_integer(type)) {
9673 type = promote_integer(type);
9674 if (warning.traditional) {
9675 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9676 warningf(&expr->base.source_position,
9677 "'%T' switch expression not converted to '%T' in ISO C",
9681 } else if (is_type_valid(type)) {
9682 errorf(&expr->base.source_position,
9683 "switch quantity is not an integer, but '%T'", type);
9684 type = type_error_type;
9686 statement->switchs.expression = create_implicit_cast(expr, type);
9687 expect(')', end_error);
9688 rem_anchor_token(')');
9690 switch_statement_t *rem = current_switch;
9691 current_switch = &statement->switchs;
9692 statement->switchs.body = parse_statement();
9693 current_switch = rem;
9695 if (warning.switch_default &&
9696 statement->switchs.default_label == NULL) {
9697 warningf(&statement->base.source_position, "switch has no default case");
9699 if (warning.switch_enum)
9700 check_enum_cases(&statement->switchs);
9706 return create_invalid_statement();
9709 static statement_t *parse_loop_body(statement_t *const loop)
9711 statement_t *const rem = current_loop;
9712 current_loop = loop;
9714 statement_t *const body = parse_statement();
9721 * Parse a while statement.
9723 static statement_t *parse_while(void)
9725 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9729 PUSH_PARENT(statement);
9731 expect('(', end_error);
9732 add_anchor_token(')');
9733 expression_t *const cond = parse_expression();
9734 statement->whiles.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 'while'-statement");
9738 mark_vars_read(cond, NULL);
9739 rem_anchor_token(')');
9740 expect(')', end_error);
9742 statement->whiles.body = parse_loop_body(statement);
9748 return create_invalid_statement();
9752 * Parse a do statement.
9754 static statement_t *parse_do(void)
9756 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9760 PUSH_PARENT(statement);
9762 add_anchor_token(T_while);
9763 statement->do_while.body = parse_loop_body(statement);
9764 rem_anchor_token(T_while);
9766 expect(T_while, end_error);
9767 expect('(', end_error);
9768 add_anchor_token(')');
9769 expression_t *const cond = parse_expression();
9770 statement->do_while.condition = cond;
9771 /* §6.8.5:2 The controlling expression of an iteration statement shall
9772 * have scalar type. */
9773 semantic_condition(cond, "condition of 'do-while'-statement");
9774 mark_vars_read(cond, NULL);
9775 rem_anchor_token(')');
9776 expect(')', end_error);
9777 expect(';', end_error);
9783 return create_invalid_statement();
9787 * Parse a for statement.
9789 static statement_t *parse_for(void)
9791 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9795 expect('(', end_error1);
9796 add_anchor_token(')');
9798 PUSH_PARENT(statement);
9800 size_t const top = environment_top();
9801 scope_t *old_scope = scope_push(&statement->fors.scope);
9803 bool old_gcc_extension = in_gcc_extension;
9804 while (next_if(T___extension__)) {
9805 in_gcc_extension = true;
9809 } else if (is_declaration_specifier(&token, false)) {
9810 parse_declaration(record_entity, DECL_FLAGS_NONE);
9812 add_anchor_token(';');
9813 expression_t *const init = parse_expression();
9814 statement->fors.initialisation = init;
9815 mark_vars_read(init, ENT_ANY);
9816 if (warning.unused_value && !expression_has_effect(init)) {
9817 warningf(&init->base.source_position,
9818 "initialisation of 'for'-statement has no effect");
9820 rem_anchor_token(';');
9821 expect(';', end_error2);
9823 in_gcc_extension = old_gcc_extension;
9825 if (token.type != ';') {
9826 add_anchor_token(';');
9827 expression_t *const cond = parse_expression();
9828 statement->fors.condition = cond;
9829 /* §6.8.5:2 The controlling expression of an iteration statement
9830 * shall have scalar type. */
9831 semantic_condition(cond, "condition of 'for'-statement");
9832 mark_vars_read(cond, NULL);
9833 rem_anchor_token(';');
9835 expect(';', end_error2);
9836 if (token.type != ')') {
9837 expression_t *const step = parse_expression();
9838 statement->fors.step = step;
9839 mark_vars_read(step, ENT_ANY);
9840 if (warning.unused_value && !expression_has_effect(step)) {
9841 warningf(&step->base.source_position,
9842 "step of 'for'-statement has no effect");
9845 expect(')', end_error2);
9846 rem_anchor_token(')');
9847 statement->fors.body = parse_loop_body(statement);
9849 assert(current_scope == &statement->fors.scope);
9850 scope_pop(old_scope);
9851 environment_pop_to(top);
9858 rem_anchor_token(')');
9859 assert(current_scope == &statement->fors.scope);
9860 scope_pop(old_scope);
9861 environment_pop_to(top);
9865 return create_invalid_statement();
9869 * Parse a goto statement.
9871 static statement_t *parse_goto(void)
9873 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9876 if (GNU_MODE && next_if('*')) {
9877 expression_t *expression = parse_expression();
9878 mark_vars_read(expression, NULL);
9880 /* Argh: although documentation says the expression must be of type void*,
9881 * gcc accepts anything that can be casted into void* without error */
9882 type_t *type = expression->base.type;
9884 if (type != type_error_type) {
9885 if (!is_type_pointer(type) && !is_type_integer(type)) {
9886 errorf(&expression->base.source_position,
9887 "cannot convert to a pointer type");
9888 } else if (warning.other && type != type_void_ptr) {
9889 warningf(&expression->base.source_position,
9890 "type of computed goto expression should be 'void*' not '%T'", type);
9892 expression = create_implicit_cast(expression, type_void_ptr);
9895 statement->gotos.expression = expression;
9896 } else if (token.type == T_IDENTIFIER) {
9897 symbol_t *symbol = token.v.symbol;
9899 statement->gotos.label = get_label(symbol);
9902 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9904 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9909 /* remember the goto's in a list for later checking */
9910 *goto_anchor = &statement->gotos;
9911 goto_anchor = &statement->gotos.next;
9913 expect(';', end_error);
9917 return create_invalid_statement();
9921 * Parse a continue statement.
9923 static statement_t *parse_continue(void)
9925 if (current_loop == NULL) {
9926 errorf(HERE, "continue statement not within loop");
9929 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9932 expect(';', end_error);
9939 * Parse a break statement.
9941 static statement_t *parse_break(void)
9943 if (current_switch == NULL && current_loop == NULL) {
9944 errorf(HERE, "break statement not within loop or switch");
9947 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9950 expect(';', end_error);
9957 * Parse a __leave statement.
9959 static statement_t *parse_leave_statement(void)
9961 if (current_try == NULL) {
9962 errorf(HERE, "__leave statement not within __try");
9965 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9968 expect(';', end_error);
9975 * Check if a given entity represents a local variable.
9977 static bool is_local_variable(const entity_t *entity)
9979 if (entity->kind != ENTITY_VARIABLE)
9982 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9983 case STORAGE_CLASS_AUTO:
9984 case STORAGE_CLASS_REGISTER: {
9985 const type_t *type = skip_typeref(entity->declaration.type);
9986 if (is_type_function(type)) {
9998 * Check if a given expression represents a local variable.
10000 static bool expression_is_local_variable(const expression_t *expression)
10002 if (expression->base.kind != EXPR_REFERENCE) {
10005 const entity_t *entity = expression->reference.entity;
10006 return is_local_variable(entity);
10010 * Check if a given expression represents a local variable and
10011 * return its declaration then, else return NULL.
10013 entity_t *expression_is_variable(const expression_t *expression)
10015 if (expression->base.kind != EXPR_REFERENCE) {
10018 entity_t *entity = expression->reference.entity;
10019 if (entity->kind != ENTITY_VARIABLE)
10026 * Parse a return statement.
10028 static statement_t *parse_return(void)
10032 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10034 expression_t *return_value = NULL;
10035 if (token.type != ';') {
10036 return_value = parse_expression();
10037 mark_vars_read(return_value, NULL);
10040 const type_t *const func_type = skip_typeref(current_function->base.type);
10041 assert(is_type_function(func_type));
10042 type_t *const return_type = skip_typeref(func_type->function.return_type);
10044 source_position_t const *const pos = &statement->base.source_position;
10045 if (return_value != NULL) {
10046 type_t *return_value_type = skip_typeref(return_value->base.type);
10048 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10049 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10050 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10051 /* Only warn in C mode, because GCC does the same */
10052 if (c_mode & _CXX || strict_mode) {
10054 "'return' with a value, in function returning 'void'");
10055 } else if (warning.other) {
10057 "'return' with a value, in function returning 'void'");
10059 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10060 /* Only warn in C mode, because GCC does the same */
10063 "'return' with expression in function returning 'void'");
10064 } else if (warning.other) {
10066 "'return' with expression in function returning 'void'");
10070 assign_error_t error = semantic_assign(return_type, return_value);
10071 report_assign_error(error, return_type, return_value, "'return'",
10074 return_value = create_implicit_cast(return_value, return_type);
10075 /* check for returning address of a local var */
10076 if (warning.other && return_value != NULL
10077 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10078 const expression_t *expression = return_value->unary.value;
10079 if (expression_is_local_variable(expression)) {
10080 warningf(pos, "function returns address of local variable");
10083 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10084 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10085 if (c_mode & _CXX || strict_mode) {
10087 "'return' without value, in function returning non-void");
10090 "'return' without value, in function returning non-void");
10093 statement->returns.value = return_value;
10095 expect(';', end_error);
10102 * Parse a declaration statement.
10104 static statement_t *parse_declaration_statement(void)
10106 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10108 entity_t *before = current_scope->last_entity;
10110 parse_external_declaration();
10112 parse_declaration(record_entity, DECL_FLAGS_NONE);
10115 declaration_statement_t *const decl = &statement->declaration;
10116 entity_t *const begin =
10117 before != NULL ? before->base.next : current_scope->entities;
10118 decl->declarations_begin = begin;
10119 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10125 * Parse an expression statement, ie. expr ';'.
10127 static statement_t *parse_expression_statement(void)
10129 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10131 expression_t *const expr = parse_expression();
10132 statement->expression.expression = expr;
10133 mark_vars_read(expr, ENT_ANY);
10135 expect(';', end_error);
10142 * Parse a microsoft __try { } __finally { } or
10143 * __try{ } __except() { }
10145 static statement_t *parse_ms_try_statment(void)
10147 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10150 PUSH_PARENT(statement);
10152 ms_try_statement_t *rem = current_try;
10153 current_try = &statement->ms_try;
10154 statement->ms_try.try_statement = parse_compound_statement(false);
10159 if (next_if(T___except)) {
10160 expect('(', end_error);
10161 add_anchor_token(')');
10162 expression_t *const expr = parse_expression();
10163 mark_vars_read(expr, NULL);
10164 type_t * type = skip_typeref(expr->base.type);
10165 if (is_type_integer(type)) {
10166 type = promote_integer(type);
10167 } else if (is_type_valid(type)) {
10168 errorf(&expr->base.source_position,
10169 "__expect expression is not an integer, but '%T'", type);
10170 type = type_error_type;
10172 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10173 rem_anchor_token(')');
10174 expect(')', end_error);
10175 statement->ms_try.final_statement = parse_compound_statement(false);
10176 } else if (next_if(T__finally)) {
10177 statement->ms_try.final_statement = parse_compound_statement(false);
10179 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10180 return create_invalid_statement();
10184 return create_invalid_statement();
10187 static statement_t *parse_empty_statement(void)
10189 if (warning.empty_statement) {
10190 warningf(HERE, "statement is empty");
10192 statement_t *const statement = create_empty_statement();
10197 static statement_t *parse_local_label_declaration(void)
10199 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10203 entity_t *begin = NULL, *end = NULL;
10206 if (token.type != T_IDENTIFIER) {
10207 parse_error_expected("while parsing local label declaration",
10208 T_IDENTIFIER, NULL);
10211 symbol_t *symbol = token.v.symbol;
10212 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10213 if (entity != NULL && entity->base.parent_scope == current_scope) {
10214 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10215 symbol, &entity->base.source_position);
10217 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10219 entity->base.parent_scope = current_scope;
10220 entity->base.namespc = NAMESPACE_LABEL;
10221 entity->base.source_position = token.source_position;
10222 entity->base.symbol = symbol;
10225 end->base.next = entity;
10230 environment_push(entity);
10233 } while (next_if(','));
10236 statement->declaration.declarations_begin = begin;
10237 statement->declaration.declarations_end = end;
10241 static void parse_namespace_definition(void)
10245 entity_t *entity = NULL;
10246 symbol_t *symbol = NULL;
10248 if (token.type == T_IDENTIFIER) {
10249 symbol = token.v.symbol;
10252 entity = get_entity(symbol, NAMESPACE_NORMAL);
10253 if (entity != NULL &&
10254 entity->kind != ENTITY_NAMESPACE &&
10255 entity->base.parent_scope == current_scope) {
10256 if (!is_error_entity(entity)) {
10257 error_redefined_as_different_kind(&token.source_position,
10258 entity, ENTITY_NAMESPACE);
10264 if (entity == NULL) {
10265 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10266 entity->base.symbol = symbol;
10267 entity->base.source_position = token.source_position;
10268 entity->base.namespc = NAMESPACE_NORMAL;
10269 entity->base.parent_scope = current_scope;
10272 if (token.type == '=') {
10273 /* TODO: parse namespace alias */
10274 panic("namespace alias definition not supported yet");
10277 environment_push(entity);
10278 append_entity(current_scope, entity);
10280 size_t const top = environment_top();
10281 scope_t *old_scope = scope_push(&entity->namespacee.members);
10283 expect('{', end_error);
10285 expect('}', end_error);
10288 assert(current_scope == &entity->namespacee.members);
10289 scope_pop(old_scope);
10290 environment_pop_to(top);
10294 * Parse a statement.
10295 * There's also parse_statement() which additionally checks for
10296 * "statement has no effect" warnings
10298 static statement_t *intern_parse_statement(void)
10300 statement_t *statement = NULL;
10302 /* declaration or statement */
10303 add_anchor_token(';');
10304 switch (token.type) {
10305 case T_IDENTIFIER: {
10306 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10307 if (la1_type == ':') {
10308 statement = parse_label_statement();
10309 } else if (is_typedef_symbol(token.v.symbol)) {
10310 statement = parse_declaration_statement();
10312 /* it's an identifier, the grammar says this must be an
10313 * expression statement. However it is common that users mistype
10314 * declaration types, so we guess a bit here to improve robustness
10315 * for incorrect programs */
10316 switch (la1_type) {
10319 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10320 goto expression_statment;
10325 statement = parse_declaration_statement();
10329 expression_statment:
10330 statement = parse_expression_statement();
10337 case T___extension__:
10338 /* This can be a prefix to a declaration or an expression statement.
10339 * We simply eat it now and parse the rest with tail recursion. */
10340 while (next_if(T___extension__)) {}
10341 bool old_gcc_extension = in_gcc_extension;
10342 in_gcc_extension = true;
10343 statement = intern_parse_statement();
10344 in_gcc_extension = old_gcc_extension;
10348 statement = parse_declaration_statement();
10352 statement = parse_local_label_declaration();
10355 case ';': statement = parse_empty_statement(); break;
10356 case '{': statement = parse_compound_statement(false); break;
10357 case T___leave: statement = parse_leave_statement(); break;
10358 case T___try: statement = parse_ms_try_statment(); break;
10359 case T_asm: statement = parse_asm_statement(); break;
10360 case T_break: statement = parse_break(); break;
10361 case T_case: statement = parse_case_statement(); break;
10362 case T_continue: statement = parse_continue(); break;
10363 case T_default: statement = parse_default_statement(); break;
10364 case T_do: statement = parse_do(); break;
10365 case T_for: statement = parse_for(); break;
10366 case T_goto: statement = parse_goto(); break;
10367 case T_if: statement = parse_if(); break;
10368 case T_return: statement = parse_return(); break;
10369 case T_switch: statement = parse_switch(); break;
10370 case T_while: statement = parse_while(); break;
10373 statement = parse_expression_statement();
10377 errorf(HERE, "unexpected token %K while parsing statement", &token);
10378 statement = create_invalid_statement();
10383 rem_anchor_token(';');
10385 assert(statement != NULL
10386 && statement->base.source_position.input_name != NULL);
10392 * parse a statement and emits "statement has no effect" warning if needed
10393 * (This is really a wrapper around intern_parse_statement with check for 1
10394 * single warning. It is needed, because for statement expressions we have
10395 * to avoid the warning on the last statement)
10397 static statement_t *parse_statement(void)
10399 statement_t *statement = intern_parse_statement();
10401 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10402 expression_t *expression = statement->expression.expression;
10403 if (!expression_has_effect(expression)) {
10404 warningf(&expression->base.source_position,
10405 "statement has no effect");
10413 * Parse a compound statement.
10415 static statement_t *parse_compound_statement(bool inside_expression_statement)
10417 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10419 PUSH_PARENT(statement);
10422 add_anchor_token('}');
10423 /* tokens, which can start a statement */
10424 /* TODO MS, __builtin_FOO */
10425 add_anchor_token('!');
10426 add_anchor_token('&');
10427 add_anchor_token('(');
10428 add_anchor_token('*');
10429 add_anchor_token('+');
10430 add_anchor_token('-');
10431 add_anchor_token('{');
10432 add_anchor_token('~');
10433 add_anchor_token(T_CHARACTER_CONSTANT);
10434 add_anchor_token(T_COLONCOLON);
10435 add_anchor_token(T_FLOATINGPOINT);
10436 add_anchor_token(T_IDENTIFIER);
10437 add_anchor_token(T_INTEGER);
10438 add_anchor_token(T_MINUSMINUS);
10439 add_anchor_token(T_PLUSPLUS);
10440 add_anchor_token(T_STRING_LITERAL);
10441 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10442 add_anchor_token(T_WIDE_STRING_LITERAL);
10443 add_anchor_token(T__Bool);
10444 add_anchor_token(T__Complex);
10445 add_anchor_token(T__Imaginary);
10446 add_anchor_token(T___FUNCTION__);
10447 add_anchor_token(T___PRETTY_FUNCTION__);
10448 add_anchor_token(T___alignof__);
10449 add_anchor_token(T___attribute__);
10450 add_anchor_token(T___builtin_va_start);
10451 add_anchor_token(T___extension__);
10452 add_anchor_token(T___func__);
10453 add_anchor_token(T___imag__);
10454 add_anchor_token(T___label__);
10455 add_anchor_token(T___real__);
10456 add_anchor_token(T___thread);
10457 add_anchor_token(T_asm);
10458 add_anchor_token(T_auto);
10459 add_anchor_token(T_bool);
10460 add_anchor_token(T_break);
10461 add_anchor_token(T_case);
10462 add_anchor_token(T_char);
10463 add_anchor_token(T_class);
10464 add_anchor_token(T_const);
10465 add_anchor_token(T_const_cast);
10466 add_anchor_token(T_continue);
10467 add_anchor_token(T_default);
10468 add_anchor_token(T_delete);
10469 add_anchor_token(T_double);
10470 add_anchor_token(T_do);
10471 add_anchor_token(T_dynamic_cast);
10472 add_anchor_token(T_enum);
10473 add_anchor_token(T_extern);
10474 add_anchor_token(T_false);
10475 add_anchor_token(T_float);
10476 add_anchor_token(T_for);
10477 add_anchor_token(T_goto);
10478 add_anchor_token(T_if);
10479 add_anchor_token(T_inline);
10480 add_anchor_token(T_int);
10481 add_anchor_token(T_long);
10482 add_anchor_token(T_new);
10483 add_anchor_token(T_operator);
10484 add_anchor_token(T_register);
10485 add_anchor_token(T_reinterpret_cast);
10486 add_anchor_token(T_restrict);
10487 add_anchor_token(T_return);
10488 add_anchor_token(T_short);
10489 add_anchor_token(T_signed);
10490 add_anchor_token(T_sizeof);
10491 add_anchor_token(T_static);
10492 add_anchor_token(T_static_cast);
10493 add_anchor_token(T_struct);
10494 add_anchor_token(T_switch);
10495 add_anchor_token(T_template);
10496 add_anchor_token(T_this);
10497 add_anchor_token(T_throw);
10498 add_anchor_token(T_true);
10499 add_anchor_token(T_try);
10500 add_anchor_token(T_typedef);
10501 add_anchor_token(T_typeid);
10502 add_anchor_token(T_typename);
10503 add_anchor_token(T_typeof);
10504 add_anchor_token(T_union);
10505 add_anchor_token(T_unsigned);
10506 add_anchor_token(T_using);
10507 add_anchor_token(T_void);
10508 add_anchor_token(T_volatile);
10509 add_anchor_token(T_wchar_t);
10510 add_anchor_token(T_while);
10512 size_t const top = environment_top();
10513 scope_t *old_scope = scope_push(&statement->compound.scope);
10515 statement_t **anchor = &statement->compound.statements;
10516 bool only_decls_so_far = true;
10517 while (token.type != '}') {
10518 if (token.type == T_EOF) {
10519 errorf(&statement->base.source_position,
10520 "EOF while parsing compound statement");
10523 statement_t *sub_statement = intern_parse_statement();
10524 if (is_invalid_statement(sub_statement)) {
10525 /* an error occurred. if we are at an anchor, return */
10531 if (warning.declaration_after_statement) {
10532 if (sub_statement->kind != STATEMENT_DECLARATION) {
10533 only_decls_so_far = false;
10534 } else if (!only_decls_so_far) {
10535 warningf(&sub_statement->base.source_position,
10536 "ISO C90 forbids mixed declarations and code");
10540 *anchor = sub_statement;
10542 while (sub_statement->base.next != NULL)
10543 sub_statement = sub_statement->base.next;
10545 anchor = &sub_statement->base.next;
10549 /* look over all statements again to produce no effect warnings */
10550 if (warning.unused_value) {
10551 statement_t *sub_statement = statement->compound.statements;
10552 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10553 if (sub_statement->kind != STATEMENT_EXPRESSION)
10555 /* don't emit a warning for the last expression in an expression
10556 * statement as it has always an effect */
10557 if (inside_expression_statement && sub_statement->base.next == NULL)
10560 expression_t *expression = sub_statement->expression.expression;
10561 if (!expression_has_effect(expression)) {
10562 warningf(&expression->base.source_position,
10563 "statement has no effect");
10569 rem_anchor_token(T_while);
10570 rem_anchor_token(T_wchar_t);
10571 rem_anchor_token(T_volatile);
10572 rem_anchor_token(T_void);
10573 rem_anchor_token(T_using);
10574 rem_anchor_token(T_unsigned);
10575 rem_anchor_token(T_union);
10576 rem_anchor_token(T_typeof);
10577 rem_anchor_token(T_typename);
10578 rem_anchor_token(T_typeid);
10579 rem_anchor_token(T_typedef);
10580 rem_anchor_token(T_try);
10581 rem_anchor_token(T_true);
10582 rem_anchor_token(T_throw);
10583 rem_anchor_token(T_this);
10584 rem_anchor_token(T_template);
10585 rem_anchor_token(T_switch);
10586 rem_anchor_token(T_struct);
10587 rem_anchor_token(T_static_cast);
10588 rem_anchor_token(T_static);
10589 rem_anchor_token(T_sizeof);
10590 rem_anchor_token(T_signed);
10591 rem_anchor_token(T_short);
10592 rem_anchor_token(T_return);
10593 rem_anchor_token(T_restrict);
10594 rem_anchor_token(T_reinterpret_cast);
10595 rem_anchor_token(T_register);
10596 rem_anchor_token(T_operator);
10597 rem_anchor_token(T_new);
10598 rem_anchor_token(T_long);
10599 rem_anchor_token(T_int);
10600 rem_anchor_token(T_inline);
10601 rem_anchor_token(T_if);
10602 rem_anchor_token(T_goto);
10603 rem_anchor_token(T_for);
10604 rem_anchor_token(T_float);
10605 rem_anchor_token(T_false);
10606 rem_anchor_token(T_extern);
10607 rem_anchor_token(T_enum);
10608 rem_anchor_token(T_dynamic_cast);
10609 rem_anchor_token(T_do);
10610 rem_anchor_token(T_double);
10611 rem_anchor_token(T_delete);
10612 rem_anchor_token(T_default);
10613 rem_anchor_token(T_continue);
10614 rem_anchor_token(T_const_cast);
10615 rem_anchor_token(T_const);
10616 rem_anchor_token(T_class);
10617 rem_anchor_token(T_char);
10618 rem_anchor_token(T_case);
10619 rem_anchor_token(T_break);
10620 rem_anchor_token(T_bool);
10621 rem_anchor_token(T_auto);
10622 rem_anchor_token(T_asm);
10623 rem_anchor_token(T___thread);
10624 rem_anchor_token(T___real__);
10625 rem_anchor_token(T___label__);
10626 rem_anchor_token(T___imag__);
10627 rem_anchor_token(T___func__);
10628 rem_anchor_token(T___extension__);
10629 rem_anchor_token(T___builtin_va_start);
10630 rem_anchor_token(T___attribute__);
10631 rem_anchor_token(T___alignof__);
10632 rem_anchor_token(T___PRETTY_FUNCTION__);
10633 rem_anchor_token(T___FUNCTION__);
10634 rem_anchor_token(T__Imaginary);
10635 rem_anchor_token(T__Complex);
10636 rem_anchor_token(T__Bool);
10637 rem_anchor_token(T_WIDE_STRING_LITERAL);
10638 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10639 rem_anchor_token(T_STRING_LITERAL);
10640 rem_anchor_token(T_PLUSPLUS);
10641 rem_anchor_token(T_MINUSMINUS);
10642 rem_anchor_token(T_INTEGER);
10643 rem_anchor_token(T_IDENTIFIER);
10644 rem_anchor_token(T_FLOATINGPOINT);
10645 rem_anchor_token(T_COLONCOLON);
10646 rem_anchor_token(T_CHARACTER_CONSTANT);
10647 rem_anchor_token('~');
10648 rem_anchor_token('{');
10649 rem_anchor_token('-');
10650 rem_anchor_token('+');
10651 rem_anchor_token('*');
10652 rem_anchor_token('(');
10653 rem_anchor_token('&');
10654 rem_anchor_token('!');
10655 rem_anchor_token('}');
10656 assert(current_scope == &statement->compound.scope);
10657 scope_pop(old_scope);
10658 environment_pop_to(top);
10665 * Check for unused global static functions and variables
10667 static void check_unused_globals(void)
10669 if (!warning.unused_function && !warning.unused_variable)
10672 for (const entity_t *entity = file_scope->entities; entity != NULL;
10673 entity = entity->base.next) {
10674 if (!is_declaration(entity))
10677 const declaration_t *declaration = &entity->declaration;
10678 if (declaration->used ||
10679 declaration->modifiers & DM_UNUSED ||
10680 declaration->modifiers & DM_USED ||
10681 declaration->storage_class != STORAGE_CLASS_STATIC)
10684 type_t *const type = declaration->type;
10686 if (entity->kind == ENTITY_FUNCTION) {
10687 /* inhibit warning for static inline functions */
10688 if (entity->function.is_inline)
10691 s = entity->function.statement != NULL ? "defined" : "declared";
10696 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10697 type, declaration->base.symbol, s);
10701 static void parse_global_asm(void)
10703 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10706 expect('(', end_error);
10708 statement->asms.asm_text = parse_string_literals();
10709 statement->base.next = unit->global_asm;
10710 unit->global_asm = statement;
10712 expect(')', end_error);
10713 expect(';', end_error);
10718 static void parse_linkage_specification(void)
10721 assert(token.type == T_STRING_LITERAL);
10723 const char *linkage = parse_string_literals().begin;
10725 linkage_kind_t old_linkage = current_linkage;
10726 linkage_kind_t new_linkage;
10727 if (strcmp(linkage, "C") == 0) {
10728 new_linkage = LINKAGE_C;
10729 } else if (strcmp(linkage, "C++") == 0) {
10730 new_linkage = LINKAGE_CXX;
10732 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10733 new_linkage = LINKAGE_INVALID;
10735 current_linkage = new_linkage;
10737 if (next_if('{')) {
10739 expect('}', end_error);
10745 assert(current_linkage == new_linkage);
10746 current_linkage = old_linkage;
10749 static void parse_external(void)
10751 switch (token.type) {
10752 DECLARATION_START_NO_EXTERN
10754 case T___extension__:
10755 /* tokens below are for implicit int */
10756 case '&': /* & x; -> int& x; (and error later, because C++ has no
10758 case '*': /* * x; -> int* x; */
10759 case '(': /* (x); -> int (x); */
10760 parse_external_declaration();
10764 if (look_ahead(1)->type == T_STRING_LITERAL) {
10765 parse_linkage_specification();
10767 parse_external_declaration();
10772 parse_global_asm();
10776 parse_namespace_definition();
10780 if (!strict_mode) {
10782 warningf(HERE, "stray ';' outside of function");
10789 errorf(HERE, "stray %K outside of function", &token);
10790 if (token.type == '(' || token.type == '{' || token.type == '[')
10791 eat_until_matching_token(token.type);
10797 static void parse_externals(void)
10799 add_anchor_token('}');
10800 add_anchor_token(T_EOF);
10803 unsigned char token_anchor_copy[T_LAST_TOKEN];
10804 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10807 while (token.type != T_EOF && token.type != '}') {
10809 bool anchor_leak = false;
10810 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10811 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10813 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10814 anchor_leak = true;
10817 if (in_gcc_extension) {
10818 errorf(HERE, "Leaked __extension__");
10819 anchor_leak = true;
10829 rem_anchor_token(T_EOF);
10830 rem_anchor_token('}');
10834 * Parse a translation unit.
10836 static void parse_translation_unit(void)
10838 add_anchor_token(T_EOF);
10843 if (token.type == T_EOF)
10846 errorf(HERE, "stray %K outside of function", &token);
10847 if (token.type == '(' || token.type == '{' || token.type == '[')
10848 eat_until_matching_token(token.type);
10856 * @return the translation unit or NULL if errors occurred.
10858 void start_parsing(void)
10860 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10861 label_stack = NEW_ARR_F(stack_entry_t, 0);
10862 diagnostic_count = 0;
10866 type_set_output(stderr);
10867 ast_set_output(stderr);
10869 assert(unit == NULL);
10870 unit = allocate_ast_zero(sizeof(unit[0]));
10872 assert(file_scope == NULL);
10873 file_scope = &unit->scope;
10875 assert(current_scope == NULL);
10876 scope_push(&unit->scope);
10878 create_gnu_builtins();
10880 create_microsoft_intrinsics();
10883 translation_unit_t *finish_parsing(void)
10885 assert(current_scope == &unit->scope);
10888 assert(file_scope == &unit->scope);
10889 check_unused_globals();
10892 DEL_ARR_F(environment_stack);
10893 DEL_ARR_F(label_stack);
10895 translation_unit_t *result = unit;
10900 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10901 * are given length one. */
10902 static void complete_incomplete_arrays(void)
10904 size_t n = ARR_LEN(incomplete_arrays);
10905 for (size_t i = 0; i != n; ++i) {
10906 declaration_t *const decl = incomplete_arrays[i];
10907 type_t *const orig_type = decl->type;
10908 type_t *const type = skip_typeref(orig_type);
10910 if (!is_type_incomplete(type))
10913 if (warning.other) {
10914 warningf(&decl->base.source_position,
10915 "array '%#T' assumed to have one element",
10916 orig_type, decl->base.symbol);
10919 type_t *const new_type = duplicate_type(type);
10920 new_type->array.size_constant = true;
10921 new_type->array.has_implicit_size = true;
10922 new_type->array.size = 1;
10924 type_t *const result = identify_new_type(new_type);
10926 decl->type = result;
10930 void prepare_main_collect2(entity_t *entity)
10932 // create call to __main
10933 symbol_t *symbol = symbol_table_insert("__main");
10934 entity_t *subsubmain_ent
10935 = create_implicit_function(symbol, &builtin_source_position);
10937 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10938 type_t *ftype = subsubmain_ent->declaration.type;
10939 ref->base.source_position = builtin_source_position;
10940 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10941 ref->reference.entity = subsubmain_ent;
10943 expression_t *call = allocate_expression_zero(EXPR_CALL);
10944 call->base.source_position = builtin_source_position;
10945 call->base.type = type_void;
10946 call->call.function = ref;
10948 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10949 expr_statement->base.source_position = builtin_source_position;
10950 expr_statement->expression.expression = call;
10952 statement_t *statement = entity->function.statement;
10953 assert(statement->kind == STATEMENT_COMPOUND);
10954 compound_statement_t *compounds = &statement->compound;
10956 expr_statement->base.next = compounds->statements;
10957 compounds->statements = expr_statement;
10962 lookahead_bufpos = 0;
10963 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10966 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10967 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10968 parse_translation_unit();
10969 complete_incomplete_arrays();
10970 DEL_ARR_F(incomplete_arrays);
10971 incomplete_arrays = NULL;
10975 * create a builtin function.
10977 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10979 symbol_t *symbol = symbol_table_insert(name);
10980 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10981 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10982 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10983 entity->declaration.type = function_type;
10984 entity->declaration.implicit = true;
10985 entity->base.symbol = symbol;
10986 entity->base.source_position = builtin_source_position;
10988 entity->function.btk = kind;
10990 record_entity(entity, /*is_definition=*/false);
10996 * Create predefined gnu builtins.
10998 static void create_gnu_builtins(void)
11000 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
11002 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
11003 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
11004 GNU_BUILTIN(inf, make_function_0_type(type_double));
11005 GNU_BUILTIN(inff, make_function_0_type(type_float));
11006 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
11007 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
11008 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
11009 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
11010 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
11011 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
11012 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11013 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11014 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
11015 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
11016 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
11017 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
11018 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
11019 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
11020 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
11026 * Create predefined MS intrinsics.
11028 static void create_microsoft_intrinsics(void)
11030 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11032 /* intrinsics for all architectures */
11033 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11034 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11035 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11036 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11037 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11038 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11039 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11041 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11042 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11043 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11044 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11047 MS_BUILTIN(_enable, make_function_0_type(type_void));
11048 MS_BUILTIN(_disable, make_function_0_type(type_void));
11049 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11050 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11051 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11052 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11053 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11054 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11055 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11056 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11057 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11058 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11059 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11061 if (machine_size <= 32) {
11062 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11063 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11065 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11066 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11073 * Initialize the parser.
11075 void init_parser(void)
11077 sym_anonymous = symbol_table_insert("<anonymous>");
11079 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11081 init_expression_parsers();
11082 obstack_init(&temp_obst);
11084 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11085 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11089 * Terminate the parser.
11091 void exit_parser(void)
11093 obstack_free(&temp_obst, NULL);