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");
573 * Return the next token with a given lookahead.
575 static inline const token_t *look_ahead(size_t num)
577 assert(0 < num && num <= MAX_LOOKAHEAD);
578 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
579 return &lookahead_buffer[pos];
583 * Adds a token type to the token type anchor set (a multi-set).
585 static void add_anchor_token(int token_type)
587 assert(0 <= token_type && token_type < T_LAST_TOKEN);
588 ++token_anchor_set[token_type];
592 * Set the number of tokens types of the given type
593 * to zero and return the old count.
595 static int save_and_reset_anchor_state(int token_type)
597 assert(0 <= token_type && token_type < T_LAST_TOKEN);
598 int count = token_anchor_set[token_type];
599 token_anchor_set[token_type] = 0;
604 * Restore the number of token types to the given count.
606 static void restore_anchor_state(int token_type, int count)
608 assert(0 <= token_type && token_type < T_LAST_TOKEN);
609 token_anchor_set[token_type] = count;
613 * Remove a token type from the token type anchor set (a multi-set).
615 static void rem_anchor_token(int token_type)
617 assert(0 <= token_type && token_type < T_LAST_TOKEN);
618 assert(token_anchor_set[token_type] != 0);
619 --token_anchor_set[token_type];
623 * Return true if the token type of the current token is
626 static bool at_anchor(void)
630 return token_anchor_set[token.type];
634 * Eat tokens until a matching token type is found.
636 static void eat_until_matching_token(int type)
640 case '(': end_token = ')'; break;
641 case '{': end_token = '}'; break;
642 case '[': end_token = ']'; break;
643 default: end_token = type; break;
646 unsigned parenthesis_count = 0;
647 unsigned brace_count = 0;
648 unsigned bracket_count = 0;
649 while (token.type != end_token ||
650 parenthesis_count != 0 ||
652 bracket_count != 0) {
653 switch (token.type) {
655 case '(': ++parenthesis_count; break;
656 case '{': ++brace_count; break;
657 case '[': ++bracket_count; break;
660 if (parenthesis_count > 0)
670 if (bracket_count > 0)
673 if (token.type == end_token &&
674 parenthesis_count == 0 &&
688 * Eat input tokens until an anchor is found.
690 static void eat_until_anchor(void)
692 while (token_anchor_set[token.type] == 0) {
693 if (token.type == '(' || token.type == '{' || token.type == '[')
694 eat_until_matching_token(token.type);
700 * Eat a whole block from input tokens.
702 static void eat_block(void)
704 eat_until_matching_token('{');
705 if (token.type == '}')
709 #define eat(token_type) (assert(token.type == (token_type)), next_token())
712 * Report a parse error because an expected token was not found.
715 #if defined __GNUC__ && __GNUC__ >= 4
716 __attribute__((sentinel))
718 void parse_error_expected(const char *message, ...)
720 if (message != NULL) {
721 errorf(HERE, "%s", message);
724 va_start(ap, message);
725 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
730 * Report an incompatible type.
732 static void type_error_incompatible(const char *msg,
733 const source_position_t *source_position, type_t *type1, type_t *type2)
735 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
740 * Expect the current token is the expected token.
741 * If not, generate an error, eat the current statement,
742 * and goto the end_error label.
744 #define expect(expected, error_label) \
746 if (UNLIKELY(token.type != (expected))) { \
747 parse_error_expected(NULL, (expected), NULL); \
748 add_anchor_token(expected); \
749 eat_until_anchor(); \
750 if (token.type == expected) \
752 rem_anchor_token(expected); \
759 * Push a given scope on the scope stack and make it the
762 static scope_t *scope_push(scope_t *new_scope)
764 if (current_scope != NULL) {
765 new_scope->depth = current_scope->depth + 1;
768 scope_t *old_scope = current_scope;
769 current_scope = new_scope;
774 * Pop the current scope from the scope stack.
776 static void scope_pop(scope_t *old_scope)
778 current_scope = old_scope;
782 * Search an entity by its symbol in a given namespace.
784 static entity_t *get_entity(const symbol_t *const symbol,
785 namespace_tag_t namespc)
787 entity_t *entity = symbol->entity;
788 for (; entity != NULL; entity = entity->base.symbol_next) {
789 if (entity->base.namespc == namespc)
796 /* §6.2.3:1 24) There is only one name space for tags even though three are
798 static entity_t *get_tag(symbol_t const *const symbol,
799 entity_kind_tag_t const kind)
801 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
802 if (entity != NULL && entity->kind != kind) {
804 "'%Y' defined as wrong kind of tag (previous definition %P)",
805 symbol, &entity->base.source_position);
812 * pushs an entity on the environment stack and links the corresponding symbol
815 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
817 symbol_t *symbol = entity->base.symbol;
818 entity_namespace_t namespc = entity->base.namespc;
819 assert(namespc != NAMESPACE_INVALID);
821 /* replace/add entity into entity list of the symbol */
824 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
829 /* replace an entry? */
830 if (iter->base.namespc == namespc) {
831 entity->base.symbol_next = iter->base.symbol_next;
837 /* remember old declaration */
839 entry.symbol = symbol;
840 entry.old_entity = iter;
841 entry.namespc = namespc;
842 ARR_APP1(stack_entry_t, *stack_ptr, entry);
846 * Push an entity on the environment stack.
848 static void environment_push(entity_t *entity)
850 assert(entity->base.source_position.input_name != NULL);
851 assert(entity->base.parent_scope != NULL);
852 stack_push(&environment_stack, entity);
856 * Push a declaration on the global label stack.
858 * @param declaration the declaration
860 static void label_push(entity_t *label)
862 /* we abuse the parameters scope as parent for the labels */
863 label->base.parent_scope = ¤t_function->parameters;
864 stack_push(&label_stack, label);
868 * pops symbols from the environment stack until @p new_top is the top element
870 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
872 stack_entry_t *stack = *stack_ptr;
873 size_t top = ARR_LEN(stack);
876 assert(new_top <= top);
880 for (i = top; i > new_top; --i) {
881 stack_entry_t *entry = &stack[i - 1];
883 entity_t *old_entity = entry->old_entity;
884 symbol_t *symbol = entry->symbol;
885 entity_namespace_t namespc = entry->namespc;
887 /* replace with old_entity/remove */
890 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
892 assert(iter != NULL);
893 /* replace an entry? */
894 if (iter->base.namespc == namespc)
898 /* restore definition from outer scopes (if there was one) */
899 if (old_entity != NULL) {
900 old_entity->base.symbol_next = iter->base.symbol_next;
901 *anchor = old_entity;
903 /* remove entry from list */
904 *anchor = iter->base.symbol_next;
908 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
912 * Pop all entries from the environment stack until the new_top
915 * @param new_top the new stack top
917 static void environment_pop_to(size_t new_top)
919 stack_pop_to(&environment_stack, new_top);
923 * Pop all entries from the global label stack until the new_top
926 * @param new_top the new stack top
928 static void label_pop_to(size_t new_top)
930 stack_pop_to(&label_stack, new_top);
933 static int get_akind_rank(atomic_type_kind_t akind)
939 * Return the type rank for an atomic type.
941 static int get_rank(const type_t *type)
943 assert(!is_typeref(type));
944 if (type->kind == TYPE_ENUM)
945 return get_akind_rank(type->enumt.akind);
947 assert(type->kind == TYPE_ATOMIC);
948 return get_akind_rank(type->atomic.akind);
952 * §6.3.1.1:2 Do integer promotion for a given type.
954 * @param type the type to promote
955 * @return the promoted type
957 static type_t *promote_integer(type_t *type)
959 if (type->kind == TYPE_BITFIELD)
960 type = type->bitfield.base_type;
962 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
969 * Create a cast expression.
971 * @param expression the expression to cast
972 * @param dest_type the destination type
974 static expression_t *create_cast_expression(expression_t *expression,
977 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
979 cast->unary.value = expression;
980 cast->base.type = dest_type;
986 * Check if a given expression represents a null pointer constant.
988 * @param expression the expression to check
990 static bool is_null_pointer_constant(const expression_t *expression)
992 /* skip void* cast */
993 if (expression->kind == EXPR_UNARY_CAST ||
994 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
995 type_t *const type = skip_typeref(expression->base.type);
996 if (types_compatible(type, type_void_ptr))
997 expression = expression->unary.value;
1000 type_t *const type = skip_typeref(expression->base.type);
1002 is_type_integer(type) &&
1003 is_constant_expression(expression) &&
1004 !fold_constant_to_bool(expression);
1008 * Create an implicit cast expression.
1010 * @param expression the expression to cast
1011 * @param dest_type the destination type
1013 static expression_t *create_implicit_cast(expression_t *expression,
1016 type_t *const source_type = expression->base.type;
1018 if (source_type == dest_type)
1021 return create_cast_expression(expression, dest_type);
1024 typedef enum assign_error_t {
1026 ASSIGN_ERROR_INCOMPATIBLE,
1027 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1028 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1029 ASSIGN_WARNING_POINTER_FROM_INT,
1030 ASSIGN_WARNING_INT_FROM_POINTER
1033 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1034 const expression_t *const right,
1035 const char *context,
1036 const source_position_t *source_position)
1038 type_t *const orig_type_right = right->base.type;
1039 type_t *const type_left = skip_typeref(orig_type_left);
1040 type_t *const type_right = skip_typeref(orig_type_right);
1043 case ASSIGN_SUCCESS:
1045 case ASSIGN_ERROR_INCOMPATIBLE:
1046 errorf(source_position,
1047 "destination type '%T' in %s is incompatible with type '%T'",
1048 orig_type_left, context, orig_type_right);
1051 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1052 if (warning.other) {
1053 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1054 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1056 /* the left type has all qualifiers from the right type */
1057 unsigned missing_qualifiers
1058 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1059 warningf(source_position,
1060 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1061 orig_type_left, context, orig_type_right, missing_qualifiers);
1066 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1067 if (warning.other) {
1068 warningf(source_position,
1069 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1070 orig_type_left, context, right, orig_type_right);
1074 case ASSIGN_WARNING_POINTER_FROM_INT:
1075 if (warning.other) {
1076 warningf(source_position,
1077 "%s makes pointer '%T' from integer '%T' without a cast",
1078 context, orig_type_left, orig_type_right);
1082 case ASSIGN_WARNING_INT_FROM_POINTER:
1083 if (warning.other) {
1084 warningf(source_position,
1085 "%s makes integer '%T' from pointer '%T' without a cast",
1086 context, orig_type_left, orig_type_right);
1091 panic("invalid error value");
1095 /** Implements the rules from §6.5.16.1 */
1096 static assign_error_t semantic_assign(type_t *orig_type_left,
1097 const expression_t *const right)
1099 type_t *const orig_type_right = right->base.type;
1100 type_t *const type_left = skip_typeref(orig_type_left);
1101 type_t *const type_right = skip_typeref(orig_type_right);
1103 if (is_type_pointer(type_left)) {
1104 if (is_null_pointer_constant(right)) {
1105 return ASSIGN_SUCCESS;
1106 } else if (is_type_pointer(type_right)) {
1107 type_t *points_to_left
1108 = skip_typeref(type_left->pointer.points_to);
1109 type_t *points_to_right
1110 = skip_typeref(type_right->pointer.points_to);
1111 assign_error_t res = ASSIGN_SUCCESS;
1113 /* the left type has all qualifiers from the right type */
1114 unsigned missing_qualifiers
1115 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1116 if (missing_qualifiers != 0) {
1117 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1120 points_to_left = get_unqualified_type(points_to_left);
1121 points_to_right = get_unqualified_type(points_to_right);
1123 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1126 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1127 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1128 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1131 if (!types_compatible(points_to_left, points_to_right)) {
1132 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1136 } else if (is_type_integer(type_right)) {
1137 return ASSIGN_WARNING_POINTER_FROM_INT;
1139 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1140 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1141 && is_type_pointer(type_right))) {
1142 return ASSIGN_SUCCESS;
1143 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1144 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1145 type_t *const unqual_type_left = get_unqualified_type(type_left);
1146 type_t *const unqual_type_right = get_unqualified_type(type_right);
1147 if (types_compatible(unqual_type_left, unqual_type_right)) {
1148 return ASSIGN_SUCCESS;
1150 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1151 return ASSIGN_WARNING_INT_FROM_POINTER;
1154 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1155 return ASSIGN_SUCCESS;
1157 return ASSIGN_ERROR_INCOMPATIBLE;
1160 static expression_t *parse_constant_expression(void)
1162 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1164 if (!is_constant_expression(result)) {
1165 errorf(&result->base.source_position,
1166 "expression '%E' is not constant", result);
1172 static expression_t *parse_assignment_expression(void)
1174 return parse_sub_expression(PREC_ASSIGNMENT);
1177 static string_t parse_string_literals(void)
1179 assert(token.type == T_STRING_LITERAL);
1180 string_t result = token.v.string;
1184 while (token.type == T_STRING_LITERAL) {
1185 result = concat_strings(&result, &token.v.string);
1193 * compare two string, ignoring double underscores on the second.
1195 static int strcmp_underscore(const char *s1, const char *s2)
1197 if (s2[0] == '_' && s2[1] == '_') {
1198 size_t len2 = strlen(s2);
1199 size_t len1 = strlen(s1);
1200 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1201 return strncmp(s1, s2+2, len2-4);
1205 return strcmp(s1, s2);
1208 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1210 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1211 attribute->kind = kind;
1216 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1219 * __attribute__ ( ( attribute-list ) )
1223 * attribute_list , attrib
1228 * any-word ( identifier )
1229 * any-word ( identifier , nonempty-expr-list )
1230 * any-word ( expr-list )
1232 * where the "identifier" must not be declared as a type, and
1233 * "any-word" may be any identifier (including one declared as a
1234 * type), a reserved word storage class specifier, type specifier or
1235 * type qualifier. ??? This still leaves out most reserved keywords
1236 * (following the old parser), shouldn't we include them, and why not
1237 * allow identifiers declared as types to start the arguments?
1239 * Matze: this all looks confusing and little systematic, so we're even less
1240 * strict and parse any list of things which are identifiers or
1241 * (assignment-)expressions.
1243 static attribute_argument_t *parse_attribute_arguments(void)
1245 if (token.type == ')')
1248 attribute_argument_t *first = NULL;
1249 attribute_argument_t *last = NULL;
1251 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1253 /* is it an identifier */
1254 if (token.type == T_IDENTIFIER
1255 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1256 symbol_t *symbol = token.v.symbol;
1257 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1258 argument->v.symbol = symbol;
1261 /* must be an expression */
1262 expression_t *expression = parse_assignment_expression();
1264 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1265 argument->v.expression = expression;
1268 /* append argument */
1272 last->next = argument;
1276 if (token.type == ',') {
1280 expect(')', end_error);
1291 static attribute_t *parse_attribute_asm(void)
1295 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1297 expect('(', end_error);
1298 attribute->a.arguments = parse_attribute_arguments();
1305 static symbol_t *get_symbol_from_token(void)
1307 switch(token.type) {
1309 return token.v.symbol;
1338 /* maybe we need more tokens ... add them on demand */
1339 return get_token_symbol(&token);
1345 static attribute_t *parse_attribute_gnu_single(void)
1347 /* parse "any-word" */
1348 symbol_t *symbol = get_symbol_from_token();
1349 if (symbol == NULL) {
1350 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1354 const char *name = symbol->string;
1357 attribute_kind_t kind;
1358 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1359 const char *attribute_name = get_attribute_name(kind);
1360 if (attribute_name != NULL
1361 && strcmp_underscore(attribute_name, name) == 0)
1365 if (kind >= ATTRIBUTE_GNU_LAST) {
1366 if (warning.attribute) {
1367 warningf(HERE, "unknown attribute '%s' ignored", name);
1369 /* TODO: we should still save the attribute in the list... */
1370 kind = ATTRIBUTE_UNKNOWN;
1373 attribute_t *attribute = allocate_attribute_zero(kind);
1375 /* parse arguments */
1376 if (token.type == '(') {
1378 attribute->a.arguments = parse_attribute_arguments();
1387 static attribute_t *parse_attribute_gnu(void)
1389 attribute_t *first = NULL;
1390 attribute_t *last = NULL;
1392 eat(T___attribute__);
1393 expect('(', end_error);
1394 expect('(', end_error);
1396 if (token.type == ')') {
1398 expect(')', end_error);
1403 attribute_t *attribute = parse_attribute_gnu_single();
1404 if (attribute == NULL)
1410 last->next = attribute;
1414 if (token.type == ')') {
1418 expect(',', end_error);
1420 expect(')', end_error);
1426 /** Parse attributes. */
1427 static attribute_t *parse_attributes(attribute_t *first)
1429 attribute_t *last = first;
1432 while (last->next != NULL)
1436 attribute_t *attribute;
1437 switch (token.type) {
1438 case T___attribute__:
1439 attribute = parse_attribute_gnu();
1443 attribute = parse_attribute_asm();
1448 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1453 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1456 case T__forceinline:
1458 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1463 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1468 /* TODO record modifier */
1470 warningf(HERE, "Ignoring declaration modifier %K", &token);
1471 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1481 last->next = attribute;
1487 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1489 static entity_t *determine_lhs_ent(expression_t *const expr,
1492 switch (expr->kind) {
1493 case EXPR_REFERENCE: {
1494 entity_t *const entity = expr->reference.entity;
1495 /* we should only find variables as lvalues... */
1496 if (entity->base.kind != ENTITY_VARIABLE
1497 && entity->base.kind != ENTITY_PARAMETER)
1503 case EXPR_ARRAY_ACCESS: {
1504 expression_t *const ref = expr->array_access.array_ref;
1505 entity_t * ent = NULL;
1506 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1507 ent = determine_lhs_ent(ref, lhs_ent);
1510 mark_vars_read(expr->select.compound, lhs_ent);
1512 mark_vars_read(expr->array_access.index, lhs_ent);
1517 if (is_type_compound(skip_typeref(expr->base.type))) {
1518 return determine_lhs_ent(expr->select.compound, lhs_ent);
1520 mark_vars_read(expr->select.compound, lhs_ent);
1525 case EXPR_UNARY_DEREFERENCE: {
1526 expression_t *const val = expr->unary.value;
1527 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1529 return determine_lhs_ent(val->unary.value, lhs_ent);
1531 mark_vars_read(val, NULL);
1537 mark_vars_read(expr, NULL);
1542 #define ENT_ANY ((entity_t*)-1)
1545 * Mark declarations, which are read. This is used to detect variables, which
1549 * x is not marked as "read", because it is only read to calculate its own new
1553 * x and y are not detected as "not read", because multiple variables are
1556 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1558 switch (expr->kind) {
1559 case EXPR_REFERENCE: {
1560 entity_t *const entity = expr->reference.entity;
1561 if (entity->kind != ENTITY_VARIABLE
1562 && entity->kind != ENTITY_PARAMETER)
1565 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1566 if (entity->kind == ENTITY_VARIABLE) {
1567 entity->variable.read = true;
1569 entity->parameter.read = true;
1576 // TODO respect pure/const
1577 mark_vars_read(expr->call.function, NULL);
1578 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1579 mark_vars_read(arg->expression, NULL);
1583 case EXPR_CONDITIONAL:
1584 // TODO lhs_decl should depend on whether true/false have an effect
1585 mark_vars_read(expr->conditional.condition, NULL);
1586 if (expr->conditional.true_expression != NULL)
1587 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1588 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1592 if (lhs_ent == ENT_ANY
1593 && !is_type_compound(skip_typeref(expr->base.type)))
1595 mark_vars_read(expr->select.compound, lhs_ent);
1598 case EXPR_ARRAY_ACCESS: {
1599 expression_t *const ref = expr->array_access.array_ref;
1600 mark_vars_read(ref, lhs_ent);
1601 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1602 mark_vars_read(expr->array_access.index, lhs_ent);
1607 mark_vars_read(expr->va_arge.ap, lhs_ent);
1611 mark_vars_read(expr->va_copye.src, lhs_ent);
1614 case EXPR_UNARY_CAST:
1615 /* Special case: Use void cast to mark a variable as "read" */
1616 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1621 case EXPR_UNARY_THROW:
1622 if (expr->unary.value == NULL)
1625 case EXPR_UNARY_DEREFERENCE:
1626 case EXPR_UNARY_DELETE:
1627 case EXPR_UNARY_DELETE_ARRAY:
1628 if (lhs_ent == ENT_ANY)
1632 case EXPR_UNARY_NEGATE:
1633 case EXPR_UNARY_PLUS:
1634 case EXPR_UNARY_BITWISE_NEGATE:
1635 case EXPR_UNARY_NOT:
1636 case EXPR_UNARY_TAKE_ADDRESS:
1637 case EXPR_UNARY_POSTFIX_INCREMENT:
1638 case EXPR_UNARY_POSTFIX_DECREMENT:
1639 case EXPR_UNARY_PREFIX_INCREMENT:
1640 case EXPR_UNARY_PREFIX_DECREMENT:
1641 case EXPR_UNARY_CAST_IMPLICIT:
1642 case EXPR_UNARY_ASSUME:
1644 mark_vars_read(expr->unary.value, lhs_ent);
1647 case EXPR_BINARY_ADD:
1648 case EXPR_BINARY_SUB:
1649 case EXPR_BINARY_MUL:
1650 case EXPR_BINARY_DIV:
1651 case EXPR_BINARY_MOD:
1652 case EXPR_BINARY_EQUAL:
1653 case EXPR_BINARY_NOTEQUAL:
1654 case EXPR_BINARY_LESS:
1655 case EXPR_BINARY_LESSEQUAL:
1656 case EXPR_BINARY_GREATER:
1657 case EXPR_BINARY_GREATEREQUAL:
1658 case EXPR_BINARY_BITWISE_AND:
1659 case EXPR_BINARY_BITWISE_OR:
1660 case EXPR_BINARY_BITWISE_XOR:
1661 case EXPR_BINARY_LOGICAL_AND:
1662 case EXPR_BINARY_LOGICAL_OR:
1663 case EXPR_BINARY_SHIFTLEFT:
1664 case EXPR_BINARY_SHIFTRIGHT:
1665 case EXPR_BINARY_COMMA:
1666 case EXPR_BINARY_ISGREATER:
1667 case EXPR_BINARY_ISGREATEREQUAL:
1668 case EXPR_BINARY_ISLESS:
1669 case EXPR_BINARY_ISLESSEQUAL:
1670 case EXPR_BINARY_ISLESSGREATER:
1671 case EXPR_BINARY_ISUNORDERED:
1672 mark_vars_read(expr->binary.left, lhs_ent);
1673 mark_vars_read(expr->binary.right, lhs_ent);
1676 case EXPR_BINARY_ASSIGN:
1677 case EXPR_BINARY_MUL_ASSIGN:
1678 case EXPR_BINARY_DIV_ASSIGN:
1679 case EXPR_BINARY_MOD_ASSIGN:
1680 case EXPR_BINARY_ADD_ASSIGN:
1681 case EXPR_BINARY_SUB_ASSIGN:
1682 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1683 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1684 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1685 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1686 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1687 if (lhs_ent == ENT_ANY)
1689 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1690 mark_vars_read(expr->binary.right, lhs_ent);
1695 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1701 case EXPR_CHARACTER_CONSTANT:
1702 case EXPR_WIDE_CHARACTER_CONSTANT:
1703 case EXPR_STRING_LITERAL:
1704 case EXPR_WIDE_STRING_LITERAL:
1705 case EXPR_COMPOUND_LITERAL: // TODO init?
1707 case EXPR_CLASSIFY_TYPE:
1710 case EXPR_BUILTIN_CONSTANT_P:
1711 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1713 case EXPR_STATEMENT: // TODO
1714 case EXPR_LABEL_ADDRESS:
1715 case EXPR_REFERENCE_ENUM_VALUE:
1719 panic("unhandled expression");
1722 static designator_t *parse_designation(void)
1724 designator_t *result = NULL;
1725 designator_t *last = NULL;
1728 designator_t *designator;
1729 switch (token.type) {
1731 designator = allocate_ast_zero(sizeof(designator[0]));
1732 designator->source_position = token.source_position;
1734 add_anchor_token(']');
1735 designator->array_index = parse_constant_expression();
1736 rem_anchor_token(']');
1737 expect(']', end_error);
1740 designator = allocate_ast_zero(sizeof(designator[0]));
1741 designator->source_position = token.source_position;
1743 if (token.type != T_IDENTIFIER) {
1744 parse_error_expected("while parsing designator",
1745 T_IDENTIFIER, NULL);
1748 designator->symbol = token.v.symbol;
1752 expect('=', end_error);
1756 assert(designator != NULL);
1758 last->next = designator;
1760 result = designator;
1768 static initializer_t *initializer_from_string(array_type_t *type,
1769 const string_t *const string)
1771 /* TODO: check len vs. size of array type */
1774 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1775 initializer->string.string = *string;
1780 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1781 wide_string_t *const string)
1783 /* TODO: check len vs. size of array type */
1786 initializer_t *const initializer =
1787 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1788 initializer->wide_string.string = *string;
1794 * Build an initializer from a given expression.
1796 static initializer_t *initializer_from_expression(type_t *orig_type,
1797 expression_t *expression)
1799 /* TODO check that expression is a constant expression */
1801 /* §6.7.8.14/15 char array may be initialized by string literals */
1802 type_t *type = skip_typeref(orig_type);
1803 type_t *expr_type_orig = expression->base.type;
1804 type_t *expr_type = skip_typeref(expr_type_orig);
1805 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1806 array_type_t *const array_type = &type->array;
1807 type_t *const element_type = skip_typeref(array_type->element_type);
1809 if (element_type->kind == TYPE_ATOMIC) {
1810 atomic_type_kind_t akind = element_type->atomic.akind;
1811 switch (expression->kind) {
1812 case EXPR_STRING_LITERAL:
1813 if (akind == ATOMIC_TYPE_CHAR
1814 || akind == ATOMIC_TYPE_SCHAR
1815 || akind == ATOMIC_TYPE_UCHAR) {
1816 return initializer_from_string(array_type,
1817 &expression->string.value);
1821 case EXPR_WIDE_STRING_LITERAL: {
1822 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1823 if (get_unqualified_type(element_type) == bare_wchar_type) {
1824 return initializer_from_wide_string(array_type,
1825 &expression->wide_string.value);
1836 assign_error_t error = semantic_assign(type, expression);
1837 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1839 report_assign_error(error, type, expression, "initializer",
1840 &expression->base.source_position);
1842 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1843 result->value.value = create_implicit_cast(expression, type);
1849 * Checks if a given expression can be used as an constant initializer.
1851 static bool is_initializer_constant(const expression_t *expression)
1853 return is_constant_expression(expression)
1854 || is_address_constant(expression);
1858 * Parses an scalar initializer.
1860 * §6.7.8.11; eat {} without warning
1862 static initializer_t *parse_scalar_initializer(type_t *type,
1863 bool must_be_constant)
1865 /* there might be extra {} hierarchies */
1867 if (token.type == '{') {
1869 warningf(HERE, "extra curly braces around scalar initializer");
1873 } while (token.type == '{');
1876 expression_t *expression = parse_assignment_expression();
1877 mark_vars_read(expression, NULL);
1878 if (must_be_constant && !is_initializer_constant(expression)) {
1879 errorf(&expression->base.source_position,
1880 "initialisation expression '%E' is not constant",
1884 initializer_t *initializer = initializer_from_expression(type, expression);
1886 if (initializer == NULL) {
1887 errorf(&expression->base.source_position,
1888 "expression '%E' (type '%T') doesn't match expected type '%T'",
1889 expression, expression->base.type, type);
1894 bool additional_warning_displayed = false;
1895 while (braces > 0) {
1896 if (token.type == ',') {
1899 if (token.type != '}') {
1900 if (!additional_warning_displayed && warning.other) {
1901 warningf(HERE, "additional elements in scalar initializer");
1902 additional_warning_displayed = true;
1913 * An entry in the type path.
1915 typedef struct type_path_entry_t type_path_entry_t;
1916 struct type_path_entry_t {
1917 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1919 size_t index; /**< For array types: the current index. */
1920 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1925 * A type path expression a position inside compound or array types.
1927 typedef struct type_path_t type_path_t;
1928 struct type_path_t {
1929 type_path_entry_t *path; /**< An flexible array containing the current path. */
1930 type_t *top_type; /**< type of the element the path points */
1931 size_t max_index; /**< largest index in outermost array */
1935 * Prints a type path for debugging.
1937 static __attribute__((unused)) void debug_print_type_path(
1938 const type_path_t *path)
1940 size_t len = ARR_LEN(path->path);
1942 for (size_t i = 0; i < len; ++i) {
1943 const type_path_entry_t *entry = & path->path[i];
1945 type_t *type = skip_typeref(entry->type);
1946 if (is_type_compound(type)) {
1947 /* in gcc mode structs can have no members */
1948 if (entry->v.compound_entry == NULL) {
1952 fprintf(stderr, ".%s",
1953 entry->v.compound_entry->base.symbol->string);
1954 } else if (is_type_array(type)) {
1955 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1957 fprintf(stderr, "-INVALID-");
1960 if (path->top_type != NULL) {
1961 fprintf(stderr, " (");
1962 print_type(path->top_type);
1963 fprintf(stderr, ")");
1968 * Return the top type path entry, ie. in a path
1969 * (type).a.b returns the b.
1971 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1973 size_t len = ARR_LEN(path->path);
1975 return &path->path[len-1];
1979 * Enlarge the type path by an (empty) element.
1981 static type_path_entry_t *append_to_type_path(type_path_t *path)
1983 size_t len = ARR_LEN(path->path);
1984 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1986 type_path_entry_t *result = & path->path[len];
1987 memset(result, 0, sizeof(result[0]));
1992 * Descending into a sub-type. Enter the scope of the current top_type.
1994 static void descend_into_subtype(type_path_t *path)
1996 type_t *orig_top_type = path->top_type;
1997 type_t *top_type = skip_typeref(orig_top_type);
1999 type_path_entry_t *top = append_to_type_path(path);
2000 top->type = top_type;
2002 if (is_type_compound(top_type)) {
2003 compound_t *compound = top_type->compound.compound;
2004 entity_t *entry = compound->members.entities;
2006 if (entry != NULL) {
2007 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2008 top->v.compound_entry = &entry->declaration;
2009 path->top_type = entry->declaration.type;
2011 path->top_type = NULL;
2013 } else if (is_type_array(top_type)) {
2015 path->top_type = top_type->array.element_type;
2017 assert(!is_type_valid(top_type));
2022 * Pop an entry from the given type path, ie. returning from
2023 * (type).a.b to (type).a
2025 static void ascend_from_subtype(type_path_t *path)
2027 type_path_entry_t *top = get_type_path_top(path);
2029 path->top_type = top->type;
2031 size_t len = ARR_LEN(path->path);
2032 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2036 * Pop entries from the given type path until the given
2037 * path level is reached.
2039 static void ascend_to(type_path_t *path, size_t top_path_level)
2041 size_t len = ARR_LEN(path->path);
2043 while (len > top_path_level) {
2044 ascend_from_subtype(path);
2045 len = ARR_LEN(path->path);
2049 static bool walk_designator(type_path_t *path, const designator_t *designator,
2050 bool used_in_offsetof)
2052 for (; designator != NULL; designator = designator->next) {
2053 type_path_entry_t *top = get_type_path_top(path);
2054 type_t *orig_type = top->type;
2056 type_t *type = skip_typeref(orig_type);
2058 if (designator->symbol != NULL) {
2059 symbol_t *symbol = designator->symbol;
2060 if (!is_type_compound(type)) {
2061 if (is_type_valid(type)) {
2062 errorf(&designator->source_position,
2063 "'.%Y' designator used for non-compound type '%T'",
2067 top->type = type_error_type;
2068 top->v.compound_entry = NULL;
2069 orig_type = type_error_type;
2071 compound_t *compound = type->compound.compound;
2072 entity_t *iter = compound->members.entities;
2073 for (; iter != NULL; iter = iter->base.next) {
2074 if (iter->base.symbol == symbol) {
2079 errorf(&designator->source_position,
2080 "'%T' has no member named '%Y'", orig_type, symbol);
2083 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2084 if (used_in_offsetof) {
2085 type_t *real_type = skip_typeref(iter->declaration.type);
2086 if (real_type->kind == TYPE_BITFIELD) {
2087 errorf(&designator->source_position,
2088 "offsetof designator '%Y' may not specify bitfield",
2094 top->type = orig_type;
2095 top->v.compound_entry = &iter->declaration;
2096 orig_type = iter->declaration.type;
2099 expression_t *array_index = designator->array_index;
2100 assert(designator->array_index != NULL);
2102 if (!is_type_array(type)) {
2103 if (is_type_valid(type)) {
2104 errorf(&designator->source_position,
2105 "[%E] designator used for non-array type '%T'",
2106 array_index, orig_type);
2111 long index = fold_constant_to_int(array_index);
2112 if (!used_in_offsetof) {
2114 errorf(&designator->source_position,
2115 "array index [%E] must be positive", array_index);
2116 } else if (type->array.size_constant) {
2117 long array_size = type->array.size;
2118 if (index >= array_size) {
2119 errorf(&designator->source_position,
2120 "designator [%E] (%d) exceeds array size %d",
2121 array_index, index, array_size);
2126 top->type = orig_type;
2127 top->v.index = (size_t) index;
2128 orig_type = type->array.element_type;
2130 path->top_type = orig_type;
2132 if (designator->next != NULL) {
2133 descend_into_subtype(path);
2142 static void advance_current_object(type_path_t *path, size_t top_path_level)
2144 type_path_entry_t *top = get_type_path_top(path);
2146 type_t *type = skip_typeref(top->type);
2147 if (is_type_union(type)) {
2148 /* in unions only the first element is initialized */
2149 top->v.compound_entry = NULL;
2150 } else if (is_type_struct(type)) {
2151 declaration_t *entry = top->v.compound_entry;
2153 entity_t *next_entity = entry->base.next;
2154 if (next_entity != NULL) {
2155 assert(is_declaration(next_entity));
2156 entry = &next_entity->declaration;
2161 top->v.compound_entry = entry;
2162 if (entry != NULL) {
2163 path->top_type = entry->type;
2166 } else if (is_type_array(type)) {
2167 assert(is_type_array(type));
2171 if (!type->array.size_constant || top->v.index < type->array.size) {
2175 assert(!is_type_valid(type));
2179 /* we're past the last member of the current sub-aggregate, try if we
2180 * can ascend in the type hierarchy and continue with another subobject */
2181 size_t len = ARR_LEN(path->path);
2183 if (len > top_path_level) {
2184 ascend_from_subtype(path);
2185 advance_current_object(path, top_path_level);
2187 path->top_type = NULL;
2192 * skip any {...} blocks until a closing bracket is reached.
2194 static void skip_initializers(void)
2196 if (token.type == '{')
2199 while (token.type != '}') {
2200 if (token.type == T_EOF)
2202 if (token.type == '{') {
2210 static initializer_t *create_empty_initializer(void)
2212 static initializer_t empty_initializer
2213 = { .list = { { INITIALIZER_LIST }, 0 } };
2214 return &empty_initializer;
2218 * Parse a part of an initialiser for a struct or union,
2220 static initializer_t *parse_sub_initializer(type_path_t *path,
2221 type_t *outer_type, size_t top_path_level,
2222 parse_initializer_env_t *env)
2224 if (token.type == '}') {
2225 /* empty initializer */
2226 return create_empty_initializer();
2229 type_t *orig_type = path->top_type;
2230 type_t *type = NULL;
2232 if (orig_type == NULL) {
2233 /* We are initializing an empty compound. */
2235 type = skip_typeref(orig_type);
2238 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2241 designator_t *designator = NULL;
2242 if (token.type == '.' || token.type == '[') {
2243 designator = parse_designation();
2244 goto finish_designator;
2245 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2246 /* GNU-style designator ("identifier: value") */
2247 designator = allocate_ast_zero(sizeof(designator[0]));
2248 designator->source_position = token.source_position;
2249 designator->symbol = token.v.symbol;
2254 /* reset path to toplevel, evaluate designator from there */
2255 ascend_to(path, top_path_level);
2256 if (!walk_designator(path, designator, false)) {
2257 /* can't continue after designation error */
2261 initializer_t *designator_initializer
2262 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2263 designator_initializer->designator.designator = designator;
2264 ARR_APP1(initializer_t*, initializers, designator_initializer);
2266 orig_type = path->top_type;
2267 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2272 if (token.type == '{') {
2273 if (type != NULL && is_type_scalar(type)) {
2274 sub = parse_scalar_initializer(type, env->must_be_constant);
2278 if (env->entity != NULL) {
2280 "extra brace group at end of initializer for '%Y'",
2281 env->entity->base.symbol);
2283 errorf(HERE, "extra brace group at end of initializer");
2286 descend_into_subtype(path);
2288 add_anchor_token('}');
2289 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2291 rem_anchor_token('}');
2294 ascend_from_subtype(path);
2295 expect('}', end_error);
2297 expect('}', end_error);
2298 goto error_parse_next;
2302 /* must be an expression */
2303 expression_t *expression = parse_assignment_expression();
2304 mark_vars_read(expression, NULL);
2306 if (env->must_be_constant && !is_initializer_constant(expression)) {
2307 errorf(&expression->base.source_position,
2308 "Initialisation expression '%E' is not constant",
2313 /* we are already outside, ... */
2314 type_t *const outer_type_skip = skip_typeref(outer_type);
2315 if (is_type_compound(outer_type_skip) &&
2316 !outer_type_skip->compound.compound->complete) {
2317 goto error_parse_next;
2322 /* handle { "string" } special case */
2323 if ((expression->kind == EXPR_STRING_LITERAL
2324 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2325 && outer_type != NULL) {
2326 sub = initializer_from_expression(outer_type, expression);
2328 if (token.type == ',') {
2331 if (token.type != '}' && warning.other) {
2332 warningf(HERE, "excessive elements in initializer for type '%T'",
2335 /* TODO: eat , ... */
2340 /* descend into subtypes until expression matches type */
2342 orig_type = path->top_type;
2343 type = skip_typeref(orig_type);
2345 sub = initializer_from_expression(orig_type, expression);
2349 if (!is_type_valid(type)) {
2352 if (is_type_scalar(type)) {
2353 errorf(&expression->base.source_position,
2354 "expression '%E' doesn't match expected type '%T'",
2355 expression, orig_type);
2359 descend_into_subtype(path);
2363 /* update largest index of top array */
2364 const type_path_entry_t *first = &path->path[0];
2365 type_t *first_type = first->type;
2366 first_type = skip_typeref(first_type);
2367 if (is_type_array(first_type)) {
2368 size_t index = first->v.index;
2369 if (index > path->max_index)
2370 path->max_index = index;
2374 /* append to initializers list */
2375 ARR_APP1(initializer_t*, initializers, sub);
2378 if (warning.other) {
2379 if (env->entity != NULL) {
2380 warningf(HERE, "excess elements in initializer for '%Y'",
2381 env->entity->base.symbol);
2383 warningf(HERE, "excess elements in initializer");
2389 if (token.type == '}') {
2392 expect(',', end_error);
2393 if (token.type == '}') {
2398 /* advance to the next declaration if we are not at the end */
2399 advance_current_object(path, top_path_level);
2400 orig_type = path->top_type;
2401 if (orig_type != NULL)
2402 type = skip_typeref(orig_type);
2408 size_t len = ARR_LEN(initializers);
2409 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2410 initializer_t *result = allocate_ast_zero(size);
2411 result->kind = INITIALIZER_LIST;
2412 result->list.len = len;
2413 memcpy(&result->list.initializers, initializers,
2414 len * sizeof(initializers[0]));
2416 DEL_ARR_F(initializers);
2417 ascend_to(path, top_path_level+1);
2422 skip_initializers();
2423 DEL_ARR_F(initializers);
2424 ascend_to(path, top_path_level+1);
2429 * Parses an initializer. Parsers either a compound literal
2430 * (env->declaration == NULL) or an initializer of a declaration.
2432 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2434 type_t *type = skip_typeref(env->type);
2435 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2436 initializer_t *result;
2438 if (is_type_scalar(type)) {
2439 result = parse_scalar_initializer(type, env->must_be_constant);
2440 } else if (token.type == '{') {
2444 memset(&path, 0, sizeof(path));
2445 path.top_type = env->type;
2446 path.path = NEW_ARR_F(type_path_entry_t, 0);
2448 descend_into_subtype(&path);
2450 add_anchor_token('}');
2451 result = parse_sub_initializer(&path, env->type, 1, env);
2452 rem_anchor_token('}');
2454 max_index = path.max_index;
2455 DEL_ARR_F(path.path);
2457 expect('}', end_error);
2459 /* parse_scalar_initializer() also works in this case: we simply
2460 * have an expression without {} around it */
2461 result = parse_scalar_initializer(type, env->must_be_constant);
2464 /* §6.7.8:22 array initializers for arrays with unknown size determine
2465 * the array type size */
2466 if (is_type_array(type) && type->array.size_expression == NULL
2467 && result != NULL) {
2469 switch (result->kind) {
2470 case INITIALIZER_LIST:
2471 assert(max_index != 0xdeadbeaf);
2472 size = max_index + 1;
2475 case INITIALIZER_STRING:
2476 size = result->string.string.size;
2479 case INITIALIZER_WIDE_STRING:
2480 size = result->wide_string.string.size;
2483 case INITIALIZER_DESIGNATOR:
2484 case INITIALIZER_VALUE:
2485 /* can happen for parse errors */
2490 internal_errorf(HERE, "invalid initializer type");
2493 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2494 cnst->base.type = type_size_t;
2495 cnst->conste.v.int_value = size;
2497 type_t *new_type = duplicate_type(type);
2499 new_type->array.size_expression = cnst;
2500 new_type->array.size_constant = true;
2501 new_type->array.has_implicit_size = true;
2502 new_type->array.size = size;
2503 env->type = new_type;
2511 static void append_entity(scope_t *scope, entity_t *entity)
2513 if (scope->last_entity != NULL) {
2514 scope->last_entity->base.next = entity;
2516 scope->entities = entity;
2518 scope->last_entity = entity;
2522 static compound_t *parse_compound_type_specifier(bool is_struct)
2530 symbol_t *symbol = NULL;
2531 compound_t *compound = NULL;
2532 attribute_t *attributes = NULL;
2534 if (token.type == T___attribute__) {
2535 attributes = parse_attributes(NULL);
2538 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2539 if (token.type == T_IDENTIFIER) {
2540 /* the compound has a name, check if we have seen it already */
2541 symbol = token.v.symbol;
2544 entity_t *entity = get_tag(symbol, kind);
2545 if (entity != NULL) {
2546 compound = &entity->compound;
2547 if (compound->base.parent_scope != current_scope &&
2548 (token.type == '{' || token.type == ';')) {
2549 /* we're in an inner scope and have a definition. Shadow
2550 * existing definition in outer scope */
2552 } else if (compound->complete && token.type == '{') {
2553 assert(symbol != NULL);
2554 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2555 is_struct ? "struct" : "union", symbol,
2556 &compound->base.source_position);
2557 /* clear members in the hope to avoid further errors */
2558 compound->members.entities = NULL;
2561 } else if (token.type != '{') {
2563 parse_error_expected("while parsing struct type specifier",
2564 T_IDENTIFIER, '{', NULL);
2566 parse_error_expected("while parsing union type specifier",
2567 T_IDENTIFIER, '{', NULL);
2573 if (compound == NULL) {
2574 entity_t *entity = allocate_entity_zero(kind);
2575 compound = &entity->compound;
2577 compound->alignment = 1;
2578 compound->base.namespc = NAMESPACE_TAG;
2579 compound->base.source_position = token.source_position;
2580 compound->base.symbol = symbol;
2581 compound->base.parent_scope = current_scope;
2582 if (symbol != NULL) {
2583 environment_push(entity);
2585 append_entity(current_scope, entity);
2588 if (token.type == '{') {
2589 parse_compound_type_entries(compound);
2591 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2592 if (symbol == NULL) {
2593 assert(anonymous_entity == NULL);
2594 anonymous_entity = (entity_t*)compound;
2598 if (attributes != NULL) {
2599 handle_entity_attributes(attributes, (entity_t*) compound);
2605 static void parse_enum_entries(type_t *const enum_type)
2609 if (token.type == '}') {
2610 errorf(HERE, "empty enum not allowed");
2615 add_anchor_token('}');
2617 if (token.type != T_IDENTIFIER) {
2618 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2620 rem_anchor_token('}');
2624 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2625 entity->enum_value.enum_type = enum_type;
2626 entity->base.symbol = token.v.symbol;
2627 entity->base.source_position = token.source_position;
2630 if (token.type == '=') {
2632 expression_t *value = parse_constant_expression();
2634 value = create_implicit_cast(value, enum_type);
2635 entity->enum_value.value = value;
2640 record_entity(entity, false);
2642 if (token.type != ',')
2645 } while (token.type != '}');
2646 rem_anchor_token('}');
2648 expect('}', end_error);
2654 static type_t *parse_enum_specifier(void)
2660 if (token.type == T_IDENTIFIER) {
2661 symbol = token.v.symbol;
2664 entity = get_tag(symbol, ENTITY_ENUM);
2665 if (entity != NULL) {
2666 if (entity->base.parent_scope != current_scope &&
2667 (token.type == '{' || token.type == ';')) {
2668 /* we're in an inner scope and have a definition. Shadow
2669 * existing definition in outer scope */
2671 } else if (entity->enume.complete && token.type == '{') {
2672 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2673 symbol, &entity->base.source_position);
2676 } else if (token.type != '{') {
2677 parse_error_expected("while parsing enum type specifier",
2678 T_IDENTIFIER, '{', NULL);
2685 if (entity == NULL) {
2686 entity = allocate_entity_zero(ENTITY_ENUM);
2687 entity->base.namespc = NAMESPACE_TAG;
2688 entity->base.source_position = token.source_position;
2689 entity->base.symbol = symbol;
2690 entity->base.parent_scope = current_scope;
2693 type_t *const type = allocate_type_zero(TYPE_ENUM);
2694 type->enumt.enume = &entity->enume;
2695 type->enumt.akind = ATOMIC_TYPE_INT;
2697 if (token.type == '{') {
2698 if (symbol != NULL) {
2699 environment_push(entity);
2701 append_entity(current_scope, entity);
2702 entity->enume.complete = true;
2704 parse_enum_entries(type);
2705 parse_attributes(NULL);
2707 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2708 if (symbol == NULL) {
2709 assert(anonymous_entity == NULL);
2710 anonymous_entity = entity;
2712 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2713 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2721 * if a symbol is a typedef to another type, return true
2723 static bool is_typedef_symbol(symbol_t *symbol)
2725 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2726 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2729 static type_t *parse_typeof(void)
2735 expect('(', end_error);
2736 add_anchor_token(')');
2738 expression_t *expression = NULL;
2740 bool old_type_prop = in_type_prop;
2741 bool old_gcc_extension = in_gcc_extension;
2742 in_type_prop = true;
2744 while (token.type == T___extension__) {
2745 /* This can be a prefix to a typename or an expression. */
2747 in_gcc_extension = true;
2749 switch (token.type) {
2751 if (is_typedef_symbol(token.v.symbol)) {
2752 type = parse_typename();
2754 expression = parse_expression();
2755 type = revert_automatic_type_conversion(expression);
2760 type = parse_typename();
2764 expression = parse_expression();
2765 type = expression->base.type;
2768 in_type_prop = old_type_prop;
2769 in_gcc_extension = old_gcc_extension;
2771 rem_anchor_token(')');
2772 expect(')', end_error);
2774 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2775 typeof_type->typeoft.expression = expression;
2776 typeof_type->typeoft.typeof_type = type;
2783 typedef enum specifiers_t {
2784 SPECIFIER_SIGNED = 1 << 0,
2785 SPECIFIER_UNSIGNED = 1 << 1,
2786 SPECIFIER_LONG = 1 << 2,
2787 SPECIFIER_INT = 1 << 3,
2788 SPECIFIER_DOUBLE = 1 << 4,
2789 SPECIFIER_CHAR = 1 << 5,
2790 SPECIFIER_WCHAR_T = 1 << 6,
2791 SPECIFIER_SHORT = 1 << 7,
2792 SPECIFIER_LONG_LONG = 1 << 8,
2793 SPECIFIER_FLOAT = 1 << 9,
2794 SPECIFIER_BOOL = 1 << 10,
2795 SPECIFIER_VOID = 1 << 11,
2796 SPECIFIER_INT8 = 1 << 12,
2797 SPECIFIER_INT16 = 1 << 13,
2798 SPECIFIER_INT32 = 1 << 14,
2799 SPECIFIER_INT64 = 1 << 15,
2800 SPECIFIER_INT128 = 1 << 16,
2801 SPECIFIER_COMPLEX = 1 << 17,
2802 SPECIFIER_IMAGINARY = 1 << 18,
2805 static type_t *create_builtin_type(symbol_t *const symbol,
2806 type_t *const real_type)
2808 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2809 type->builtin.symbol = symbol;
2810 type->builtin.real_type = real_type;
2811 return identify_new_type(type);
2814 static type_t *get_typedef_type(symbol_t *symbol)
2816 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2817 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2820 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2821 type->typedeft.typedefe = &entity->typedefe;
2826 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2828 expect('(', end_error);
2830 attribute_property_argument_t *property
2831 = allocate_ast_zero(sizeof(*property));
2834 if (token.type != T_IDENTIFIER) {
2835 parse_error_expected("while parsing property declspec",
2836 T_IDENTIFIER, NULL);
2841 symbol_t *symbol = token.v.symbol;
2843 if (strcmp(symbol->string, "put") == 0) {
2845 } else if (strcmp(symbol->string, "get") == 0) {
2848 errorf(HERE, "expected put or get in property declspec");
2851 expect('=', end_error);
2852 if (token.type != T_IDENTIFIER) {
2853 parse_error_expected("while parsing property declspec",
2854 T_IDENTIFIER, NULL);
2858 property->put_symbol = token.v.symbol;
2860 property->get_symbol = token.v.symbol;
2863 if (token.type == ')')
2865 expect(',', end_error);
2868 attribute->a.property = property;
2870 expect(')', end_error);
2876 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2878 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2879 if (token.type == T_restrict) {
2880 kind = ATTRIBUTE_MS_RESTRICT;
2882 } else if (token.type == T_IDENTIFIER) {
2883 const char *name = token.v.symbol->string;
2885 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2887 const char *attribute_name = get_attribute_name(k);
2888 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2894 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2895 warningf(HERE, "unknown __declspec '%s' ignored", name);
2898 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2902 attribute_t *attribute = allocate_attribute_zero(kind);
2904 if (kind == ATTRIBUTE_MS_PROPERTY) {
2905 return parse_attribute_ms_property(attribute);
2908 /* parse arguments */
2909 if (token.type == '(') {
2911 attribute->a.arguments = parse_attribute_arguments();
2917 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2921 expect('(', end_error);
2923 if (token.type == ')') {
2928 add_anchor_token(')');
2930 attribute_t *last = first;
2933 while (last->next != NULL)
2937 attribute_t *attribute
2938 = parse_microsoft_extended_decl_modifier_single();
2939 if (attribute == NULL)
2945 last->next = attribute;
2949 if (token.type == ')') {
2952 expect(',', end_error);
2955 rem_anchor_token(')');
2956 expect(')', end_error);
2960 rem_anchor_token(')');
2964 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2966 entity_t *entity = allocate_entity_zero(kind);
2967 entity->base.source_position = *HERE;
2968 entity->base.symbol = symbol;
2969 if (is_declaration(entity)) {
2970 entity->declaration.type = type_error_type;
2971 entity->declaration.implicit = true;
2972 } else if (kind == ENTITY_TYPEDEF) {
2973 entity->typedefe.type = type_error_type;
2974 entity->typedefe.builtin = true;
2976 if (kind != ENTITY_COMPOUND_MEMBER)
2977 record_entity(entity, false);
2981 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2983 type_t *type = NULL;
2984 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2985 unsigned type_specifiers = 0;
2986 bool newtype = false;
2987 bool saw_error = false;
2988 bool old_gcc_extension = in_gcc_extension;
2990 specifiers->source_position = token.source_position;
2993 specifiers->attributes = parse_attributes(specifiers->attributes);
2995 switch (token.type) {
2997 #define MATCH_STORAGE_CLASS(token, class) \
2999 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3000 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3002 specifiers->storage_class = class; \
3003 if (specifiers->thread_local) \
3004 goto check_thread_storage_class; \
3008 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3009 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3010 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3011 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3012 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3015 specifiers->attributes
3016 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
3020 if (specifiers->thread_local) {
3021 errorf(HERE, "duplicate '__thread'");
3023 specifiers->thread_local = true;
3024 check_thread_storage_class:
3025 switch (specifiers->storage_class) {
3026 case STORAGE_CLASS_EXTERN:
3027 case STORAGE_CLASS_NONE:
3028 case STORAGE_CLASS_STATIC:
3032 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3033 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3034 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3035 wrong_thread_stoarge_class:
3036 errorf(HERE, "'__thread' used with '%s'", wrong);
3043 /* type qualifiers */
3044 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3046 qualifiers |= qualifier; \
3050 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3051 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3052 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3053 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3054 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3055 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3056 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3057 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3059 case T___extension__:
3061 in_gcc_extension = true;
3064 /* type specifiers */
3065 #define MATCH_SPECIFIER(token, specifier, name) \
3067 if (type_specifiers & specifier) { \
3068 errorf(HERE, "multiple " name " type specifiers given"); \
3070 type_specifiers |= specifier; \
3075 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3076 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3077 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3078 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3079 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3080 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3081 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3082 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3083 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3084 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3085 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3086 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3087 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3088 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3089 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3090 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3091 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3092 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3096 specifiers->is_inline = true;
3100 case T__forceinline:
3102 specifiers->modifiers |= DM_FORCEINLINE;
3107 if (type_specifiers & SPECIFIER_LONG_LONG) {
3108 errorf(HERE, "multiple type specifiers given");
3109 } else if (type_specifiers & SPECIFIER_LONG) {
3110 type_specifiers |= SPECIFIER_LONG_LONG;
3112 type_specifiers |= SPECIFIER_LONG;
3117 #define CHECK_DOUBLE_TYPE() \
3118 if ( type != NULL) \
3119 errorf(HERE, "multiple data types in declaration specifiers");
3122 CHECK_DOUBLE_TYPE();
3123 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3125 type->compound.compound = parse_compound_type_specifier(true);
3128 CHECK_DOUBLE_TYPE();
3129 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3130 type->compound.compound = parse_compound_type_specifier(false);
3133 CHECK_DOUBLE_TYPE();
3134 type = parse_enum_specifier();
3137 CHECK_DOUBLE_TYPE();
3138 type = parse_typeof();
3140 case T___builtin_va_list:
3141 CHECK_DOUBLE_TYPE();
3142 type = duplicate_type(type_valist);
3146 case T_IDENTIFIER: {
3147 /* only parse identifier if we haven't found a type yet */
3148 if (type != NULL || type_specifiers != 0) {
3149 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3150 * declaration, so it doesn't generate errors about expecting '(' or
3152 switch (look_ahead(1)->type) {
3159 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3163 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3168 goto finish_specifiers;
3172 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3173 if (typedef_type == NULL) {
3174 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3175 * declaration, so it doesn't generate 'implicit int' followed by more
3176 * errors later on. */
3177 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3183 errorf(HERE, "%K does not name a type", &token);
3186 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3188 type = allocate_type_zero(TYPE_TYPEDEF);
3189 type->typedeft.typedefe = &entity->typedefe;
3193 if (la1_type == '&' || la1_type == '*')
3194 goto finish_specifiers;
3199 goto finish_specifiers;
3204 type = typedef_type;
3208 /* function specifier */
3210 goto finish_specifiers;
3215 specifiers->attributes = parse_attributes(specifiers->attributes);
3217 in_gcc_extension = old_gcc_extension;
3219 if (type == NULL || (saw_error && type_specifiers != 0)) {
3220 atomic_type_kind_t atomic_type;
3222 /* match valid basic types */
3223 switch (type_specifiers) {
3224 case SPECIFIER_VOID:
3225 atomic_type = ATOMIC_TYPE_VOID;
3227 case SPECIFIER_WCHAR_T:
3228 atomic_type = ATOMIC_TYPE_WCHAR_T;
3230 case SPECIFIER_CHAR:
3231 atomic_type = ATOMIC_TYPE_CHAR;
3233 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3234 atomic_type = ATOMIC_TYPE_SCHAR;
3236 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3237 atomic_type = ATOMIC_TYPE_UCHAR;
3239 case SPECIFIER_SHORT:
3240 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3241 case SPECIFIER_SHORT | SPECIFIER_INT:
3242 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3243 atomic_type = ATOMIC_TYPE_SHORT;
3245 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3246 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3247 atomic_type = ATOMIC_TYPE_USHORT;
3250 case SPECIFIER_SIGNED:
3251 case SPECIFIER_SIGNED | SPECIFIER_INT:
3252 atomic_type = ATOMIC_TYPE_INT;
3254 case SPECIFIER_UNSIGNED:
3255 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3256 atomic_type = ATOMIC_TYPE_UINT;
3258 case SPECIFIER_LONG:
3259 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3260 case SPECIFIER_LONG | SPECIFIER_INT:
3261 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3262 atomic_type = ATOMIC_TYPE_LONG;
3264 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3265 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3266 atomic_type = ATOMIC_TYPE_ULONG;
3269 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3270 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3271 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3272 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3274 atomic_type = ATOMIC_TYPE_LONGLONG;
3275 goto warn_about_long_long;
3277 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3278 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3280 atomic_type = ATOMIC_TYPE_ULONGLONG;
3281 warn_about_long_long:
3282 if (warning.long_long) {
3283 warningf(&specifiers->source_position,
3284 "ISO C90 does not support 'long long'");
3288 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3289 atomic_type = unsigned_int8_type_kind;
3292 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3293 atomic_type = unsigned_int16_type_kind;
3296 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3297 atomic_type = unsigned_int32_type_kind;
3300 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3301 atomic_type = unsigned_int64_type_kind;
3304 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3305 atomic_type = unsigned_int128_type_kind;
3308 case SPECIFIER_INT8:
3309 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3310 atomic_type = int8_type_kind;
3313 case SPECIFIER_INT16:
3314 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3315 atomic_type = int16_type_kind;
3318 case SPECIFIER_INT32:
3319 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3320 atomic_type = int32_type_kind;
3323 case SPECIFIER_INT64:
3324 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3325 atomic_type = int64_type_kind;
3328 case SPECIFIER_INT128:
3329 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3330 atomic_type = int128_type_kind;
3333 case SPECIFIER_FLOAT:
3334 atomic_type = ATOMIC_TYPE_FLOAT;
3336 case SPECIFIER_DOUBLE:
3337 atomic_type = ATOMIC_TYPE_DOUBLE;
3339 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3340 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3342 case SPECIFIER_BOOL:
3343 atomic_type = ATOMIC_TYPE_BOOL;
3345 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3346 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3347 atomic_type = ATOMIC_TYPE_FLOAT;
3349 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3350 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3351 atomic_type = ATOMIC_TYPE_DOUBLE;
3353 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3354 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3355 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3358 /* invalid specifier combination, give an error message */
3359 if (type_specifiers == 0) {
3363 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3364 if (!(c_mode & _CXX) && !strict_mode) {
3365 if (warning.implicit_int) {
3366 warningf(HERE, "no type specifiers in declaration, using 'int'");
3368 atomic_type = ATOMIC_TYPE_INT;
3371 errorf(HERE, "no type specifiers given in declaration");
3373 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3374 (type_specifiers & SPECIFIER_UNSIGNED)) {
3375 errorf(HERE, "signed and unsigned specifiers given");
3376 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3377 errorf(HERE, "only integer types can be signed or unsigned");
3379 errorf(HERE, "multiple datatypes in declaration");
3384 if (type_specifiers & SPECIFIER_COMPLEX) {
3385 type = allocate_type_zero(TYPE_COMPLEX);
3386 type->complex.akind = atomic_type;
3387 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3388 type = allocate_type_zero(TYPE_IMAGINARY);
3389 type->imaginary.akind = atomic_type;
3391 type = allocate_type_zero(TYPE_ATOMIC);
3392 type->atomic.akind = atomic_type;
3395 } else if (type_specifiers != 0) {
3396 errorf(HERE, "multiple datatypes in declaration");
3399 /* FIXME: check type qualifiers here */
3400 type->base.qualifiers = qualifiers;
3403 type = identify_new_type(type);
3405 type = typehash_insert(type);
3408 if (specifiers->attributes != NULL)
3409 type = handle_type_attributes(specifiers->attributes, type);
3410 specifiers->type = type;
3414 specifiers->type = type_error_type;
3418 static type_qualifiers_t parse_type_qualifiers(void)
3420 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3423 switch (token.type) {
3424 /* type qualifiers */
3425 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3426 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3427 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3428 /* microsoft extended type modifiers */
3429 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3430 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3431 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3432 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3433 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3442 * Parses an K&R identifier list
3444 static void parse_identifier_list(scope_t *scope)
3447 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3448 entity->base.source_position = token.source_position;
3449 entity->base.namespc = NAMESPACE_NORMAL;
3450 entity->base.symbol = token.v.symbol;
3451 /* a K&R parameter has no type, yet */
3455 append_entity(scope, entity);
3457 if (token.type != ',') {
3461 } while (token.type == T_IDENTIFIER);
3464 static entity_t *parse_parameter(void)
3466 declaration_specifiers_t specifiers;
3467 memset(&specifiers, 0, sizeof(specifiers));
3469 parse_declaration_specifiers(&specifiers);
3471 entity_t *entity = parse_declarator(&specifiers,
3472 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3473 anonymous_entity = NULL;
3477 static void semantic_parameter_incomplete(const entity_t *entity)
3479 assert(entity->kind == ENTITY_PARAMETER);
3481 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3482 * list in a function declarator that is part of a
3483 * definition of that function shall not have
3484 * incomplete type. */
3485 type_t *type = skip_typeref(entity->declaration.type);
3486 if (is_type_incomplete(type)) {
3487 errorf(&entity->base.source_position,
3488 "parameter '%#T' has incomplete type",
3489 entity->declaration.type, entity->base.symbol);
3493 static bool has_parameters(void)
3495 /* func(void) is not a parameter */
3496 if (token.type == T_IDENTIFIER) {
3497 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3500 if (entity->kind != ENTITY_TYPEDEF)
3502 if (skip_typeref(entity->typedefe.type) != type_void)
3504 } else if (token.type != T_void) {
3507 if (look_ahead(1)->type != ')')
3514 * Parses function type parameters (and optionally creates variable_t entities
3515 * for them in a scope)
3517 static void parse_parameters(function_type_t *type, scope_t *scope)
3520 add_anchor_token(')');
3521 int saved_comma_state = save_and_reset_anchor_state(',');
3523 if (token.type == T_IDENTIFIER &&
3524 !is_typedef_symbol(token.v.symbol)) {
3525 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3526 if (la1_type == ',' || la1_type == ')') {
3527 type->kr_style_parameters = true;
3528 parse_identifier_list(scope);
3529 goto parameters_finished;
3533 if (token.type == ')') {
3534 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3535 if (!(c_mode & _CXX))
3536 type->unspecified_parameters = true;
3537 goto parameters_finished;
3540 if (has_parameters()) {
3541 function_parameter_t **anchor = &type->parameters;
3543 switch (token.type) {
3546 type->variadic = true;
3547 goto parameters_finished;
3550 case T___extension__:
3553 entity_t *entity = parse_parameter();
3554 if (entity->kind == ENTITY_TYPEDEF) {
3555 errorf(&entity->base.source_position,
3556 "typedef not allowed as function parameter");
3559 assert(is_declaration(entity));
3561 semantic_parameter_incomplete(entity);
3563 function_parameter_t *const parameter =
3564 allocate_parameter(entity->declaration.type);
3566 if (scope != NULL) {
3567 append_entity(scope, entity);
3570 *anchor = parameter;
3571 anchor = ¶meter->next;
3576 goto parameters_finished;
3578 if (token.type != ',') {
3579 goto parameters_finished;
3586 parameters_finished:
3587 rem_anchor_token(')');
3588 expect(')', end_error);
3591 restore_anchor_state(',', saved_comma_state);
3594 typedef enum construct_type_kind_t {
3597 CONSTRUCT_REFERENCE,
3600 } construct_type_kind_t;
3602 typedef union construct_type_t construct_type_t;
3604 typedef struct construct_type_base_t {
3605 construct_type_kind_t kind;
3606 construct_type_t *next;
3607 } construct_type_base_t;
3609 typedef struct parsed_pointer_t {
3610 construct_type_base_t base;
3611 type_qualifiers_t type_qualifiers;
3612 variable_t *base_variable; /**< MS __based extension. */
3615 typedef struct parsed_reference_t {
3616 construct_type_base_t base;
3617 } parsed_reference_t;
3619 typedef struct construct_function_type_t {
3620 construct_type_base_t base;
3621 type_t *function_type;
3622 } construct_function_type_t;
3624 typedef struct parsed_array_t {
3625 construct_type_base_t base;
3626 type_qualifiers_t type_qualifiers;
3632 union construct_type_t {
3633 construct_type_kind_t kind;
3634 construct_type_base_t base;
3635 parsed_pointer_t pointer;
3636 parsed_reference_t reference;
3637 construct_function_type_t function;
3638 parsed_array_t array;
3641 static construct_type_t *parse_pointer_declarator(void)
3645 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3646 memset(pointer, 0, sizeof(pointer[0]));
3647 pointer->base.kind = CONSTRUCT_POINTER;
3648 pointer->type_qualifiers = parse_type_qualifiers();
3649 //pointer->base_variable = base_variable;
3651 return (construct_type_t*) pointer;
3654 static construct_type_t *parse_reference_declarator(void)
3658 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3659 parsed_reference_t *reference = &cons->reference;
3660 memset(reference, 0, sizeof(*reference));
3661 cons->kind = CONSTRUCT_REFERENCE;
3666 static construct_type_t *parse_array_declarator(void)
3669 add_anchor_token(']');
3671 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3672 parsed_array_t *array = &cons->array;
3673 memset(array, 0, sizeof(*array));
3674 cons->kind = CONSTRUCT_ARRAY;
3676 if (token.type == T_static) {
3677 array->is_static = true;
3681 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3682 if (type_qualifiers != 0) {
3683 if (token.type == T_static) {
3684 array->is_static = true;
3688 array->type_qualifiers = type_qualifiers;
3690 if (token.type == '*' && look_ahead(1)->type == ']') {
3691 array->is_variable = true;
3693 } else if (token.type != ']') {
3694 expression_t *const size = parse_assignment_expression();
3696 /* §6.7.5.2:1 Array size must have integer type */
3697 type_t *const orig_type = size->base.type;
3698 type_t *const type = skip_typeref(orig_type);
3699 if (!is_type_integer(type) && is_type_valid(type)) {
3700 errorf(&size->base.source_position,
3701 "array size '%E' must have integer type but has type '%T'",
3706 mark_vars_read(size, NULL);
3709 rem_anchor_token(']');
3710 expect(']', end_error);
3716 static construct_type_t *parse_function_declarator(scope_t *scope)
3718 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3719 function_type_t *ftype = &type->function;
3721 ftype->linkage = current_linkage;
3722 ftype->calling_convention = CC_DEFAULT;
3724 parse_parameters(ftype, scope);
3726 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3727 construct_function_type_t *function = &cons->function;
3728 memset(function, 0, sizeof(*function));
3729 cons->kind = CONSTRUCT_FUNCTION;
3730 function->function_type = type;
3735 typedef struct parse_declarator_env_t {
3736 bool may_be_abstract : 1;
3737 bool must_be_abstract : 1;
3738 decl_modifiers_t modifiers;
3740 source_position_t source_position;
3742 attribute_t *attributes;
3743 } parse_declarator_env_t;
3745 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3747 /* construct a single linked list of construct_type_t's which describe
3748 * how to construct the final declarator type */
3749 construct_type_t *first = NULL;
3750 construct_type_t **anchor = &first;
3752 env->attributes = parse_attributes(env->attributes);
3755 construct_type_t *type;
3756 //variable_t *based = NULL; /* MS __based extension */
3757 switch (token.type) {
3759 if (!(c_mode & _CXX))
3760 errorf(HERE, "references are only available for C++");
3761 type = parse_reference_declarator();
3766 source_position_t const pos = *HERE;
3768 expect('(', end_error);
3769 add_anchor_token(')');
3770 based = parse_microsoft_based();
3771 rem_anchor_token(')');
3772 expect(')', end_error);
3773 if (token.type != '*') {
3774 if (token.type == T__based) {
3775 errorf(&pos, "__based type modifier specified more than once");
3776 } else if (warning.other) {
3778 "__based does not precede a pointer declarator, ignored");
3783 panic("based currently disabled");
3789 type = parse_pointer_declarator();
3793 goto ptr_operator_end;
3797 anchor = &type->base.next;
3799 /* TODO: find out if this is correct */
3800 env->attributes = parse_attributes(env->attributes);
3805 modifiers |= env->modifiers;
3806 env->modifiers = modifiers;
3809 construct_type_t *inner_types = NULL;
3811 switch (token.type) {
3813 if (env->must_be_abstract) {
3814 errorf(HERE, "no identifier expected in typename");
3816 env->symbol = token.v.symbol;
3817 env->source_position = token.source_position;
3822 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3823 * interpreted as ``function with no parameter specification'', rather
3824 * than redundant parentheses around the omitted identifier. */
3825 if (look_ahead(1)->type != ')') {
3827 add_anchor_token(')');
3828 inner_types = parse_inner_declarator(env);
3829 if (inner_types != NULL) {
3830 /* All later declarators only modify the return type */
3831 env->must_be_abstract = true;
3833 rem_anchor_token(')');
3834 expect(')', end_error);
3838 if (env->may_be_abstract)
3840 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3845 construct_type_t **const p = anchor;
3848 construct_type_t *type;
3849 switch (token.type) {
3851 scope_t *scope = NULL;
3852 if (!env->must_be_abstract) {
3853 scope = &env->parameters;
3856 type = parse_function_declarator(scope);
3860 type = parse_array_declarator();
3863 goto declarator_finished;
3866 /* insert in the middle of the list (at p) */
3867 type->base.next = *p;
3870 anchor = &type->base.next;
3873 declarator_finished:
3874 /* append inner_types at the end of the list, we don't to set anchor anymore
3875 * as it's not needed anymore */
3876 *anchor = inner_types;
3883 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3885 construct_type_t *iter = construct_list;
3886 for (; iter != NULL; iter = iter->base.next) {
3887 switch (iter->kind) {
3888 case CONSTRUCT_INVALID:
3890 case CONSTRUCT_FUNCTION: {
3891 construct_function_type_t *function = &iter->function;
3892 type_t *function_type = function->function_type;
3894 function_type->function.return_type = type;
3896 type_t *skipped_return_type = skip_typeref(type);
3898 if (is_type_function(skipped_return_type)) {
3899 errorf(HERE, "function returning function is not allowed");
3900 } else if (is_type_array(skipped_return_type)) {
3901 errorf(HERE, "function returning array is not allowed");
3903 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3905 "type qualifiers in return type of function type are meaningless");
3909 /* The function type was constructed earlier. Freeing it here will
3910 * destroy other types. */
3911 type = typehash_insert(function_type);
3915 case CONSTRUCT_POINTER: {
3916 if (is_type_reference(skip_typeref(type)))
3917 errorf(HERE, "cannot declare a pointer to reference");
3919 parsed_pointer_t *pointer = &iter->pointer;
3920 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3924 case CONSTRUCT_REFERENCE:
3925 if (is_type_reference(skip_typeref(type)))
3926 errorf(HERE, "cannot declare a reference to reference");
3928 type = make_reference_type(type);
3931 case CONSTRUCT_ARRAY: {
3932 if (is_type_reference(skip_typeref(type)))
3933 errorf(HERE, "cannot declare an array of references");
3935 parsed_array_t *array = &iter->array;
3936 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3938 expression_t *size_expression = array->size;
3939 if (size_expression != NULL) {
3941 = create_implicit_cast(size_expression, type_size_t);
3944 array_type->base.qualifiers = array->type_qualifiers;
3945 array_type->array.element_type = type;
3946 array_type->array.is_static = array->is_static;
3947 array_type->array.is_variable = array->is_variable;
3948 array_type->array.size_expression = size_expression;
3950 if (size_expression != NULL) {
3951 if (is_constant_expression(size_expression)) {
3953 = fold_constant_to_int(size_expression);
3954 array_type->array.size = size;
3955 array_type->array.size_constant = true;
3956 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3957 * have a value greater than zero. */
3959 if (size < 0 || !GNU_MODE) {
3960 errorf(&size_expression->base.source_position,
3961 "size of array must be greater than zero");
3962 } else if (warning.other) {
3963 warningf(&size_expression->base.source_position,
3964 "zero length arrays are a GCC extension");
3968 array_type->array.is_vla = true;
3972 type_t *skipped_type = skip_typeref(type);
3974 if (is_type_incomplete(skipped_type)) {
3975 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3976 } else if (is_type_function(skipped_type)) {
3977 errorf(HERE, "array of functions is not allowed");
3979 type = identify_new_type(array_type);
3983 internal_errorf(HERE, "invalid type construction found");
3989 static type_t *automatic_type_conversion(type_t *orig_type);
3991 static type_t *semantic_parameter(const source_position_t *pos,
3993 const declaration_specifiers_t *specifiers,
3996 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3997 * shall be adjusted to ``qualified pointer to type'',
3999 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4000 * type'' shall be adjusted to ``pointer to function
4001 * returning type'', as in 6.3.2.1. */
4002 type = automatic_type_conversion(type);
4004 if (specifiers->is_inline && is_type_valid(type)) {
4005 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
4008 /* §6.9.1:6 The declarations in the declaration list shall contain
4009 * no storage-class specifier other than register and no
4010 * initializations. */
4011 if (specifiers->thread_local || (
4012 specifiers->storage_class != STORAGE_CLASS_NONE &&
4013 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4015 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
4018 /* delay test for incomplete type, because we might have (void)
4019 * which is legal but incomplete... */
4024 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4025 declarator_flags_t flags)
4027 parse_declarator_env_t env;
4028 memset(&env, 0, sizeof(env));
4029 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
4031 construct_type_t *construct_type = parse_inner_declarator(&env);
4033 construct_declarator_type(construct_type, specifiers->type);
4034 type_t *type = skip_typeref(orig_type);
4036 if (construct_type != NULL) {
4037 obstack_free(&temp_obst, construct_type);
4040 attribute_t *attributes = parse_attributes(env.attributes);
4041 /* append (shared) specifier attribute behind attributes of this
4043 if (attributes != NULL) {
4044 attribute_t *last = attributes;
4045 while (last->next != NULL)
4047 last->next = specifiers->attributes;
4049 attributes = specifiers->attributes;
4053 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4054 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4055 entity->base.symbol = env.symbol;
4056 entity->base.source_position = env.source_position;
4057 entity->typedefe.type = orig_type;
4059 if (anonymous_entity != NULL) {
4060 if (is_type_compound(type)) {
4061 assert(anonymous_entity->compound.alias == NULL);
4062 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4063 anonymous_entity->kind == ENTITY_UNION);
4064 anonymous_entity->compound.alias = entity;
4065 anonymous_entity = NULL;
4066 } else if (is_type_enum(type)) {
4067 assert(anonymous_entity->enume.alias == NULL);
4068 assert(anonymous_entity->kind == ENTITY_ENUM);
4069 anonymous_entity->enume.alias = entity;
4070 anonymous_entity = NULL;
4074 /* create a declaration type entity */
4075 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4076 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4078 if (env.symbol != NULL) {
4079 if (specifiers->is_inline && is_type_valid(type)) {
4080 errorf(&env.source_position,
4081 "compound member '%Y' declared 'inline'", env.symbol);
4084 if (specifiers->thread_local ||
4085 specifiers->storage_class != STORAGE_CLASS_NONE) {
4086 errorf(&env.source_position,
4087 "compound member '%Y' must have no storage class",
4091 } else if (flags & DECL_IS_PARAMETER) {
4092 orig_type = semantic_parameter(&env.source_position, orig_type,
4093 specifiers, env.symbol);
4095 entity = allocate_entity_zero(ENTITY_PARAMETER);
4096 } else if (is_type_function(type)) {
4097 entity = allocate_entity_zero(ENTITY_FUNCTION);
4099 entity->function.is_inline = specifiers->is_inline;
4100 entity->function.parameters = env.parameters;
4102 if (env.symbol != NULL) {
4103 /* this needs fixes for C++ */
4104 bool in_function_scope = current_function != NULL;
4106 if (specifiers->thread_local || (
4107 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4108 specifiers->storage_class != STORAGE_CLASS_NONE &&
4109 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4111 errorf(&env.source_position,
4112 "invalid storage class for function '%Y'", env.symbol);
4116 entity = allocate_entity_zero(ENTITY_VARIABLE);
4118 entity->variable.thread_local = specifiers->thread_local;
4120 if (env.symbol != NULL) {
4121 if (specifiers->is_inline && is_type_valid(type)) {
4122 errorf(&env.source_position,
4123 "variable '%Y' declared 'inline'", env.symbol);
4126 bool invalid_storage_class = false;
4127 if (current_scope == file_scope) {
4128 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4129 specifiers->storage_class != STORAGE_CLASS_NONE &&
4130 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4131 invalid_storage_class = true;
4134 if (specifiers->thread_local &&
4135 specifiers->storage_class == STORAGE_CLASS_NONE) {
4136 invalid_storage_class = true;
4139 if (invalid_storage_class) {
4140 errorf(&env.source_position,
4141 "invalid storage class for variable '%Y'", env.symbol);
4146 if (env.symbol != NULL) {
4147 entity->base.symbol = env.symbol;
4148 entity->base.source_position = env.source_position;
4150 entity->base.source_position = specifiers->source_position;
4152 entity->base.namespc = NAMESPACE_NORMAL;
4153 entity->declaration.type = orig_type;
4154 entity->declaration.alignment = get_type_alignment(orig_type);
4155 entity->declaration.modifiers = env.modifiers;
4156 entity->declaration.attributes = attributes;
4158 storage_class_t storage_class = specifiers->storage_class;
4159 entity->declaration.declared_storage_class = storage_class;
4161 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4162 storage_class = STORAGE_CLASS_AUTO;
4163 entity->declaration.storage_class = storage_class;
4166 if (attributes != NULL) {
4167 handle_entity_attributes(attributes, entity);
4173 static type_t *parse_abstract_declarator(type_t *base_type)
4175 parse_declarator_env_t env;
4176 memset(&env, 0, sizeof(env));
4177 env.may_be_abstract = true;
4178 env.must_be_abstract = true;
4180 construct_type_t *construct_type = parse_inner_declarator(&env);
4182 type_t *result = construct_declarator_type(construct_type, base_type);
4183 if (construct_type != NULL) {
4184 obstack_free(&temp_obst, construct_type);
4186 result = handle_type_attributes(env.attributes, result);
4192 * Check if the declaration of main is suspicious. main should be a
4193 * function with external linkage, returning int, taking either zero
4194 * arguments, two, or three arguments of appropriate types, ie.
4196 * int main([ int argc, char **argv [, char **env ] ]).
4198 * @param decl the declaration to check
4199 * @param type the function type of the declaration
4201 static void check_main(const entity_t *entity)
4203 const source_position_t *pos = &entity->base.source_position;
4204 if (entity->kind != ENTITY_FUNCTION) {
4205 warningf(pos, "'main' is not a function");
4209 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4210 warningf(pos, "'main' is normally a non-static function");
4213 type_t *type = skip_typeref(entity->declaration.type);
4214 assert(is_type_function(type));
4216 function_type_t *func_type = &type->function;
4217 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4218 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4219 func_type->return_type);
4221 const function_parameter_t *parm = func_type->parameters;
4223 type_t *const first_type = parm->type;
4224 if (!types_compatible(skip_typeref(first_type), type_int)) {
4226 "first argument of 'main' should be 'int', but is '%T'",
4231 type_t *const second_type = parm->type;
4232 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4233 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4237 type_t *const third_type = parm->type;
4238 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4239 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4243 goto warn_arg_count;
4247 warningf(pos, "'main' takes only zero, two or three arguments");
4253 * Check if a symbol is the equal to "main".
4255 static bool is_sym_main(const symbol_t *const sym)
4257 return strcmp(sym->string, "main") == 0;
4260 static void error_redefined_as_different_kind(const source_position_t *pos,
4261 const entity_t *old, entity_kind_t new_kind)
4263 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4264 get_entity_kind_name(old->kind), old->base.symbol,
4265 get_entity_kind_name(new_kind), &old->base.source_position);
4268 static bool is_error_entity(entity_t *const ent)
4270 if (is_declaration(ent)) {
4271 return is_type_valid(skip_typeref(ent->declaration.type));
4272 } else if (ent->kind == ENTITY_TYPEDEF) {
4273 return is_type_valid(skip_typeref(ent->typedefe.type));
4279 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4280 * for various problems that occur for multiple definitions
4282 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4284 const symbol_t *const symbol = entity->base.symbol;
4285 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4286 const source_position_t *pos = &entity->base.source_position;
4288 /* can happen in error cases */
4292 entity_t *const previous_entity = get_entity(symbol, namespc);
4293 /* pushing the same entity twice will break the stack structure */
4294 assert(previous_entity != entity);
4296 if (entity->kind == ENTITY_FUNCTION) {
4297 type_t *const orig_type = entity->declaration.type;
4298 type_t *const type = skip_typeref(orig_type);
4300 assert(is_type_function(type));
4301 if (type->function.unspecified_parameters &&
4302 warning.strict_prototypes &&
4303 previous_entity == NULL) {
4304 warningf(pos, "function declaration '%#T' is not a prototype",
4308 if (warning.main && current_scope == file_scope
4309 && is_sym_main(symbol)) {
4314 if (is_declaration(entity) &&
4315 warning.nested_externs &&
4316 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4317 current_scope != file_scope) {
4318 warningf(pos, "nested extern declaration of '%#T'",
4319 entity->declaration.type, symbol);
4322 if (previous_entity != NULL) {
4323 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4324 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4325 assert(previous_entity->kind == ENTITY_PARAMETER);
4327 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4328 entity->declaration.type, symbol,
4329 previous_entity->declaration.type, symbol,
4330 &previous_entity->base.source_position);
4334 if (previous_entity->base.parent_scope == current_scope) {
4335 if (previous_entity->kind != entity->kind) {
4336 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4337 error_redefined_as_different_kind(pos, previous_entity,
4342 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4343 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4344 symbol, &previous_entity->base.source_position);
4347 if (previous_entity->kind == ENTITY_TYPEDEF) {
4348 /* TODO: C++ allows this for exactly the same type */
4349 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4350 symbol, &previous_entity->base.source_position);
4354 /* at this point we should have only VARIABLES or FUNCTIONS */
4355 assert(is_declaration(previous_entity) && is_declaration(entity));
4357 declaration_t *const prev_decl = &previous_entity->declaration;
4358 declaration_t *const decl = &entity->declaration;
4360 /* can happen for K&R style declarations */
4361 if (prev_decl->type == NULL &&
4362 previous_entity->kind == ENTITY_PARAMETER &&
4363 entity->kind == ENTITY_PARAMETER) {
4364 prev_decl->type = decl->type;
4365 prev_decl->storage_class = decl->storage_class;
4366 prev_decl->declared_storage_class = decl->declared_storage_class;
4367 prev_decl->modifiers = decl->modifiers;
4368 return previous_entity;
4371 type_t *const orig_type = decl->type;
4372 assert(orig_type != NULL);
4373 type_t *const type = skip_typeref(orig_type);
4374 type_t *const prev_type = skip_typeref(prev_decl->type);
4376 if (!types_compatible(type, prev_type)) {
4378 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4379 orig_type, symbol, prev_decl->type, symbol,
4380 &previous_entity->base.source_position);
4382 unsigned old_storage_class = prev_decl->storage_class;
4384 if (warning.redundant_decls &&
4387 !(prev_decl->modifiers & DM_USED) &&
4388 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4389 warningf(&previous_entity->base.source_position,
4390 "unnecessary static forward declaration for '%#T'",
4391 prev_decl->type, symbol);
4394 storage_class_t new_storage_class = decl->storage_class;
4396 /* pretend no storage class means extern for function
4397 * declarations (except if the previous declaration is neither
4398 * none nor extern) */
4399 if (entity->kind == ENTITY_FUNCTION) {
4400 /* the previous declaration could have unspecified parameters or
4401 * be a typedef, so use the new type */
4402 if (prev_type->function.unspecified_parameters || is_definition)
4403 prev_decl->type = type;
4405 switch (old_storage_class) {
4406 case STORAGE_CLASS_NONE:
4407 old_storage_class = STORAGE_CLASS_EXTERN;
4410 case STORAGE_CLASS_EXTERN:
4411 if (is_definition) {
4412 if (warning.missing_prototypes &&
4413 prev_type->function.unspecified_parameters &&
4414 !is_sym_main(symbol)) {
4415 warningf(pos, "no previous prototype for '%#T'",
4418 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4419 new_storage_class = STORAGE_CLASS_EXTERN;
4426 } else if (is_type_incomplete(prev_type)) {
4427 prev_decl->type = type;
4430 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4431 new_storage_class == STORAGE_CLASS_EXTERN) {
4432 warn_redundant_declaration:
4433 if (!is_definition &&
4434 warning.redundant_decls &&
4435 is_type_valid(prev_type) &&
4436 strcmp(previous_entity->base.source_position.input_name,
4437 "<builtin>") != 0) {
4439 "redundant declaration for '%Y' (declared %P)",
4440 symbol, &previous_entity->base.source_position);
4442 } else if (current_function == NULL) {
4443 if (old_storage_class != STORAGE_CLASS_STATIC &&
4444 new_storage_class == STORAGE_CLASS_STATIC) {
4446 "static declaration of '%Y' follows non-static declaration (declared %P)",
4447 symbol, &previous_entity->base.source_position);
4448 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4449 prev_decl->storage_class = STORAGE_CLASS_NONE;
4450 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4452 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4454 goto error_redeclaration;
4455 goto warn_redundant_declaration;
4457 } else if (is_type_valid(prev_type)) {
4458 if (old_storage_class == new_storage_class) {
4459 error_redeclaration:
4460 errorf(pos, "redeclaration of '%Y' (declared %P)",
4461 symbol, &previous_entity->base.source_position);
4464 "redeclaration of '%Y' with different linkage (declared %P)",
4465 symbol, &previous_entity->base.source_position);
4470 prev_decl->modifiers |= decl->modifiers;
4471 if (entity->kind == ENTITY_FUNCTION) {
4472 previous_entity->function.is_inline |= entity->function.is_inline;
4474 return previous_entity;
4477 if (warning.shadow) {
4478 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4479 get_entity_kind_name(entity->kind), symbol,
4480 get_entity_kind_name(previous_entity->kind),
4481 &previous_entity->base.source_position);
4485 if (entity->kind == ENTITY_FUNCTION) {
4486 if (is_definition &&
4487 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4488 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4489 warningf(pos, "no previous prototype for '%#T'",
4490 entity->declaration.type, symbol);
4491 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4492 warningf(pos, "no previous declaration for '%#T'",
4493 entity->declaration.type, symbol);
4496 } else if (warning.missing_declarations &&
4497 entity->kind == ENTITY_VARIABLE &&
4498 current_scope == file_scope) {
4499 declaration_t *declaration = &entity->declaration;
4500 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4501 warningf(pos, "no previous declaration for '%#T'",
4502 declaration->type, symbol);
4507 assert(entity->base.parent_scope == NULL);
4508 assert(current_scope != NULL);
4510 entity->base.parent_scope = current_scope;
4511 entity->base.namespc = NAMESPACE_NORMAL;
4512 environment_push(entity);
4513 append_entity(current_scope, entity);
4518 static void parser_error_multiple_definition(entity_t *entity,
4519 const source_position_t *source_position)
4521 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4522 entity->base.symbol, &entity->base.source_position);
4525 static bool is_declaration_specifier(const token_t *token,
4526 bool only_specifiers_qualifiers)
4528 switch (token->type) {
4533 return is_typedef_symbol(token->v.symbol);
4535 case T___extension__:
4537 return !only_specifiers_qualifiers;
4544 static void parse_init_declarator_rest(entity_t *entity)
4546 assert(is_declaration(entity));
4547 declaration_t *const declaration = &entity->declaration;
4551 type_t *orig_type = declaration->type;
4552 type_t *type = skip_typeref(orig_type);
4554 if (entity->kind == ENTITY_VARIABLE
4555 && entity->variable.initializer != NULL) {
4556 parser_error_multiple_definition(entity, HERE);
4559 bool must_be_constant = false;
4560 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4561 entity->base.parent_scope == file_scope) {
4562 must_be_constant = true;
4565 if (is_type_function(type)) {
4566 errorf(&entity->base.source_position,
4567 "function '%#T' is initialized like a variable",
4568 orig_type, entity->base.symbol);
4569 orig_type = type_error_type;
4572 parse_initializer_env_t env;
4573 env.type = orig_type;
4574 env.must_be_constant = must_be_constant;
4575 env.entity = entity;
4576 current_init_decl = entity;
4578 initializer_t *initializer = parse_initializer(&env);
4579 current_init_decl = NULL;
4581 if (entity->kind == ENTITY_VARIABLE) {
4582 /* §6.7.5:22 array initializers for arrays with unknown size
4583 * determine the array type size */
4584 declaration->type = env.type;
4585 entity->variable.initializer = initializer;
4589 /* parse rest of a declaration without any declarator */
4590 static void parse_anonymous_declaration_rest(
4591 const declaration_specifiers_t *specifiers)
4594 anonymous_entity = NULL;
4596 if (warning.other) {
4597 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4598 specifiers->thread_local) {
4599 warningf(&specifiers->source_position,
4600 "useless storage class in empty declaration");
4603 type_t *type = specifiers->type;
4604 switch (type->kind) {
4605 case TYPE_COMPOUND_STRUCT:
4606 case TYPE_COMPOUND_UNION: {
4607 if (type->compound.compound->base.symbol == NULL) {
4608 warningf(&specifiers->source_position,
4609 "unnamed struct/union that defines no instances");
4618 warningf(&specifiers->source_position, "empty declaration");
4624 static void check_variable_type_complete(entity_t *ent)
4626 if (ent->kind != ENTITY_VARIABLE)
4629 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4630 * type for the object shall be complete [...] */
4631 declaration_t *decl = &ent->declaration;
4632 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4633 decl->storage_class == STORAGE_CLASS_STATIC)
4636 type_t *const orig_type = decl->type;
4637 type_t *const type = skip_typeref(orig_type);
4638 if (!is_type_incomplete(type))
4641 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4642 * are given length one. */
4643 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4644 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4648 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4649 orig_type, ent->base.symbol);
4653 static void parse_declaration_rest(entity_t *ndeclaration,
4654 const declaration_specifiers_t *specifiers,
4655 parsed_declaration_func finished_declaration,
4656 declarator_flags_t flags)
4658 add_anchor_token(';');
4659 add_anchor_token(',');
4661 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4663 if (token.type == '=') {
4664 parse_init_declarator_rest(entity);
4665 } else if (entity->kind == ENTITY_VARIABLE) {
4666 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4667 * [...] where the extern specifier is explicitly used. */
4668 declaration_t *decl = &entity->declaration;
4669 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4670 type_t *type = decl->type;
4671 if (is_type_reference(skip_typeref(type))) {
4672 errorf(&entity->base.source_position,
4673 "reference '%#T' must be initialized",
4674 type, entity->base.symbol);
4679 check_variable_type_complete(entity);
4681 if (token.type != ',')
4685 add_anchor_token('=');
4686 ndeclaration = parse_declarator(specifiers, flags);
4687 rem_anchor_token('=');
4689 expect(';', end_error);
4692 anonymous_entity = NULL;
4693 rem_anchor_token(';');
4694 rem_anchor_token(',');
4697 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4699 symbol_t *symbol = entity->base.symbol;
4700 if (symbol == NULL) {
4701 errorf(HERE, "anonymous declaration not valid as function parameter");
4705 assert(entity->base.namespc == NAMESPACE_NORMAL);
4706 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4707 if (previous_entity == NULL
4708 || previous_entity->base.parent_scope != current_scope) {
4709 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4714 if (is_definition) {
4715 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4718 return record_entity(entity, false);
4721 static void parse_declaration(parsed_declaration_func finished_declaration,
4722 declarator_flags_t flags)
4724 declaration_specifiers_t specifiers;
4725 memset(&specifiers, 0, sizeof(specifiers));
4727 add_anchor_token(';');
4728 parse_declaration_specifiers(&specifiers);
4729 rem_anchor_token(';');
4731 if (token.type == ';') {
4732 parse_anonymous_declaration_rest(&specifiers);
4734 entity_t *entity = parse_declarator(&specifiers, flags);
4735 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4740 static type_t *get_default_promoted_type(type_t *orig_type)
4742 type_t *result = orig_type;
4744 type_t *type = skip_typeref(orig_type);
4745 if (is_type_integer(type)) {
4746 result = promote_integer(type);
4747 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4748 result = type_double;
4754 static void parse_kr_declaration_list(entity_t *entity)
4756 if (entity->kind != ENTITY_FUNCTION)
4759 type_t *type = skip_typeref(entity->declaration.type);
4760 assert(is_type_function(type));
4761 if (!type->function.kr_style_parameters)
4764 add_anchor_token('{');
4766 /* push function parameters */
4767 size_t const top = environment_top();
4768 scope_t *old_scope = scope_push(&entity->function.parameters);
4770 entity_t *parameter = entity->function.parameters.entities;
4771 for ( ; parameter != NULL; parameter = parameter->base.next) {
4772 assert(parameter->base.parent_scope == NULL);
4773 parameter->base.parent_scope = current_scope;
4774 environment_push(parameter);
4777 /* parse declaration list */
4779 switch (token.type) {
4781 case T___extension__:
4782 /* This covers symbols, which are no type, too, and results in
4783 * better error messages. The typical cases are misspelled type
4784 * names and missing includes. */
4786 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4794 /* pop function parameters */
4795 assert(current_scope == &entity->function.parameters);
4796 scope_pop(old_scope);
4797 environment_pop_to(top);
4799 /* update function type */
4800 type_t *new_type = duplicate_type(type);
4802 function_parameter_t *parameters = NULL;
4803 function_parameter_t **anchor = ¶meters;
4805 /* did we have an earlier prototype? */
4806 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4807 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4810 function_parameter_t *proto_parameter = NULL;
4811 if (proto_type != NULL) {
4812 type_t *proto_type_type = proto_type->declaration.type;
4813 proto_parameter = proto_type_type->function.parameters;
4814 /* If a K&R function definition has a variadic prototype earlier, then
4815 * make the function definition variadic, too. This should conform to
4816 * §6.7.5.3:15 and §6.9.1:8. */
4817 new_type->function.variadic = proto_type_type->function.variadic;
4819 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4821 new_type->function.unspecified_parameters = true;
4824 bool need_incompatible_warning = false;
4825 parameter = entity->function.parameters.entities;
4826 for (; parameter != NULL; parameter = parameter->base.next,
4828 proto_parameter == NULL ? NULL : proto_parameter->next) {
4829 if (parameter->kind != ENTITY_PARAMETER)
4832 type_t *parameter_type = parameter->declaration.type;
4833 if (parameter_type == NULL) {
4835 errorf(HERE, "no type specified for function parameter '%Y'",
4836 parameter->base.symbol);
4837 parameter_type = type_error_type;
4839 if (warning.implicit_int) {
4840 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4841 parameter->base.symbol);
4843 parameter_type = type_int;
4845 parameter->declaration.type = parameter_type;
4848 semantic_parameter_incomplete(parameter);
4850 /* we need the default promoted types for the function type */
4851 type_t *not_promoted = parameter_type;
4852 parameter_type = get_default_promoted_type(parameter_type);
4854 /* gcc special: if the type of the prototype matches the unpromoted
4855 * type don't promote */
4856 if (!strict_mode && proto_parameter != NULL) {
4857 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4858 type_t *promo_skip = skip_typeref(parameter_type);
4859 type_t *param_skip = skip_typeref(not_promoted);
4860 if (!types_compatible(proto_p_type, promo_skip)
4861 && types_compatible(proto_p_type, param_skip)) {
4863 need_incompatible_warning = true;
4864 parameter_type = not_promoted;
4867 function_parameter_t *const parameter
4868 = allocate_parameter(parameter_type);
4870 *anchor = parameter;
4871 anchor = ¶meter->next;
4874 new_type->function.parameters = parameters;
4875 new_type = identify_new_type(new_type);
4877 if (warning.other && need_incompatible_warning) {
4878 type_t *proto_type_type = proto_type->declaration.type;
4880 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4881 proto_type_type, proto_type->base.symbol,
4882 new_type, entity->base.symbol,
4883 &proto_type->base.source_position);
4886 entity->declaration.type = new_type;
4888 rem_anchor_token('{');
4891 static bool first_err = true;
4894 * When called with first_err set, prints the name of the current function,
4897 static void print_in_function(void)
4901 diagnosticf("%s: In function '%Y':\n",
4902 current_function->base.base.source_position.input_name,
4903 current_function->base.base.symbol);
4908 * Check if all labels are defined in the current function.
4909 * Check if all labels are used in the current function.
4911 static void check_labels(void)
4913 for (const goto_statement_t *goto_statement = goto_first;
4914 goto_statement != NULL;
4915 goto_statement = goto_statement->next) {
4916 /* skip computed gotos */
4917 if (goto_statement->expression != NULL)
4920 label_t *label = goto_statement->label;
4923 if (label->base.source_position.input_name == NULL) {
4924 print_in_function();
4925 errorf(&goto_statement->base.source_position,
4926 "label '%Y' used but not defined", label->base.symbol);
4930 if (warning.unused_label) {
4931 for (const label_statement_t *label_statement = label_first;
4932 label_statement != NULL;
4933 label_statement = label_statement->next) {
4934 label_t *label = label_statement->label;
4936 if (! label->used) {
4937 print_in_function();
4938 warningf(&label_statement->base.source_position,
4939 "label '%Y' defined but not used", label->base.symbol);
4945 static void warn_unused_entity(entity_t *entity, entity_t *last)
4947 entity_t const *const end = last != NULL ? last->base.next : NULL;
4948 for (; entity != end; entity = entity->base.next) {
4949 if (!is_declaration(entity))
4952 declaration_t *declaration = &entity->declaration;
4953 if (declaration->implicit)
4956 if (!declaration->used) {
4957 print_in_function();
4958 const char *what = get_entity_kind_name(entity->kind);
4959 warningf(&entity->base.source_position, "%s '%Y' is unused",
4960 what, entity->base.symbol);
4961 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4962 print_in_function();
4963 const char *what = get_entity_kind_name(entity->kind);
4964 warningf(&entity->base.source_position, "%s '%Y' is never read",
4965 what, entity->base.symbol);
4970 static void check_unused_variables(statement_t *const stmt, void *const env)
4974 switch (stmt->kind) {
4975 case STATEMENT_DECLARATION: {
4976 declaration_statement_t const *const decls = &stmt->declaration;
4977 warn_unused_entity(decls->declarations_begin,
4978 decls->declarations_end);
4983 warn_unused_entity(stmt->fors.scope.entities, NULL);
4992 * Check declarations of current_function for unused entities.
4994 static void check_declarations(void)
4996 if (warning.unused_parameter) {
4997 const scope_t *scope = ¤t_function->parameters;
4999 /* do not issue unused warnings for main */
5000 if (!is_sym_main(current_function->base.base.symbol)) {
5001 warn_unused_entity(scope->entities, NULL);
5004 if (warning.unused_variable) {
5005 walk_statements(current_function->statement, check_unused_variables,
5010 static int determine_truth(expression_t const* const cond)
5013 !is_constant_expression(cond) ? 0 :
5014 fold_constant_to_bool(cond) ? 1 :
5018 static void check_reachable(statement_t *);
5019 static bool reaches_end;
5021 static bool expression_returns(expression_t const *const expr)
5023 switch (expr->kind) {
5025 expression_t const *const func = expr->call.function;
5026 if (func->kind == EXPR_REFERENCE) {
5027 entity_t *entity = func->reference.entity;
5028 if (entity->kind == ENTITY_FUNCTION
5029 && entity->declaration.modifiers & DM_NORETURN)
5033 if (!expression_returns(func))
5036 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5037 if (!expression_returns(arg->expression))
5044 case EXPR_REFERENCE:
5045 case EXPR_REFERENCE_ENUM_VALUE:
5047 case EXPR_CHARACTER_CONSTANT:
5048 case EXPR_WIDE_CHARACTER_CONSTANT:
5049 case EXPR_STRING_LITERAL:
5050 case EXPR_WIDE_STRING_LITERAL:
5051 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5052 case EXPR_LABEL_ADDRESS:
5053 case EXPR_CLASSIFY_TYPE:
5054 case EXPR_SIZEOF: // TODO handle obscure VLA case
5057 case EXPR_BUILTIN_CONSTANT_P:
5058 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5063 case EXPR_STATEMENT: {
5064 bool old_reaches_end = reaches_end;
5065 reaches_end = false;
5066 check_reachable(expr->statement.statement);
5067 bool returns = reaches_end;
5068 reaches_end = old_reaches_end;
5072 case EXPR_CONDITIONAL:
5073 // TODO handle constant expression
5075 if (!expression_returns(expr->conditional.condition))
5078 if (expr->conditional.true_expression != NULL
5079 && expression_returns(expr->conditional.true_expression))
5082 return expression_returns(expr->conditional.false_expression);
5085 return expression_returns(expr->select.compound);
5087 case EXPR_ARRAY_ACCESS:
5089 expression_returns(expr->array_access.array_ref) &&
5090 expression_returns(expr->array_access.index);
5093 return expression_returns(expr->va_starte.ap);
5096 return expression_returns(expr->va_arge.ap);
5099 return expression_returns(expr->va_copye.src);
5101 EXPR_UNARY_CASES_MANDATORY
5102 return expression_returns(expr->unary.value);
5104 case EXPR_UNARY_THROW:
5108 // TODO handle constant lhs of && and ||
5110 expression_returns(expr->binary.left) &&
5111 expression_returns(expr->binary.right);
5117 panic("unhandled expression");
5120 static bool initializer_returns(initializer_t const *const init)
5122 switch (init->kind) {
5123 case INITIALIZER_VALUE:
5124 return expression_returns(init->value.value);
5126 case INITIALIZER_LIST: {
5127 initializer_t * const* i = init->list.initializers;
5128 initializer_t * const* const end = i + init->list.len;
5129 bool returns = true;
5130 for (; i != end; ++i) {
5131 if (!initializer_returns(*i))
5137 case INITIALIZER_STRING:
5138 case INITIALIZER_WIDE_STRING:
5139 case INITIALIZER_DESIGNATOR: // designators have no payload
5142 panic("unhandled initializer");
5145 static bool noreturn_candidate;
5147 static void check_reachable(statement_t *const stmt)
5149 if (stmt->base.reachable)
5151 if (stmt->kind != STATEMENT_DO_WHILE)
5152 stmt->base.reachable = true;
5154 statement_t *last = stmt;
5156 switch (stmt->kind) {
5157 case STATEMENT_INVALID:
5158 case STATEMENT_EMPTY:
5160 next = stmt->base.next;
5163 case STATEMENT_DECLARATION: {
5164 declaration_statement_t const *const decl = &stmt->declaration;
5165 entity_t const * ent = decl->declarations_begin;
5166 entity_t const *const last = decl->declarations_end;
5168 for (;; ent = ent->base.next) {
5169 if (ent->kind == ENTITY_VARIABLE &&
5170 ent->variable.initializer != NULL &&
5171 !initializer_returns(ent->variable.initializer)) {
5178 next = stmt->base.next;
5182 case STATEMENT_COMPOUND:
5183 next = stmt->compound.statements;
5185 next = stmt->base.next;
5188 case STATEMENT_RETURN: {
5189 expression_t const *const val = stmt->returns.value;
5190 if (val == NULL || expression_returns(val))
5191 noreturn_candidate = false;
5195 case STATEMENT_IF: {
5196 if_statement_t const *const ifs = &stmt->ifs;
5197 expression_t const *const cond = ifs->condition;
5199 if (!expression_returns(cond))
5202 int const val = determine_truth(cond);
5205 check_reachable(ifs->true_statement);
5210 if (ifs->false_statement != NULL) {
5211 check_reachable(ifs->false_statement);
5215 next = stmt->base.next;
5219 case STATEMENT_SWITCH: {
5220 switch_statement_t const *const switchs = &stmt->switchs;
5221 expression_t const *const expr = switchs->expression;
5223 if (!expression_returns(expr))
5226 if (is_constant_expression(expr)) {
5227 long const val = fold_constant_to_int(expr);
5228 case_label_statement_t * defaults = NULL;
5229 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5230 if (i->expression == NULL) {
5235 if (i->first_case <= val && val <= i->last_case) {
5236 check_reachable((statement_t*)i);
5241 if (defaults != NULL) {
5242 check_reachable((statement_t*)defaults);
5246 bool has_default = false;
5247 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5248 if (i->expression == NULL)
5251 check_reachable((statement_t*)i);
5258 next = stmt->base.next;
5262 case STATEMENT_EXPRESSION: {
5263 /* Check for noreturn function call */
5264 expression_t const *const expr = stmt->expression.expression;
5265 if (!expression_returns(expr))
5268 next = stmt->base.next;
5272 case STATEMENT_CONTINUE: {
5273 statement_t *parent = stmt;
5275 parent = parent->base.parent;
5276 if (parent == NULL) /* continue not within loop */
5280 switch (parent->kind) {
5281 case STATEMENT_WHILE: goto continue_while;
5282 case STATEMENT_DO_WHILE: goto continue_do_while;
5283 case STATEMENT_FOR: goto continue_for;
5290 case STATEMENT_BREAK: {
5291 statement_t *parent = stmt;
5293 parent = parent->base.parent;
5294 if (parent == NULL) /* break not within loop/switch */
5297 switch (parent->kind) {
5298 case STATEMENT_SWITCH:
5299 case STATEMENT_WHILE:
5300 case STATEMENT_DO_WHILE:
5303 next = parent->base.next;
5304 goto found_break_parent;
5313 case STATEMENT_GOTO:
5314 if (stmt->gotos.expression) {
5315 if (!expression_returns(stmt->gotos.expression))
5318 statement_t *parent = stmt->base.parent;
5319 if (parent == NULL) /* top level goto */
5323 next = stmt->gotos.label->statement;
5324 if (next == NULL) /* missing label */
5329 case STATEMENT_LABEL:
5330 next = stmt->label.statement;
5333 case STATEMENT_CASE_LABEL:
5334 next = stmt->case_label.statement;
5337 case STATEMENT_WHILE: {
5338 while_statement_t const *const whiles = &stmt->whiles;
5339 expression_t const *const cond = whiles->condition;
5341 if (!expression_returns(cond))
5344 int const val = determine_truth(cond);
5347 check_reachable(whiles->body);
5352 next = stmt->base.next;
5356 case STATEMENT_DO_WHILE:
5357 next = stmt->do_while.body;
5360 case STATEMENT_FOR: {
5361 for_statement_t *const fors = &stmt->fors;
5363 if (fors->condition_reachable)
5365 fors->condition_reachable = true;
5367 expression_t const *const cond = fors->condition;
5372 } else if (expression_returns(cond)) {
5373 val = determine_truth(cond);
5379 check_reachable(fors->body);
5384 next = stmt->base.next;
5388 case STATEMENT_MS_TRY: {
5389 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5390 check_reachable(ms_try->try_statement);
5391 next = ms_try->final_statement;
5395 case STATEMENT_LEAVE: {
5396 statement_t *parent = stmt;
5398 parent = parent->base.parent;
5399 if (parent == NULL) /* __leave not within __try */
5402 if (parent->kind == STATEMENT_MS_TRY) {
5404 next = parent->ms_try.final_statement;
5412 panic("invalid statement kind");
5415 while (next == NULL) {
5416 next = last->base.parent;
5418 noreturn_candidate = false;
5420 type_t *const type = skip_typeref(current_function->base.type);
5421 assert(is_type_function(type));
5422 type_t *const ret = skip_typeref(type->function.return_type);
5423 if (warning.return_type &&
5424 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5425 is_type_valid(ret) &&
5426 !is_sym_main(current_function->base.base.symbol)) {
5427 warningf(&stmt->base.source_position,
5428 "control reaches end of non-void function");
5433 switch (next->kind) {
5434 case STATEMENT_INVALID:
5435 case STATEMENT_EMPTY:
5436 case STATEMENT_DECLARATION:
5437 case STATEMENT_EXPRESSION:
5439 case STATEMENT_RETURN:
5440 case STATEMENT_CONTINUE:
5441 case STATEMENT_BREAK:
5442 case STATEMENT_GOTO:
5443 case STATEMENT_LEAVE:
5444 panic("invalid control flow in function");
5446 case STATEMENT_COMPOUND:
5447 if (next->compound.stmt_expr) {
5453 case STATEMENT_SWITCH:
5454 case STATEMENT_LABEL:
5455 case STATEMENT_CASE_LABEL:
5457 next = next->base.next;
5460 case STATEMENT_WHILE: {
5462 if (next->base.reachable)
5464 next->base.reachable = true;
5466 while_statement_t const *const whiles = &next->whiles;
5467 expression_t const *const cond = whiles->condition;
5469 if (!expression_returns(cond))
5472 int const val = determine_truth(cond);
5475 check_reachable(whiles->body);
5481 next = next->base.next;
5485 case STATEMENT_DO_WHILE: {
5487 if (next->base.reachable)
5489 next->base.reachable = true;
5491 do_while_statement_t const *const dw = &next->do_while;
5492 expression_t const *const cond = dw->condition;
5494 if (!expression_returns(cond))
5497 int const val = determine_truth(cond);
5500 check_reachable(dw->body);
5506 next = next->base.next;
5510 case STATEMENT_FOR: {
5512 for_statement_t *const fors = &next->fors;
5514 fors->step_reachable = true;
5516 if (fors->condition_reachable)
5518 fors->condition_reachable = true;
5520 expression_t const *const cond = fors->condition;
5525 } else if (expression_returns(cond)) {
5526 val = determine_truth(cond);
5532 check_reachable(fors->body);
5538 next = next->base.next;
5542 case STATEMENT_MS_TRY:
5544 next = next->ms_try.final_statement;
5549 check_reachable(next);
5552 static void check_unreachable(statement_t* const stmt, void *const env)
5556 switch (stmt->kind) {
5557 case STATEMENT_DO_WHILE:
5558 if (!stmt->base.reachable) {
5559 expression_t const *const cond = stmt->do_while.condition;
5560 if (determine_truth(cond) >= 0) {
5561 warningf(&cond->base.source_position,
5562 "condition of do-while-loop is unreachable");
5567 case STATEMENT_FOR: {
5568 for_statement_t const* const fors = &stmt->fors;
5570 // if init and step are unreachable, cond is unreachable, too
5571 if (!stmt->base.reachable && !fors->step_reachable) {
5572 warningf(&stmt->base.source_position, "statement is unreachable");
5574 if (!stmt->base.reachable && fors->initialisation != NULL) {
5575 warningf(&fors->initialisation->base.source_position,
5576 "initialisation of for-statement is unreachable");
5579 if (!fors->condition_reachable && fors->condition != NULL) {
5580 warningf(&fors->condition->base.source_position,
5581 "condition of for-statement is unreachable");
5584 if (!fors->step_reachable && fors->step != NULL) {
5585 warningf(&fors->step->base.source_position,
5586 "step of for-statement is unreachable");
5592 case STATEMENT_COMPOUND:
5593 if (stmt->compound.statements != NULL)
5595 goto warn_unreachable;
5597 case STATEMENT_DECLARATION: {
5598 /* Only warn if there is at least one declarator with an initializer.
5599 * This typically occurs in switch statements. */
5600 declaration_statement_t const *const decl = &stmt->declaration;
5601 entity_t const * ent = decl->declarations_begin;
5602 entity_t const *const last = decl->declarations_end;
5604 for (;; ent = ent->base.next) {
5605 if (ent->kind == ENTITY_VARIABLE &&
5606 ent->variable.initializer != NULL) {
5607 goto warn_unreachable;
5617 if (!stmt->base.reachable)
5618 warningf(&stmt->base.source_position, "statement is unreachable");
5623 static void parse_external_declaration(void)
5625 /* function-definitions and declarations both start with declaration
5627 declaration_specifiers_t specifiers;
5628 memset(&specifiers, 0, sizeof(specifiers));
5630 add_anchor_token(';');
5631 parse_declaration_specifiers(&specifiers);
5632 rem_anchor_token(';');
5634 /* must be a declaration */
5635 if (token.type == ';') {
5636 parse_anonymous_declaration_rest(&specifiers);
5640 add_anchor_token(',');
5641 add_anchor_token('=');
5642 add_anchor_token(';');
5643 add_anchor_token('{');
5645 /* declarator is common to both function-definitions and declarations */
5646 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5648 rem_anchor_token('{');
5649 rem_anchor_token(';');
5650 rem_anchor_token('=');
5651 rem_anchor_token(',');
5653 /* must be a declaration */
5654 switch (token.type) {
5658 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5663 /* must be a function definition */
5664 parse_kr_declaration_list(ndeclaration);
5666 if (token.type != '{') {
5667 parse_error_expected("while parsing function definition", '{', NULL);
5668 eat_until_matching_token(';');
5672 assert(is_declaration(ndeclaration));
5673 type_t *const orig_type = ndeclaration->declaration.type;
5674 type_t * type = skip_typeref(orig_type);
5676 if (!is_type_function(type)) {
5677 if (is_type_valid(type)) {
5678 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5679 type, ndeclaration->base.symbol);
5683 } else if (is_typeref(orig_type)) {
5685 errorf(&ndeclaration->base.source_position,
5686 "type of function definition '%#T' is a typedef",
5687 orig_type, ndeclaration->base.symbol);
5690 if (warning.aggregate_return &&
5691 is_type_compound(skip_typeref(type->function.return_type))) {
5692 warningf(HERE, "function '%Y' returns an aggregate",
5693 ndeclaration->base.symbol);
5695 if (warning.traditional && !type->function.unspecified_parameters) {
5696 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5697 ndeclaration->base.symbol);
5699 if (warning.old_style_definition && type->function.unspecified_parameters) {
5700 warningf(HERE, "old-style function definition '%Y'",
5701 ndeclaration->base.symbol);
5704 /* §6.7.5.3:14 a function definition with () means no
5705 * parameters (and not unspecified parameters) */
5706 if (type->function.unspecified_parameters &&
5707 type->function.parameters == NULL) {
5708 type_t *copy = duplicate_type(type);
5709 copy->function.unspecified_parameters = false;
5710 type = identify_new_type(copy);
5712 ndeclaration->declaration.type = type;
5715 entity_t *const entity = record_entity(ndeclaration, true);
5716 assert(entity->kind == ENTITY_FUNCTION);
5717 assert(ndeclaration->kind == ENTITY_FUNCTION);
5719 function_t *function = &entity->function;
5720 if (ndeclaration != entity) {
5721 function->parameters = ndeclaration->function.parameters;
5723 assert(is_declaration(entity));
5724 type = skip_typeref(entity->declaration.type);
5726 /* push function parameters and switch scope */
5727 size_t const top = environment_top();
5728 scope_t *old_scope = scope_push(&function->parameters);
5730 entity_t *parameter = function->parameters.entities;
5731 for (; parameter != NULL; parameter = parameter->base.next) {
5732 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5733 parameter->base.parent_scope = current_scope;
5735 assert(parameter->base.parent_scope == NULL
5736 || parameter->base.parent_scope == current_scope);
5737 parameter->base.parent_scope = current_scope;
5738 if (parameter->base.symbol == NULL) {
5739 errorf(¶meter->base.source_position, "parameter name omitted");
5742 environment_push(parameter);
5745 if (function->statement != NULL) {
5746 parser_error_multiple_definition(entity, HERE);
5749 /* parse function body */
5750 int label_stack_top = label_top();
5751 function_t *old_current_function = current_function;
5752 current_function = function;
5753 current_parent = NULL;
5756 goto_anchor = &goto_first;
5758 label_anchor = &label_first;
5760 statement_t *const body = parse_compound_statement(false);
5761 function->statement = body;
5764 check_declarations();
5765 if (warning.return_type ||
5766 warning.unreachable_code ||
5767 (warning.missing_noreturn
5768 && !(function->base.modifiers & DM_NORETURN))) {
5769 noreturn_candidate = true;
5770 check_reachable(body);
5771 if (warning.unreachable_code)
5772 walk_statements(body, check_unreachable, NULL);
5773 if (warning.missing_noreturn &&
5774 noreturn_candidate &&
5775 !(function->base.modifiers & DM_NORETURN)) {
5776 warningf(&body->base.source_position,
5777 "function '%#T' is candidate for attribute 'noreturn'",
5778 type, entity->base.symbol);
5782 assert(current_parent == NULL);
5783 assert(current_function == function);
5784 current_function = old_current_function;
5785 label_pop_to(label_stack_top);
5788 assert(current_scope == &function->parameters);
5789 scope_pop(old_scope);
5790 environment_pop_to(top);
5793 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5794 source_position_t *source_position,
5795 const symbol_t *symbol)
5797 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5799 type->bitfield.base_type = base_type;
5800 type->bitfield.size_expression = size;
5803 type_t *skipped_type = skip_typeref(base_type);
5804 if (!is_type_integer(skipped_type)) {
5805 errorf(HERE, "bitfield base type '%T' is not an integer type",
5809 bit_size = get_type_size(base_type) * 8;
5812 if (is_constant_expression(size)) {
5813 long v = fold_constant_to_int(size);
5814 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5817 errorf(source_position, "negative width in bit-field '%Y'",
5819 } else if (v == 0 && symbol != NULL) {
5820 errorf(source_position, "zero width for bit-field '%Y'",
5822 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5823 errorf(source_position, "width of '%Y' exceeds its type",
5826 type->bitfield.bit_size = v;
5833 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5835 entity_t *iter = compound->members.entities;
5836 for (; iter != NULL; iter = iter->base.next) {
5837 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5840 if (iter->base.symbol == symbol) {
5842 } else if (iter->base.symbol == NULL) {
5843 /* search in anonymous structs and unions */
5844 type_t *type = skip_typeref(iter->declaration.type);
5845 if (is_type_compound(type)) {
5846 if (find_compound_entry(type->compound.compound, symbol)
5857 static void check_deprecated(const source_position_t *source_position,
5858 const entity_t *entity)
5860 if (!warning.deprecated_declarations)
5862 if (!is_declaration(entity))
5864 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5867 char const *const prefix = get_entity_kind_name(entity->kind);
5868 const char *deprecated_string
5869 = get_deprecated_string(entity->declaration.attributes);
5870 if (deprecated_string != NULL) {
5871 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5872 prefix, entity->base.symbol, &entity->base.source_position,
5875 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5876 entity->base.symbol, &entity->base.source_position);
5881 static expression_t *create_select(const source_position_t *pos,
5883 type_qualifiers_t qualifiers,
5886 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5888 check_deprecated(pos, entry);
5890 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5891 select->select.compound = addr;
5892 select->select.compound_entry = entry;
5894 type_t *entry_type = entry->declaration.type;
5895 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5897 /* we always do the auto-type conversions; the & and sizeof parser contains
5898 * code to revert this! */
5899 select->base.type = automatic_type_conversion(res_type);
5900 if (res_type->kind == TYPE_BITFIELD) {
5901 select->base.type = res_type->bitfield.base_type;
5908 * Find entry with symbol in compound. Search anonymous structs and unions and
5909 * creates implicit select expressions for them.
5910 * Returns the adress for the innermost compound.
5912 static expression_t *find_create_select(const source_position_t *pos,
5914 type_qualifiers_t qualifiers,
5915 compound_t *compound, symbol_t *symbol)
5917 entity_t *iter = compound->members.entities;
5918 for (; iter != NULL; iter = iter->base.next) {
5919 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5922 symbol_t *iter_symbol = iter->base.symbol;
5923 if (iter_symbol == NULL) {
5924 type_t *type = iter->declaration.type;
5925 if (type->kind != TYPE_COMPOUND_STRUCT
5926 && type->kind != TYPE_COMPOUND_UNION)
5929 compound_t *sub_compound = type->compound.compound;
5931 if (find_compound_entry(sub_compound, symbol) == NULL)
5934 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5935 sub_addr->base.source_position = *pos;
5936 sub_addr->select.implicit = true;
5937 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5941 if (iter_symbol == symbol) {
5942 return create_select(pos, addr, qualifiers, iter);
5949 static void parse_compound_declarators(compound_t *compound,
5950 const declaration_specifiers_t *specifiers)
5955 if (token.type == ':') {
5956 source_position_t source_position = *HERE;
5959 type_t *base_type = specifiers->type;
5960 expression_t *size = parse_constant_expression();
5962 type_t *type = make_bitfield_type(base_type, size,
5963 &source_position, NULL);
5965 attribute_t *attributes = parse_attributes(NULL);
5966 if (attributes != NULL) {
5967 attribute_t *last = attributes;
5968 while (last->next != NULL)
5970 last->next = specifiers->attributes;
5972 attributes = specifiers->attributes;
5975 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5976 entity->base.namespc = NAMESPACE_NORMAL;
5977 entity->base.source_position = source_position;
5978 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5979 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5980 entity->declaration.type = type;
5981 entity->declaration.attributes = attributes;
5983 if (attributes != NULL) {
5984 handle_entity_attributes(attributes, entity);
5986 append_entity(&compound->members, entity);
5988 entity = parse_declarator(specifiers,
5989 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5990 if (entity->kind == ENTITY_TYPEDEF) {
5991 errorf(&entity->base.source_position,
5992 "typedef not allowed as compound member");
5994 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5996 /* make sure we don't define a symbol multiple times */
5997 symbol_t *symbol = entity->base.symbol;
5998 if (symbol != NULL) {
5999 entity_t *prev = find_compound_entry(compound, symbol);
6001 errorf(&entity->base.source_position,
6002 "multiple declarations of symbol '%Y' (declared %P)",
6003 symbol, &prev->base.source_position);
6007 if (token.type == ':') {
6008 source_position_t source_position = *HERE;
6010 expression_t *size = parse_constant_expression();
6012 type_t *type = entity->declaration.type;
6013 type_t *bitfield_type = make_bitfield_type(type, size,
6014 &source_position, entity->base.symbol);
6016 attribute_t *attributes = parse_attributes(NULL);
6017 entity->declaration.type = bitfield_type;
6018 handle_entity_attributes(attributes, entity);
6020 type_t *orig_type = entity->declaration.type;
6021 type_t *type = skip_typeref(orig_type);
6022 if (is_type_function(type)) {
6023 errorf(&entity->base.source_position,
6024 "compound member '%Y' must not have function type '%T'",
6025 entity->base.symbol, orig_type);
6026 } else if (is_type_incomplete(type)) {
6027 /* §6.7.2.1:16 flexible array member */
6028 if (!is_type_array(type) ||
6029 token.type != ';' ||
6030 look_ahead(1)->type != '}') {
6031 errorf(&entity->base.source_position,
6032 "compound member '%Y' has incomplete type '%T'",
6033 entity->base.symbol, orig_type);
6038 append_entity(&compound->members, entity);
6042 if (token.type != ',')
6046 expect(';', end_error);
6049 anonymous_entity = NULL;
6052 static void parse_compound_type_entries(compound_t *compound)
6055 add_anchor_token('}');
6057 while (token.type != '}') {
6058 if (token.type == T_EOF) {
6059 errorf(HERE, "EOF while parsing struct");
6062 declaration_specifiers_t specifiers;
6063 memset(&specifiers, 0, sizeof(specifiers));
6064 parse_declaration_specifiers(&specifiers);
6066 parse_compound_declarators(compound, &specifiers);
6068 rem_anchor_token('}');
6072 compound->complete = true;
6075 static type_t *parse_typename(void)
6077 declaration_specifiers_t specifiers;
6078 memset(&specifiers, 0, sizeof(specifiers));
6079 parse_declaration_specifiers(&specifiers);
6080 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6081 specifiers.thread_local) {
6082 /* TODO: improve error message, user does probably not know what a
6083 * storage class is...
6085 errorf(HERE, "typename may not have a storage class");
6088 type_t *result = parse_abstract_declarator(specifiers.type);
6096 typedef expression_t* (*parse_expression_function)(void);
6097 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6099 typedef struct expression_parser_function_t expression_parser_function_t;
6100 struct expression_parser_function_t {
6101 parse_expression_function parser;
6102 precedence_t infix_precedence;
6103 parse_expression_infix_function infix_parser;
6106 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6109 * Prints an error message if an expression was expected but not read
6111 static expression_t *expected_expression_error(void)
6113 /* skip the error message if the error token was read */
6114 if (token.type != T_ERROR) {
6115 errorf(HERE, "expected expression, got token %K", &token);
6119 return create_invalid_expression();
6123 * Parse a string constant.
6125 static expression_t *parse_string_const(void)
6128 if (token.type == T_STRING_LITERAL) {
6129 string_t res = token.v.string;
6131 while (token.type == T_STRING_LITERAL) {
6132 res = concat_strings(&res, &token.v.string);
6135 if (token.type != T_WIDE_STRING_LITERAL) {
6136 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6137 /* note: that we use type_char_ptr here, which is already the
6138 * automatic converted type. revert_automatic_type_conversion
6139 * will construct the array type */
6140 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6141 cnst->string.value = res;
6145 wres = concat_string_wide_string(&res, &token.v.wide_string);
6147 wres = token.v.wide_string;
6152 switch (token.type) {
6153 case T_WIDE_STRING_LITERAL:
6154 wres = concat_wide_strings(&wres, &token.v.wide_string);
6157 case T_STRING_LITERAL:
6158 wres = concat_wide_string_string(&wres, &token.v.string);
6162 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6163 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6164 cnst->wide_string.value = wres;
6173 * Parse a boolean constant.
6175 static expression_t *parse_bool_const(bool value)
6177 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6178 cnst->base.type = type_bool;
6179 cnst->conste.v.int_value = value;
6187 * Parse an integer constant.
6189 static expression_t *parse_int_const(void)
6191 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6192 cnst->base.type = token.datatype;
6193 cnst->conste.v.int_value = token.v.intvalue;
6201 * Parse a character constant.
6203 static expression_t *parse_character_constant(void)
6205 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6206 cnst->base.type = token.datatype;
6207 cnst->conste.v.character = token.v.string;
6209 if (cnst->conste.v.character.size != 1) {
6211 errorf(HERE, "more than 1 character in character constant");
6212 } else if (warning.multichar) {
6213 warningf(HERE, "multi-character character constant");
6222 * Parse a wide character constant.
6224 static expression_t *parse_wide_character_constant(void)
6226 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6227 cnst->base.type = token.datatype;
6228 cnst->conste.v.wide_character = token.v.wide_string;
6230 if (cnst->conste.v.wide_character.size != 1) {
6232 errorf(HERE, "more than 1 character in character constant");
6233 } else if (warning.multichar) {
6234 warningf(HERE, "multi-character character constant");
6243 * Parse a float constant.
6245 static expression_t *parse_float_const(void)
6247 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6248 cnst->base.type = token.datatype;
6249 cnst->conste.v.float_value = token.v.floatvalue;
6256 static entity_t *create_implicit_function(symbol_t *symbol,
6257 const source_position_t *source_position)
6259 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6260 ntype->function.return_type = type_int;
6261 ntype->function.unspecified_parameters = true;
6262 ntype->function.linkage = LINKAGE_C;
6263 type_t *type = identify_new_type(ntype);
6265 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6266 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6267 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6268 entity->declaration.type = type;
6269 entity->declaration.implicit = true;
6270 entity->base.symbol = symbol;
6271 entity->base.source_position = *source_position;
6273 if (current_scope != NULL) {
6274 bool strict_prototypes_old = warning.strict_prototypes;
6275 warning.strict_prototypes = false;
6276 record_entity(entity, false);
6277 warning.strict_prototypes = strict_prototypes_old;
6284 * Creates a return_type (func)(argument_type) function type if not
6287 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6288 type_t *argument_type2)
6290 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6291 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6292 parameter1->next = parameter2;
6294 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6295 type->function.return_type = return_type;
6296 type->function.parameters = parameter1;
6298 return identify_new_type(type);
6302 * Creates a return_type (func)(argument_type) function type if not
6305 * @param return_type the return type
6306 * @param argument_type the argument type
6308 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6310 function_parameter_t *const parameter = allocate_parameter(argument_type);
6312 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6313 type->function.return_type = return_type;
6314 type->function.parameters = parameter;
6316 return identify_new_type(type);
6320 * Creates a return_type (func)(argument_type, ...) function type if not
6323 * @param return_type the return type
6324 * @param argument_type the argument type
6326 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6328 function_parameter_t *const parameter = allocate_parameter(argument_type);
6330 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6331 type->function.return_type = return_type;
6332 type->function.parameters = parameter;
6333 type->function.variadic = true;
6335 return identify_new_type(type);
6339 * Creates a return_type (func)(void) function type if not
6342 * @param return_type the return type
6344 static type_t *make_function_0_type(type_t *return_type)
6346 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6347 type->function.return_type = return_type;
6348 type->function.parameters = NULL;
6350 return identify_new_type(type);
6354 * Creates a NO_RETURN return_type (func)(void) function type if not
6357 * @param return_type the return type
6359 static type_t *make_function_0_type_noreturn(type_t *return_type)
6361 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6362 type->function.return_type = return_type;
6363 type->function.parameters = NULL;
6364 type->function.modifiers |= DM_NORETURN;
6365 return identify_new_type(type);
6369 * Performs automatic type cast as described in §6.3.2.1.
6371 * @param orig_type the original type
6373 static type_t *automatic_type_conversion(type_t *orig_type)
6375 type_t *type = skip_typeref(orig_type);
6376 if (is_type_array(type)) {
6377 array_type_t *array_type = &type->array;
6378 type_t *element_type = array_type->element_type;
6379 unsigned qualifiers = array_type->base.qualifiers;
6381 return make_pointer_type(element_type, qualifiers);
6384 if (is_type_function(type)) {
6385 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6392 * reverts the automatic casts of array to pointer types and function
6393 * to function-pointer types as defined §6.3.2.1
6395 type_t *revert_automatic_type_conversion(const expression_t *expression)
6397 switch (expression->kind) {
6398 case EXPR_REFERENCE: {
6399 entity_t *entity = expression->reference.entity;
6400 if (is_declaration(entity)) {
6401 return entity->declaration.type;
6402 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6403 return entity->enum_value.enum_type;
6405 panic("no declaration or enum in reference");
6410 entity_t *entity = expression->select.compound_entry;
6411 assert(is_declaration(entity));
6412 type_t *type = entity->declaration.type;
6413 return get_qualified_type(type,
6414 expression->base.type->base.qualifiers);
6417 case EXPR_UNARY_DEREFERENCE: {
6418 const expression_t *const value = expression->unary.value;
6419 type_t *const type = skip_typeref(value->base.type);
6420 if (!is_type_pointer(type))
6421 return type_error_type;
6422 return type->pointer.points_to;
6425 case EXPR_ARRAY_ACCESS: {
6426 const expression_t *array_ref = expression->array_access.array_ref;
6427 type_t *type_left = skip_typeref(array_ref->base.type);
6428 if (!is_type_pointer(type_left))
6429 return type_error_type;
6430 return type_left->pointer.points_to;
6433 case EXPR_STRING_LITERAL: {
6434 size_t size = expression->string.value.size;
6435 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6438 case EXPR_WIDE_STRING_LITERAL: {
6439 size_t size = expression->wide_string.value.size;
6440 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6443 case EXPR_COMPOUND_LITERAL:
6444 return expression->compound_literal.type;
6447 return expression->base.type;
6452 * Find an entity matching a symbol in a scope.
6453 * Uses current scope if scope is NULL
6455 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6456 namespace_tag_t namespc)
6458 if (scope == NULL) {
6459 return get_entity(symbol, namespc);
6462 /* we should optimize here, if scope grows above a certain size we should
6463 construct a hashmap here... */
6464 entity_t *entity = scope->entities;
6465 for ( ; entity != NULL; entity = entity->base.next) {
6466 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6473 static entity_t *parse_qualified_identifier(void)
6475 /* namespace containing the symbol */
6477 const scope_t *lookup_scope = NULL;
6479 if (token.type == T_COLONCOLON) {
6481 lookup_scope = &unit->scope;
6486 if (token.type != T_IDENTIFIER) {
6487 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6488 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6490 symbol = token.v.symbol;
6494 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6496 if (token.type != T_COLONCOLON)
6500 switch (entity->kind) {
6501 case ENTITY_NAMESPACE:
6502 lookup_scope = &entity->namespacee.members;
6507 lookup_scope = &entity->compound.members;
6510 errorf(HERE, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6511 symbol, get_entity_kind_name(entity->kind));
6516 if (entity == NULL) {
6517 if (!strict_mode && token.type == '(') {
6518 /* an implicitly declared function */
6519 if (warning.error_implicit_function_declaration) {
6520 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6521 } else if (warning.implicit_function_declaration) {
6522 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6525 entity = create_implicit_function(symbol, HERE);
6527 errorf(HERE, "unknown identifier '%Y' found.", symbol);
6528 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6535 /* skip further qualifications */
6536 while (token.type == T_IDENTIFIER) {
6538 if (token.type != T_COLONCOLON)
6543 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6546 static expression_t *parse_reference(void)
6548 entity_t *entity = parse_qualified_identifier();
6551 if (is_declaration(entity)) {
6552 orig_type = entity->declaration.type;
6553 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6554 orig_type = entity->enum_value.enum_type;
6556 panic("expected declaration or enum value in reference");
6559 /* we always do the auto-type conversions; the & and sizeof parser contains
6560 * code to revert this! */
6561 type_t *type = automatic_type_conversion(orig_type);
6563 expression_kind_t kind = EXPR_REFERENCE;
6564 if (entity->kind == ENTITY_ENUM_VALUE)
6565 kind = EXPR_REFERENCE_ENUM_VALUE;
6567 expression_t *expression = allocate_expression_zero(kind);
6568 expression->reference.entity = entity;
6569 expression->base.type = type;
6571 /* this declaration is used */
6572 if (is_declaration(entity)) {
6573 entity->declaration.used = true;
6576 if (entity->base.parent_scope != file_scope
6577 && (current_function != NULL
6578 && entity->base.parent_scope->depth < current_function->parameters.depth)
6579 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6580 if (entity->kind == ENTITY_VARIABLE) {
6581 /* access of a variable from an outer function */
6582 entity->variable.address_taken = true;
6583 } else if (entity->kind == ENTITY_PARAMETER) {
6584 entity->parameter.address_taken = true;
6586 current_function->need_closure = true;
6589 check_deprecated(HERE, entity);
6591 if (warning.init_self && entity == current_init_decl && !in_type_prop
6592 && entity->kind == ENTITY_VARIABLE) {
6593 current_init_decl = NULL;
6594 warningf(HERE, "variable '%#T' is initialized by itself",
6595 entity->declaration.type, entity->base.symbol);
6601 static bool semantic_cast(expression_t *cast)
6603 expression_t *expression = cast->unary.value;
6604 type_t *orig_dest_type = cast->base.type;
6605 type_t *orig_type_right = expression->base.type;
6606 type_t const *dst_type = skip_typeref(orig_dest_type);
6607 type_t const *src_type = skip_typeref(orig_type_right);
6608 source_position_t const *pos = &cast->base.source_position;
6610 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6611 if (dst_type == type_void)
6614 /* only integer and pointer can be casted to pointer */
6615 if (is_type_pointer(dst_type) &&
6616 !is_type_pointer(src_type) &&
6617 !is_type_integer(src_type) &&
6618 is_type_valid(src_type)) {
6619 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6623 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6624 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6628 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6629 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6633 if (warning.cast_qual &&
6634 is_type_pointer(src_type) &&
6635 is_type_pointer(dst_type)) {
6636 type_t *src = skip_typeref(src_type->pointer.points_to);
6637 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6638 unsigned missing_qualifiers =
6639 src->base.qualifiers & ~dst->base.qualifiers;
6640 if (missing_qualifiers != 0) {
6642 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6643 missing_qualifiers, orig_type_right);
6649 static expression_t *parse_compound_literal(type_t *type)
6651 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6653 parse_initializer_env_t env;
6656 env.must_be_constant = false;
6657 initializer_t *initializer = parse_initializer(&env);
6660 expression->compound_literal.initializer = initializer;
6661 expression->compound_literal.type = type;
6662 expression->base.type = automatic_type_conversion(type);
6668 * Parse a cast expression.
6670 static expression_t *parse_cast(void)
6672 add_anchor_token(')');
6674 source_position_t source_position = token.source_position;
6676 type_t *type = parse_typename();
6678 rem_anchor_token(')');
6679 expect(')', end_error);
6681 if (token.type == '{') {
6682 return parse_compound_literal(type);
6685 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6686 cast->base.source_position = source_position;
6688 expression_t *value = parse_sub_expression(PREC_CAST);
6689 cast->base.type = type;
6690 cast->unary.value = value;
6692 if (! semantic_cast(cast)) {
6693 /* TODO: record the error in the AST. else it is impossible to detect it */
6698 return create_invalid_expression();
6702 * Parse a statement expression.
6704 static expression_t *parse_statement_expression(void)
6706 add_anchor_token(')');
6708 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6710 statement_t *statement = parse_compound_statement(true);
6711 statement->compound.stmt_expr = true;
6712 expression->statement.statement = statement;
6714 /* find last statement and use its type */
6715 type_t *type = type_void;
6716 const statement_t *stmt = statement->compound.statements;
6718 while (stmt->base.next != NULL)
6719 stmt = stmt->base.next;
6721 if (stmt->kind == STATEMENT_EXPRESSION) {
6722 type = stmt->expression.expression->base.type;
6724 } else if (warning.other) {
6725 warningf(&expression->base.source_position, "empty statement expression ({})");
6727 expression->base.type = type;
6729 rem_anchor_token(')');
6730 expect(')', end_error);
6737 * Parse a parenthesized expression.
6739 static expression_t *parse_parenthesized_expression(void)
6743 switch (token.type) {
6745 /* gcc extension: a statement expression */
6746 return parse_statement_expression();
6750 return parse_cast();
6752 if (is_typedef_symbol(token.v.symbol)) {
6753 return parse_cast();
6757 add_anchor_token(')');
6758 expression_t *result = parse_expression();
6759 result->base.parenthesized = true;
6760 rem_anchor_token(')');
6761 expect(')', end_error);
6767 static expression_t *parse_function_keyword(void)
6771 if (current_function == NULL) {
6772 errorf(HERE, "'__func__' used outside of a function");
6775 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6776 expression->base.type = type_char_ptr;
6777 expression->funcname.kind = FUNCNAME_FUNCTION;
6784 static expression_t *parse_pretty_function_keyword(void)
6786 if (current_function == NULL) {
6787 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6790 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6791 expression->base.type = type_char_ptr;
6792 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6794 eat(T___PRETTY_FUNCTION__);
6799 static expression_t *parse_funcsig_keyword(void)
6801 if (current_function == NULL) {
6802 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6805 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6806 expression->base.type = type_char_ptr;
6807 expression->funcname.kind = FUNCNAME_FUNCSIG;
6814 static expression_t *parse_funcdname_keyword(void)
6816 if (current_function == NULL) {
6817 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6820 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6821 expression->base.type = type_char_ptr;
6822 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6824 eat(T___FUNCDNAME__);
6829 static designator_t *parse_designator(void)
6831 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6832 result->source_position = *HERE;
6834 if (token.type != T_IDENTIFIER) {
6835 parse_error_expected("while parsing member designator",
6836 T_IDENTIFIER, NULL);
6839 result->symbol = token.v.symbol;
6842 designator_t *last_designator = result;
6844 if (token.type == '.') {
6846 if (token.type != T_IDENTIFIER) {
6847 parse_error_expected("while parsing member designator",
6848 T_IDENTIFIER, NULL);
6851 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6852 designator->source_position = *HERE;
6853 designator->symbol = token.v.symbol;
6856 last_designator->next = designator;
6857 last_designator = designator;
6860 if (token.type == '[') {
6862 add_anchor_token(']');
6863 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6864 designator->source_position = *HERE;
6865 designator->array_index = parse_expression();
6866 rem_anchor_token(']');
6867 expect(']', end_error);
6868 if (designator->array_index == NULL) {
6872 last_designator->next = designator;
6873 last_designator = designator;
6885 * Parse the __builtin_offsetof() expression.
6887 static expression_t *parse_offsetof(void)
6889 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6890 expression->base.type = type_size_t;
6892 eat(T___builtin_offsetof);
6894 expect('(', end_error);
6895 add_anchor_token(',');
6896 type_t *type = parse_typename();
6897 rem_anchor_token(',');
6898 expect(',', end_error);
6899 add_anchor_token(')');
6900 designator_t *designator = parse_designator();
6901 rem_anchor_token(')');
6902 expect(')', end_error);
6904 expression->offsetofe.type = type;
6905 expression->offsetofe.designator = designator;
6908 memset(&path, 0, sizeof(path));
6909 path.top_type = type;
6910 path.path = NEW_ARR_F(type_path_entry_t, 0);
6912 descend_into_subtype(&path);
6914 if (!walk_designator(&path, designator, true)) {
6915 return create_invalid_expression();
6918 DEL_ARR_F(path.path);
6922 return create_invalid_expression();
6926 * Parses a _builtin_va_start() expression.
6928 static expression_t *parse_va_start(void)
6930 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6932 eat(T___builtin_va_start);
6934 expect('(', end_error);
6935 add_anchor_token(',');
6936 expression->va_starte.ap = parse_assignment_expression();
6937 rem_anchor_token(',');
6938 expect(',', end_error);
6939 expression_t *const expr = parse_assignment_expression();
6940 if (expr->kind == EXPR_REFERENCE) {
6941 entity_t *const entity = expr->reference.entity;
6942 if (!current_function->base.type->function.variadic) {
6943 errorf(&expr->base.source_position,
6944 "'va_start' used in non-variadic function");
6945 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6946 entity->base.next != NULL ||
6947 entity->kind != ENTITY_PARAMETER) {
6948 errorf(&expr->base.source_position,
6949 "second argument of 'va_start' must be last parameter of the current function");
6951 expression->va_starte.parameter = &entity->variable;
6953 expect(')', end_error);
6956 expect(')', end_error);
6958 return create_invalid_expression();
6962 * Parses a __builtin_va_arg() expression.
6964 static expression_t *parse_va_arg(void)
6966 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6968 eat(T___builtin_va_arg);
6970 expect('(', end_error);
6972 ap.expression = parse_assignment_expression();
6973 expression->va_arge.ap = ap.expression;
6974 check_call_argument(type_valist, &ap, 1);
6976 expect(',', end_error);
6977 expression->base.type = parse_typename();
6978 expect(')', end_error);
6982 return create_invalid_expression();
6986 * Parses a __builtin_va_copy() expression.
6988 static expression_t *parse_va_copy(void)
6990 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6992 eat(T___builtin_va_copy);
6994 expect('(', end_error);
6995 expression_t *dst = parse_assignment_expression();
6996 assign_error_t error = semantic_assign(type_valist, dst);
6997 report_assign_error(error, type_valist, dst, "call argument 1",
6998 &dst->base.source_position);
6999 expression->va_copye.dst = dst;
7001 expect(',', end_error);
7003 call_argument_t src;
7004 src.expression = parse_assignment_expression();
7005 check_call_argument(type_valist, &src, 2);
7006 expression->va_copye.src = src.expression;
7007 expect(')', end_error);
7011 return create_invalid_expression();
7015 * Parses a __builtin_constant_p() expression.
7017 static expression_t *parse_builtin_constant(void)
7019 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
7021 eat(T___builtin_constant_p);
7023 expect('(', end_error);
7024 add_anchor_token(')');
7025 expression->builtin_constant.value = parse_assignment_expression();
7026 rem_anchor_token(')');
7027 expect(')', end_error);
7028 expression->base.type = type_int;
7032 return create_invalid_expression();
7036 * Parses a __builtin_types_compatible_p() expression.
7038 static expression_t *parse_builtin_types_compatible(void)
7040 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7042 eat(T___builtin_types_compatible_p);
7044 expect('(', end_error);
7045 add_anchor_token(')');
7046 add_anchor_token(',');
7047 expression->builtin_types_compatible.left = parse_typename();
7048 rem_anchor_token(',');
7049 expect(',', end_error);
7050 expression->builtin_types_compatible.right = parse_typename();
7051 rem_anchor_token(')');
7052 expect(')', end_error);
7053 expression->base.type = type_int;
7057 return create_invalid_expression();
7061 * Parses a __builtin_is_*() compare expression.
7063 static expression_t *parse_compare_builtin(void)
7065 expression_t *expression;
7067 switch (token.type) {
7068 case T___builtin_isgreater:
7069 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7071 case T___builtin_isgreaterequal:
7072 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7074 case T___builtin_isless:
7075 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7077 case T___builtin_islessequal:
7078 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7080 case T___builtin_islessgreater:
7081 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7083 case T___builtin_isunordered:
7084 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7087 internal_errorf(HERE, "invalid compare builtin found");
7089 expression->base.source_position = *HERE;
7092 expect('(', end_error);
7093 expression->binary.left = parse_assignment_expression();
7094 expect(',', end_error);
7095 expression->binary.right = parse_assignment_expression();
7096 expect(')', end_error);
7098 type_t *const orig_type_left = expression->binary.left->base.type;
7099 type_t *const orig_type_right = expression->binary.right->base.type;
7101 type_t *const type_left = skip_typeref(orig_type_left);
7102 type_t *const type_right = skip_typeref(orig_type_right);
7103 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7104 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7105 type_error_incompatible("invalid operands in comparison",
7106 &expression->base.source_position, orig_type_left, orig_type_right);
7109 semantic_comparison(&expression->binary);
7114 return create_invalid_expression();
7118 * Parses a MS assume() expression.
7120 static expression_t *parse_assume(void)
7122 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7126 expect('(', end_error);
7127 add_anchor_token(')');
7128 expression->unary.value = parse_assignment_expression();
7129 rem_anchor_token(')');
7130 expect(')', end_error);
7132 expression->base.type = type_void;
7135 return create_invalid_expression();
7139 * Return the declaration for a given label symbol or create a new one.
7141 * @param symbol the symbol of the label
7143 static label_t *get_label(symbol_t *symbol)
7146 assert(current_function != NULL);
7148 label = get_entity(symbol, NAMESPACE_LABEL);
7149 /* if we found a local label, we already created the declaration */
7150 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7151 if (label->base.parent_scope != current_scope) {
7152 assert(label->base.parent_scope->depth < current_scope->depth);
7153 current_function->goto_to_outer = true;
7155 return &label->label;
7158 label = get_entity(symbol, NAMESPACE_LABEL);
7159 /* if we found a label in the same function, then we already created the
7162 && label->base.parent_scope == ¤t_function->parameters) {
7163 return &label->label;
7166 /* otherwise we need to create a new one */
7167 label = allocate_entity_zero(ENTITY_LABEL);
7168 label->base.namespc = NAMESPACE_LABEL;
7169 label->base.symbol = symbol;
7173 return &label->label;
7177 * Parses a GNU && label address expression.
7179 static expression_t *parse_label_address(void)
7181 source_position_t source_position = token.source_position;
7183 if (token.type != T_IDENTIFIER) {
7184 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7187 symbol_t *symbol = token.v.symbol;
7190 label_t *label = get_label(symbol);
7192 label->address_taken = true;
7194 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7195 expression->base.source_position = source_position;
7197 /* label address is threaten as a void pointer */
7198 expression->base.type = type_void_ptr;
7199 expression->label_address.label = label;
7202 return create_invalid_expression();
7206 * Parse a microsoft __noop expression.
7208 static expression_t *parse_noop_expression(void)
7210 /* the result is a (int)0 */
7211 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7212 cnst->base.type = type_int;
7213 cnst->conste.v.int_value = 0;
7214 cnst->conste.is_ms_noop = true;
7218 if (token.type == '(') {
7219 /* parse arguments */
7221 add_anchor_token(')');
7222 add_anchor_token(',');
7224 if (token.type != ')') {
7226 (void)parse_assignment_expression();
7227 if (token.type != ',')
7233 rem_anchor_token(',');
7234 rem_anchor_token(')');
7235 expect(')', end_error);
7242 * Parses a primary expression.
7244 static expression_t *parse_primary_expression(void)
7246 switch (token.type) {
7247 case T_false: return parse_bool_const(false);
7248 case T_true: return parse_bool_const(true);
7249 case T_INTEGER: return parse_int_const();
7250 case T_CHARACTER_CONSTANT: return parse_character_constant();
7251 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7252 case T_FLOATINGPOINT: return parse_float_const();
7253 case T_STRING_LITERAL:
7254 case T_WIDE_STRING_LITERAL: return parse_string_const();
7255 case T___FUNCTION__:
7256 case T___func__: return parse_function_keyword();
7257 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7258 case T___FUNCSIG__: return parse_funcsig_keyword();
7259 case T___FUNCDNAME__: return parse_funcdname_keyword();
7260 case T___builtin_offsetof: return parse_offsetof();
7261 case T___builtin_va_start: return parse_va_start();
7262 case T___builtin_va_arg: return parse_va_arg();
7263 case T___builtin_va_copy: return parse_va_copy();
7264 case T___builtin_isgreater:
7265 case T___builtin_isgreaterequal:
7266 case T___builtin_isless:
7267 case T___builtin_islessequal:
7268 case T___builtin_islessgreater:
7269 case T___builtin_isunordered: return parse_compare_builtin();
7270 case T___builtin_constant_p: return parse_builtin_constant();
7271 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7272 case T__assume: return parse_assume();
7275 return parse_label_address();
7278 case '(': return parse_parenthesized_expression();
7279 case T___noop: return parse_noop_expression();
7281 /* Gracefully handle type names while parsing expressions. */
7283 return parse_reference();
7285 if (!is_typedef_symbol(token.v.symbol)) {
7286 return parse_reference();
7290 source_position_t const pos = *HERE;
7291 type_t const *const type = parse_typename();
7292 errorf(&pos, "encountered type '%T' while parsing expression", type);
7293 return create_invalid_expression();
7297 errorf(HERE, "unexpected token %K, expected an expression", &token);
7298 return create_invalid_expression();
7302 * Check if the expression has the character type and issue a warning then.
7304 static void check_for_char_index_type(const expression_t *expression)
7306 type_t *const type = expression->base.type;
7307 const type_t *const base_type = skip_typeref(type);
7309 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7310 warning.char_subscripts) {
7311 warningf(&expression->base.source_position,
7312 "array subscript has type '%T'", type);
7316 static expression_t *parse_array_expression(expression_t *left)
7318 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7321 add_anchor_token(']');
7323 expression_t *inside = parse_expression();
7325 type_t *const orig_type_left = left->base.type;
7326 type_t *const orig_type_inside = inside->base.type;
7328 type_t *const type_left = skip_typeref(orig_type_left);
7329 type_t *const type_inside = skip_typeref(orig_type_inside);
7331 type_t *return_type;
7332 array_access_expression_t *array_access = &expression->array_access;
7333 if (is_type_pointer(type_left)) {
7334 return_type = type_left->pointer.points_to;
7335 array_access->array_ref = left;
7336 array_access->index = inside;
7337 check_for_char_index_type(inside);
7338 } else if (is_type_pointer(type_inside)) {
7339 return_type = type_inside->pointer.points_to;
7340 array_access->array_ref = inside;
7341 array_access->index = left;
7342 array_access->flipped = true;
7343 check_for_char_index_type(left);
7345 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7347 "array access on object with non-pointer types '%T', '%T'",
7348 orig_type_left, orig_type_inside);
7350 return_type = type_error_type;
7351 array_access->array_ref = left;
7352 array_access->index = inside;
7355 expression->base.type = automatic_type_conversion(return_type);
7357 rem_anchor_token(']');
7358 expect(']', end_error);
7363 static expression_t *parse_typeprop(expression_kind_t const kind)
7365 expression_t *tp_expression = allocate_expression_zero(kind);
7366 tp_expression->base.type = type_size_t;
7368 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7370 /* we only refer to a type property, mark this case */
7371 bool old = in_type_prop;
7372 in_type_prop = true;
7375 expression_t *expression;
7376 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7378 add_anchor_token(')');
7379 orig_type = parse_typename();
7380 rem_anchor_token(')');
7381 expect(')', end_error);
7383 if (token.type == '{') {
7384 /* It was not sizeof(type) after all. It is sizeof of an expression
7385 * starting with a compound literal */
7386 expression = parse_compound_literal(orig_type);
7387 goto typeprop_expression;
7390 expression = parse_sub_expression(PREC_UNARY);
7392 typeprop_expression:
7393 tp_expression->typeprop.tp_expression = expression;
7395 orig_type = revert_automatic_type_conversion(expression);
7396 expression->base.type = orig_type;
7399 tp_expression->typeprop.type = orig_type;
7400 type_t const* const type = skip_typeref(orig_type);
7401 char const* const wrong_type =
7402 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7403 is_type_incomplete(type) ? "incomplete" :
7404 type->kind == TYPE_FUNCTION ? "function designator" :
7405 type->kind == TYPE_BITFIELD ? "bitfield" :
7407 if (wrong_type != NULL) {
7408 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7409 errorf(&tp_expression->base.source_position,
7410 "operand of %s expression must not be of %s type '%T'",
7411 what, wrong_type, orig_type);
7416 return tp_expression;
7419 static expression_t *parse_sizeof(void)
7421 return parse_typeprop(EXPR_SIZEOF);
7424 static expression_t *parse_alignof(void)
7426 return parse_typeprop(EXPR_ALIGNOF);
7429 static expression_t *parse_select_expression(expression_t *addr)
7431 assert(token.type == '.' || token.type == T_MINUSGREATER);
7432 bool select_left_arrow = (token.type == T_MINUSGREATER);
7435 if (token.type != T_IDENTIFIER) {
7436 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7437 return create_invalid_expression();
7439 symbol_t *symbol = token.v.symbol;
7442 type_t *const orig_type = addr->base.type;
7443 type_t *const type = skip_typeref(orig_type);
7446 bool saw_error = false;
7447 if (is_type_pointer(type)) {
7448 if (!select_left_arrow) {
7450 "request for member '%Y' in something not a struct or union, but '%T'",
7454 type_left = skip_typeref(type->pointer.points_to);
7456 if (select_left_arrow && is_type_valid(type)) {
7457 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7463 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7464 type_left->kind != TYPE_COMPOUND_UNION) {
7466 if (is_type_valid(type_left) && !saw_error) {
7468 "request for member '%Y' in something not a struct or union, but '%T'",
7471 return create_invalid_expression();
7474 compound_t *compound = type_left->compound.compound;
7475 if (!compound->complete) {
7476 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7478 return create_invalid_expression();
7481 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7482 expression_t *result
7483 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7485 if (result == NULL) {
7486 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7487 return create_invalid_expression();
7493 static void check_call_argument(type_t *expected_type,
7494 call_argument_t *argument, unsigned pos)
7496 type_t *expected_type_skip = skip_typeref(expected_type);
7497 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7498 expression_t *arg_expr = argument->expression;
7499 type_t *arg_type = skip_typeref(arg_expr->base.type);
7501 /* handle transparent union gnu extension */
7502 if (is_type_union(expected_type_skip)
7503 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7504 compound_t *union_decl = expected_type_skip->compound.compound;
7505 type_t *best_type = NULL;
7506 entity_t *entry = union_decl->members.entities;
7507 for ( ; entry != NULL; entry = entry->base.next) {
7508 assert(is_declaration(entry));
7509 type_t *decl_type = entry->declaration.type;
7510 error = semantic_assign(decl_type, arg_expr);
7511 if (error == ASSIGN_ERROR_INCOMPATIBLE
7512 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7515 if (error == ASSIGN_SUCCESS) {
7516 best_type = decl_type;
7517 } else if (best_type == NULL) {
7518 best_type = decl_type;
7522 if (best_type != NULL) {
7523 expected_type = best_type;
7527 error = semantic_assign(expected_type, arg_expr);
7528 argument->expression = create_implicit_cast(arg_expr, expected_type);
7530 if (error != ASSIGN_SUCCESS) {
7531 /* report exact scope in error messages (like "in argument 3") */
7533 snprintf(buf, sizeof(buf), "call argument %u", pos);
7534 report_assign_error(error, expected_type, arg_expr, buf,
7535 &arg_expr->base.source_position);
7536 } else if (warning.traditional || warning.conversion) {
7537 type_t *const promoted_type = get_default_promoted_type(arg_type);
7538 if (!types_compatible(expected_type_skip, promoted_type) &&
7539 !types_compatible(expected_type_skip, type_void_ptr) &&
7540 !types_compatible(type_void_ptr, promoted_type)) {
7541 /* Deliberately show the skipped types in this warning */
7542 warningf(&arg_expr->base.source_position,
7543 "passing call argument %u as '%T' rather than '%T' due to prototype",
7544 pos, expected_type_skip, promoted_type);
7550 * Handle the semantic restrictions of builtin calls
7552 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7553 switch (call->function->reference.entity->function.btk) {
7554 case bk_gnu_builtin_return_address:
7555 case bk_gnu_builtin_frame_address: {
7556 /* argument must be constant */
7557 call_argument_t *argument = call->arguments;
7559 if (! is_constant_expression(argument->expression)) {
7560 errorf(&call->base.source_position,
7561 "argument of '%Y' must be a constant expression",
7562 call->function->reference.entity->base.symbol);
7566 case bk_gnu_builtin_prefetch: {
7567 /* second and third argument must be constant if existent */
7568 call_argument_t *rw = call->arguments->next;
7569 call_argument_t *locality = NULL;
7572 if (! is_constant_expression(rw->expression)) {
7573 errorf(&call->base.source_position,
7574 "second argument of '%Y' must be a constant expression",
7575 call->function->reference.entity->base.symbol);
7577 locality = rw->next;
7579 if (locality != NULL) {
7580 if (! is_constant_expression(locality->expression)) {
7581 errorf(&call->base.source_position,
7582 "third argument of '%Y' must be a constant expression",
7583 call->function->reference.entity->base.symbol);
7585 locality = rw->next;
7595 * Parse a call expression, ie. expression '( ... )'.
7597 * @param expression the function address
7599 static expression_t *parse_call_expression(expression_t *expression)
7601 expression_t *result = allocate_expression_zero(EXPR_CALL);
7602 call_expression_t *call = &result->call;
7603 call->function = expression;
7605 type_t *const orig_type = expression->base.type;
7606 type_t *const type = skip_typeref(orig_type);
7608 function_type_t *function_type = NULL;
7609 if (is_type_pointer(type)) {
7610 type_t *const to_type = skip_typeref(type->pointer.points_to);
7612 if (is_type_function(to_type)) {
7613 function_type = &to_type->function;
7614 call->base.type = function_type->return_type;
7618 if (function_type == NULL && is_type_valid(type)) {
7620 "called object '%E' (type '%T') is not a pointer to a function",
7621 expression, orig_type);
7624 /* parse arguments */
7626 add_anchor_token(')');
7627 add_anchor_token(',');
7629 if (token.type != ')') {
7630 call_argument_t **anchor = &call->arguments;
7632 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7633 argument->expression = parse_assignment_expression();
7636 anchor = &argument->next;
7638 if (token.type != ',')
7643 rem_anchor_token(',');
7644 rem_anchor_token(')');
7645 expect(')', end_error);
7647 if (function_type == NULL)
7650 /* check type and count of call arguments */
7651 function_parameter_t *parameter = function_type->parameters;
7652 call_argument_t *argument = call->arguments;
7653 if (!function_type->unspecified_parameters) {
7654 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7655 parameter = parameter->next, argument = argument->next) {
7656 check_call_argument(parameter->type, argument, ++pos);
7659 if (parameter != NULL) {
7660 errorf(HERE, "too few arguments to function '%E'", expression);
7661 } else if (argument != NULL && !function_type->variadic) {
7662 errorf(HERE, "too many arguments to function '%E'", expression);
7666 /* do default promotion for other arguments */
7667 for (; argument != NULL; argument = argument->next) {
7668 type_t *type = argument->expression->base.type;
7670 type = get_default_promoted_type(type);
7672 argument->expression
7673 = create_implicit_cast(argument->expression, type);
7676 check_format(&result->call);
7678 if (warning.aggregate_return &&
7679 is_type_compound(skip_typeref(function_type->return_type))) {
7680 warningf(&result->base.source_position,
7681 "function call has aggregate value");
7684 if (call->function->kind == EXPR_REFERENCE) {
7685 reference_expression_t *reference = &call->function->reference;
7686 if (reference->entity->kind == ENTITY_FUNCTION &&
7687 reference->entity->function.btk != bk_none)
7688 handle_builtin_argument_restrictions(call);
7695 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7697 static bool same_compound_type(const type_t *type1, const type_t *type2)
7700 is_type_compound(type1) &&
7701 type1->kind == type2->kind &&
7702 type1->compound.compound == type2->compound.compound;
7705 static expression_t const *get_reference_address(expression_t const *expr)
7707 bool regular_take_address = true;
7709 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7710 expr = expr->unary.value;
7712 regular_take_address = false;
7715 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7718 expr = expr->unary.value;
7721 if (expr->kind != EXPR_REFERENCE)
7724 /* special case for functions which are automatically converted to a
7725 * pointer to function without an extra TAKE_ADDRESS operation */
7726 if (!regular_take_address &&
7727 expr->reference.entity->kind != ENTITY_FUNCTION) {
7734 static void warn_reference_address_as_bool(expression_t const* expr)
7736 if (!warning.address)
7739 expr = get_reference_address(expr);
7741 warningf(&expr->base.source_position,
7742 "the address of '%Y' will always evaluate as 'true'",
7743 expr->reference.entity->base.symbol);
7747 static void warn_assignment_in_condition(const expression_t *const expr)
7749 if (!warning.parentheses)
7751 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7753 if (expr->base.parenthesized)
7755 warningf(&expr->base.source_position,
7756 "suggest parentheses around assignment used as truth value");
7759 static void semantic_condition(expression_t const *const expr,
7760 char const *const context)
7762 type_t *const type = skip_typeref(expr->base.type);
7763 if (is_type_scalar(type)) {
7764 warn_reference_address_as_bool(expr);
7765 warn_assignment_in_condition(expr);
7766 } else if (is_type_valid(type)) {
7767 errorf(&expr->base.source_position,
7768 "%s must have scalar type", context);
7773 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7775 * @param expression the conditional expression
7777 static expression_t *parse_conditional_expression(expression_t *expression)
7779 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7781 conditional_expression_t *conditional = &result->conditional;
7782 conditional->condition = expression;
7785 add_anchor_token(':');
7787 /* §6.5.15:2 The first operand shall have scalar type. */
7788 semantic_condition(expression, "condition of conditional operator");
7790 expression_t *true_expression = expression;
7791 bool gnu_cond = false;
7792 if (GNU_MODE && token.type == ':') {
7795 true_expression = parse_expression();
7797 rem_anchor_token(':');
7798 expect(':', end_error);
7800 expression_t *false_expression =
7801 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7803 type_t *const orig_true_type = true_expression->base.type;
7804 type_t *const orig_false_type = false_expression->base.type;
7805 type_t *const true_type = skip_typeref(orig_true_type);
7806 type_t *const false_type = skip_typeref(orig_false_type);
7809 type_t *result_type;
7810 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7811 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7812 /* ISO/IEC 14882:1998(E) §5.16:2 */
7813 if (true_expression->kind == EXPR_UNARY_THROW) {
7814 result_type = false_type;
7815 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7816 result_type = true_type;
7818 if (warning.other && (
7819 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7820 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7822 warningf(&conditional->base.source_position,
7823 "ISO C forbids conditional expression with only one void side");
7825 result_type = type_void;
7827 } else if (is_type_arithmetic(true_type)
7828 && is_type_arithmetic(false_type)) {
7829 result_type = semantic_arithmetic(true_type, false_type);
7831 true_expression = create_implicit_cast(true_expression, result_type);
7832 false_expression = create_implicit_cast(false_expression, result_type);
7834 conditional->true_expression = true_expression;
7835 conditional->false_expression = false_expression;
7836 conditional->base.type = result_type;
7837 } else if (same_compound_type(true_type, false_type)) {
7838 /* just take 1 of the 2 types */
7839 result_type = true_type;
7840 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7841 type_t *pointer_type;
7843 expression_t *other_expression;
7844 if (is_type_pointer(true_type) &&
7845 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7846 pointer_type = true_type;
7847 other_type = false_type;
7848 other_expression = false_expression;
7850 pointer_type = false_type;
7851 other_type = true_type;
7852 other_expression = true_expression;
7855 if (is_null_pointer_constant(other_expression)) {
7856 result_type = pointer_type;
7857 } else if (is_type_pointer(other_type)) {
7858 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7859 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7862 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7863 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7865 } else if (types_compatible(get_unqualified_type(to1),
7866 get_unqualified_type(to2))) {
7869 if (warning.other) {
7870 warningf(&conditional->base.source_position,
7871 "pointer types '%T' and '%T' in conditional expression are incompatible",
7872 true_type, false_type);
7877 type_t *const type =
7878 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7879 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7880 } else if (is_type_integer(other_type)) {
7881 if (warning.other) {
7882 warningf(&conditional->base.source_position,
7883 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7885 result_type = pointer_type;
7887 if (is_type_valid(other_type)) {
7888 type_error_incompatible("while parsing conditional",
7889 &expression->base.source_position, true_type, false_type);
7891 result_type = type_error_type;
7894 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7895 type_error_incompatible("while parsing conditional",
7896 &conditional->base.source_position, true_type,
7899 result_type = type_error_type;
7902 conditional->true_expression
7903 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7904 conditional->false_expression
7905 = create_implicit_cast(false_expression, result_type);
7906 conditional->base.type = result_type;
7911 * Parse an extension expression.
7913 static expression_t *parse_extension(void)
7915 eat(T___extension__);
7917 bool old_gcc_extension = in_gcc_extension;
7918 in_gcc_extension = true;
7919 expression_t *expression = parse_sub_expression(PREC_UNARY);
7920 in_gcc_extension = old_gcc_extension;
7925 * Parse a __builtin_classify_type() expression.
7927 static expression_t *parse_builtin_classify_type(void)
7929 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7930 result->base.type = type_int;
7932 eat(T___builtin_classify_type);
7934 expect('(', end_error);
7935 add_anchor_token(')');
7936 expression_t *expression = parse_expression();
7937 rem_anchor_token(')');
7938 expect(')', end_error);
7939 result->classify_type.type_expression = expression;
7943 return create_invalid_expression();
7947 * Parse a delete expression
7948 * ISO/IEC 14882:1998(E) §5.3.5
7950 static expression_t *parse_delete(void)
7952 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7953 result->base.type = type_void;
7957 if (token.type == '[') {
7959 result->kind = EXPR_UNARY_DELETE_ARRAY;
7960 expect(']', end_error);
7964 expression_t *const value = parse_sub_expression(PREC_CAST);
7965 result->unary.value = value;
7967 type_t *const type = skip_typeref(value->base.type);
7968 if (!is_type_pointer(type)) {
7969 if (is_type_valid(type)) {
7970 errorf(&value->base.source_position,
7971 "operand of delete must have pointer type");
7973 } else if (warning.other &&
7974 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7975 warningf(&value->base.source_position,
7976 "deleting 'void*' is undefined");
7983 * Parse a throw expression
7984 * ISO/IEC 14882:1998(E) §15:1
7986 static expression_t *parse_throw(void)
7988 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7989 result->base.type = type_void;
7993 expression_t *value = NULL;
7994 switch (token.type) {
7996 value = parse_assignment_expression();
7997 /* ISO/IEC 14882:1998(E) §15.1:3 */
7998 type_t *const orig_type = value->base.type;
7999 type_t *const type = skip_typeref(orig_type);
8000 if (is_type_incomplete(type)) {
8001 errorf(&value->base.source_position,
8002 "cannot throw object of incomplete type '%T'", orig_type);
8003 } else if (is_type_pointer(type)) {
8004 type_t *const points_to = skip_typeref(type->pointer.points_to);
8005 if (is_type_incomplete(points_to) &&
8006 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8007 errorf(&value->base.source_position,
8008 "cannot throw pointer to incomplete type '%T'", orig_type);
8016 result->unary.value = value;
8021 static bool check_pointer_arithmetic(const source_position_t *source_position,
8022 type_t *pointer_type,
8023 type_t *orig_pointer_type)
8025 type_t *points_to = pointer_type->pointer.points_to;
8026 points_to = skip_typeref(points_to);
8028 if (is_type_incomplete(points_to)) {
8029 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
8030 errorf(source_position,
8031 "arithmetic with pointer to incomplete type '%T' not allowed",
8034 } else if (warning.pointer_arith) {
8035 warningf(source_position,
8036 "pointer of type '%T' used in arithmetic",
8039 } else if (is_type_function(points_to)) {
8041 errorf(source_position,
8042 "arithmetic with pointer to function type '%T' not allowed",
8045 } else if (warning.pointer_arith) {
8046 warningf(source_position,
8047 "pointer to a function '%T' used in arithmetic",
8054 static bool is_lvalue(const expression_t *expression)
8056 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8057 switch (expression->kind) {
8058 case EXPR_ARRAY_ACCESS:
8059 case EXPR_COMPOUND_LITERAL:
8060 case EXPR_REFERENCE:
8062 case EXPR_UNARY_DEREFERENCE:
8066 type_t *type = skip_typeref(expression->base.type);
8068 /* ISO/IEC 14882:1998(E) §3.10:3 */
8069 is_type_reference(type) ||
8070 /* Claim it is an lvalue, if the type is invalid. There was a parse
8071 * error before, which maybe prevented properly recognizing it as
8073 !is_type_valid(type);
8078 static void semantic_incdec(unary_expression_t *expression)
8080 type_t *const orig_type = expression->value->base.type;
8081 type_t *const type = skip_typeref(orig_type);
8082 if (is_type_pointer(type)) {
8083 if (!check_pointer_arithmetic(&expression->base.source_position,
8087 } else if (!is_type_real(type) && is_type_valid(type)) {
8088 /* TODO: improve error message */
8089 errorf(&expression->base.source_position,
8090 "operation needs an arithmetic or pointer type");
8093 if (!is_lvalue(expression->value)) {
8094 /* TODO: improve error message */
8095 errorf(&expression->base.source_position, "lvalue required as operand");
8097 expression->base.type = orig_type;
8100 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8102 type_t *const orig_type = expression->value->base.type;
8103 type_t *const type = skip_typeref(orig_type);
8104 if (!is_type_arithmetic(type)) {
8105 if (is_type_valid(type)) {
8106 /* TODO: improve error message */
8107 errorf(&expression->base.source_position,
8108 "operation needs an arithmetic type");
8113 expression->base.type = orig_type;
8116 static void semantic_unexpr_plus(unary_expression_t *expression)
8118 semantic_unexpr_arithmetic(expression);
8119 if (warning.traditional)
8120 warningf(&expression->base.source_position,
8121 "traditional C rejects the unary plus operator");
8124 static void semantic_not(unary_expression_t *expression)
8126 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8127 semantic_condition(expression->value, "operand of !");
8128 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8131 static void semantic_unexpr_integer(unary_expression_t *expression)
8133 type_t *const orig_type = expression->value->base.type;
8134 type_t *const type = skip_typeref(orig_type);
8135 if (!is_type_integer(type)) {
8136 if (is_type_valid(type)) {
8137 errorf(&expression->base.source_position,
8138 "operand of ~ must be of integer type");
8143 expression->base.type = orig_type;
8146 static void semantic_dereference(unary_expression_t *expression)
8148 type_t *const orig_type = expression->value->base.type;
8149 type_t *const type = skip_typeref(orig_type);
8150 if (!is_type_pointer(type)) {
8151 if (is_type_valid(type)) {
8152 errorf(&expression->base.source_position,
8153 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8158 type_t *result_type = type->pointer.points_to;
8159 result_type = automatic_type_conversion(result_type);
8160 expression->base.type = result_type;
8164 * Record that an address is taken (expression represents an lvalue).
8166 * @param expression the expression
8167 * @param may_be_register if true, the expression might be an register
8169 static void set_address_taken(expression_t *expression, bool may_be_register)
8171 if (expression->kind != EXPR_REFERENCE)
8174 entity_t *const entity = expression->reference.entity;
8176 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8179 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8180 && !may_be_register) {
8181 errorf(&expression->base.source_position,
8182 "address of register %s '%Y' requested",
8183 get_entity_kind_name(entity->kind), entity->base.symbol);
8186 if (entity->kind == ENTITY_VARIABLE) {
8187 entity->variable.address_taken = true;
8189 assert(entity->kind == ENTITY_PARAMETER);
8190 entity->parameter.address_taken = true;
8195 * Check the semantic of the address taken expression.
8197 static void semantic_take_addr(unary_expression_t *expression)
8199 expression_t *value = expression->value;
8200 value->base.type = revert_automatic_type_conversion(value);
8202 type_t *orig_type = value->base.type;
8203 type_t *type = skip_typeref(orig_type);
8204 if (!is_type_valid(type))
8208 if (!is_lvalue(value)) {
8209 errorf(&expression->base.source_position, "'&' requires an lvalue");
8211 if (type->kind == TYPE_BITFIELD) {
8212 errorf(&expression->base.source_position,
8213 "'&' not allowed on object with bitfield type '%T'",
8217 set_address_taken(value, false);
8219 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8222 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8223 static expression_t *parse_##unexpression_type(void) \
8225 expression_t *unary_expression \
8226 = allocate_expression_zero(unexpression_type); \
8228 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8230 sfunc(&unary_expression->unary); \
8232 return unary_expression; \
8235 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8236 semantic_unexpr_arithmetic)
8237 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8238 semantic_unexpr_plus)
8239 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8241 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8242 semantic_dereference)
8243 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8245 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8246 semantic_unexpr_integer)
8247 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8249 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8252 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8254 static expression_t *parse_##unexpression_type(expression_t *left) \
8256 expression_t *unary_expression \
8257 = allocate_expression_zero(unexpression_type); \
8259 unary_expression->unary.value = left; \
8261 sfunc(&unary_expression->unary); \
8263 return unary_expression; \
8266 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8267 EXPR_UNARY_POSTFIX_INCREMENT,
8269 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8270 EXPR_UNARY_POSTFIX_DECREMENT,
8273 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8275 /* TODO: handle complex + imaginary types */
8277 type_left = get_unqualified_type(type_left);
8278 type_right = get_unqualified_type(type_right);
8280 /* §6.3.1.8 Usual arithmetic conversions */
8281 if (type_left == type_long_double || type_right == type_long_double) {
8282 return type_long_double;
8283 } else if (type_left == type_double || type_right == type_double) {
8285 } else if (type_left == type_float || type_right == type_float) {
8289 type_left = promote_integer(type_left);
8290 type_right = promote_integer(type_right);
8292 if (type_left == type_right)
8295 bool const signed_left = is_type_signed(type_left);
8296 bool const signed_right = is_type_signed(type_right);
8297 int const rank_left = get_rank(type_left);
8298 int const rank_right = get_rank(type_right);
8300 if (signed_left == signed_right)
8301 return rank_left >= rank_right ? type_left : type_right;
8310 u_rank = rank_right;
8311 u_type = type_right;
8313 s_rank = rank_right;
8314 s_type = type_right;
8319 if (u_rank >= s_rank)
8322 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8324 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8325 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8329 case ATOMIC_TYPE_INT: return type_unsigned_int;
8330 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8331 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8333 default: panic("invalid atomic type");
8338 * Check the semantic restrictions for a binary expression.
8340 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8342 expression_t *const left = expression->left;
8343 expression_t *const right = expression->right;
8344 type_t *const orig_type_left = left->base.type;
8345 type_t *const orig_type_right = right->base.type;
8346 type_t *const type_left = skip_typeref(orig_type_left);
8347 type_t *const type_right = skip_typeref(orig_type_right);
8349 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8350 /* TODO: improve error message */
8351 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8352 errorf(&expression->base.source_position,
8353 "operation needs arithmetic types");
8358 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8359 expression->left = create_implicit_cast(left, arithmetic_type);
8360 expression->right = create_implicit_cast(right, arithmetic_type);
8361 expression->base.type = arithmetic_type;
8364 static void warn_div_by_zero(binary_expression_t const *const expression)
8366 if (!warning.div_by_zero ||
8367 !is_type_integer(expression->base.type))
8370 expression_t const *const right = expression->right;
8371 /* The type of the right operand can be different for /= */
8372 if (is_type_integer(right->base.type) &&
8373 is_constant_expression(right) &&
8374 !fold_constant_to_bool(right)) {
8375 warningf(&expression->base.source_position, "division by zero");
8380 * Check the semantic restrictions for a div/mod expression.
8382 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8384 semantic_binexpr_arithmetic(expression);
8385 warn_div_by_zero(expression);
8388 static void warn_addsub_in_shift(const expression_t *const expr)
8390 if (expr->base.parenthesized)
8394 switch (expr->kind) {
8395 case EXPR_BINARY_ADD: op = '+'; break;
8396 case EXPR_BINARY_SUB: op = '-'; break;
8400 warningf(&expr->base.source_position,
8401 "suggest parentheses around '%c' inside shift", op);
8404 static bool semantic_shift(binary_expression_t *expression)
8406 expression_t *const left = expression->left;
8407 expression_t *const right = expression->right;
8408 type_t *const orig_type_left = left->base.type;
8409 type_t *const orig_type_right = right->base.type;
8410 type_t * type_left = skip_typeref(orig_type_left);
8411 type_t * type_right = skip_typeref(orig_type_right);
8413 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8414 /* TODO: improve error message */
8415 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8416 errorf(&expression->base.source_position,
8417 "operands of shift operation must have integer types");
8422 type_left = promote_integer(type_left);
8424 if (is_constant_expression(right)) {
8425 long count = fold_constant_to_int(right);
8427 warningf(&right->base.source_position,
8428 "shift count must be non-negative");
8429 } else if ((unsigned long)count >=
8430 get_atomic_type_size(type_left->atomic.akind) * 8) {
8431 warningf(&right->base.source_position,
8432 "shift count must be less than type width");
8436 type_right = promote_integer(type_right);
8437 expression->right = create_implicit_cast(right, type_right);
8442 static void semantic_shift_op(binary_expression_t *expression)
8444 expression_t *const left = expression->left;
8445 expression_t *const right = expression->right;
8447 if (!semantic_shift(expression))
8450 if (warning.parentheses) {
8451 warn_addsub_in_shift(left);
8452 warn_addsub_in_shift(right);
8455 type_t *const orig_type_left = left->base.type;
8456 type_t * type_left = skip_typeref(orig_type_left);
8458 type_left = promote_integer(type_left);
8459 expression->left = create_implicit_cast(left, type_left);
8460 expression->base.type = type_left;
8463 static void semantic_add(binary_expression_t *expression)
8465 expression_t *const left = expression->left;
8466 expression_t *const right = expression->right;
8467 type_t *const orig_type_left = left->base.type;
8468 type_t *const orig_type_right = right->base.type;
8469 type_t *const type_left = skip_typeref(orig_type_left);
8470 type_t *const type_right = skip_typeref(orig_type_right);
8473 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8474 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8475 expression->left = create_implicit_cast(left, arithmetic_type);
8476 expression->right = create_implicit_cast(right, arithmetic_type);
8477 expression->base.type = arithmetic_type;
8478 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8479 check_pointer_arithmetic(&expression->base.source_position,
8480 type_left, orig_type_left);
8481 expression->base.type = type_left;
8482 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8483 check_pointer_arithmetic(&expression->base.source_position,
8484 type_right, orig_type_right);
8485 expression->base.type = type_right;
8486 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8487 errorf(&expression->base.source_position,
8488 "invalid operands to binary + ('%T', '%T')",
8489 orig_type_left, orig_type_right);
8493 static void semantic_sub(binary_expression_t *expression)
8495 expression_t *const left = expression->left;
8496 expression_t *const right = expression->right;
8497 type_t *const orig_type_left = left->base.type;
8498 type_t *const orig_type_right = right->base.type;
8499 type_t *const type_left = skip_typeref(orig_type_left);
8500 type_t *const type_right = skip_typeref(orig_type_right);
8501 source_position_t const *const pos = &expression->base.source_position;
8504 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8505 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8506 expression->left = create_implicit_cast(left, arithmetic_type);
8507 expression->right = create_implicit_cast(right, arithmetic_type);
8508 expression->base.type = arithmetic_type;
8509 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8510 check_pointer_arithmetic(&expression->base.source_position,
8511 type_left, orig_type_left);
8512 expression->base.type = type_left;
8513 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8514 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8515 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8516 if (!types_compatible(unqual_left, unqual_right)) {
8518 "subtracting pointers to incompatible types '%T' and '%T'",
8519 orig_type_left, orig_type_right);
8520 } else if (!is_type_object(unqual_left)) {
8521 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8522 errorf(pos, "subtracting pointers to non-object types '%T'",
8524 } else if (warning.other) {
8525 warningf(pos, "subtracting pointers to void");
8528 expression->base.type = type_ptrdiff_t;
8529 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8530 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8531 orig_type_left, orig_type_right);
8535 static void warn_string_literal_address(expression_t const* expr)
8537 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8538 expr = expr->unary.value;
8539 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8541 expr = expr->unary.value;
8544 if (expr->kind == EXPR_STRING_LITERAL ||
8545 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8546 warningf(&expr->base.source_position,
8547 "comparison with string literal results in unspecified behaviour");
8551 static void warn_comparison_in_comparison(const expression_t *const expr)
8553 if (expr->base.parenthesized)
8555 switch (expr->base.kind) {
8556 case EXPR_BINARY_LESS:
8557 case EXPR_BINARY_GREATER:
8558 case EXPR_BINARY_LESSEQUAL:
8559 case EXPR_BINARY_GREATEREQUAL:
8560 case EXPR_BINARY_NOTEQUAL:
8561 case EXPR_BINARY_EQUAL:
8562 warningf(&expr->base.source_position,
8563 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8570 static bool maybe_negative(expression_t const *const expr)
8573 !is_constant_expression(expr) ||
8574 fold_constant_to_int(expr) < 0;
8578 * Check the semantics of comparison expressions.
8580 * @param expression The expression to check.
8582 static void semantic_comparison(binary_expression_t *expression)
8584 expression_t *left = expression->left;
8585 expression_t *right = expression->right;
8587 if (warning.address) {
8588 warn_string_literal_address(left);
8589 warn_string_literal_address(right);
8591 expression_t const* const func_left = get_reference_address(left);
8592 if (func_left != NULL && is_null_pointer_constant(right)) {
8593 warningf(&expression->base.source_position,
8594 "the address of '%Y' will never be NULL",
8595 func_left->reference.entity->base.symbol);
8598 expression_t const* const func_right = get_reference_address(right);
8599 if (func_right != NULL && is_null_pointer_constant(right)) {
8600 warningf(&expression->base.source_position,
8601 "the address of '%Y' will never be NULL",
8602 func_right->reference.entity->base.symbol);
8606 if (warning.parentheses) {
8607 warn_comparison_in_comparison(left);
8608 warn_comparison_in_comparison(right);
8611 type_t *orig_type_left = left->base.type;
8612 type_t *orig_type_right = right->base.type;
8613 type_t *type_left = skip_typeref(orig_type_left);
8614 type_t *type_right = skip_typeref(orig_type_right);
8616 /* TODO non-arithmetic types */
8617 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8618 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8620 /* test for signed vs unsigned compares */
8621 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8622 bool const signed_left = is_type_signed(type_left);
8623 bool const signed_right = is_type_signed(type_right);
8624 if (signed_left != signed_right) {
8625 /* FIXME long long needs better const folding magic */
8626 /* TODO check whether constant value can be represented by other type */
8627 if ((signed_left && maybe_negative(left)) ||
8628 (signed_right && maybe_negative(right))) {
8629 warningf(&expression->base.source_position,
8630 "comparison between signed and unsigned");
8635 expression->left = create_implicit_cast(left, arithmetic_type);
8636 expression->right = create_implicit_cast(right, arithmetic_type);
8637 expression->base.type = arithmetic_type;
8638 if (warning.float_equal &&
8639 (expression->base.kind == EXPR_BINARY_EQUAL ||
8640 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8641 is_type_float(arithmetic_type)) {
8642 warningf(&expression->base.source_position,
8643 "comparing floating point with == or != is unsafe");
8645 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8646 /* TODO check compatibility */
8647 } else if (is_type_pointer(type_left)) {
8648 expression->right = create_implicit_cast(right, type_left);
8649 } else if (is_type_pointer(type_right)) {
8650 expression->left = create_implicit_cast(left, type_right);
8651 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8652 type_error_incompatible("invalid operands in comparison",
8653 &expression->base.source_position,
8654 type_left, type_right);
8656 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8660 * Checks if a compound type has constant fields.
8662 static bool has_const_fields(const compound_type_t *type)
8664 compound_t *compound = type->compound;
8665 entity_t *entry = compound->members.entities;
8667 for (; entry != NULL; entry = entry->base.next) {
8668 if (!is_declaration(entry))
8671 const type_t *decl_type = skip_typeref(entry->declaration.type);
8672 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8679 static bool is_valid_assignment_lhs(expression_t const* const left)
8681 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8682 type_t *const type_left = skip_typeref(orig_type_left);
8684 if (!is_lvalue(left)) {
8685 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8690 if (left->kind == EXPR_REFERENCE
8691 && left->reference.entity->kind == ENTITY_FUNCTION) {
8692 errorf(HERE, "cannot assign to function '%E'", left);
8696 if (is_type_array(type_left)) {
8697 errorf(HERE, "cannot assign to array '%E'", left);
8700 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8701 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8705 if (is_type_incomplete(type_left)) {
8706 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8707 left, orig_type_left);
8710 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8711 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8712 left, orig_type_left);
8719 static void semantic_arithmetic_assign(binary_expression_t *expression)
8721 expression_t *left = expression->left;
8722 expression_t *right = expression->right;
8723 type_t *orig_type_left = left->base.type;
8724 type_t *orig_type_right = right->base.type;
8726 if (!is_valid_assignment_lhs(left))
8729 type_t *type_left = skip_typeref(orig_type_left);
8730 type_t *type_right = skip_typeref(orig_type_right);
8732 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8733 /* TODO: improve error message */
8734 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8735 errorf(&expression->base.source_position,
8736 "operation needs arithmetic types");
8741 /* combined instructions are tricky. We can't create an implicit cast on
8742 * the left side, because we need the uncasted form for the store.
8743 * The ast2firm pass has to know that left_type must be right_type
8744 * for the arithmetic operation and create a cast by itself */
8745 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8746 expression->right = create_implicit_cast(right, arithmetic_type);
8747 expression->base.type = type_left;
8750 static void semantic_divmod_assign(binary_expression_t *expression)
8752 semantic_arithmetic_assign(expression);
8753 warn_div_by_zero(expression);
8756 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8758 expression_t *const left = expression->left;
8759 expression_t *const right = expression->right;
8760 type_t *const orig_type_left = left->base.type;
8761 type_t *const orig_type_right = right->base.type;
8762 type_t *const type_left = skip_typeref(orig_type_left);
8763 type_t *const type_right = skip_typeref(orig_type_right);
8765 if (!is_valid_assignment_lhs(left))
8768 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8769 /* combined instructions are tricky. We can't create an implicit cast on
8770 * the left side, because we need the uncasted form for the store.
8771 * The ast2firm pass has to know that left_type must be right_type
8772 * for the arithmetic operation and create a cast by itself */
8773 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8774 expression->right = create_implicit_cast(right, arithmetic_type);
8775 expression->base.type = type_left;
8776 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8777 check_pointer_arithmetic(&expression->base.source_position,
8778 type_left, orig_type_left);
8779 expression->base.type = type_left;
8780 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8781 errorf(&expression->base.source_position,
8782 "incompatible types '%T' and '%T' in assignment",
8783 orig_type_left, orig_type_right);
8787 static void semantic_integer_assign(binary_expression_t *expression)
8789 expression_t *left = expression->left;
8790 expression_t *right = expression->right;
8791 type_t *orig_type_left = left->base.type;
8792 type_t *orig_type_right = right->base.type;
8794 if (!is_valid_assignment_lhs(left))
8797 type_t *type_left = skip_typeref(orig_type_left);
8798 type_t *type_right = skip_typeref(orig_type_right);
8800 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8801 /* TODO: improve error message */
8802 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8803 errorf(&expression->base.source_position,
8804 "operation needs integer types");
8809 /* combined instructions are tricky. We can't create an implicit cast on
8810 * the left side, because we need the uncasted form for the store.
8811 * The ast2firm pass has to know that left_type must be right_type
8812 * for the arithmetic operation and create a cast by itself */
8813 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8814 expression->right = create_implicit_cast(right, arithmetic_type);
8815 expression->base.type = type_left;
8818 static void semantic_shift_assign(binary_expression_t *expression)
8820 expression_t *left = expression->left;
8822 if (!is_valid_assignment_lhs(left))
8825 if (!semantic_shift(expression))
8828 expression->base.type = skip_typeref(left->base.type);
8831 static void warn_logical_and_within_or(const expression_t *const expr)
8833 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8835 if (expr->base.parenthesized)
8837 warningf(&expr->base.source_position,
8838 "suggest parentheses around && within ||");
8842 * Check the semantic restrictions of a logical expression.
8844 static void semantic_logical_op(binary_expression_t *expression)
8846 /* §6.5.13:2 Each of the operands shall have scalar type.
8847 * §6.5.14:2 Each of the operands shall have scalar type. */
8848 semantic_condition(expression->left, "left operand of logical operator");
8849 semantic_condition(expression->right, "right operand of logical operator");
8850 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8851 warning.parentheses) {
8852 warn_logical_and_within_or(expression->left);
8853 warn_logical_and_within_or(expression->right);
8855 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8859 * Check the semantic restrictions of a binary assign expression.
8861 static void semantic_binexpr_assign(binary_expression_t *expression)
8863 expression_t *left = expression->left;
8864 type_t *orig_type_left = left->base.type;
8866 if (!is_valid_assignment_lhs(left))
8869 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8870 report_assign_error(error, orig_type_left, expression->right,
8871 "assignment", &left->base.source_position);
8872 expression->right = create_implicit_cast(expression->right, orig_type_left);
8873 expression->base.type = orig_type_left;
8877 * Determine if the outermost operation (or parts thereof) of the given
8878 * expression has no effect in order to generate a warning about this fact.
8879 * Therefore in some cases this only examines some of the operands of the
8880 * expression (see comments in the function and examples below).
8882 * f() + 23; // warning, because + has no effect
8883 * x || f(); // no warning, because x controls execution of f()
8884 * x ? y : f(); // warning, because y has no effect
8885 * (void)x; // no warning to be able to suppress the warning
8886 * This function can NOT be used for an "expression has definitely no effect"-
8888 static bool expression_has_effect(const expression_t *const expr)
8890 switch (expr->kind) {
8891 case EXPR_UNKNOWN: break;
8892 case EXPR_INVALID: return true; /* do NOT warn */
8893 case EXPR_REFERENCE: return false;
8894 case EXPR_REFERENCE_ENUM_VALUE: return false;
8895 /* suppress the warning for microsoft __noop operations */
8896 case EXPR_CONST: return expr->conste.is_ms_noop;
8897 case EXPR_CHARACTER_CONSTANT: return false;
8898 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8899 case EXPR_STRING_LITERAL: return false;
8900 case EXPR_WIDE_STRING_LITERAL: return false;
8901 case EXPR_LABEL_ADDRESS: return false;
8904 const call_expression_t *const call = &expr->call;
8905 if (call->function->kind != EXPR_REFERENCE)
8908 switch (call->function->reference.entity->function.btk) {
8909 /* FIXME: which builtins have no effect? */
8910 default: return true;
8914 /* Generate the warning if either the left or right hand side of a
8915 * conditional expression has no effect */
8916 case EXPR_CONDITIONAL: {
8917 conditional_expression_t const *const cond = &expr->conditional;
8918 expression_t const *const t = cond->true_expression;
8920 (t == NULL || expression_has_effect(t)) &&
8921 expression_has_effect(cond->false_expression);
8924 case EXPR_SELECT: return false;
8925 case EXPR_ARRAY_ACCESS: return false;
8926 case EXPR_SIZEOF: return false;
8927 case EXPR_CLASSIFY_TYPE: return false;
8928 case EXPR_ALIGNOF: return false;
8930 case EXPR_FUNCNAME: return false;
8931 case EXPR_BUILTIN_CONSTANT_P: return false;
8932 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8933 case EXPR_OFFSETOF: return false;
8934 case EXPR_VA_START: return true;
8935 case EXPR_VA_ARG: return true;
8936 case EXPR_VA_COPY: return true;
8937 case EXPR_STATEMENT: return true; // TODO
8938 case EXPR_COMPOUND_LITERAL: return false;
8940 case EXPR_UNARY_NEGATE: return false;
8941 case EXPR_UNARY_PLUS: return false;
8942 case EXPR_UNARY_BITWISE_NEGATE: return false;
8943 case EXPR_UNARY_NOT: return false;
8944 case EXPR_UNARY_DEREFERENCE: return false;
8945 case EXPR_UNARY_TAKE_ADDRESS: return false;
8946 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8947 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8948 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8949 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8951 /* Treat void casts as if they have an effect in order to being able to
8952 * suppress the warning */
8953 case EXPR_UNARY_CAST: {
8954 type_t *const type = skip_typeref(expr->base.type);
8955 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8958 case EXPR_UNARY_CAST_IMPLICIT: return true;
8959 case EXPR_UNARY_ASSUME: return true;
8960 case EXPR_UNARY_DELETE: return true;
8961 case EXPR_UNARY_DELETE_ARRAY: return true;
8962 case EXPR_UNARY_THROW: return true;
8964 case EXPR_BINARY_ADD: return false;
8965 case EXPR_BINARY_SUB: return false;
8966 case EXPR_BINARY_MUL: return false;
8967 case EXPR_BINARY_DIV: return false;
8968 case EXPR_BINARY_MOD: return false;
8969 case EXPR_BINARY_EQUAL: return false;
8970 case EXPR_BINARY_NOTEQUAL: return false;
8971 case EXPR_BINARY_LESS: return false;
8972 case EXPR_BINARY_LESSEQUAL: return false;
8973 case EXPR_BINARY_GREATER: return false;
8974 case EXPR_BINARY_GREATEREQUAL: return false;
8975 case EXPR_BINARY_BITWISE_AND: return false;
8976 case EXPR_BINARY_BITWISE_OR: return false;
8977 case EXPR_BINARY_BITWISE_XOR: return false;
8978 case EXPR_BINARY_SHIFTLEFT: return false;
8979 case EXPR_BINARY_SHIFTRIGHT: return false;
8980 case EXPR_BINARY_ASSIGN: return true;
8981 case EXPR_BINARY_MUL_ASSIGN: return true;
8982 case EXPR_BINARY_DIV_ASSIGN: return true;
8983 case EXPR_BINARY_MOD_ASSIGN: return true;
8984 case EXPR_BINARY_ADD_ASSIGN: return true;
8985 case EXPR_BINARY_SUB_ASSIGN: return true;
8986 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8987 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8988 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8989 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8990 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8992 /* Only examine the right hand side of && and ||, because the left hand
8993 * side already has the effect of controlling the execution of the right
8995 case EXPR_BINARY_LOGICAL_AND:
8996 case EXPR_BINARY_LOGICAL_OR:
8997 /* Only examine the right hand side of a comma expression, because the left
8998 * hand side has a separate warning */
8999 case EXPR_BINARY_COMMA:
9000 return expression_has_effect(expr->binary.right);
9002 case EXPR_BINARY_ISGREATER: return false;
9003 case EXPR_BINARY_ISGREATEREQUAL: return false;
9004 case EXPR_BINARY_ISLESS: return false;
9005 case EXPR_BINARY_ISLESSEQUAL: return false;
9006 case EXPR_BINARY_ISLESSGREATER: return false;
9007 case EXPR_BINARY_ISUNORDERED: return false;
9010 internal_errorf(HERE, "unexpected expression");
9013 static void semantic_comma(binary_expression_t *expression)
9015 if (warning.unused_value) {
9016 const expression_t *const left = expression->left;
9017 if (!expression_has_effect(left)) {
9018 warningf(&left->base.source_position,
9019 "left-hand operand of comma expression has no effect");
9022 expression->base.type = expression->right->base.type;
9026 * @param prec_r precedence of the right operand
9028 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
9029 static expression_t *parse_##binexpression_type(expression_t *left) \
9031 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
9032 binexpr->binary.left = left; \
9035 expression_t *right = parse_sub_expression(prec_r); \
9037 binexpr->binary.right = right; \
9038 sfunc(&binexpr->binary); \
9043 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9044 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9045 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9046 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9047 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9048 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9049 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9050 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9051 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9052 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9053 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9054 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9055 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9056 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9057 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9058 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9059 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9060 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9061 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9062 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9063 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9064 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9065 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9066 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9067 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9068 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9069 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9070 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9071 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9072 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9075 static expression_t *parse_sub_expression(precedence_t precedence)
9077 if (token.type < 0) {
9078 return expected_expression_error();
9081 expression_parser_function_t *parser
9082 = &expression_parsers[token.type];
9083 source_position_t source_position = token.source_position;
9086 if (parser->parser != NULL) {
9087 left = parser->parser();
9089 left = parse_primary_expression();
9091 assert(left != NULL);
9092 left->base.source_position = source_position;
9095 if (token.type < 0) {
9096 return expected_expression_error();
9099 parser = &expression_parsers[token.type];
9100 if (parser->infix_parser == NULL)
9102 if (parser->infix_precedence < precedence)
9105 left = parser->infix_parser(left);
9107 assert(left != NULL);
9108 assert(left->kind != EXPR_UNKNOWN);
9109 left->base.source_position = source_position;
9116 * Parse an expression.
9118 static expression_t *parse_expression(void)
9120 return parse_sub_expression(PREC_EXPRESSION);
9124 * Register a parser for a prefix-like operator.
9126 * @param parser the parser function
9127 * @param token_type the token type of the prefix token
9129 static void register_expression_parser(parse_expression_function parser,
9132 expression_parser_function_t *entry = &expression_parsers[token_type];
9134 if (entry->parser != NULL) {
9135 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9136 panic("trying to register multiple expression parsers for a token");
9138 entry->parser = parser;
9142 * Register a parser for an infix operator with given precedence.
9144 * @param parser the parser function
9145 * @param token_type the token type of the infix operator
9146 * @param precedence the precedence of the operator
9148 static void register_infix_parser(parse_expression_infix_function parser,
9149 int token_type, precedence_t precedence)
9151 expression_parser_function_t *entry = &expression_parsers[token_type];
9153 if (entry->infix_parser != NULL) {
9154 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9155 panic("trying to register multiple infix expression parsers for a "
9158 entry->infix_parser = parser;
9159 entry->infix_precedence = precedence;
9163 * Initialize the expression parsers.
9165 static void init_expression_parsers(void)
9167 memset(&expression_parsers, 0, sizeof(expression_parsers));
9169 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9170 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9171 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9172 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9173 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9174 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9175 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9176 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9177 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9178 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9179 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9180 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9181 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9182 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9183 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9184 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9185 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9186 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9187 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9188 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9189 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9190 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9191 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9192 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9193 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9194 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9195 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9196 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9197 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9198 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9199 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9200 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9201 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9202 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9203 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9204 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9205 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9207 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9208 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9209 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9210 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9211 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9212 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9213 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9214 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9215 register_expression_parser(parse_sizeof, T_sizeof);
9216 register_expression_parser(parse_alignof, T___alignof__);
9217 register_expression_parser(parse_extension, T___extension__);
9218 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9219 register_expression_parser(parse_delete, T_delete);
9220 register_expression_parser(parse_throw, T_throw);
9224 * Parse a asm statement arguments specification.
9226 static asm_argument_t *parse_asm_arguments(bool is_out)
9228 asm_argument_t *result = NULL;
9229 asm_argument_t **anchor = &result;
9231 while (token.type == T_STRING_LITERAL || token.type == '[') {
9232 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9233 memset(argument, 0, sizeof(argument[0]));
9235 if (token.type == '[') {
9237 if (token.type != T_IDENTIFIER) {
9238 parse_error_expected("while parsing asm argument",
9239 T_IDENTIFIER, NULL);
9242 argument->symbol = token.v.symbol;
9244 expect(']', end_error);
9247 argument->constraints = parse_string_literals();
9248 expect('(', end_error);
9249 add_anchor_token(')');
9250 expression_t *expression = parse_expression();
9251 rem_anchor_token(')');
9253 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9254 * change size or type representation (e.g. int -> long is ok, but
9255 * int -> float is not) */
9256 if (expression->kind == EXPR_UNARY_CAST) {
9257 type_t *const type = expression->base.type;
9258 type_kind_t const kind = type->kind;
9259 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9262 if (kind == TYPE_ATOMIC) {
9263 atomic_type_kind_t const akind = type->atomic.akind;
9264 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9265 size = get_atomic_type_size(akind);
9267 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9268 size = get_atomic_type_size(get_intptr_kind());
9272 expression_t *const value = expression->unary.value;
9273 type_t *const value_type = value->base.type;
9274 type_kind_t const value_kind = value_type->kind;
9276 unsigned value_flags;
9277 unsigned value_size;
9278 if (value_kind == TYPE_ATOMIC) {
9279 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9280 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9281 value_size = get_atomic_type_size(value_akind);
9282 } else if (value_kind == TYPE_POINTER) {
9283 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9284 value_size = get_atomic_type_size(get_intptr_kind());
9289 if (value_flags != flags || value_size != size)
9293 } while (expression->kind == EXPR_UNARY_CAST);
9297 if (!is_lvalue(expression)) {
9298 errorf(&expression->base.source_position,
9299 "asm output argument is not an lvalue");
9302 if (argument->constraints.begin[0] == '+')
9303 mark_vars_read(expression, NULL);
9305 mark_vars_read(expression, NULL);
9307 argument->expression = expression;
9308 expect(')', end_error);
9310 set_address_taken(expression, true);
9313 anchor = &argument->next;
9315 if (token.type != ',')
9326 * Parse a asm statement clobber specification.
9328 static asm_clobber_t *parse_asm_clobbers(void)
9330 asm_clobber_t *result = NULL;
9331 asm_clobber_t *last = NULL;
9333 while (token.type == T_STRING_LITERAL) {
9334 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9335 clobber->clobber = parse_string_literals();
9338 last->next = clobber;
9344 if (token.type != ',')
9353 * Parse an asm statement.
9355 static statement_t *parse_asm_statement(void)
9357 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9358 asm_statement_t *asm_statement = &statement->asms;
9362 if (token.type == T_volatile) {
9364 asm_statement->is_volatile = true;
9367 expect('(', end_error);
9368 add_anchor_token(')');
9369 add_anchor_token(':');
9370 asm_statement->asm_text = parse_string_literals();
9372 if (token.type != ':') {
9373 rem_anchor_token(':');
9378 asm_statement->outputs = parse_asm_arguments(true);
9379 if (token.type != ':') {
9380 rem_anchor_token(':');
9385 asm_statement->inputs = parse_asm_arguments(false);
9386 if (token.type != ':') {
9387 rem_anchor_token(':');
9390 rem_anchor_token(':');
9393 asm_statement->clobbers = parse_asm_clobbers();
9396 rem_anchor_token(')');
9397 expect(')', end_error);
9398 expect(';', end_error);
9400 if (asm_statement->outputs == NULL) {
9401 /* GCC: An 'asm' instruction without any output operands will be treated
9402 * identically to a volatile 'asm' instruction. */
9403 asm_statement->is_volatile = true;
9408 return create_invalid_statement();
9412 * Parse a case statement.
9414 static statement_t *parse_case_statement(void)
9416 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9417 source_position_t *const pos = &statement->base.source_position;
9421 expression_t *const expression = parse_expression();
9422 statement->case_label.expression = expression;
9423 if (!is_constant_expression(expression)) {
9424 /* This check does not prevent the error message in all cases of an
9425 * prior error while parsing the expression. At least it catches the
9426 * common case of a mistyped enum entry. */
9427 if (is_type_valid(skip_typeref(expression->base.type))) {
9428 errorf(pos, "case label does not reduce to an integer constant");
9430 statement->case_label.is_bad = true;
9432 long const val = fold_constant_to_int(expression);
9433 statement->case_label.first_case = val;
9434 statement->case_label.last_case = val;
9438 if (token.type == T_DOTDOTDOT) {
9440 expression_t *const end_range = parse_expression();
9441 statement->case_label.end_range = end_range;
9442 if (!is_constant_expression(end_range)) {
9443 /* This check does not prevent the error message in all cases of an
9444 * prior error while parsing the expression. At least it catches the
9445 * common case of a mistyped enum entry. */
9446 if (is_type_valid(skip_typeref(end_range->base.type))) {
9447 errorf(pos, "case range does not reduce to an integer constant");
9449 statement->case_label.is_bad = true;
9451 long const val = fold_constant_to_int(end_range);
9452 statement->case_label.last_case = val;
9454 if (warning.other && val < statement->case_label.first_case) {
9455 statement->case_label.is_empty_range = true;
9456 warningf(pos, "empty range specified");
9462 PUSH_PARENT(statement);
9464 expect(':', end_error);
9467 if (current_switch != NULL) {
9468 if (! statement->case_label.is_bad) {
9469 /* Check for duplicate case values */
9470 case_label_statement_t *c = &statement->case_label;
9471 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9472 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9475 if (c->last_case < l->first_case || c->first_case > l->last_case)
9478 errorf(pos, "duplicate case value (previously used %P)",
9479 &l->base.source_position);
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;
9491 errorf(pos, "case label not within a switch statement");
9494 statement_t *const inner_stmt = parse_statement();
9495 statement->case_label.statement = inner_stmt;
9496 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9497 errorf(&inner_stmt->base.source_position, "declaration after case label");
9505 * Parse a default statement.
9507 static statement_t *parse_default_statement(void)
9509 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9513 PUSH_PARENT(statement);
9515 expect(':', end_error);
9516 if (current_switch != NULL) {
9517 const case_label_statement_t *def_label = current_switch->default_label;
9518 if (def_label != NULL) {
9519 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9520 &def_label->base.source_position);
9522 current_switch->default_label = &statement->case_label;
9524 /* link all cases into the switch statement */
9525 if (current_switch->last_case == NULL) {
9526 current_switch->first_case = &statement->case_label;
9528 current_switch->last_case->next = &statement->case_label;
9530 current_switch->last_case = &statement->case_label;
9533 errorf(&statement->base.source_position,
9534 "'default' label not within a switch statement");
9537 statement_t *const inner_stmt = parse_statement();
9538 statement->case_label.statement = inner_stmt;
9539 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9540 errorf(&inner_stmt->base.source_position, "declaration after default label");
9547 return create_invalid_statement();
9551 * Parse a label statement.
9553 static statement_t *parse_label_statement(void)
9555 assert(token.type == T_IDENTIFIER);
9556 symbol_t *symbol = token.v.symbol;
9557 label_t *label = get_label(symbol);
9559 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9560 statement->label.label = label;
9564 PUSH_PARENT(statement);
9566 /* if statement is already set then the label is defined twice,
9567 * otherwise it was just mentioned in a goto/local label declaration so far
9569 if (label->statement != NULL) {
9570 errorf(HERE, "duplicate label '%Y' (declared %P)",
9571 symbol, &label->base.source_position);
9573 label->base.source_position = token.source_position;
9574 label->statement = statement;
9579 if (token.type == '}') {
9580 /* TODO only warn? */
9581 if (warning.other && false) {
9582 warningf(HERE, "label at end of compound statement");
9583 statement->label.statement = create_empty_statement();
9585 errorf(HERE, "label at end of compound statement");
9586 statement->label.statement = create_invalid_statement();
9588 } else if (token.type == ';') {
9589 /* Eat an empty statement here, to avoid the warning about an empty
9590 * statement after a label. label:; is commonly used to have a label
9591 * before a closing brace. */
9592 statement->label.statement = create_empty_statement();
9595 statement_t *const inner_stmt = parse_statement();
9596 statement->label.statement = inner_stmt;
9597 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9598 errorf(&inner_stmt->base.source_position, "declaration after label");
9602 /* remember the labels in a list for later checking */
9603 *label_anchor = &statement->label;
9604 label_anchor = &statement->label.next;
9611 * Parse an if statement.
9613 static statement_t *parse_if(void)
9615 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9619 PUSH_PARENT(statement);
9621 add_anchor_token('{');
9623 expect('(', end_error);
9624 add_anchor_token(')');
9625 expression_t *const expr = parse_expression();
9626 statement->ifs.condition = expr;
9627 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9629 semantic_condition(expr, "condition of 'if'-statment");
9630 mark_vars_read(expr, NULL);
9631 rem_anchor_token(')');
9632 expect(')', end_error);
9635 rem_anchor_token('{');
9637 add_anchor_token(T_else);
9638 statement_t *const true_stmt = parse_statement();
9639 statement->ifs.true_statement = true_stmt;
9640 rem_anchor_token(T_else);
9642 if (token.type == T_else) {
9644 statement->ifs.false_statement = parse_statement();
9645 } else if (warning.parentheses &&
9646 true_stmt->kind == STATEMENT_IF &&
9647 true_stmt->ifs.false_statement != NULL) {
9648 warningf(&true_stmt->base.source_position,
9649 "suggest explicit braces to avoid ambiguous 'else'");
9657 * Check that all enums are handled in a switch.
9659 * @param statement the switch statement to check
9661 static void check_enum_cases(const switch_statement_t *statement)
9663 const type_t *type = skip_typeref(statement->expression->base.type);
9664 if (! is_type_enum(type))
9666 const enum_type_t *enumt = &type->enumt;
9668 /* if we have a default, no warnings */
9669 if (statement->default_label != NULL)
9672 /* FIXME: calculation of value should be done while parsing */
9673 /* TODO: quadratic algorithm here. Change to an n log n one */
9674 long last_value = -1;
9675 const entity_t *entry = enumt->enume->base.next;
9676 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9677 entry = entry->base.next) {
9678 const expression_t *expression = entry->enum_value.value;
9679 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9681 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9682 if (l->expression == NULL)
9684 if (l->first_case <= value && value <= l->last_case) {
9690 warningf(&statement->base.source_position,
9691 "enumeration value '%Y' not handled in switch",
9692 entry->base.symbol);
9699 * Parse a switch statement.
9701 static statement_t *parse_switch(void)
9703 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9707 PUSH_PARENT(statement);
9709 expect('(', end_error);
9710 add_anchor_token(')');
9711 expression_t *const expr = parse_expression();
9712 mark_vars_read(expr, NULL);
9713 type_t * type = skip_typeref(expr->base.type);
9714 if (is_type_integer(type)) {
9715 type = promote_integer(type);
9716 if (warning.traditional) {
9717 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9718 warningf(&expr->base.source_position,
9719 "'%T' switch expression not converted to '%T' in ISO C",
9723 } else if (is_type_valid(type)) {
9724 errorf(&expr->base.source_position,
9725 "switch quantity is not an integer, but '%T'", type);
9726 type = type_error_type;
9728 statement->switchs.expression = create_implicit_cast(expr, type);
9729 expect(')', end_error);
9730 rem_anchor_token(')');
9732 switch_statement_t *rem = current_switch;
9733 current_switch = &statement->switchs;
9734 statement->switchs.body = parse_statement();
9735 current_switch = rem;
9737 if (warning.switch_default &&
9738 statement->switchs.default_label == NULL) {
9739 warningf(&statement->base.source_position, "switch has no default case");
9741 if (warning.switch_enum)
9742 check_enum_cases(&statement->switchs);
9748 return create_invalid_statement();
9751 static statement_t *parse_loop_body(statement_t *const loop)
9753 statement_t *const rem = current_loop;
9754 current_loop = loop;
9756 statement_t *const body = parse_statement();
9763 * Parse a while statement.
9765 static statement_t *parse_while(void)
9767 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9771 PUSH_PARENT(statement);
9773 expect('(', end_error);
9774 add_anchor_token(')');
9775 expression_t *const cond = parse_expression();
9776 statement->whiles.condition = cond;
9777 /* §6.8.5:2 The controlling expression of an iteration statement shall
9778 * have scalar type. */
9779 semantic_condition(cond, "condition of 'while'-statement");
9780 mark_vars_read(cond, NULL);
9781 rem_anchor_token(')');
9782 expect(')', end_error);
9784 statement->whiles.body = parse_loop_body(statement);
9790 return create_invalid_statement();
9794 * Parse a do statement.
9796 static statement_t *parse_do(void)
9798 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9802 PUSH_PARENT(statement);
9804 add_anchor_token(T_while);
9805 statement->do_while.body = parse_loop_body(statement);
9806 rem_anchor_token(T_while);
9808 expect(T_while, end_error);
9809 expect('(', end_error);
9810 add_anchor_token(')');
9811 expression_t *const cond = parse_expression();
9812 statement->do_while.condition = cond;
9813 /* §6.8.5:2 The controlling expression of an iteration statement shall
9814 * have scalar type. */
9815 semantic_condition(cond, "condition of 'do-while'-statement");
9816 mark_vars_read(cond, NULL);
9817 rem_anchor_token(')');
9818 expect(')', end_error);
9819 expect(';', end_error);
9825 return create_invalid_statement();
9829 * Parse a for statement.
9831 static statement_t *parse_for(void)
9833 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9837 expect('(', end_error1);
9838 add_anchor_token(')');
9840 PUSH_PARENT(statement);
9842 size_t const top = environment_top();
9843 scope_t *old_scope = scope_push(&statement->fors.scope);
9845 bool old_gcc_extension = in_gcc_extension;
9846 while (token.type == T___extension__) {
9848 in_gcc_extension = true;
9851 if (token.type == ';') {
9853 } else if (is_declaration_specifier(&token, false)) {
9854 parse_declaration(record_entity, DECL_FLAGS_NONE);
9856 add_anchor_token(';');
9857 expression_t *const init = parse_expression();
9858 statement->fors.initialisation = init;
9859 mark_vars_read(init, ENT_ANY);
9860 if (warning.unused_value && !expression_has_effect(init)) {
9861 warningf(&init->base.source_position,
9862 "initialisation of 'for'-statement has no effect");
9864 rem_anchor_token(';');
9865 expect(';', end_error2);
9867 in_gcc_extension = old_gcc_extension;
9869 if (token.type != ';') {
9870 add_anchor_token(';');
9871 expression_t *const cond = parse_expression();
9872 statement->fors.condition = cond;
9873 /* §6.8.5:2 The controlling expression of an iteration statement
9874 * shall have scalar type. */
9875 semantic_condition(cond, "condition of 'for'-statement");
9876 mark_vars_read(cond, NULL);
9877 rem_anchor_token(';');
9879 expect(';', end_error2);
9880 if (token.type != ')') {
9881 expression_t *const step = parse_expression();
9882 statement->fors.step = step;
9883 mark_vars_read(step, ENT_ANY);
9884 if (warning.unused_value && !expression_has_effect(step)) {
9885 warningf(&step->base.source_position,
9886 "step of 'for'-statement has no effect");
9889 expect(')', end_error2);
9890 rem_anchor_token(')');
9891 statement->fors.body = parse_loop_body(statement);
9893 assert(current_scope == &statement->fors.scope);
9894 scope_pop(old_scope);
9895 environment_pop_to(top);
9902 rem_anchor_token(')');
9903 assert(current_scope == &statement->fors.scope);
9904 scope_pop(old_scope);
9905 environment_pop_to(top);
9909 return create_invalid_statement();
9913 * Parse a goto statement.
9915 static statement_t *parse_goto(void)
9917 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9920 if (GNU_MODE && token.type == '*') {
9922 expression_t *expression = parse_expression();
9923 mark_vars_read(expression, NULL);
9925 /* Argh: although documentation says the expression must be of type void*,
9926 * gcc accepts anything that can be casted into void* without error */
9927 type_t *type = expression->base.type;
9929 if (type != type_error_type) {
9930 if (!is_type_pointer(type) && !is_type_integer(type)) {
9931 errorf(&expression->base.source_position,
9932 "cannot convert to a pointer type");
9933 } else if (warning.other && type != type_void_ptr) {
9934 warningf(&expression->base.source_position,
9935 "type of computed goto expression should be 'void*' not '%T'", type);
9937 expression = create_implicit_cast(expression, type_void_ptr);
9940 statement->gotos.expression = expression;
9941 } else if (token.type == T_IDENTIFIER) {
9942 symbol_t *symbol = token.v.symbol;
9944 statement->gotos.label = get_label(symbol);
9947 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9949 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9954 /* remember the goto's in a list for later checking */
9955 *goto_anchor = &statement->gotos;
9956 goto_anchor = &statement->gotos.next;
9958 expect(';', end_error);
9962 return create_invalid_statement();
9966 * Parse a continue statement.
9968 static statement_t *parse_continue(void)
9970 if (current_loop == NULL) {
9971 errorf(HERE, "continue statement not within loop");
9974 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9977 expect(';', end_error);
9984 * Parse a break statement.
9986 static statement_t *parse_break(void)
9988 if (current_switch == NULL && current_loop == NULL) {
9989 errorf(HERE, "break statement not within loop or switch");
9992 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9995 expect(';', end_error);
10002 * Parse a __leave statement.
10004 static statement_t *parse_leave_statement(void)
10006 if (current_try == NULL) {
10007 errorf(HERE, "__leave statement not within __try");
10010 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
10013 expect(';', end_error);
10020 * Check if a given entity represents a local variable.
10022 static bool is_local_variable(const entity_t *entity)
10024 if (entity->kind != ENTITY_VARIABLE)
10027 switch ((storage_class_tag_t) entity->declaration.storage_class) {
10028 case STORAGE_CLASS_AUTO:
10029 case STORAGE_CLASS_REGISTER: {
10030 const type_t *type = skip_typeref(entity->declaration.type);
10031 if (is_type_function(type)) {
10043 * Check if a given expression represents a local variable.
10045 static bool expression_is_local_variable(const expression_t *expression)
10047 if (expression->base.kind != EXPR_REFERENCE) {
10050 const entity_t *entity = expression->reference.entity;
10051 return is_local_variable(entity);
10055 * Check if a given expression represents a local variable and
10056 * return its declaration then, else return NULL.
10058 entity_t *expression_is_variable(const expression_t *expression)
10060 if (expression->base.kind != EXPR_REFERENCE) {
10063 entity_t *entity = expression->reference.entity;
10064 if (entity->kind != ENTITY_VARIABLE)
10071 * Parse a return statement.
10073 static statement_t *parse_return(void)
10077 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10079 expression_t *return_value = NULL;
10080 if (token.type != ';') {
10081 return_value = parse_expression();
10082 mark_vars_read(return_value, NULL);
10085 const type_t *const func_type = skip_typeref(current_function->base.type);
10086 assert(is_type_function(func_type));
10087 type_t *const return_type = skip_typeref(func_type->function.return_type);
10089 source_position_t const *const pos = &statement->base.source_position;
10090 if (return_value != NULL) {
10091 type_t *return_value_type = skip_typeref(return_value->base.type);
10093 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10094 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10095 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10096 /* Only warn in C mode, because GCC does the same */
10097 if (c_mode & _CXX || strict_mode) {
10099 "'return' with a value, in function returning 'void'");
10100 } else if (warning.other) {
10102 "'return' with a value, in function returning 'void'");
10104 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10105 /* Only warn in C mode, because GCC does the same */
10108 "'return' with expression in function returning 'void'");
10109 } else if (warning.other) {
10111 "'return' with expression in function returning 'void'");
10115 assign_error_t error = semantic_assign(return_type, return_value);
10116 report_assign_error(error, return_type, return_value, "'return'",
10119 return_value = create_implicit_cast(return_value, return_type);
10120 /* check for returning address of a local var */
10121 if (warning.other && return_value != NULL
10122 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10123 const expression_t *expression = return_value->unary.value;
10124 if (expression_is_local_variable(expression)) {
10125 warningf(pos, "function returns address of local variable");
10128 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10129 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10130 if (c_mode & _CXX || strict_mode) {
10132 "'return' without value, in function returning non-void");
10135 "'return' without value, in function returning non-void");
10138 statement->returns.value = return_value;
10140 expect(';', end_error);
10147 * Parse a declaration statement.
10149 static statement_t *parse_declaration_statement(void)
10151 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10153 entity_t *before = current_scope->last_entity;
10155 parse_external_declaration();
10157 parse_declaration(record_entity, DECL_FLAGS_NONE);
10160 declaration_statement_t *const decl = &statement->declaration;
10161 entity_t *const begin =
10162 before != NULL ? before->base.next : current_scope->entities;
10163 decl->declarations_begin = begin;
10164 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10170 * Parse an expression statement, ie. expr ';'.
10172 static statement_t *parse_expression_statement(void)
10174 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10176 expression_t *const expr = parse_expression();
10177 statement->expression.expression = expr;
10178 mark_vars_read(expr, ENT_ANY);
10180 expect(';', end_error);
10187 * Parse a microsoft __try { } __finally { } or
10188 * __try{ } __except() { }
10190 static statement_t *parse_ms_try_statment(void)
10192 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10195 PUSH_PARENT(statement);
10197 ms_try_statement_t *rem = current_try;
10198 current_try = &statement->ms_try;
10199 statement->ms_try.try_statement = parse_compound_statement(false);
10204 if (token.type == T___except) {
10206 expect('(', end_error);
10207 add_anchor_token(')');
10208 expression_t *const expr = parse_expression();
10209 mark_vars_read(expr, NULL);
10210 type_t * type = skip_typeref(expr->base.type);
10211 if (is_type_integer(type)) {
10212 type = promote_integer(type);
10213 } else if (is_type_valid(type)) {
10214 errorf(&expr->base.source_position,
10215 "__expect expression is not an integer, but '%T'", type);
10216 type = type_error_type;
10218 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10219 rem_anchor_token(')');
10220 expect(')', end_error);
10221 statement->ms_try.final_statement = parse_compound_statement(false);
10222 } else if (token.type == T__finally) {
10224 statement->ms_try.final_statement = parse_compound_statement(false);
10226 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10227 return create_invalid_statement();
10231 return create_invalid_statement();
10234 static statement_t *parse_empty_statement(void)
10236 if (warning.empty_statement) {
10237 warningf(HERE, "statement is empty");
10239 statement_t *const statement = create_empty_statement();
10244 static statement_t *parse_local_label_declaration(void)
10246 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10250 entity_t *begin = NULL, *end = NULL;
10253 if (token.type != T_IDENTIFIER) {
10254 parse_error_expected("while parsing local label declaration",
10255 T_IDENTIFIER, NULL);
10258 symbol_t *symbol = token.v.symbol;
10259 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10260 if (entity != NULL && entity->base.parent_scope == current_scope) {
10261 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10262 symbol, &entity->base.source_position);
10264 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10266 entity->base.parent_scope = current_scope;
10267 entity->base.namespc = NAMESPACE_LABEL;
10268 entity->base.source_position = token.source_position;
10269 entity->base.symbol = symbol;
10272 end->base.next = entity;
10277 environment_push(entity);
10281 if (token.type != ',')
10287 statement->declaration.declarations_begin = begin;
10288 statement->declaration.declarations_end = end;
10292 static void parse_namespace_definition(void)
10296 entity_t *entity = NULL;
10297 symbol_t *symbol = NULL;
10299 if (token.type == T_IDENTIFIER) {
10300 symbol = token.v.symbol;
10303 entity = get_entity(symbol, NAMESPACE_NORMAL);
10304 if (entity != NULL &&
10305 entity->kind != ENTITY_NAMESPACE &&
10306 entity->base.parent_scope == current_scope) {
10307 if (!is_error_entity(entity)) {
10308 error_redefined_as_different_kind(&token.source_position,
10309 entity, ENTITY_NAMESPACE);
10315 if (entity == NULL) {
10316 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10317 entity->base.symbol = symbol;
10318 entity->base.source_position = token.source_position;
10319 entity->base.namespc = NAMESPACE_NORMAL;
10320 entity->base.parent_scope = current_scope;
10323 if (token.type == '=') {
10324 /* TODO: parse namespace alias */
10325 panic("namespace alias definition not supported yet");
10328 environment_push(entity);
10329 append_entity(current_scope, entity);
10331 size_t const top = environment_top();
10332 scope_t *old_scope = scope_push(&entity->namespacee.members);
10334 expect('{', end_error);
10336 expect('}', end_error);
10339 assert(current_scope == &entity->namespacee.members);
10340 scope_pop(old_scope);
10341 environment_pop_to(top);
10345 * Parse a statement.
10346 * There's also parse_statement() which additionally checks for
10347 * "statement has no effect" warnings
10349 static statement_t *intern_parse_statement(void)
10351 statement_t *statement = NULL;
10353 /* declaration or statement */
10354 add_anchor_token(';');
10355 switch (token.type) {
10356 case T_IDENTIFIER: {
10357 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10358 if (la1_type == ':') {
10359 statement = parse_label_statement();
10360 } else if (is_typedef_symbol(token.v.symbol)) {
10361 statement = parse_declaration_statement();
10363 /* it's an identifier, the grammar says this must be an
10364 * expression statement. However it is common that users mistype
10365 * declaration types, so we guess a bit here to improve robustness
10366 * for incorrect programs */
10367 switch (la1_type) {
10370 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10371 goto expression_statment;
10376 statement = parse_declaration_statement();
10380 expression_statment:
10381 statement = parse_expression_statement();
10388 case T___extension__:
10389 /* This can be a prefix to a declaration or an expression statement.
10390 * We simply eat it now and parse the rest with tail recursion. */
10393 } while (token.type == T___extension__);
10394 bool old_gcc_extension = in_gcc_extension;
10395 in_gcc_extension = true;
10396 statement = intern_parse_statement();
10397 in_gcc_extension = old_gcc_extension;
10401 statement = parse_declaration_statement();
10405 statement = parse_local_label_declaration();
10408 case ';': statement = parse_empty_statement(); break;
10409 case '{': statement = parse_compound_statement(false); break;
10410 case T___leave: statement = parse_leave_statement(); break;
10411 case T___try: statement = parse_ms_try_statment(); break;
10412 case T_asm: statement = parse_asm_statement(); break;
10413 case T_break: statement = parse_break(); break;
10414 case T_case: statement = parse_case_statement(); break;
10415 case T_continue: statement = parse_continue(); break;
10416 case T_default: statement = parse_default_statement(); break;
10417 case T_do: statement = parse_do(); break;
10418 case T_for: statement = parse_for(); break;
10419 case T_goto: statement = parse_goto(); break;
10420 case T_if: statement = parse_if(); break;
10421 case T_return: statement = parse_return(); break;
10422 case T_switch: statement = parse_switch(); break;
10423 case T_while: statement = parse_while(); break;
10426 statement = parse_expression_statement();
10430 errorf(HERE, "unexpected token %K while parsing statement", &token);
10431 statement = create_invalid_statement();
10436 rem_anchor_token(';');
10438 assert(statement != NULL
10439 && statement->base.source_position.input_name != NULL);
10445 * parse a statement and emits "statement has no effect" warning if needed
10446 * (This is really a wrapper around intern_parse_statement with check for 1
10447 * single warning. It is needed, because for statement expressions we have
10448 * to avoid the warning on the last statement)
10450 static statement_t *parse_statement(void)
10452 statement_t *statement = intern_parse_statement();
10454 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10455 expression_t *expression = statement->expression.expression;
10456 if (!expression_has_effect(expression)) {
10457 warningf(&expression->base.source_position,
10458 "statement has no effect");
10466 * Parse a compound statement.
10468 static statement_t *parse_compound_statement(bool inside_expression_statement)
10470 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10472 PUSH_PARENT(statement);
10475 add_anchor_token('}');
10476 /* tokens, which can start a statement */
10477 /* TODO MS, __builtin_FOO */
10478 add_anchor_token('!');
10479 add_anchor_token('&');
10480 add_anchor_token('(');
10481 add_anchor_token('*');
10482 add_anchor_token('+');
10483 add_anchor_token('-');
10484 add_anchor_token('{');
10485 add_anchor_token('~');
10486 add_anchor_token(T_CHARACTER_CONSTANT);
10487 add_anchor_token(T_COLONCOLON);
10488 add_anchor_token(T_FLOATINGPOINT);
10489 add_anchor_token(T_IDENTIFIER);
10490 add_anchor_token(T_INTEGER);
10491 add_anchor_token(T_MINUSMINUS);
10492 add_anchor_token(T_PLUSPLUS);
10493 add_anchor_token(T_STRING_LITERAL);
10494 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10495 add_anchor_token(T_WIDE_STRING_LITERAL);
10496 add_anchor_token(T__Bool);
10497 add_anchor_token(T__Complex);
10498 add_anchor_token(T__Imaginary);
10499 add_anchor_token(T___FUNCTION__);
10500 add_anchor_token(T___PRETTY_FUNCTION__);
10501 add_anchor_token(T___alignof__);
10502 add_anchor_token(T___attribute__);
10503 add_anchor_token(T___builtin_va_start);
10504 add_anchor_token(T___extension__);
10505 add_anchor_token(T___func__);
10506 add_anchor_token(T___imag__);
10507 add_anchor_token(T___label__);
10508 add_anchor_token(T___real__);
10509 add_anchor_token(T___thread);
10510 add_anchor_token(T_asm);
10511 add_anchor_token(T_auto);
10512 add_anchor_token(T_bool);
10513 add_anchor_token(T_break);
10514 add_anchor_token(T_case);
10515 add_anchor_token(T_char);
10516 add_anchor_token(T_class);
10517 add_anchor_token(T_const);
10518 add_anchor_token(T_const_cast);
10519 add_anchor_token(T_continue);
10520 add_anchor_token(T_default);
10521 add_anchor_token(T_delete);
10522 add_anchor_token(T_double);
10523 add_anchor_token(T_do);
10524 add_anchor_token(T_dynamic_cast);
10525 add_anchor_token(T_enum);
10526 add_anchor_token(T_extern);
10527 add_anchor_token(T_false);
10528 add_anchor_token(T_float);
10529 add_anchor_token(T_for);
10530 add_anchor_token(T_goto);
10531 add_anchor_token(T_if);
10532 add_anchor_token(T_inline);
10533 add_anchor_token(T_int);
10534 add_anchor_token(T_long);
10535 add_anchor_token(T_new);
10536 add_anchor_token(T_operator);
10537 add_anchor_token(T_register);
10538 add_anchor_token(T_reinterpret_cast);
10539 add_anchor_token(T_restrict);
10540 add_anchor_token(T_return);
10541 add_anchor_token(T_short);
10542 add_anchor_token(T_signed);
10543 add_anchor_token(T_sizeof);
10544 add_anchor_token(T_static);
10545 add_anchor_token(T_static_cast);
10546 add_anchor_token(T_struct);
10547 add_anchor_token(T_switch);
10548 add_anchor_token(T_template);
10549 add_anchor_token(T_this);
10550 add_anchor_token(T_throw);
10551 add_anchor_token(T_true);
10552 add_anchor_token(T_try);
10553 add_anchor_token(T_typedef);
10554 add_anchor_token(T_typeid);
10555 add_anchor_token(T_typename);
10556 add_anchor_token(T_typeof);
10557 add_anchor_token(T_union);
10558 add_anchor_token(T_unsigned);
10559 add_anchor_token(T_using);
10560 add_anchor_token(T_void);
10561 add_anchor_token(T_volatile);
10562 add_anchor_token(T_wchar_t);
10563 add_anchor_token(T_while);
10565 size_t const top = environment_top();
10566 scope_t *old_scope = scope_push(&statement->compound.scope);
10568 statement_t **anchor = &statement->compound.statements;
10569 bool only_decls_so_far = true;
10570 while (token.type != '}') {
10571 if (token.type == T_EOF) {
10572 errorf(&statement->base.source_position,
10573 "EOF while parsing compound statement");
10576 statement_t *sub_statement = intern_parse_statement();
10577 if (is_invalid_statement(sub_statement)) {
10578 /* an error occurred. if we are at an anchor, return */
10584 if (warning.declaration_after_statement) {
10585 if (sub_statement->kind != STATEMENT_DECLARATION) {
10586 only_decls_so_far = false;
10587 } else if (!only_decls_so_far) {
10588 warningf(&sub_statement->base.source_position,
10589 "ISO C90 forbids mixed declarations and code");
10593 *anchor = sub_statement;
10595 while (sub_statement->base.next != NULL)
10596 sub_statement = sub_statement->base.next;
10598 anchor = &sub_statement->base.next;
10602 /* look over all statements again to produce no effect warnings */
10603 if (warning.unused_value) {
10604 statement_t *sub_statement = statement->compound.statements;
10605 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10606 if (sub_statement->kind != STATEMENT_EXPRESSION)
10608 /* don't emit a warning for the last expression in an expression
10609 * statement as it has always an effect */
10610 if (inside_expression_statement && sub_statement->base.next == NULL)
10613 expression_t *expression = sub_statement->expression.expression;
10614 if (!expression_has_effect(expression)) {
10615 warningf(&expression->base.source_position,
10616 "statement has no effect");
10622 rem_anchor_token(T_while);
10623 rem_anchor_token(T_wchar_t);
10624 rem_anchor_token(T_volatile);
10625 rem_anchor_token(T_void);
10626 rem_anchor_token(T_using);
10627 rem_anchor_token(T_unsigned);
10628 rem_anchor_token(T_union);
10629 rem_anchor_token(T_typeof);
10630 rem_anchor_token(T_typename);
10631 rem_anchor_token(T_typeid);
10632 rem_anchor_token(T_typedef);
10633 rem_anchor_token(T_try);
10634 rem_anchor_token(T_true);
10635 rem_anchor_token(T_throw);
10636 rem_anchor_token(T_this);
10637 rem_anchor_token(T_template);
10638 rem_anchor_token(T_switch);
10639 rem_anchor_token(T_struct);
10640 rem_anchor_token(T_static_cast);
10641 rem_anchor_token(T_static);
10642 rem_anchor_token(T_sizeof);
10643 rem_anchor_token(T_signed);
10644 rem_anchor_token(T_short);
10645 rem_anchor_token(T_return);
10646 rem_anchor_token(T_restrict);
10647 rem_anchor_token(T_reinterpret_cast);
10648 rem_anchor_token(T_register);
10649 rem_anchor_token(T_operator);
10650 rem_anchor_token(T_new);
10651 rem_anchor_token(T_long);
10652 rem_anchor_token(T_int);
10653 rem_anchor_token(T_inline);
10654 rem_anchor_token(T_if);
10655 rem_anchor_token(T_goto);
10656 rem_anchor_token(T_for);
10657 rem_anchor_token(T_float);
10658 rem_anchor_token(T_false);
10659 rem_anchor_token(T_extern);
10660 rem_anchor_token(T_enum);
10661 rem_anchor_token(T_dynamic_cast);
10662 rem_anchor_token(T_do);
10663 rem_anchor_token(T_double);
10664 rem_anchor_token(T_delete);
10665 rem_anchor_token(T_default);
10666 rem_anchor_token(T_continue);
10667 rem_anchor_token(T_const_cast);
10668 rem_anchor_token(T_const);
10669 rem_anchor_token(T_class);
10670 rem_anchor_token(T_char);
10671 rem_anchor_token(T_case);
10672 rem_anchor_token(T_break);
10673 rem_anchor_token(T_bool);
10674 rem_anchor_token(T_auto);
10675 rem_anchor_token(T_asm);
10676 rem_anchor_token(T___thread);
10677 rem_anchor_token(T___real__);
10678 rem_anchor_token(T___label__);
10679 rem_anchor_token(T___imag__);
10680 rem_anchor_token(T___func__);
10681 rem_anchor_token(T___extension__);
10682 rem_anchor_token(T___builtin_va_start);
10683 rem_anchor_token(T___attribute__);
10684 rem_anchor_token(T___alignof__);
10685 rem_anchor_token(T___PRETTY_FUNCTION__);
10686 rem_anchor_token(T___FUNCTION__);
10687 rem_anchor_token(T__Imaginary);
10688 rem_anchor_token(T__Complex);
10689 rem_anchor_token(T__Bool);
10690 rem_anchor_token(T_WIDE_STRING_LITERAL);
10691 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10692 rem_anchor_token(T_STRING_LITERAL);
10693 rem_anchor_token(T_PLUSPLUS);
10694 rem_anchor_token(T_MINUSMINUS);
10695 rem_anchor_token(T_INTEGER);
10696 rem_anchor_token(T_IDENTIFIER);
10697 rem_anchor_token(T_FLOATINGPOINT);
10698 rem_anchor_token(T_COLONCOLON);
10699 rem_anchor_token(T_CHARACTER_CONSTANT);
10700 rem_anchor_token('~');
10701 rem_anchor_token('{');
10702 rem_anchor_token('-');
10703 rem_anchor_token('+');
10704 rem_anchor_token('*');
10705 rem_anchor_token('(');
10706 rem_anchor_token('&');
10707 rem_anchor_token('!');
10708 rem_anchor_token('}');
10709 assert(current_scope == &statement->compound.scope);
10710 scope_pop(old_scope);
10711 environment_pop_to(top);
10718 * Check for unused global static functions and variables
10720 static void check_unused_globals(void)
10722 if (!warning.unused_function && !warning.unused_variable)
10725 for (const entity_t *entity = file_scope->entities; entity != NULL;
10726 entity = entity->base.next) {
10727 if (!is_declaration(entity))
10730 const declaration_t *declaration = &entity->declaration;
10731 if (declaration->used ||
10732 declaration->modifiers & DM_UNUSED ||
10733 declaration->modifiers & DM_USED ||
10734 declaration->storage_class != STORAGE_CLASS_STATIC)
10737 type_t *const type = declaration->type;
10739 if (entity->kind == ENTITY_FUNCTION) {
10740 /* inhibit warning for static inline functions */
10741 if (entity->function.is_inline)
10744 s = entity->function.statement != NULL ? "defined" : "declared";
10749 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10750 type, declaration->base.symbol, s);
10754 static void parse_global_asm(void)
10756 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10759 expect('(', end_error);
10761 statement->asms.asm_text = parse_string_literals();
10762 statement->base.next = unit->global_asm;
10763 unit->global_asm = statement;
10765 expect(')', end_error);
10766 expect(';', end_error);
10771 static void parse_linkage_specification(void)
10774 assert(token.type == T_STRING_LITERAL);
10776 const char *linkage = parse_string_literals().begin;
10778 linkage_kind_t old_linkage = current_linkage;
10779 linkage_kind_t new_linkage;
10780 if (strcmp(linkage, "C") == 0) {
10781 new_linkage = LINKAGE_C;
10782 } else if (strcmp(linkage, "C++") == 0) {
10783 new_linkage = LINKAGE_CXX;
10785 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10786 new_linkage = LINKAGE_INVALID;
10788 current_linkage = new_linkage;
10790 if (token.type == '{') {
10793 expect('}', end_error);
10799 assert(current_linkage == new_linkage);
10800 current_linkage = old_linkage;
10803 static void parse_external(void)
10805 switch (token.type) {
10806 DECLARATION_START_NO_EXTERN
10808 case T___extension__:
10809 /* tokens below are for implicit int */
10810 case '&': /* & x; -> int& x; (and error later, because C++ has no
10812 case '*': /* * x; -> int* x; */
10813 case '(': /* (x); -> int (x); */
10814 parse_external_declaration();
10818 if (look_ahead(1)->type == T_STRING_LITERAL) {
10819 parse_linkage_specification();
10821 parse_external_declaration();
10826 parse_global_asm();
10830 parse_namespace_definition();
10834 if (!strict_mode) {
10836 warningf(HERE, "stray ';' outside of function");
10843 errorf(HERE, "stray %K outside of function", &token);
10844 if (token.type == '(' || token.type == '{' || token.type == '[')
10845 eat_until_matching_token(token.type);
10851 static void parse_externals(void)
10853 add_anchor_token('}');
10854 add_anchor_token(T_EOF);
10857 unsigned char token_anchor_copy[T_LAST_TOKEN];
10858 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10861 while (token.type != T_EOF && token.type != '}') {
10863 bool anchor_leak = false;
10864 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10865 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10867 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10868 anchor_leak = true;
10871 if (in_gcc_extension) {
10872 errorf(HERE, "Leaked __extension__");
10873 anchor_leak = true;
10883 rem_anchor_token(T_EOF);
10884 rem_anchor_token('}');
10888 * Parse a translation unit.
10890 static void parse_translation_unit(void)
10892 add_anchor_token(T_EOF);
10897 if (token.type == T_EOF)
10900 errorf(HERE, "stray %K outside of function", &token);
10901 if (token.type == '(' || token.type == '{' || token.type == '[')
10902 eat_until_matching_token(token.type);
10910 * @return the translation unit or NULL if errors occurred.
10912 void start_parsing(void)
10914 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10915 label_stack = NEW_ARR_F(stack_entry_t, 0);
10916 diagnostic_count = 0;
10920 type_set_output(stderr);
10921 ast_set_output(stderr);
10923 assert(unit == NULL);
10924 unit = allocate_ast_zero(sizeof(unit[0]));
10926 assert(file_scope == NULL);
10927 file_scope = &unit->scope;
10929 assert(current_scope == NULL);
10930 scope_push(&unit->scope);
10932 create_gnu_builtins();
10934 create_microsoft_intrinsics();
10937 translation_unit_t *finish_parsing(void)
10939 assert(current_scope == &unit->scope);
10942 assert(file_scope == &unit->scope);
10943 check_unused_globals();
10946 DEL_ARR_F(environment_stack);
10947 DEL_ARR_F(label_stack);
10949 translation_unit_t *result = unit;
10954 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10955 * are given length one. */
10956 static void complete_incomplete_arrays(void)
10958 size_t n = ARR_LEN(incomplete_arrays);
10959 for (size_t i = 0; i != n; ++i) {
10960 declaration_t *const decl = incomplete_arrays[i];
10961 type_t *const orig_type = decl->type;
10962 type_t *const type = skip_typeref(orig_type);
10964 if (!is_type_incomplete(type))
10967 if (warning.other) {
10968 warningf(&decl->base.source_position,
10969 "array '%#T' assumed to have one element",
10970 orig_type, decl->base.symbol);
10973 type_t *const new_type = duplicate_type(type);
10974 new_type->array.size_constant = true;
10975 new_type->array.has_implicit_size = true;
10976 new_type->array.size = 1;
10978 type_t *const result = identify_new_type(new_type);
10980 decl->type = result;
10984 void prepare_main_collect2(entity_t *entity)
10986 // create call to __main
10987 symbol_t *symbol = symbol_table_insert("__main");
10988 entity_t *subsubmain_ent
10989 = create_implicit_function(symbol, &builtin_source_position);
10991 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10992 type_t *ftype = subsubmain_ent->declaration.type;
10993 ref->base.source_position = builtin_source_position;
10994 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10995 ref->reference.entity = subsubmain_ent;
10997 expression_t *call = allocate_expression_zero(EXPR_CALL);
10998 call->base.source_position = builtin_source_position;
10999 call->base.type = type_void;
11000 call->call.function = ref;
11002 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
11003 expr_statement->base.source_position = builtin_source_position;
11004 expr_statement->expression.expression = call;
11006 statement_t *statement = entity->function.statement;
11007 assert(statement->kind == STATEMENT_COMPOUND);
11008 compound_statement_t *compounds = &statement->compound;
11010 expr_statement->base.next = compounds->statements;
11011 compounds->statements = expr_statement;
11016 lookahead_bufpos = 0;
11017 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
11020 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
11021 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
11022 parse_translation_unit();
11023 complete_incomplete_arrays();
11024 DEL_ARR_F(incomplete_arrays);
11025 incomplete_arrays = NULL;
11029 * create a builtin function.
11031 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
11033 symbol_t *symbol = symbol_table_insert(name);
11034 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
11035 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
11036 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
11037 entity->declaration.type = function_type;
11038 entity->declaration.implicit = true;
11039 entity->base.symbol = symbol;
11040 entity->base.source_position = builtin_source_position;
11042 entity->function.btk = kind;
11044 record_entity(entity, /*is_definition=*/false);
11050 * Create predefined gnu builtins.
11052 static void create_gnu_builtins(void)
11054 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
11056 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
11057 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
11058 GNU_BUILTIN(inf, make_function_0_type(type_double));
11059 GNU_BUILTIN(inff, make_function_0_type(type_float));
11060 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
11061 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
11062 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
11063 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
11064 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
11065 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
11066 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11067 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11068 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
11069 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
11070 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
11071 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
11072 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
11073 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
11074 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
11080 * Create predefined MS intrinsics.
11082 static void create_microsoft_intrinsics(void)
11084 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11086 /* intrinsics for all architectures */
11087 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11088 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11089 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11090 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11091 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11092 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11093 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11095 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11096 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11097 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11098 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11101 MS_BUILTIN(_enable, make_function_0_type(type_void));
11102 MS_BUILTIN(_disable, make_function_0_type(type_void));
11103 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11104 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11105 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11106 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11107 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11108 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11109 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11110 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11111 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11112 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11113 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11115 if (machine_size <= 32) {
11116 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11117 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11119 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11120 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11127 * Initialize the parser.
11129 void init_parser(void)
11131 sym_anonymous = symbol_table_insert("<anonymous>");
11133 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11135 init_expression_parsers();
11136 obstack_init(&temp_obst);
11138 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11139 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11143 * Terminate the parser.
11145 void exit_parser(void)
11147 obstack_free(&temp_obst, NULL);