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"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
113 #define PUSH_PARENT(stmt) \
114 statement_t *const prev_parent = current_parent; \
115 ((void)(current_parent = (stmt)))
116 #define POP_PARENT ((void)(current_parent = prev_parent))
118 /** special symbol used for anonymous entities. */
119 static symbol_t *sym_anonymous = NULL;
121 /** The token anchor set */
122 static unsigned char token_anchor_set[T_LAST_TOKEN];
124 /** The current source position. */
125 #define HERE (&token.source_position)
127 /** true if we are in GCC mode. */
128 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
130 static statement_t *parse_compound_statement(bool inside_expression_statement);
131 static statement_t *parse_statement(void);
133 static expression_t *parse_sub_expression(precedence_t);
134 static expression_t *parse_expression(void);
135 static type_t *parse_typename(void);
136 static void parse_externals(void);
137 static void parse_external(void);
139 static void parse_compound_type_entries(compound_t *compound_declaration);
141 static void check_call_argument(type_t *expected_type,
142 call_argument_t *argument, unsigned pos);
144 typedef enum declarator_flags_t {
146 DECL_MAY_BE_ABSTRACT = 1U << 0,
147 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
148 DECL_IS_PARAMETER = 1U << 2
149 } declarator_flags_t;
151 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
152 declarator_flags_t flags);
154 static entity_t *record_entity(entity_t *entity, bool is_definition);
156 static void semantic_comparison(binary_expression_t *expression);
158 static void create_gnu_builtins(void);
159 static void create_microsoft_intrinsics(void);
161 #define STORAGE_CLASSES \
162 STORAGE_CLASSES_NO_EXTERN \
165 #define STORAGE_CLASSES_NO_EXTERN \
172 #define TYPE_QUALIFIERS \
177 case T__forceinline: \
178 case T___attribute__:
180 #define COMPLEX_SPECIFIERS \
182 #define IMAGINARY_SPECIFIERS \
185 #define TYPE_SPECIFIERS \
187 case T___builtin_va_list: \
212 #define DECLARATION_START \
217 #define DECLARATION_START_NO_EXTERN \
218 STORAGE_CLASSES_NO_EXTERN \
222 #define TYPENAME_START \
226 #define EXPRESSION_START \
235 case T_CHARACTER_CONSTANT: \
236 case T_FLOATINGPOINT: \
240 case T_STRING_LITERAL: \
241 case T_WIDE_CHARACTER_CONSTANT: \
242 case T_WIDE_STRING_LITERAL: \
243 case T___FUNCDNAME__: \
244 case T___FUNCSIG__: \
245 case T___FUNCTION__: \
246 case T___PRETTY_FUNCTION__: \
247 case T___alignof__: \
248 case T___builtin_classify_type: \
249 case T___builtin_constant_p: \
250 case T___builtin_isgreater: \
251 case T___builtin_isgreaterequal: \
252 case T___builtin_isless: \
253 case T___builtin_islessequal: \
254 case T___builtin_islessgreater: \
255 case T___builtin_isunordered: \
256 case T___builtin_offsetof: \
257 case T___builtin_va_arg: \
258 case T___builtin_va_start: \
259 case T___builtin_va_copy: \
270 * Allocate an AST node with given size and
271 * initialize all fields with zero.
273 static void *allocate_ast_zero(size_t size)
275 void *res = allocate_ast(size);
276 memset(res, 0, size);
281 * Returns the size of an entity node.
283 * @param kind the entity kind
285 static size_t get_entity_struct_size(entity_kind_t kind)
287 static const size_t sizes[] = {
288 [ENTITY_VARIABLE] = sizeof(variable_t),
289 [ENTITY_PARAMETER] = sizeof(parameter_t),
290 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
291 [ENTITY_FUNCTION] = sizeof(function_t),
292 [ENTITY_TYPEDEF] = sizeof(typedef_t),
293 [ENTITY_STRUCT] = sizeof(compound_t),
294 [ENTITY_UNION] = sizeof(compound_t),
295 [ENTITY_ENUM] = sizeof(enum_t),
296 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
297 [ENTITY_LABEL] = sizeof(label_t),
298 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
299 [ENTITY_NAMESPACE] = sizeof(namespace_t)
301 assert(kind < lengthof(sizes));
302 assert(sizes[kind] != 0);
307 * Allocate an entity of given kind and initialize all
310 * @param kind the kind of the entity to allocate
312 static entity_t *allocate_entity_zero(entity_kind_t kind)
314 size_t size = get_entity_struct_size(kind);
315 entity_t *entity = allocate_ast_zero(size);
321 * Returns the size of a statement node.
323 * @param kind the statement kind
325 static size_t get_statement_struct_size(statement_kind_t kind)
327 static const size_t sizes[] = {
328 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
329 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
330 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
331 [STATEMENT_RETURN] = sizeof(return_statement_t),
332 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
333 [STATEMENT_IF] = sizeof(if_statement_t),
334 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
335 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
336 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
337 [STATEMENT_BREAK] = sizeof(statement_base_t),
338 [STATEMENT_GOTO] = sizeof(goto_statement_t),
339 [STATEMENT_LABEL] = sizeof(label_statement_t),
340 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
341 [STATEMENT_WHILE] = sizeof(while_statement_t),
342 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
343 [STATEMENT_FOR] = sizeof(for_statement_t),
344 [STATEMENT_ASM] = sizeof(asm_statement_t),
345 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
346 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
348 assert(kind < lengthof(sizes));
349 assert(sizes[kind] != 0);
354 * Returns the size of an expression node.
356 * @param kind the expression kind
358 static size_t get_expression_struct_size(expression_kind_t kind)
360 static const size_t sizes[] = {
361 [EXPR_INVALID] = sizeof(expression_base_t),
362 [EXPR_REFERENCE] = sizeof(reference_expression_t),
363 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
364 [EXPR_CONST] = sizeof(const_expression_t),
365 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
366 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
367 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
368 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
369 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
370 [EXPR_CALL] = sizeof(call_expression_t),
371 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
372 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
373 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
374 [EXPR_SELECT] = sizeof(select_expression_t),
375 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
376 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
377 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
378 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
379 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
380 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
381 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
382 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
383 [EXPR_VA_START] = sizeof(va_start_expression_t),
384 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
385 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
386 [EXPR_STATEMENT] = sizeof(statement_expression_t),
387 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
389 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
390 return sizes[EXPR_UNARY_FIRST];
392 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
393 return sizes[EXPR_BINARY_FIRST];
395 assert(kind < lengthof(sizes));
396 assert(sizes[kind] != 0);
401 * Allocate a statement node of given kind and initialize all
402 * fields with zero. Sets its source position to the position
403 * of the current token.
405 static statement_t *allocate_statement_zero(statement_kind_t kind)
407 size_t size = get_statement_struct_size(kind);
408 statement_t *res = allocate_ast_zero(size);
410 res->base.kind = kind;
411 res->base.parent = current_parent;
412 res->base.source_position = token.source_position;
417 * Allocate an expression node of given kind and initialize all
420 * @param kind the kind of the expression to allocate
422 static expression_t *allocate_expression_zero(expression_kind_t kind)
424 size_t size = get_expression_struct_size(kind);
425 expression_t *res = allocate_ast_zero(size);
427 res->base.kind = kind;
428 res->base.type = type_error_type;
429 res->base.source_position = token.source_position;
434 * Creates a new invalid expression at the source position
435 * of the current token.
437 static expression_t *create_invalid_expression(void)
439 return allocate_expression_zero(EXPR_INVALID);
443 * Creates a new invalid statement.
445 static statement_t *create_invalid_statement(void)
447 return allocate_statement_zero(STATEMENT_INVALID);
451 * Allocate a new empty statement.
453 static statement_t *create_empty_statement(void)
455 return allocate_statement_zero(STATEMENT_EMPTY);
459 * Returns the size of a type node.
461 * @param kind the type kind
463 static size_t get_type_struct_size(type_kind_t kind)
465 static const size_t sizes[] = {
466 [TYPE_ATOMIC] = sizeof(atomic_type_t),
467 [TYPE_COMPLEX] = sizeof(complex_type_t),
468 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
469 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
470 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
471 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
472 [TYPE_ENUM] = sizeof(enum_type_t),
473 [TYPE_FUNCTION] = sizeof(function_type_t),
474 [TYPE_POINTER] = sizeof(pointer_type_t),
475 [TYPE_ARRAY] = sizeof(array_type_t),
476 [TYPE_BUILTIN] = sizeof(builtin_type_t),
477 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
478 [TYPE_TYPEOF] = sizeof(typeof_type_t),
480 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
481 assert(kind <= TYPE_TYPEOF);
482 assert(sizes[kind] != 0);
487 * Allocate a type node of given kind and initialize all
490 * @param kind type kind to allocate
492 static type_t *allocate_type_zero(type_kind_t kind)
494 size_t size = get_type_struct_size(kind);
495 type_t *res = obstack_alloc(type_obst, size);
496 memset(res, 0, size);
497 res->base.kind = kind;
502 static function_parameter_t *allocate_parameter(type_t *const type)
504 function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
505 memset(param, 0, sizeof(*param));
511 * Returns the size of an initializer node.
513 * @param kind the initializer kind
515 static size_t get_initializer_size(initializer_kind_t kind)
517 static const size_t sizes[] = {
518 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
519 [INITIALIZER_STRING] = sizeof(initializer_string_t),
520 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
521 [INITIALIZER_LIST] = sizeof(initializer_list_t),
522 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
524 assert(kind < lengthof(sizes));
525 assert(sizes[kind] != 0);
530 * Allocate an initializer node of given kind and initialize all
533 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
535 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
542 * Returns the index of the top element of the environment stack.
544 static size_t environment_top(void)
546 return ARR_LEN(environment_stack);
550 * Returns the index of the top element of the global label stack.
552 static size_t label_top(void)
554 return ARR_LEN(label_stack);
558 * Return the next token.
560 static inline void next_token(void)
562 token = lookahead_buffer[lookahead_bufpos];
563 lookahead_buffer[lookahead_bufpos] = lexer_token;
566 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
569 print_token(stderr, &token);
570 fprintf(stderr, "\n");
574 static inline bool next_if(int const type)
576 if (token.type == type) {
585 * Return the next token with a given lookahead.
587 static inline const token_t *look_ahead(size_t num)
589 assert(0 < num && num <= MAX_LOOKAHEAD);
590 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
591 return &lookahead_buffer[pos];
595 * Adds a token type to the token type anchor set (a multi-set).
597 static void add_anchor_token(int token_type)
599 assert(0 <= token_type && token_type < T_LAST_TOKEN);
600 ++token_anchor_set[token_type];
604 * Set the number of tokens types of the given type
605 * to zero and return the old count.
607 static int save_and_reset_anchor_state(int token_type)
609 assert(0 <= token_type && token_type < T_LAST_TOKEN);
610 int count = token_anchor_set[token_type];
611 token_anchor_set[token_type] = 0;
616 * Restore the number of token types to the given count.
618 static void restore_anchor_state(int token_type, int count)
620 assert(0 <= token_type && token_type < T_LAST_TOKEN);
621 token_anchor_set[token_type] = count;
625 * Remove a token type from the token type anchor set (a multi-set).
627 static void rem_anchor_token(int token_type)
629 assert(0 <= token_type && token_type < T_LAST_TOKEN);
630 assert(token_anchor_set[token_type] != 0);
631 --token_anchor_set[token_type];
635 * Return true if the token type of the current token is
638 static bool at_anchor(void)
642 return token_anchor_set[token.type];
646 * Eat tokens until a matching token type is found.
648 static void eat_until_matching_token(int type)
652 case '(': end_token = ')'; break;
653 case '{': end_token = '}'; break;
654 case '[': end_token = ']'; break;
655 default: end_token = type; break;
658 unsigned parenthesis_count = 0;
659 unsigned brace_count = 0;
660 unsigned bracket_count = 0;
661 while (token.type != end_token ||
662 parenthesis_count != 0 ||
664 bracket_count != 0) {
665 switch (token.type) {
667 case '(': ++parenthesis_count; break;
668 case '{': ++brace_count; break;
669 case '[': ++bracket_count; break;
672 if (parenthesis_count > 0)
682 if (bracket_count > 0)
685 if (token.type == end_token &&
686 parenthesis_count == 0 &&
700 * Eat input tokens until an anchor is found.
702 static void eat_until_anchor(void)
704 while (token_anchor_set[token.type] == 0) {
705 if (token.type == '(' || token.type == '{' || token.type == '[')
706 eat_until_matching_token(token.type);
712 * Eat a whole block from input tokens.
714 static void eat_block(void)
716 eat_until_matching_token('{');
720 #define eat(token_type) (assert(token.type == (token_type)), next_token())
723 * Report a parse error because an expected token was not found.
726 #if defined __GNUC__ && __GNUC__ >= 4
727 __attribute__((sentinel))
729 void parse_error_expected(const char *message, ...)
731 if (message != NULL) {
732 errorf(HERE, "%s", message);
735 va_start(ap, message);
736 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
741 * Report an incompatible type.
743 static void type_error_incompatible(const char *msg,
744 const source_position_t *source_position, type_t *type1, type_t *type2)
746 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
751 * Expect the current token is the expected token.
752 * If not, generate an error, eat the current statement,
753 * and goto the end_error label.
755 #define expect(expected, error_label) \
757 if (UNLIKELY(token.type != (expected))) { \
758 parse_error_expected(NULL, (expected), NULL); \
759 add_anchor_token(expected); \
760 eat_until_anchor(); \
761 next_if((expected)); \
762 rem_anchor_token(expected); \
769 * Push a given scope on the scope stack and make it the
772 static scope_t *scope_push(scope_t *new_scope)
774 if (current_scope != NULL) {
775 new_scope->depth = current_scope->depth + 1;
778 scope_t *old_scope = current_scope;
779 current_scope = new_scope;
784 * Pop the current scope from the scope stack.
786 static void scope_pop(scope_t *old_scope)
788 current_scope = old_scope;
792 * Search an entity by its symbol in a given namespace.
794 static entity_t *get_entity(const symbol_t *const symbol,
795 namespace_tag_t namespc)
797 entity_t *entity = symbol->entity;
798 for (; entity != NULL; entity = entity->base.symbol_next) {
799 if (entity->base.namespc == namespc)
806 /* §6.2.3:1 24) There is only one name space for tags even though three are
808 static entity_t *get_tag(symbol_t const *const symbol,
809 entity_kind_tag_t const kind)
811 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
812 if (entity != NULL && entity->kind != kind) {
814 "'%Y' defined as wrong kind of tag (previous definition %P)",
815 symbol, &entity->base.source_position);
822 * pushs an entity on the environment stack and links the corresponding symbol
825 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
827 symbol_t *symbol = entity->base.symbol;
828 entity_namespace_t namespc = entity->base.namespc;
829 assert(namespc != NAMESPACE_INVALID);
831 /* replace/add entity into entity list of the symbol */
834 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
839 /* replace an entry? */
840 if (iter->base.namespc == namespc) {
841 entity->base.symbol_next = iter->base.symbol_next;
847 /* remember old declaration */
849 entry.symbol = symbol;
850 entry.old_entity = iter;
851 entry.namespc = namespc;
852 ARR_APP1(stack_entry_t, *stack_ptr, entry);
856 * Push an entity on the environment stack.
858 static void environment_push(entity_t *entity)
860 assert(entity->base.source_position.input_name != NULL);
861 assert(entity->base.parent_scope != NULL);
862 stack_push(&environment_stack, entity);
866 * Push a declaration on the global label stack.
868 * @param declaration the declaration
870 static void label_push(entity_t *label)
872 /* we abuse the parameters scope as parent for the labels */
873 label->base.parent_scope = ¤t_function->parameters;
874 stack_push(&label_stack, label);
878 * pops symbols from the environment stack until @p new_top is the top element
880 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
882 stack_entry_t *stack = *stack_ptr;
883 size_t top = ARR_LEN(stack);
886 assert(new_top <= top);
890 for (i = top; i > new_top; --i) {
891 stack_entry_t *entry = &stack[i - 1];
893 entity_t *old_entity = entry->old_entity;
894 symbol_t *symbol = entry->symbol;
895 entity_namespace_t namespc = entry->namespc;
897 /* replace with old_entity/remove */
900 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
902 assert(iter != NULL);
903 /* replace an entry? */
904 if (iter->base.namespc == namespc)
908 /* restore definition from outer scopes (if there was one) */
909 if (old_entity != NULL) {
910 old_entity->base.symbol_next = iter->base.symbol_next;
911 *anchor = old_entity;
913 /* remove entry from list */
914 *anchor = iter->base.symbol_next;
918 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
922 * Pop all entries from the environment stack until the new_top
925 * @param new_top the new stack top
927 static void environment_pop_to(size_t new_top)
929 stack_pop_to(&environment_stack, new_top);
933 * Pop all entries from the global label stack until the new_top
936 * @param new_top the new stack top
938 static void label_pop_to(size_t new_top)
940 stack_pop_to(&label_stack, new_top);
943 static int get_akind_rank(atomic_type_kind_t akind)
949 * Return the type rank for an atomic type.
951 static int get_rank(const type_t *type)
953 assert(!is_typeref(type));
954 if (type->kind == TYPE_ENUM)
955 return get_akind_rank(type->enumt.akind);
957 assert(type->kind == TYPE_ATOMIC);
958 return get_akind_rank(type->atomic.akind);
962 * §6.3.1.1:2 Do integer promotion for a given type.
964 * @param type the type to promote
965 * @return the promoted type
967 static type_t *promote_integer(type_t *type)
969 if (type->kind == TYPE_BITFIELD)
970 type = type->bitfield.base_type;
972 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
979 * Create a cast expression.
981 * @param expression the expression to cast
982 * @param dest_type the destination type
984 static expression_t *create_cast_expression(expression_t *expression,
987 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
989 cast->unary.value = expression;
990 cast->base.type = dest_type;
996 * Check if a given expression represents a null pointer constant.
998 * @param expression the expression to check
1000 static bool is_null_pointer_constant(const expression_t *expression)
1002 /* skip void* cast */
1003 if (expression->kind == EXPR_UNARY_CAST ||
1004 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1005 type_t *const type = skip_typeref(expression->base.type);
1006 if (types_compatible(type, type_void_ptr))
1007 expression = expression->unary.value;
1010 type_t *const type = skip_typeref(expression->base.type);
1012 is_type_integer(type) &&
1013 is_constant_expression(expression) &&
1014 !fold_constant_to_bool(expression);
1018 * Create an implicit cast expression.
1020 * @param expression the expression to cast
1021 * @param dest_type the destination type
1023 static expression_t *create_implicit_cast(expression_t *expression,
1026 type_t *const source_type = expression->base.type;
1028 if (source_type == dest_type)
1031 return create_cast_expression(expression, dest_type);
1034 typedef enum assign_error_t {
1036 ASSIGN_ERROR_INCOMPATIBLE,
1037 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1038 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1039 ASSIGN_WARNING_POINTER_FROM_INT,
1040 ASSIGN_WARNING_INT_FROM_POINTER
1043 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1044 const expression_t *const right,
1045 const char *context,
1046 const source_position_t *source_position)
1048 type_t *const orig_type_right = right->base.type;
1049 type_t *const type_left = skip_typeref(orig_type_left);
1050 type_t *const type_right = skip_typeref(orig_type_right);
1053 case ASSIGN_SUCCESS:
1055 case ASSIGN_ERROR_INCOMPATIBLE:
1056 errorf(source_position,
1057 "destination type '%T' in %s is incompatible with type '%T'",
1058 orig_type_left, context, orig_type_right);
1061 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1062 if (warning.other) {
1063 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1064 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1066 /* the left type has all qualifiers from the right type */
1067 unsigned missing_qualifiers
1068 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1069 warningf(source_position,
1070 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1071 orig_type_left, context, orig_type_right, missing_qualifiers);
1076 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1077 if (warning.other) {
1078 warningf(source_position,
1079 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1080 orig_type_left, context, right, orig_type_right);
1084 case ASSIGN_WARNING_POINTER_FROM_INT:
1085 if (warning.other) {
1086 warningf(source_position,
1087 "%s makes pointer '%T' from integer '%T' without a cast",
1088 context, orig_type_left, orig_type_right);
1092 case ASSIGN_WARNING_INT_FROM_POINTER:
1093 if (warning.other) {
1094 warningf(source_position,
1095 "%s makes integer '%T' from pointer '%T' without a cast",
1096 context, orig_type_left, orig_type_right);
1101 panic("invalid error value");
1105 /** Implements the rules from §6.5.16.1 */
1106 static assign_error_t semantic_assign(type_t *orig_type_left,
1107 const expression_t *const right)
1109 type_t *const orig_type_right = right->base.type;
1110 type_t *const type_left = skip_typeref(orig_type_left);
1111 type_t *const type_right = skip_typeref(orig_type_right);
1113 if (is_type_pointer(type_left)) {
1114 if (is_null_pointer_constant(right)) {
1115 return ASSIGN_SUCCESS;
1116 } else if (is_type_pointer(type_right)) {
1117 type_t *points_to_left
1118 = skip_typeref(type_left->pointer.points_to);
1119 type_t *points_to_right
1120 = skip_typeref(type_right->pointer.points_to);
1121 assign_error_t res = ASSIGN_SUCCESS;
1123 /* the left type has all qualifiers from the right type */
1124 unsigned missing_qualifiers
1125 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1126 if (missing_qualifiers != 0) {
1127 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1130 points_to_left = get_unqualified_type(points_to_left);
1131 points_to_right = get_unqualified_type(points_to_right);
1133 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1136 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1137 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1138 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1141 if (!types_compatible(points_to_left, points_to_right)) {
1142 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1146 } else if (is_type_integer(type_right)) {
1147 return ASSIGN_WARNING_POINTER_FROM_INT;
1149 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1150 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1151 && is_type_pointer(type_right))) {
1152 return ASSIGN_SUCCESS;
1153 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1154 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1155 type_t *const unqual_type_left = get_unqualified_type(type_left);
1156 type_t *const unqual_type_right = get_unqualified_type(type_right);
1157 if (types_compatible(unqual_type_left, unqual_type_right)) {
1158 return ASSIGN_SUCCESS;
1160 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1161 return ASSIGN_WARNING_INT_FROM_POINTER;
1164 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1165 return ASSIGN_SUCCESS;
1167 return ASSIGN_ERROR_INCOMPATIBLE;
1170 static expression_t *parse_constant_expression(void)
1172 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1174 if (!is_constant_expression(result)) {
1175 errorf(&result->base.source_position,
1176 "expression '%E' is not constant", result);
1182 static expression_t *parse_assignment_expression(void)
1184 return parse_sub_expression(PREC_ASSIGNMENT);
1187 static string_t parse_string_literals(void)
1189 assert(token.type == T_STRING_LITERAL);
1190 string_t result = token.v.string;
1194 while (token.type == T_STRING_LITERAL) {
1195 result = concat_strings(&result, &token.v.string);
1203 * compare two string, ignoring double underscores on the second.
1205 static int strcmp_underscore(const char *s1, const char *s2)
1207 if (s2[0] == '_' && s2[1] == '_') {
1208 size_t len2 = strlen(s2);
1209 size_t len1 = strlen(s1);
1210 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1211 return strncmp(s1, s2+2, len2-4);
1215 return strcmp(s1, s2);
1218 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1220 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1221 attribute->kind = kind;
1226 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1229 * __attribute__ ( ( attribute-list ) )
1233 * attribute_list , attrib
1238 * any-word ( identifier )
1239 * any-word ( identifier , nonempty-expr-list )
1240 * any-word ( expr-list )
1242 * where the "identifier" must not be declared as a type, and
1243 * "any-word" may be any identifier (including one declared as a
1244 * type), a reserved word storage class specifier, type specifier or
1245 * type qualifier. ??? This still leaves out most reserved keywords
1246 * (following the old parser), shouldn't we include them, and why not
1247 * allow identifiers declared as types to start the arguments?
1249 * Matze: this all looks confusing and little systematic, so we're even less
1250 * strict and parse any list of things which are identifiers or
1251 * (assignment-)expressions.
1253 static attribute_argument_t *parse_attribute_arguments(void)
1255 attribute_argument_t *first = NULL;
1256 attribute_argument_t **anchor = &first;
1257 if (token.type != ')') do {
1258 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1260 /* is it an identifier */
1261 if (token.type == T_IDENTIFIER
1262 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1263 symbol_t *symbol = token.v.symbol;
1264 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1265 argument->v.symbol = symbol;
1268 /* must be an expression */
1269 expression_t *expression = parse_assignment_expression();
1271 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1272 argument->v.expression = expression;
1275 /* append argument */
1277 anchor = &argument->next;
1278 } while (next_if(','));
1279 expect(')', end_error);
1288 static attribute_t *parse_attribute_asm(void)
1292 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1294 expect('(', end_error);
1295 attribute->a.arguments = parse_attribute_arguments();
1302 static symbol_t *get_symbol_from_token(void)
1304 switch(token.type) {
1306 return token.v.symbol;
1335 /* maybe we need more tokens ... add them on demand */
1336 return get_token_symbol(&token);
1342 static attribute_t *parse_attribute_gnu_single(void)
1344 /* parse "any-word" */
1345 symbol_t *symbol = get_symbol_from_token();
1346 if (symbol == NULL) {
1347 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1351 const char *name = symbol->string;
1354 attribute_kind_t kind;
1355 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1356 const char *attribute_name = get_attribute_name(kind);
1357 if (attribute_name != NULL
1358 && strcmp_underscore(attribute_name, name) == 0)
1362 if (kind >= ATTRIBUTE_GNU_LAST) {
1363 if (warning.attribute) {
1364 warningf(HERE, "unknown attribute '%s' ignored", name);
1366 /* TODO: we should still save the attribute in the list... */
1367 kind = ATTRIBUTE_UNKNOWN;
1370 attribute_t *attribute = allocate_attribute_zero(kind);
1372 /* parse arguments */
1374 attribute->a.arguments = parse_attribute_arguments();
1382 static attribute_t *parse_attribute_gnu(void)
1384 attribute_t *first = NULL;
1385 attribute_t **anchor = &first;
1387 eat(T___attribute__);
1388 expect('(', end_error);
1389 expect('(', end_error);
1391 if (token.type != ')') do {
1392 attribute_t *attribute = parse_attribute_gnu_single();
1393 if (attribute == NULL)
1396 *anchor = attribute;
1397 anchor = &attribute->next;
1398 } while (next_if(','));
1399 expect(')', end_error);
1400 expect(')', end_error);
1406 /** Parse attributes. */
1407 static attribute_t *parse_attributes(attribute_t *first)
1409 attribute_t **anchor = &first;
1411 while (*anchor != NULL)
1412 anchor = &(*anchor)->next;
1414 attribute_t *attribute;
1415 switch (token.type) {
1416 case T___attribute__:
1417 attribute = parse_attribute_gnu();
1421 attribute = parse_attribute_asm();
1426 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1431 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1434 case T__forceinline:
1436 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1441 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1446 /* TODO record modifier */
1448 warningf(HERE, "Ignoring declaration modifier %K", &token);
1449 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1456 *anchor = attribute;
1457 anchor = &attribute->next;
1461 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1463 static entity_t *determine_lhs_ent(expression_t *const expr,
1466 switch (expr->kind) {
1467 case EXPR_REFERENCE: {
1468 entity_t *const entity = expr->reference.entity;
1469 /* we should only find variables as lvalues... */
1470 if (entity->base.kind != ENTITY_VARIABLE
1471 && entity->base.kind != ENTITY_PARAMETER)
1477 case EXPR_ARRAY_ACCESS: {
1478 expression_t *const ref = expr->array_access.array_ref;
1479 entity_t * ent = NULL;
1480 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1481 ent = determine_lhs_ent(ref, lhs_ent);
1484 mark_vars_read(expr->select.compound, lhs_ent);
1486 mark_vars_read(expr->array_access.index, lhs_ent);
1491 if (is_type_compound(skip_typeref(expr->base.type))) {
1492 return determine_lhs_ent(expr->select.compound, lhs_ent);
1494 mark_vars_read(expr->select.compound, lhs_ent);
1499 case EXPR_UNARY_DEREFERENCE: {
1500 expression_t *const val = expr->unary.value;
1501 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1503 return determine_lhs_ent(val->unary.value, lhs_ent);
1505 mark_vars_read(val, NULL);
1511 mark_vars_read(expr, NULL);
1516 #define ENT_ANY ((entity_t*)-1)
1519 * Mark declarations, which are read. This is used to detect variables, which
1523 * x is not marked as "read", because it is only read to calculate its own new
1527 * x and y are not detected as "not read", because multiple variables are
1530 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1532 switch (expr->kind) {
1533 case EXPR_REFERENCE: {
1534 entity_t *const entity = expr->reference.entity;
1535 if (entity->kind != ENTITY_VARIABLE
1536 && entity->kind != ENTITY_PARAMETER)
1539 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1540 if (entity->kind == ENTITY_VARIABLE) {
1541 entity->variable.read = true;
1543 entity->parameter.read = true;
1550 // TODO respect pure/const
1551 mark_vars_read(expr->call.function, NULL);
1552 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1553 mark_vars_read(arg->expression, NULL);
1557 case EXPR_CONDITIONAL:
1558 // TODO lhs_decl should depend on whether true/false have an effect
1559 mark_vars_read(expr->conditional.condition, NULL);
1560 if (expr->conditional.true_expression != NULL)
1561 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1562 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1566 if (lhs_ent == ENT_ANY
1567 && !is_type_compound(skip_typeref(expr->base.type)))
1569 mark_vars_read(expr->select.compound, lhs_ent);
1572 case EXPR_ARRAY_ACCESS: {
1573 expression_t *const ref = expr->array_access.array_ref;
1574 mark_vars_read(ref, lhs_ent);
1575 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1576 mark_vars_read(expr->array_access.index, lhs_ent);
1581 mark_vars_read(expr->va_arge.ap, lhs_ent);
1585 mark_vars_read(expr->va_copye.src, lhs_ent);
1588 case EXPR_UNARY_CAST:
1589 /* Special case: Use void cast to mark a variable as "read" */
1590 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1595 case EXPR_UNARY_THROW:
1596 if (expr->unary.value == NULL)
1599 case EXPR_UNARY_DEREFERENCE:
1600 case EXPR_UNARY_DELETE:
1601 case EXPR_UNARY_DELETE_ARRAY:
1602 if (lhs_ent == ENT_ANY)
1606 case EXPR_UNARY_NEGATE:
1607 case EXPR_UNARY_PLUS:
1608 case EXPR_UNARY_BITWISE_NEGATE:
1609 case EXPR_UNARY_NOT:
1610 case EXPR_UNARY_TAKE_ADDRESS:
1611 case EXPR_UNARY_POSTFIX_INCREMENT:
1612 case EXPR_UNARY_POSTFIX_DECREMENT:
1613 case EXPR_UNARY_PREFIX_INCREMENT:
1614 case EXPR_UNARY_PREFIX_DECREMENT:
1615 case EXPR_UNARY_CAST_IMPLICIT:
1616 case EXPR_UNARY_ASSUME:
1618 mark_vars_read(expr->unary.value, lhs_ent);
1621 case EXPR_BINARY_ADD:
1622 case EXPR_BINARY_SUB:
1623 case EXPR_BINARY_MUL:
1624 case EXPR_BINARY_DIV:
1625 case EXPR_BINARY_MOD:
1626 case EXPR_BINARY_EQUAL:
1627 case EXPR_BINARY_NOTEQUAL:
1628 case EXPR_BINARY_LESS:
1629 case EXPR_BINARY_LESSEQUAL:
1630 case EXPR_BINARY_GREATER:
1631 case EXPR_BINARY_GREATEREQUAL:
1632 case EXPR_BINARY_BITWISE_AND:
1633 case EXPR_BINARY_BITWISE_OR:
1634 case EXPR_BINARY_BITWISE_XOR:
1635 case EXPR_BINARY_LOGICAL_AND:
1636 case EXPR_BINARY_LOGICAL_OR:
1637 case EXPR_BINARY_SHIFTLEFT:
1638 case EXPR_BINARY_SHIFTRIGHT:
1639 case EXPR_BINARY_COMMA:
1640 case EXPR_BINARY_ISGREATER:
1641 case EXPR_BINARY_ISGREATEREQUAL:
1642 case EXPR_BINARY_ISLESS:
1643 case EXPR_BINARY_ISLESSEQUAL:
1644 case EXPR_BINARY_ISLESSGREATER:
1645 case EXPR_BINARY_ISUNORDERED:
1646 mark_vars_read(expr->binary.left, lhs_ent);
1647 mark_vars_read(expr->binary.right, lhs_ent);
1650 case EXPR_BINARY_ASSIGN:
1651 case EXPR_BINARY_MUL_ASSIGN:
1652 case EXPR_BINARY_DIV_ASSIGN:
1653 case EXPR_BINARY_MOD_ASSIGN:
1654 case EXPR_BINARY_ADD_ASSIGN:
1655 case EXPR_BINARY_SUB_ASSIGN:
1656 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1657 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1658 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1659 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1660 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1661 if (lhs_ent == ENT_ANY)
1663 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1664 mark_vars_read(expr->binary.right, lhs_ent);
1669 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1675 case EXPR_CHARACTER_CONSTANT:
1676 case EXPR_WIDE_CHARACTER_CONSTANT:
1677 case EXPR_STRING_LITERAL:
1678 case EXPR_WIDE_STRING_LITERAL:
1679 case EXPR_COMPOUND_LITERAL: // TODO init?
1681 case EXPR_CLASSIFY_TYPE:
1684 case EXPR_BUILTIN_CONSTANT_P:
1685 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1687 case EXPR_STATEMENT: // TODO
1688 case EXPR_LABEL_ADDRESS:
1689 case EXPR_REFERENCE_ENUM_VALUE:
1693 panic("unhandled expression");
1696 static designator_t *parse_designation(void)
1698 designator_t *result = NULL;
1699 designator_t **anchor = &result;
1702 designator_t *designator;
1703 switch (token.type) {
1705 designator = allocate_ast_zero(sizeof(designator[0]));
1706 designator->source_position = token.source_position;
1708 add_anchor_token(']');
1709 designator->array_index = parse_constant_expression();
1710 rem_anchor_token(']');
1711 expect(']', end_error);
1714 designator = allocate_ast_zero(sizeof(designator[0]));
1715 designator->source_position = token.source_position;
1717 if (token.type != T_IDENTIFIER) {
1718 parse_error_expected("while parsing designator",
1719 T_IDENTIFIER, NULL);
1722 designator->symbol = token.v.symbol;
1726 expect('=', end_error);
1730 assert(designator != NULL);
1731 *anchor = designator;
1732 anchor = &designator->next;
1738 static initializer_t *initializer_from_string(array_type_t *type,
1739 const string_t *const string)
1741 /* TODO: check len vs. size of array type */
1744 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1745 initializer->string.string = *string;
1750 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1751 wide_string_t *const string)
1753 /* TODO: check len vs. size of array type */
1756 initializer_t *const initializer =
1757 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1758 initializer->wide_string.string = *string;
1764 * Build an initializer from a given expression.
1766 static initializer_t *initializer_from_expression(type_t *orig_type,
1767 expression_t *expression)
1769 /* TODO check that expression is a constant expression */
1771 /* §6.7.8.14/15 char array may be initialized by string literals */
1772 type_t *type = skip_typeref(orig_type);
1773 type_t *expr_type_orig = expression->base.type;
1774 type_t *expr_type = skip_typeref(expr_type_orig);
1775 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1776 array_type_t *const array_type = &type->array;
1777 type_t *const element_type = skip_typeref(array_type->element_type);
1779 if (element_type->kind == TYPE_ATOMIC) {
1780 atomic_type_kind_t akind = element_type->atomic.akind;
1781 switch (expression->kind) {
1782 case EXPR_STRING_LITERAL:
1783 if (akind == ATOMIC_TYPE_CHAR
1784 || akind == ATOMIC_TYPE_SCHAR
1785 || akind == ATOMIC_TYPE_UCHAR) {
1786 return initializer_from_string(array_type,
1787 &expression->string.value);
1791 case EXPR_WIDE_STRING_LITERAL: {
1792 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1793 if (get_unqualified_type(element_type) == bare_wchar_type) {
1794 return initializer_from_wide_string(array_type,
1795 &expression->wide_string.value);
1806 assign_error_t error = semantic_assign(type, expression);
1807 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1809 report_assign_error(error, type, expression, "initializer",
1810 &expression->base.source_position);
1812 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1813 result->value.value = create_implicit_cast(expression, type);
1819 * Checks if a given expression can be used as an constant initializer.
1821 static bool is_initializer_constant(const expression_t *expression)
1823 return is_constant_expression(expression)
1824 || is_address_constant(expression);
1828 * Parses an scalar initializer.
1830 * §6.7.8.11; eat {} without warning
1832 static initializer_t *parse_scalar_initializer(type_t *type,
1833 bool must_be_constant)
1835 /* there might be extra {} hierarchies */
1839 warningf(HERE, "extra curly braces around scalar initializer");
1842 } while (next_if('{'));
1845 expression_t *expression = parse_assignment_expression();
1846 mark_vars_read(expression, NULL);
1847 if (must_be_constant && !is_initializer_constant(expression)) {
1848 errorf(&expression->base.source_position,
1849 "initialisation expression '%E' is not constant",
1853 initializer_t *initializer = initializer_from_expression(type, expression);
1855 if (initializer == NULL) {
1856 errorf(&expression->base.source_position,
1857 "expression '%E' (type '%T') doesn't match expected type '%T'",
1858 expression, expression->base.type, type);
1863 bool additional_warning_displayed = false;
1864 while (braces > 0) {
1866 if (token.type != '}') {
1867 if (!additional_warning_displayed && warning.other) {
1868 warningf(HERE, "additional elements in scalar initializer");
1869 additional_warning_displayed = true;
1880 * An entry in the type path.
1882 typedef struct type_path_entry_t type_path_entry_t;
1883 struct type_path_entry_t {
1884 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1886 size_t index; /**< For array types: the current index. */
1887 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1892 * A type path expression a position inside compound or array types.
1894 typedef struct type_path_t type_path_t;
1895 struct type_path_t {
1896 type_path_entry_t *path; /**< An flexible array containing the current path. */
1897 type_t *top_type; /**< type of the element the path points */
1898 size_t max_index; /**< largest index in outermost array */
1902 * Prints a type path for debugging.
1904 static __attribute__((unused)) void debug_print_type_path(
1905 const type_path_t *path)
1907 size_t len = ARR_LEN(path->path);
1909 for (size_t i = 0; i < len; ++i) {
1910 const type_path_entry_t *entry = & path->path[i];
1912 type_t *type = skip_typeref(entry->type);
1913 if (is_type_compound(type)) {
1914 /* in gcc mode structs can have no members */
1915 if (entry->v.compound_entry == NULL) {
1919 fprintf(stderr, ".%s",
1920 entry->v.compound_entry->base.symbol->string);
1921 } else if (is_type_array(type)) {
1922 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1924 fprintf(stderr, "-INVALID-");
1927 if (path->top_type != NULL) {
1928 fprintf(stderr, " (");
1929 print_type(path->top_type);
1930 fprintf(stderr, ")");
1935 * Return the top type path entry, ie. in a path
1936 * (type).a.b returns the b.
1938 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1940 size_t len = ARR_LEN(path->path);
1942 return &path->path[len-1];
1946 * Enlarge the type path by an (empty) element.
1948 static type_path_entry_t *append_to_type_path(type_path_t *path)
1950 size_t len = ARR_LEN(path->path);
1951 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1953 type_path_entry_t *result = & path->path[len];
1954 memset(result, 0, sizeof(result[0]));
1959 * Descending into a sub-type. Enter the scope of the current top_type.
1961 static void descend_into_subtype(type_path_t *path)
1963 type_t *orig_top_type = path->top_type;
1964 type_t *top_type = skip_typeref(orig_top_type);
1966 type_path_entry_t *top = append_to_type_path(path);
1967 top->type = top_type;
1969 if (is_type_compound(top_type)) {
1970 compound_t *compound = top_type->compound.compound;
1971 entity_t *entry = compound->members.entities;
1973 if (entry != NULL) {
1974 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1975 top->v.compound_entry = &entry->declaration;
1976 path->top_type = entry->declaration.type;
1978 path->top_type = NULL;
1980 } else if (is_type_array(top_type)) {
1982 path->top_type = top_type->array.element_type;
1984 assert(!is_type_valid(top_type));
1989 * Pop an entry from the given type path, ie. returning from
1990 * (type).a.b to (type).a
1992 static void ascend_from_subtype(type_path_t *path)
1994 type_path_entry_t *top = get_type_path_top(path);
1996 path->top_type = top->type;
1998 size_t len = ARR_LEN(path->path);
1999 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2003 * Pop entries from the given type path until the given
2004 * path level is reached.
2006 static void ascend_to(type_path_t *path, size_t top_path_level)
2008 size_t len = ARR_LEN(path->path);
2010 while (len > top_path_level) {
2011 ascend_from_subtype(path);
2012 len = ARR_LEN(path->path);
2016 static bool walk_designator(type_path_t *path, const designator_t *designator,
2017 bool used_in_offsetof)
2019 for (; designator != NULL; designator = designator->next) {
2020 type_path_entry_t *top = get_type_path_top(path);
2021 type_t *orig_type = top->type;
2023 type_t *type = skip_typeref(orig_type);
2025 if (designator->symbol != NULL) {
2026 symbol_t *symbol = designator->symbol;
2027 if (!is_type_compound(type)) {
2028 if (is_type_valid(type)) {
2029 errorf(&designator->source_position,
2030 "'.%Y' designator used for non-compound type '%T'",
2034 top->type = type_error_type;
2035 top->v.compound_entry = NULL;
2036 orig_type = type_error_type;
2038 compound_t *compound = type->compound.compound;
2039 entity_t *iter = compound->members.entities;
2040 for (; iter != NULL; iter = iter->base.next) {
2041 if (iter->base.symbol == symbol) {
2046 errorf(&designator->source_position,
2047 "'%T' has no member named '%Y'", orig_type, symbol);
2050 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2051 if (used_in_offsetof) {
2052 type_t *real_type = skip_typeref(iter->declaration.type);
2053 if (real_type->kind == TYPE_BITFIELD) {
2054 errorf(&designator->source_position,
2055 "offsetof designator '%Y' may not specify bitfield",
2061 top->type = orig_type;
2062 top->v.compound_entry = &iter->declaration;
2063 orig_type = iter->declaration.type;
2066 expression_t *array_index = designator->array_index;
2067 assert(designator->array_index != NULL);
2069 if (!is_type_array(type)) {
2070 if (is_type_valid(type)) {
2071 errorf(&designator->source_position,
2072 "[%E] designator used for non-array type '%T'",
2073 array_index, orig_type);
2078 long index = fold_constant_to_int(array_index);
2079 if (!used_in_offsetof) {
2081 errorf(&designator->source_position,
2082 "array index [%E] must be positive", array_index);
2083 } else if (type->array.size_constant) {
2084 long array_size = type->array.size;
2085 if (index >= array_size) {
2086 errorf(&designator->source_position,
2087 "designator [%E] (%d) exceeds array size %d",
2088 array_index, index, array_size);
2093 top->type = orig_type;
2094 top->v.index = (size_t) index;
2095 orig_type = type->array.element_type;
2097 path->top_type = orig_type;
2099 if (designator->next != NULL) {
2100 descend_into_subtype(path);
2109 static void advance_current_object(type_path_t *path, size_t top_path_level)
2111 type_path_entry_t *top = get_type_path_top(path);
2113 type_t *type = skip_typeref(top->type);
2114 if (is_type_union(type)) {
2115 /* in unions only the first element is initialized */
2116 top->v.compound_entry = NULL;
2117 } else if (is_type_struct(type)) {
2118 declaration_t *entry = top->v.compound_entry;
2120 entity_t *next_entity = entry->base.next;
2121 if (next_entity != NULL) {
2122 assert(is_declaration(next_entity));
2123 entry = &next_entity->declaration;
2128 top->v.compound_entry = entry;
2129 if (entry != NULL) {
2130 path->top_type = entry->type;
2133 } else if (is_type_array(type)) {
2134 assert(is_type_array(type));
2138 if (!type->array.size_constant || top->v.index < type->array.size) {
2142 assert(!is_type_valid(type));
2146 /* we're past the last member of the current sub-aggregate, try if we
2147 * can ascend in the type hierarchy and continue with another subobject */
2148 size_t len = ARR_LEN(path->path);
2150 if (len > top_path_level) {
2151 ascend_from_subtype(path);
2152 advance_current_object(path, top_path_level);
2154 path->top_type = NULL;
2159 * skip any {...} blocks until a closing bracket is reached.
2161 static void skip_initializers(void)
2165 while (token.type != '}') {
2166 if (token.type == T_EOF)
2168 if (token.type == '{') {
2176 static initializer_t *create_empty_initializer(void)
2178 static initializer_t empty_initializer
2179 = { .list = { { INITIALIZER_LIST }, 0 } };
2180 return &empty_initializer;
2184 * Parse a part of an initialiser for a struct or union,
2186 static initializer_t *parse_sub_initializer(type_path_t *path,
2187 type_t *outer_type, size_t top_path_level,
2188 parse_initializer_env_t *env)
2190 if (token.type == '}') {
2191 /* empty initializer */
2192 return create_empty_initializer();
2195 type_t *orig_type = path->top_type;
2196 type_t *type = NULL;
2198 if (orig_type == NULL) {
2199 /* We are initializing an empty compound. */
2201 type = skip_typeref(orig_type);
2204 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2207 designator_t *designator = NULL;
2208 if (token.type == '.' || token.type == '[') {
2209 designator = parse_designation();
2210 goto finish_designator;
2211 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2212 /* GNU-style designator ("identifier: value") */
2213 designator = allocate_ast_zero(sizeof(designator[0]));
2214 designator->source_position = token.source_position;
2215 designator->symbol = token.v.symbol;
2220 /* reset path to toplevel, evaluate designator from there */
2221 ascend_to(path, top_path_level);
2222 if (!walk_designator(path, designator, false)) {
2223 /* can't continue after designation error */
2227 initializer_t *designator_initializer
2228 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2229 designator_initializer->designator.designator = designator;
2230 ARR_APP1(initializer_t*, initializers, designator_initializer);
2232 orig_type = path->top_type;
2233 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2238 if (token.type == '{') {
2239 if (type != NULL && is_type_scalar(type)) {
2240 sub = parse_scalar_initializer(type, env->must_be_constant);
2244 if (env->entity != NULL) {
2246 "extra brace group at end of initializer for '%Y'",
2247 env->entity->base.symbol);
2249 errorf(HERE, "extra brace group at end of initializer");
2252 descend_into_subtype(path);
2254 add_anchor_token('}');
2255 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2257 rem_anchor_token('}');
2260 ascend_from_subtype(path);
2261 expect('}', end_error);
2263 expect('}', end_error);
2264 goto error_parse_next;
2268 /* must be an expression */
2269 expression_t *expression = parse_assignment_expression();
2270 mark_vars_read(expression, NULL);
2272 if (env->must_be_constant && !is_initializer_constant(expression)) {
2273 errorf(&expression->base.source_position,
2274 "Initialisation expression '%E' is not constant",
2279 /* we are already outside, ... */
2280 if (outer_type == NULL)
2281 goto error_parse_next;
2282 type_t *const outer_type_skip = skip_typeref(outer_type);
2283 if (is_type_compound(outer_type_skip) &&
2284 !outer_type_skip->compound.compound->complete) {
2285 goto error_parse_next;
2290 /* handle { "string" } special case */
2291 if ((expression->kind == EXPR_STRING_LITERAL
2292 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2293 && outer_type != NULL) {
2294 sub = initializer_from_expression(outer_type, expression);
2297 if (token.type != '}' && warning.other) {
2298 warningf(HERE, "excessive elements in initializer for type '%T'",
2301 /* TODO: eat , ... */
2306 /* descend into subtypes until expression matches type */
2308 orig_type = path->top_type;
2309 type = skip_typeref(orig_type);
2311 sub = initializer_from_expression(orig_type, expression);
2315 if (!is_type_valid(type)) {
2318 if (is_type_scalar(type)) {
2319 errorf(&expression->base.source_position,
2320 "expression '%E' doesn't match expected type '%T'",
2321 expression, orig_type);
2325 descend_into_subtype(path);
2329 /* update largest index of top array */
2330 const type_path_entry_t *first = &path->path[0];
2331 type_t *first_type = first->type;
2332 first_type = skip_typeref(first_type);
2333 if (is_type_array(first_type)) {
2334 size_t index = first->v.index;
2335 if (index > path->max_index)
2336 path->max_index = index;
2340 /* append to initializers list */
2341 ARR_APP1(initializer_t*, initializers, sub);
2344 if (warning.other) {
2345 if (env->entity != NULL) {
2346 warningf(HERE, "excess elements in initializer for '%Y'",
2347 env->entity->base.symbol);
2349 warningf(HERE, "excess elements in initializer");
2355 if (token.type == '}') {
2358 expect(',', end_error);
2359 if (token.type == '}') {
2364 /* advance to the next declaration if we are not at the end */
2365 advance_current_object(path, top_path_level);
2366 orig_type = path->top_type;
2367 if (orig_type != NULL)
2368 type = skip_typeref(orig_type);
2374 size_t len = ARR_LEN(initializers);
2375 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2376 initializer_t *result = allocate_ast_zero(size);
2377 result->kind = INITIALIZER_LIST;
2378 result->list.len = len;
2379 memcpy(&result->list.initializers, initializers,
2380 len * sizeof(initializers[0]));
2382 DEL_ARR_F(initializers);
2383 ascend_to(path, top_path_level+1);
2388 skip_initializers();
2389 DEL_ARR_F(initializers);
2390 ascend_to(path, top_path_level+1);
2395 * Parses an initializer. Parsers either a compound literal
2396 * (env->declaration == NULL) or an initializer of a declaration.
2398 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2400 type_t *type = skip_typeref(env->type);
2401 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2402 initializer_t *result;
2404 if (is_type_scalar(type)) {
2405 result = parse_scalar_initializer(type, env->must_be_constant);
2406 } else if (token.type == '{') {
2410 memset(&path, 0, sizeof(path));
2411 path.top_type = env->type;
2412 path.path = NEW_ARR_F(type_path_entry_t, 0);
2414 descend_into_subtype(&path);
2416 add_anchor_token('}');
2417 result = parse_sub_initializer(&path, env->type, 1, env);
2418 rem_anchor_token('}');
2420 max_index = path.max_index;
2421 DEL_ARR_F(path.path);
2423 expect('}', end_error);
2425 /* parse_scalar_initializer() also works in this case: we simply
2426 * have an expression without {} around it */
2427 result = parse_scalar_initializer(type, env->must_be_constant);
2430 /* §6.7.8:22 array initializers for arrays with unknown size determine
2431 * the array type size */
2432 if (is_type_array(type) && type->array.size_expression == NULL
2433 && result != NULL) {
2435 switch (result->kind) {
2436 case INITIALIZER_LIST:
2437 assert(max_index != 0xdeadbeaf);
2438 size = max_index + 1;
2441 case INITIALIZER_STRING:
2442 size = result->string.string.size;
2445 case INITIALIZER_WIDE_STRING:
2446 size = result->wide_string.string.size;
2449 case INITIALIZER_DESIGNATOR:
2450 case INITIALIZER_VALUE:
2451 /* can happen for parse errors */
2456 internal_errorf(HERE, "invalid initializer type");
2459 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2460 cnst->base.type = type_size_t;
2461 cnst->conste.v.int_value = size;
2463 type_t *new_type = duplicate_type(type);
2465 new_type->array.size_expression = cnst;
2466 new_type->array.size_constant = true;
2467 new_type->array.has_implicit_size = true;
2468 new_type->array.size = size;
2469 env->type = new_type;
2477 static void append_entity(scope_t *scope, entity_t *entity)
2479 if (scope->last_entity != NULL) {
2480 scope->last_entity->base.next = entity;
2482 scope->entities = entity;
2484 entity->base.parent_entity = current_entity;
2485 scope->last_entity = entity;
2489 static compound_t *parse_compound_type_specifier(bool is_struct)
2491 eat(is_struct ? T_struct : T_union);
2493 symbol_t *symbol = NULL;
2494 compound_t *compound = NULL;
2495 attribute_t *attributes = NULL;
2497 if (token.type == T___attribute__) {
2498 attributes = parse_attributes(NULL);
2501 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2502 if (token.type == T_IDENTIFIER) {
2503 /* the compound has a name, check if we have seen it already */
2504 symbol = token.v.symbol;
2507 entity_t *entity = get_tag(symbol, kind);
2508 if (entity != NULL) {
2509 compound = &entity->compound;
2510 if (compound->base.parent_scope != current_scope &&
2511 (token.type == '{' || token.type == ';')) {
2512 /* we're in an inner scope and have a definition. Shadow
2513 * existing definition in outer scope */
2515 } else if (compound->complete && token.type == '{') {
2516 assert(symbol != NULL);
2517 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2518 is_struct ? "struct" : "union", symbol,
2519 &compound->base.source_position);
2520 /* clear members in the hope to avoid further errors */
2521 compound->members.entities = NULL;
2524 } else if (token.type != '{') {
2526 parse_error_expected("while parsing struct type specifier",
2527 T_IDENTIFIER, '{', NULL);
2529 parse_error_expected("while parsing union type specifier",
2530 T_IDENTIFIER, '{', NULL);
2536 if (compound == NULL) {
2537 entity_t *entity = allocate_entity_zero(kind);
2538 compound = &entity->compound;
2540 compound->alignment = 1;
2541 compound->base.namespc = NAMESPACE_TAG;
2542 compound->base.source_position = token.source_position;
2543 compound->base.symbol = symbol;
2544 compound->base.parent_scope = current_scope;
2545 if (symbol != NULL) {
2546 environment_push(entity);
2548 append_entity(current_scope, entity);
2551 if (token.type == '{') {
2552 parse_compound_type_entries(compound);
2554 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2555 if (symbol == NULL) {
2556 assert(anonymous_entity == NULL);
2557 anonymous_entity = (entity_t*)compound;
2561 if (attributes != NULL) {
2562 handle_entity_attributes(attributes, (entity_t*) compound);
2568 static void parse_enum_entries(type_t *const enum_type)
2572 if (token.type == '}') {
2573 errorf(HERE, "empty enum not allowed");
2578 add_anchor_token('}');
2580 if (token.type != T_IDENTIFIER) {
2581 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2583 rem_anchor_token('}');
2587 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2588 entity->enum_value.enum_type = enum_type;
2589 entity->base.symbol = token.v.symbol;
2590 entity->base.source_position = token.source_position;
2594 expression_t *value = parse_constant_expression();
2596 value = create_implicit_cast(value, enum_type);
2597 entity->enum_value.value = value;
2602 record_entity(entity, false);
2603 } while (next_if(',') && token.type != '}');
2604 rem_anchor_token('}');
2606 expect('}', end_error);
2612 static type_t *parse_enum_specifier(void)
2618 switch (token.type) {
2620 symbol = token.v.symbol;
2623 entity = get_tag(symbol, ENTITY_ENUM);
2624 if (entity != NULL) {
2625 if (entity->base.parent_scope != current_scope &&
2626 (token.type == '{' || token.type == ';')) {
2627 /* we're in an inner scope and have a definition. Shadow
2628 * existing definition in outer scope */
2630 } else if (entity->enume.complete && token.type == '{') {
2631 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2632 symbol, &entity->base.source_position);
2643 parse_error_expected("while parsing enum type specifier",
2644 T_IDENTIFIER, '{', NULL);
2648 if (entity == NULL) {
2649 entity = allocate_entity_zero(ENTITY_ENUM);
2650 entity->base.namespc = NAMESPACE_TAG;
2651 entity->base.source_position = token.source_position;
2652 entity->base.symbol = symbol;
2653 entity->base.parent_scope = current_scope;
2656 type_t *const type = allocate_type_zero(TYPE_ENUM);
2657 type->enumt.enume = &entity->enume;
2658 type->enumt.akind = ATOMIC_TYPE_INT;
2660 if (token.type == '{') {
2661 if (symbol != NULL) {
2662 environment_push(entity);
2664 append_entity(current_scope, entity);
2665 entity->enume.complete = true;
2667 parse_enum_entries(type);
2668 parse_attributes(NULL);
2670 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2671 if (symbol == NULL) {
2672 assert(anonymous_entity == NULL);
2673 anonymous_entity = entity;
2675 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2676 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2684 * if a symbol is a typedef to another type, return true
2686 static bool is_typedef_symbol(symbol_t *symbol)
2688 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2689 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2692 static type_t *parse_typeof(void)
2698 expect('(', end_error);
2699 add_anchor_token(')');
2701 expression_t *expression = NULL;
2703 bool old_type_prop = in_type_prop;
2704 bool old_gcc_extension = in_gcc_extension;
2705 in_type_prop = true;
2707 while (next_if(T___extension__)) {
2708 /* This can be a prefix to a typename or an expression. */
2709 in_gcc_extension = true;
2711 switch (token.type) {
2713 if (is_typedef_symbol(token.v.symbol)) {
2714 type = parse_typename();
2716 expression = parse_expression();
2717 type = revert_automatic_type_conversion(expression);
2722 type = parse_typename();
2726 expression = parse_expression();
2727 type = expression->base.type;
2730 in_type_prop = old_type_prop;
2731 in_gcc_extension = old_gcc_extension;
2733 rem_anchor_token(')');
2734 expect(')', end_error);
2736 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2737 typeof_type->typeoft.expression = expression;
2738 typeof_type->typeoft.typeof_type = type;
2745 typedef enum specifiers_t {
2746 SPECIFIER_SIGNED = 1 << 0,
2747 SPECIFIER_UNSIGNED = 1 << 1,
2748 SPECIFIER_LONG = 1 << 2,
2749 SPECIFIER_INT = 1 << 3,
2750 SPECIFIER_DOUBLE = 1 << 4,
2751 SPECIFIER_CHAR = 1 << 5,
2752 SPECIFIER_WCHAR_T = 1 << 6,
2753 SPECIFIER_SHORT = 1 << 7,
2754 SPECIFIER_LONG_LONG = 1 << 8,
2755 SPECIFIER_FLOAT = 1 << 9,
2756 SPECIFIER_BOOL = 1 << 10,
2757 SPECIFIER_VOID = 1 << 11,
2758 SPECIFIER_INT8 = 1 << 12,
2759 SPECIFIER_INT16 = 1 << 13,
2760 SPECIFIER_INT32 = 1 << 14,
2761 SPECIFIER_INT64 = 1 << 15,
2762 SPECIFIER_INT128 = 1 << 16,
2763 SPECIFIER_COMPLEX = 1 << 17,
2764 SPECIFIER_IMAGINARY = 1 << 18,
2767 static type_t *create_builtin_type(symbol_t *const symbol,
2768 type_t *const real_type)
2770 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2771 type->builtin.symbol = symbol;
2772 type->builtin.real_type = real_type;
2773 return identify_new_type(type);
2776 static type_t *get_typedef_type(symbol_t *symbol)
2778 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2779 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2782 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2783 type->typedeft.typedefe = &entity->typedefe;
2788 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2790 expect('(', end_error);
2792 attribute_property_argument_t *property
2793 = allocate_ast_zero(sizeof(*property));
2796 if (token.type != T_IDENTIFIER) {
2797 parse_error_expected("while parsing property declspec",
2798 T_IDENTIFIER, NULL);
2803 symbol_t *symbol = token.v.symbol;
2805 if (strcmp(symbol->string, "put") == 0) {
2807 } else if (strcmp(symbol->string, "get") == 0) {
2810 errorf(HERE, "expected put or get in property declspec");
2813 expect('=', end_error);
2814 if (token.type != T_IDENTIFIER) {
2815 parse_error_expected("while parsing property declspec",
2816 T_IDENTIFIER, NULL);
2820 property->put_symbol = token.v.symbol;
2822 property->get_symbol = token.v.symbol;
2825 } while (next_if(','));
2827 attribute->a.property = property;
2829 expect(')', end_error);
2835 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2837 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2838 if (next_if(T_restrict)) {
2839 kind = ATTRIBUTE_MS_RESTRICT;
2840 } else if (token.type == T_IDENTIFIER) {
2841 const char *name = token.v.symbol->string;
2843 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2845 const char *attribute_name = get_attribute_name(k);
2846 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2852 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2853 warningf(HERE, "unknown __declspec '%s' ignored", name);
2856 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2860 attribute_t *attribute = allocate_attribute_zero(kind);
2862 if (kind == ATTRIBUTE_MS_PROPERTY) {
2863 return parse_attribute_ms_property(attribute);
2866 /* parse arguments */
2868 attribute->a.arguments = parse_attribute_arguments();
2873 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2877 expect('(', end_error);
2882 add_anchor_token(')');
2884 attribute_t **anchor = &first;
2886 while (*anchor != NULL)
2887 anchor = &(*anchor)->next;
2889 attribute_t *attribute
2890 = parse_microsoft_extended_decl_modifier_single();
2891 if (attribute == NULL)
2894 *anchor = attribute;
2895 anchor = &attribute->next;
2896 } while (next_if(','));
2898 rem_anchor_token(')');
2899 expect(')', end_error);
2903 rem_anchor_token(')');
2907 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2909 entity_t *entity = allocate_entity_zero(kind);
2910 entity->base.source_position = *HERE;
2911 entity->base.symbol = symbol;
2912 if (is_declaration(entity)) {
2913 entity->declaration.type = type_error_type;
2914 entity->declaration.implicit = true;
2915 } else if (kind == ENTITY_TYPEDEF) {
2916 entity->typedefe.type = type_error_type;
2917 entity->typedefe.builtin = true;
2919 if (kind != ENTITY_COMPOUND_MEMBER)
2920 record_entity(entity, false);
2924 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2926 type_t *type = NULL;
2927 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2928 unsigned type_specifiers = 0;
2929 bool newtype = false;
2930 bool saw_error = false;
2931 bool old_gcc_extension = in_gcc_extension;
2933 specifiers->source_position = token.source_position;
2936 specifiers->attributes = parse_attributes(specifiers->attributes);
2938 switch (token.type) {
2940 #define MATCH_STORAGE_CLASS(token, class) \
2942 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2943 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2945 specifiers->storage_class = class; \
2946 if (specifiers->thread_local) \
2947 goto check_thread_storage_class; \
2951 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2952 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2953 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2954 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2955 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2958 specifiers->attributes
2959 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2963 if (specifiers->thread_local) {
2964 errorf(HERE, "duplicate '__thread'");
2966 specifiers->thread_local = true;
2967 check_thread_storage_class:
2968 switch (specifiers->storage_class) {
2969 case STORAGE_CLASS_EXTERN:
2970 case STORAGE_CLASS_NONE:
2971 case STORAGE_CLASS_STATIC:
2975 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2976 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2977 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2978 wrong_thread_stoarge_class:
2979 errorf(HERE, "'__thread' used with '%s'", wrong);
2986 /* type qualifiers */
2987 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2989 qualifiers |= qualifier; \
2993 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2994 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2995 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2996 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2997 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2998 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2999 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3000 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3002 case T___extension__:
3004 in_gcc_extension = true;
3007 /* type specifiers */
3008 #define MATCH_SPECIFIER(token, specifier, name) \
3010 if (type_specifiers & specifier) { \
3011 errorf(HERE, "multiple " name " type specifiers given"); \
3013 type_specifiers |= specifier; \
3018 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3019 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3020 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3021 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3022 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3023 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3024 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3025 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3026 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3027 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3028 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3029 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3030 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3031 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3032 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3033 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3034 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3035 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3039 specifiers->is_inline = true;
3043 case T__forceinline:
3045 specifiers->modifiers |= DM_FORCEINLINE;
3050 if (type_specifiers & SPECIFIER_LONG_LONG) {
3051 errorf(HERE, "multiple type specifiers given");
3052 } else if (type_specifiers & SPECIFIER_LONG) {
3053 type_specifiers |= SPECIFIER_LONG_LONG;
3055 type_specifiers |= SPECIFIER_LONG;
3060 #define CHECK_DOUBLE_TYPE() \
3061 if ( type != NULL) \
3062 errorf(HERE, "multiple data types in declaration specifiers");
3065 CHECK_DOUBLE_TYPE();
3066 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3068 type->compound.compound = parse_compound_type_specifier(true);
3071 CHECK_DOUBLE_TYPE();
3072 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3073 type->compound.compound = parse_compound_type_specifier(false);
3076 CHECK_DOUBLE_TYPE();
3077 type = parse_enum_specifier();
3080 CHECK_DOUBLE_TYPE();
3081 type = parse_typeof();
3083 case T___builtin_va_list:
3084 CHECK_DOUBLE_TYPE();
3085 type = duplicate_type(type_valist);
3089 case T_IDENTIFIER: {
3090 /* only parse identifier if we haven't found a type yet */
3091 if (type != NULL || type_specifiers != 0) {
3092 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3093 * declaration, so it doesn't generate errors about expecting '(' or
3095 switch (look_ahead(1)->type) {
3102 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3106 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3111 goto finish_specifiers;
3115 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3116 if (typedef_type == NULL) {
3117 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3118 * declaration, so it doesn't generate 'implicit int' followed by more
3119 * errors later on. */
3120 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3126 errorf(HERE, "%K does not name a type", &token);
3129 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3131 type = allocate_type_zero(TYPE_TYPEDEF);
3132 type->typedeft.typedefe = &entity->typedefe;
3136 if (la1_type == '&' || la1_type == '*')
3137 goto finish_specifiers;
3142 goto finish_specifiers;
3147 type = typedef_type;
3151 /* function specifier */
3153 goto finish_specifiers;
3158 specifiers->attributes = parse_attributes(specifiers->attributes);
3160 in_gcc_extension = old_gcc_extension;
3162 if (type == NULL || (saw_error && type_specifiers != 0)) {
3163 atomic_type_kind_t atomic_type;
3165 /* match valid basic types */
3166 switch (type_specifiers) {
3167 case SPECIFIER_VOID:
3168 atomic_type = ATOMIC_TYPE_VOID;
3170 case SPECIFIER_WCHAR_T:
3171 atomic_type = ATOMIC_TYPE_WCHAR_T;
3173 case SPECIFIER_CHAR:
3174 atomic_type = ATOMIC_TYPE_CHAR;
3176 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3177 atomic_type = ATOMIC_TYPE_SCHAR;
3179 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3180 atomic_type = ATOMIC_TYPE_UCHAR;
3182 case SPECIFIER_SHORT:
3183 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3184 case SPECIFIER_SHORT | SPECIFIER_INT:
3185 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3186 atomic_type = ATOMIC_TYPE_SHORT;
3188 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3189 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3190 atomic_type = ATOMIC_TYPE_USHORT;
3193 case SPECIFIER_SIGNED:
3194 case SPECIFIER_SIGNED | SPECIFIER_INT:
3195 atomic_type = ATOMIC_TYPE_INT;
3197 case SPECIFIER_UNSIGNED:
3198 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3199 atomic_type = ATOMIC_TYPE_UINT;
3201 case SPECIFIER_LONG:
3202 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3203 case SPECIFIER_LONG | SPECIFIER_INT:
3204 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3205 atomic_type = ATOMIC_TYPE_LONG;
3207 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3208 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3209 atomic_type = ATOMIC_TYPE_ULONG;
3212 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3213 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3214 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3215 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3217 atomic_type = ATOMIC_TYPE_LONGLONG;
3218 goto warn_about_long_long;
3220 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3221 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3223 atomic_type = ATOMIC_TYPE_ULONGLONG;
3224 warn_about_long_long:
3225 if (warning.long_long) {
3226 warningf(&specifiers->source_position,
3227 "ISO C90 does not support 'long long'");
3231 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3232 atomic_type = unsigned_int8_type_kind;
3235 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3236 atomic_type = unsigned_int16_type_kind;
3239 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3240 atomic_type = unsigned_int32_type_kind;
3243 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3244 atomic_type = unsigned_int64_type_kind;
3247 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3248 atomic_type = unsigned_int128_type_kind;
3251 case SPECIFIER_INT8:
3252 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3253 atomic_type = int8_type_kind;
3256 case SPECIFIER_INT16:
3257 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3258 atomic_type = int16_type_kind;
3261 case SPECIFIER_INT32:
3262 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3263 atomic_type = int32_type_kind;
3266 case SPECIFIER_INT64:
3267 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3268 atomic_type = int64_type_kind;
3271 case SPECIFIER_INT128:
3272 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3273 atomic_type = int128_type_kind;
3276 case SPECIFIER_FLOAT:
3277 atomic_type = ATOMIC_TYPE_FLOAT;
3279 case SPECIFIER_DOUBLE:
3280 atomic_type = ATOMIC_TYPE_DOUBLE;
3282 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3283 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3285 case SPECIFIER_BOOL:
3286 atomic_type = ATOMIC_TYPE_BOOL;
3288 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3289 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3290 atomic_type = ATOMIC_TYPE_FLOAT;
3292 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3293 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3294 atomic_type = ATOMIC_TYPE_DOUBLE;
3296 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3297 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3298 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3301 /* invalid specifier combination, give an error message */
3302 if (type_specifiers == 0) {
3306 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3307 if (!(c_mode & _CXX) && !strict_mode) {
3308 if (warning.implicit_int) {
3309 warningf(HERE, "no type specifiers in declaration, using 'int'");
3311 atomic_type = ATOMIC_TYPE_INT;
3314 errorf(HERE, "no type specifiers given in declaration");
3316 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3317 (type_specifiers & SPECIFIER_UNSIGNED)) {
3318 errorf(HERE, "signed and unsigned specifiers given");
3319 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3320 errorf(HERE, "only integer types can be signed or unsigned");
3322 errorf(HERE, "multiple datatypes in declaration");
3327 if (type_specifiers & SPECIFIER_COMPLEX) {
3328 type = allocate_type_zero(TYPE_COMPLEX);
3329 type->complex.akind = atomic_type;
3330 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3331 type = allocate_type_zero(TYPE_IMAGINARY);
3332 type->imaginary.akind = atomic_type;
3334 type = allocate_type_zero(TYPE_ATOMIC);
3335 type->atomic.akind = atomic_type;
3338 } else if (type_specifiers != 0) {
3339 errorf(HERE, "multiple datatypes in declaration");
3342 /* FIXME: check type qualifiers here */
3343 type->base.qualifiers = qualifiers;
3346 type = identify_new_type(type);
3348 type = typehash_insert(type);
3351 if (specifiers->attributes != NULL)
3352 type = handle_type_attributes(specifiers->attributes, type);
3353 specifiers->type = type;
3357 specifiers->type = type_error_type;
3360 static type_qualifiers_t parse_type_qualifiers(void)
3362 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3365 switch (token.type) {
3366 /* type qualifiers */
3367 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3368 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3369 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3370 /* microsoft extended type modifiers */
3371 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3372 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3373 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3374 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3375 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3384 * Parses an K&R identifier list
3386 static void parse_identifier_list(scope_t *scope)
3389 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3390 entity->base.source_position = token.source_position;
3391 entity->base.namespc = NAMESPACE_NORMAL;
3392 entity->base.symbol = token.v.symbol;
3393 /* a K&R parameter has no type, yet */
3397 append_entity(scope, entity);
3398 } while (next_if(',') && token.type == T_IDENTIFIER);
3401 static entity_t *parse_parameter(void)
3403 declaration_specifiers_t specifiers;
3404 memset(&specifiers, 0, sizeof(specifiers));
3406 parse_declaration_specifiers(&specifiers);
3408 entity_t *entity = parse_declarator(&specifiers,
3409 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3410 anonymous_entity = NULL;
3414 static void semantic_parameter_incomplete(const entity_t *entity)
3416 assert(entity->kind == ENTITY_PARAMETER);
3418 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3419 * list in a function declarator that is part of a
3420 * definition of that function shall not have
3421 * incomplete type. */
3422 type_t *type = skip_typeref(entity->declaration.type);
3423 if (is_type_incomplete(type)) {
3424 errorf(&entity->base.source_position,
3425 "parameter '%#T' has incomplete type",
3426 entity->declaration.type, entity->base.symbol);
3430 static bool has_parameters(void)
3432 /* func(void) is not a parameter */
3433 if (token.type == T_IDENTIFIER) {
3434 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3437 if (entity->kind != ENTITY_TYPEDEF)
3439 if (skip_typeref(entity->typedefe.type) != type_void)
3441 } else if (token.type != T_void) {
3444 if (look_ahead(1)->type != ')')
3451 * Parses function type parameters (and optionally creates variable_t entities
3452 * for them in a scope)
3454 static void parse_parameters(function_type_t *type, scope_t *scope)
3457 add_anchor_token(')');
3458 int saved_comma_state = save_and_reset_anchor_state(',');
3460 if (token.type == T_IDENTIFIER &&
3461 !is_typedef_symbol(token.v.symbol)) {
3462 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3463 if (la1_type == ',' || la1_type == ')') {
3464 type->kr_style_parameters = true;
3465 parse_identifier_list(scope);
3466 goto parameters_finished;
3470 if (token.type == ')') {
3471 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3472 if (!(c_mode & _CXX))
3473 type->unspecified_parameters = true;
3474 goto parameters_finished;
3477 if (has_parameters()) {
3478 function_parameter_t **anchor = &type->parameters;
3480 switch (token.type) {
3483 type->variadic = true;
3484 goto parameters_finished;
3487 case T___extension__:
3490 entity_t *entity = parse_parameter();
3491 if (entity->kind == ENTITY_TYPEDEF) {
3492 errorf(&entity->base.source_position,
3493 "typedef not allowed as function parameter");
3496 assert(is_declaration(entity));
3498 semantic_parameter_incomplete(entity);
3500 function_parameter_t *const parameter =
3501 allocate_parameter(entity->declaration.type);
3503 if (scope != NULL) {
3504 append_entity(scope, entity);
3507 *anchor = parameter;
3508 anchor = ¶meter->next;
3513 goto parameters_finished;
3515 } while (next_if(','));
3519 parameters_finished:
3520 rem_anchor_token(')');
3521 expect(')', end_error);
3524 restore_anchor_state(',', saved_comma_state);
3527 typedef enum construct_type_kind_t {
3530 CONSTRUCT_REFERENCE,
3533 } construct_type_kind_t;
3535 typedef union construct_type_t construct_type_t;
3537 typedef struct construct_type_base_t {
3538 construct_type_kind_t kind;
3539 construct_type_t *next;
3540 } construct_type_base_t;
3542 typedef struct parsed_pointer_t {
3543 construct_type_base_t base;
3544 type_qualifiers_t type_qualifiers;
3545 variable_t *base_variable; /**< MS __based extension. */
3548 typedef struct parsed_reference_t {
3549 construct_type_base_t base;
3550 } parsed_reference_t;
3552 typedef struct construct_function_type_t {
3553 construct_type_base_t base;
3554 type_t *function_type;
3555 } construct_function_type_t;
3557 typedef struct parsed_array_t {
3558 construct_type_base_t base;
3559 type_qualifiers_t type_qualifiers;
3565 union construct_type_t {
3566 construct_type_kind_t kind;
3567 construct_type_base_t base;
3568 parsed_pointer_t pointer;
3569 parsed_reference_t reference;
3570 construct_function_type_t function;
3571 parsed_array_t array;
3574 static construct_type_t *parse_pointer_declarator(void)
3578 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3579 memset(pointer, 0, sizeof(pointer[0]));
3580 pointer->base.kind = CONSTRUCT_POINTER;
3581 pointer->type_qualifiers = parse_type_qualifiers();
3582 //pointer->base_variable = base_variable;
3584 return (construct_type_t*) pointer;
3587 static construct_type_t *parse_reference_declarator(void)
3591 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3592 parsed_reference_t *reference = &cons->reference;
3593 memset(reference, 0, sizeof(*reference));
3594 cons->kind = CONSTRUCT_REFERENCE;
3599 static construct_type_t *parse_array_declarator(void)
3602 add_anchor_token(']');
3604 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3605 parsed_array_t *array = &cons->array;
3606 memset(array, 0, sizeof(*array));
3607 cons->kind = CONSTRUCT_ARRAY;
3609 if (next_if(T_static))
3610 array->is_static = true;
3612 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3613 if (type_qualifiers != 0 && next_if(T_static))
3614 array->is_static = true;
3615 array->type_qualifiers = type_qualifiers;
3617 if (token.type == '*' && look_ahead(1)->type == ']') {
3618 array->is_variable = true;
3620 } else if (token.type != ']') {
3621 expression_t *const size = parse_assignment_expression();
3623 /* §6.7.5.2:1 Array size must have integer type */
3624 type_t *const orig_type = size->base.type;
3625 type_t *const type = skip_typeref(orig_type);
3626 if (!is_type_integer(type) && is_type_valid(type)) {
3627 errorf(&size->base.source_position,
3628 "array size '%E' must have integer type but has type '%T'",
3633 mark_vars_read(size, NULL);
3636 rem_anchor_token(']');
3637 expect(']', end_error);
3643 static construct_type_t *parse_function_declarator(scope_t *scope)
3645 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3646 function_type_t *ftype = &type->function;
3648 ftype->linkage = current_linkage;
3649 ftype->calling_convention = CC_DEFAULT;
3651 parse_parameters(ftype, scope);
3653 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3654 construct_function_type_t *function = &cons->function;
3655 memset(function, 0, sizeof(*function));
3656 cons->kind = CONSTRUCT_FUNCTION;
3657 function->function_type = type;
3662 typedef struct parse_declarator_env_t {
3663 bool may_be_abstract : 1;
3664 bool must_be_abstract : 1;
3665 decl_modifiers_t modifiers;
3667 source_position_t source_position;
3669 attribute_t *attributes;
3670 } parse_declarator_env_t;
3672 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3674 /* construct a single linked list of construct_type_t's which describe
3675 * how to construct the final declarator type */
3676 construct_type_t *first = NULL;
3677 construct_type_t **anchor = &first;
3679 env->attributes = parse_attributes(env->attributes);
3682 construct_type_t *type;
3683 //variable_t *based = NULL; /* MS __based extension */
3684 switch (token.type) {
3686 if (!(c_mode & _CXX))
3687 errorf(HERE, "references are only available for C++");
3688 type = parse_reference_declarator();
3692 panic("based not supported anymore");
3697 type = parse_pointer_declarator();
3701 goto ptr_operator_end;
3705 anchor = &type->base.next;
3707 /* TODO: find out if this is correct */
3708 env->attributes = parse_attributes(env->attributes);
3712 construct_type_t *inner_types = NULL;
3714 switch (token.type) {
3716 if (env->must_be_abstract) {
3717 errorf(HERE, "no identifier expected in typename");
3719 env->symbol = token.v.symbol;
3720 env->source_position = token.source_position;
3725 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3726 * interpreted as ``function with no parameter specification'', rather
3727 * than redundant parentheses around the omitted identifier. */
3728 if (look_ahead(1)->type != ')') {
3730 add_anchor_token(')');
3731 inner_types = parse_inner_declarator(env);
3732 if (inner_types != NULL) {
3733 /* All later declarators only modify the return type */
3734 env->must_be_abstract = true;
3736 rem_anchor_token(')');
3737 expect(')', end_error);
3741 if (env->may_be_abstract)
3743 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3748 construct_type_t **const p = anchor;
3751 construct_type_t *type;
3752 switch (token.type) {
3754 scope_t *scope = NULL;
3755 if (!env->must_be_abstract) {
3756 scope = &env->parameters;
3759 type = parse_function_declarator(scope);
3763 type = parse_array_declarator();
3766 goto declarator_finished;
3769 /* insert in the middle of the list (at p) */
3770 type->base.next = *p;
3773 anchor = &type->base.next;
3776 declarator_finished:
3777 /* append inner_types at the end of the list, we don't to set anchor anymore
3778 * as it's not needed anymore */
3779 *anchor = inner_types;
3786 static type_t *construct_declarator_type(construct_type_t *construct_list,
3789 construct_type_t *iter = construct_list;
3790 for (; iter != NULL; iter = iter->base.next) {
3791 switch (iter->kind) {
3792 case CONSTRUCT_INVALID:
3794 case CONSTRUCT_FUNCTION: {
3795 construct_function_type_t *function = &iter->function;
3796 type_t *function_type = function->function_type;
3798 function_type->function.return_type = type;
3800 type_t *skipped_return_type = skip_typeref(type);
3802 if (is_type_function(skipped_return_type)) {
3803 errorf(HERE, "function returning function is not allowed");
3804 } else if (is_type_array(skipped_return_type)) {
3805 errorf(HERE, "function returning array is not allowed");
3807 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3809 "type qualifiers in return type of function type are meaningless");
3813 /* The function type was constructed earlier. Freeing it here will
3814 * destroy other types. */
3815 type = typehash_insert(function_type);
3819 case CONSTRUCT_POINTER: {
3820 if (is_type_reference(skip_typeref(type)))
3821 errorf(HERE, "cannot declare a pointer to reference");
3823 parsed_pointer_t *pointer = &iter->pointer;
3824 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3828 case CONSTRUCT_REFERENCE:
3829 if (is_type_reference(skip_typeref(type)))
3830 errorf(HERE, "cannot declare a reference to reference");
3832 type = make_reference_type(type);
3835 case CONSTRUCT_ARRAY: {
3836 if (is_type_reference(skip_typeref(type)))
3837 errorf(HERE, "cannot declare an array of references");
3839 parsed_array_t *array = &iter->array;
3840 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3842 expression_t *size_expression = array->size;
3843 if (size_expression != NULL) {
3845 = create_implicit_cast(size_expression, type_size_t);
3848 array_type->base.qualifiers = array->type_qualifiers;
3849 array_type->array.element_type = type;
3850 array_type->array.is_static = array->is_static;
3851 array_type->array.is_variable = array->is_variable;
3852 array_type->array.size_expression = size_expression;
3854 if (size_expression != NULL) {
3855 if (is_constant_expression(size_expression)) {
3857 = fold_constant_to_int(size_expression);
3858 array_type->array.size = size;
3859 array_type->array.size_constant = true;
3860 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3861 * have a value greater than zero. */
3863 if (size < 0 || !GNU_MODE) {
3864 errorf(&size_expression->base.source_position,
3865 "size of array must be greater than zero");
3866 } else if (warning.other) {
3867 warningf(&size_expression->base.source_position,
3868 "zero length arrays are a GCC extension");
3872 array_type->array.is_vla = true;
3876 type_t *skipped_type = skip_typeref(type);
3878 if (is_type_incomplete(skipped_type)) {
3879 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3880 } else if (is_type_function(skipped_type)) {
3881 errorf(HERE, "array of functions is not allowed");
3883 type = identify_new_type(array_type);
3887 internal_errorf(HERE, "invalid type construction found");
3893 static type_t *automatic_type_conversion(type_t *orig_type);
3895 static type_t *semantic_parameter(const source_position_t *pos,
3897 const declaration_specifiers_t *specifiers,
3900 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3901 * shall be adjusted to ``qualified pointer to type'',
3903 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3904 * type'' shall be adjusted to ``pointer to function
3905 * returning type'', as in 6.3.2.1. */
3906 type = automatic_type_conversion(type);
3908 if (specifiers->is_inline && is_type_valid(type)) {
3909 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3912 /* §6.9.1:6 The declarations in the declaration list shall contain
3913 * no storage-class specifier other than register and no
3914 * initializations. */
3915 if (specifiers->thread_local || (
3916 specifiers->storage_class != STORAGE_CLASS_NONE &&
3917 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3919 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3922 /* delay test for incomplete type, because we might have (void)
3923 * which is legal but incomplete... */
3928 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3929 declarator_flags_t flags)
3931 parse_declarator_env_t env;
3932 memset(&env, 0, sizeof(env));
3933 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3935 construct_type_t *construct_type = parse_inner_declarator(&env);
3937 construct_declarator_type(construct_type, specifiers->type);
3938 type_t *type = skip_typeref(orig_type);
3940 if (construct_type != NULL) {
3941 obstack_free(&temp_obst, construct_type);
3944 attribute_t *attributes = parse_attributes(env.attributes);
3945 /* append (shared) specifier attribute behind attributes of this
3947 attribute_t **anchor = &attributes;
3948 while (*anchor != NULL)
3949 anchor = &(*anchor)->next;
3950 *anchor = specifiers->attributes;
3953 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3954 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3955 entity->base.symbol = env.symbol;
3956 entity->base.source_position = env.source_position;
3957 entity->typedefe.type = orig_type;
3959 if (anonymous_entity != NULL) {
3960 if (is_type_compound(type)) {
3961 assert(anonymous_entity->compound.alias == NULL);
3962 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3963 anonymous_entity->kind == ENTITY_UNION);
3964 anonymous_entity->compound.alias = entity;
3965 anonymous_entity = NULL;
3966 } else if (is_type_enum(type)) {
3967 assert(anonymous_entity->enume.alias == NULL);
3968 assert(anonymous_entity->kind == ENTITY_ENUM);
3969 anonymous_entity->enume.alias = entity;
3970 anonymous_entity = NULL;
3974 /* create a declaration type entity */
3975 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3976 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3978 if (env.symbol != NULL) {
3979 if (specifiers->is_inline && is_type_valid(type)) {
3980 errorf(&env.source_position,
3981 "compound member '%Y' declared 'inline'", env.symbol);
3984 if (specifiers->thread_local ||
3985 specifiers->storage_class != STORAGE_CLASS_NONE) {
3986 errorf(&env.source_position,
3987 "compound member '%Y' must have no storage class",
3991 } else if (flags & DECL_IS_PARAMETER) {
3992 orig_type = semantic_parameter(&env.source_position, orig_type,
3993 specifiers, env.symbol);
3995 entity = allocate_entity_zero(ENTITY_PARAMETER);
3996 } else if (is_type_function(type)) {
3997 entity = allocate_entity_zero(ENTITY_FUNCTION);
3999 entity->function.is_inline = specifiers->is_inline;
4000 entity->function.parameters = env.parameters;
4002 if (env.symbol != NULL) {
4003 /* this needs fixes for C++ */
4004 bool in_function_scope = current_function != NULL;
4006 if (specifiers->thread_local || (
4007 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4008 specifiers->storage_class != STORAGE_CLASS_NONE &&
4009 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4011 errorf(&env.source_position,
4012 "invalid storage class for function '%Y'", env.symbol);
4016 entity = allocate_entity_zero(ENTITY_VARIABLE);
4018 entity->variable.thread_local = specifiers->thread_local;
4020 if (env.symbol != NULL) {
4021 if (specifiers->is_inline && is_type_valid(type)) {
4022 errorf(&env.source_position,
4023 "variable '%Y' declared 'inline'", env.symbol);
4026 bool invalid_storage_class = false;
4027 if (current_scope == file_scope) {
4028 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4029 specifiers->storage_class != STORAGE_CLASS_NONE &&
4030 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4031 invalid_storage_class = true;
4034 if (specifiers->thread_local &&
4035 specifiers->storage_class == STORAGE_CLASS_NONE) {
4036 invalid_storage_class = true;
4039 if (invalid_storage_class) {
4040 errorf(&env.source_position,
4041 "invalid storage class for variable '%Y'", env.symbol);
4046 if (env.symbol != NULL) {
4047 entity->base.symbol = env.symbol;
4048 entity->base.source_position = env.source_position;
4050 entity->base.source_position = specifiers->source_position;
4052 entity->base.namespc = NAMESPACE_NORMAL;
4053 entity->declaration.type = orig_type;
4054 entity->declaration.alignment = get_type_alignment(orig_type);
4055 entity->declaration.modifiers = env.modifiers;
4056 entity->declaration.attributes = attributes;
4058 storage_class_t storage_class = specifiers->storage_class;
4059 entity->declaration.declared_storage_class = storage_class;
4061 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4062 storage_class = STORAGE_CLASS_AUTO;
4063 entity->declaration.storage_class = storage_class;
4066 if (attributes != NULL) {
4067 handle_entity_attributes(attributes, entity);
4073 static type_t *parse_abstract_declarator(type_t *base_type)
4075 parse_declarator_env_t env;
4076 memset(&env, 0, sizeof(env));
4077 env.may_be_abstract = true;
4078 env.must_be_abstract = true;
4080 construct_type_t *construct_type = parse_inner_declarator(&env);
4082 type_t *result = construct_declarator_type(construct_type, base_type);
4083 if (construct_type != NULL) {
4084 obstack_free(&temp_obst, construct_type);
4086 result = handle_type_attributes(env.attributes, result);
4092 * Check if the declaration of main is suspicious. main should be a
4093 * function with external linkage, returning int, taking either zero
4094 * arguments, two, or three arguments of appropriate types, ie.
4096 * int main([ int argc, char **argv [, char **env ] ]).
4098 * @param decl the declaration to check
4099 * @param type the function type of the declaration
4101 static void check_main(const entity_t *entity)
4103 const source_position_t *pos = &entity->base.source_position;
4104 if (entity->kind != ENTITY_FUNCTION) {
4105 warningf(pos, "'main' is not a function");
4109 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4110 warningf(pos, "'main' is normally a non-static function");
4113 type_t *type = skip_typeref(entity->declaration.type);
4114 assert(is_type_function(type));
4116 function_type_t *func_type = &type->function;
4117 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4118 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4119 func_type->return_type);
4121 const function_parameter_t *parm = func_type->parameters;
4123 type_t *const first_type = parm->type;
4124 if (!types_compatible(skip_typeref(first_type), type_int)) {
4126 "first argument of 'main' should be 'int', but is '%T'",
4131 type_t *const second_type = parm->type;
4132 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4133 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4137 type_t *const third_type = parm->type;
4138 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4139 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4143 goto warn_arg_count;
4147 warningf(pos, "'main' takes only zero, two or three arguments");
4153 * Check if a symbol is the equal to "main".
4155 static bool is_sym_main(const symbol_t *const sym)
4157 return strcmp(sym->string, "main") == 0;
4160 static void error_redefined_as_different_kind(const source_position_t *pos,
4161 const entity_t *old, entity_kind_t new_kind)
4163 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4164 get_entity_kind_name(old->kind), old->base.symbol,
4165 get_entity_kind_name(new_kind), &old->base.source_position);
4168 static bool is_error_entity(entity_t *const ent)
4170 if (is_declaration(ent)) {
4171 return is_type_valid(skip_typeref(ent->declaration.type));
4172 } else if (ent->kind == ENTITY_TYPEDEF) {
4173 return is_type_valid(skip_typeref(ent->typedefe.type));
4178 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4180 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4181 if (attributes_equal(tattr, attr))
4188 * test wether new_list contains any attributes not included in old_list
4190 static bool has_new_attributes(const attribute_t *old_list,
4191 const attribute_t *new_list)
4193 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4194 if (!contains_attribute(old_list, attr))
4201 * Merge in attributes from an attribute list (probably from a previous
4202 * declaration with the same name). Warning: destroys the old structure
4203 * of the attribute list - don't reuse attributes after this call.
4205 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4208 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4210 if (contains_attribute(decl->attributes, attr))
4213 /* move attribute to new declarations attributes list */
4214 attr->next = decl->attributes;
4215 decl->attributes = attr;
4220 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4221 * for various problems that occur for multiple definitions
4223 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4225 const symbol_t *const symbol = entity->base.symbol;
4226 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4227 const source_position_t *pos = &entity->base.source_position;
4229 /* can happen in error cases */
4233 entity_t *const previous_entity = get_entity(symbol, namespc);
4234 /* pushing the same entity twice will break the stack structure */
4235 assert(previous_entity != entity);
4237 if (entity->kind == ENTITY_FUNCTION) {
4238 type_t *const orig_type = entity->declaration.type;
4239 type_t *const type = skip_typeref(orig_type);
4241 assert(is_type_function(type));
4242 if (type->function.unspecified_parameters &&
4243 warning.strict_prototypes &&
4244 previous_entity == NULL) {
4245 warningf(pos, "function declaration '%#T' is not a prototype",
4249 if (warning.main && current_scope == file_scope
4250 && is_sym_main(symbol)) {
4255 if (is_declaration(entity) &&
4256 warning.nested_externs &&
4257 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4258 current_scope != file_scope) {
4259 warningf(pos, "nested extern declaration of '%#T'",
4260 entity->declaration.type, symbol);
4263 if (previous_entity != NULL) {
4264 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4265 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4266 assert(previous_entity->kind == ENTITY_PARAMETER);
4268 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4269 entity->declaration.type, symbol,
4270 previous_entity->declaration.type, symbol,
4271 &previous_entity->base.source_position);
4275 if (previous_entity->base.parent_scope == current_scope) {
4276 if (previous_entity->kind != entity->kind) {
4277 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4278 error_redefined_as_different_kind(pos, previous_entity,
4283 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4284 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4285 symbol, &previous_entity->base.source_position);
4288 if (previous_entity->kind == ENTITY_TYPEDEF) {
4289 /* TODO: C++ allows this for exactly the same type */
4290 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4291 symbol, &previous_entity->base.source_position);
4295 /* at this point we should have only VARIABLES or FUNCTIONS */
4296 assert(is_declaration(previous_entity) && is_declaration(entity));
4298 declaration_t *const prev_decl = &previous_entity->declaration;
4299 declaration_t *const decl = &entity->declaration;
4301 /* can happen for K&R style declarations */
4302 if (prev_decl->type == NULL &&
4303 previous_entity->kind == ENTITY_PARAMETER &&
4304 entity->kind == ENTITY_PARAMETER) {
4305 prev_decl->type = decl->type;
4306 prev_decl->storage_class = decl->storage_class;
4307 prev_decl->declared_storage_class = decl->declared_storage_class;
4308 prev_decl->modifiers = decl->modifiers;
4309 return previous_entity;
4312 type_t *const orig_type = decl->type;
4313 assert(orig_type != NULL);
4314 type_t *const type = skip_typeref(orig_type);
4315 type_t *const prev_type = skip_typeref(prev_decl->type);
4317 if (!types_compatible(type, prev_type)) {
4319 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4320 orig_type, symbol, prev_decl->type, symbol,
4321 &previous_entity->base.source_position);
4323 unsigned old_storage_class = prev_decl->storage_class;
4325 if (warning.redundant_decls &&
4328 !(prev_decl->modifiers & DM_USED) &&
4329 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4330 warningf(&previous_entity->base.source_position,
4331 "unnecessary static forward declaration for '%#T'",
4332 prev_decl->type, symbol);
4335 storage_class_t new_storage_class = decl->storage_class;
4337 /* pretend no storage class means extern for function
4338 * declarations (except if the previous declaration is neither
4339 * none nor extern) */
4340 if (entity->kind == ENTITY_FUNCTION) {
4341 /* the previous declaration could have unspecified parameters or
4342 * be a typedef, so use the new type */
4343 if (prev_type->function.unspecified_parameters || is_definition)
4344 prev_decl->type = type;
4346 switch (old_storage_class) {
4347 case STORAGE_CLASS_NONE:
4348 old_storage_class = STORAGE_CLASS_EXTERN;
4351 case STORAGE_CLASS_EXTERN:
4352 if (is_definition) {
4353 if (warning.missing_prototypes &&
4354 prev_type->function.unspecified_parameters &&
4355 !is_sym_main(symbol)) {
4356 warningf(pos, "no previous prototype for '%#T'",
4359 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4360 new_storage_class = STORAGE_CLASS_EXTERN;
4367 } else if (is_type_incomplete(prev_type)) {
4368 prev_decl->type = type;
4371 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4372 new_storage_class == STORAGE_CLASS_EXTERN) {
4374 warn_redundant_declaration: ;
4376 = has_new_attributes(prev_decl->attributes,
4378 if (has_new_attrs) {
4379 merge_in_attributes(decl, prev_decl->attributes);
4380 } else if (!is_definition &&
4381 warning.redundant_decls &&
4382 is_type_valid(prev_type) &&
4383 strcmp(previous_entity->base.source_position.input_name,
4384 "<builtin>") != 0) {
4386 "redundant declaration for '%Y' (declared %P)",
4387 symbol, &previous_entity->base.source_position);
4389 } else if (current_function == NULL) {
4390 if (old_storage_class != STORAGE_CLASS_STATIC &&
4391 new_storage_class == STORAGE_CLASS_STATIC) {
4393 "static declaration of '%Y' follows non-static declaration (declared %P)",
4394 symbol, &previous_entity->base.source_position);
4395 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4396 prev_decl->storage_class = STORAGE_CLASS_NONE;
4397 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4399 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4401 goto error_redeclaration;
4402 goto warn_redundant_declaration;
4404 } else if (is_type_valid(prev_type)) {
4405 if (old_storage_class == new_storage_class) {
4406 error_redeclaration:
4407 errorf(pos, "redeclaration of '%Y' (declared %P)",
4408 symbol, &previous_entity->base.source_position);
4411 "redeclaration of '%Y' with different linkage (declared %P)",
4412 symbol, &previous_entity->base.source_position);
4417 prev_decl->modifiers |= decl->modifiers;
4418 if (entity->kind == ENTITY_FUNCTION) {
4419 previous_entity->function.is_inline |= entity->function.is_inline;
4421 return previous_entity;
4424 if (warning.shadow) {
4425 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4426 get_entity_kind_name(entity->kind), symbol,
4427 get_entity_kind_name(previous_entity->kind),
4428 &previous_entity->base.source_position);
4432 if (entity->kind == ENTITY_FUNCTION) {
4433 if (is_definition &&
4434 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4435 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4436 warningf(pos, "no previous prototype for '%#T'",
4437 entity->declaration.type, symbol);
4438 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4439 warningf(pos, "no previous declaration for '%#T'",
4440 entity->declaration.type, symbol);
4443 } else if (warning.missing_declarations &&
4444 entity->kind == ENTITY_VARIABLE &&
4445 current_scope == file_scope) {
4446 declaration_t *declaration = &entity->declaration;
4447 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4448 warningf(pos, "no previous declaration for '%#T'",
4449 declaration->type, symbol);
4454 assert(entity->base.parent_scope == NULL);
4455 assert(current_scope != NULL);
4457 entity->base.parent_scope = current_scope;
4458 entity->base.namespc = NAMESPACE_NORMAL;
4459 environment_push(entity);
4460 append_entity(current_scope, entity);
4465 static void parser_error_multiple_definition(entity_t *entity,
4466 const source_position_t *source_position)
4468 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4469 entity->base.symbol, &entity->base.source_position);
4472 static bool is_declaration_specifier(const token_t *token,
4473 bool only_specifiers_qualifiers)
4475 switch (token->type) {
4480 return is_typedef_symbol(token->v.symbol);
4482 case T___extension__:
4484 return !only_specifiers_qualifiers;
4491 static void parse_init_declarator_rest(entity_t *entity)
4493 assert(is_declaration(entity));
4494 declaration_t *const declaration = &entity->declaration;
4498 type_t *orig_type = declaration->type;
4499 type_t *type = skip_typeref(orig_type);
4501 if (entity->kind == ENTITY_VARIABLE
4502 && entity->variable.initializer != NULL) {
4503 parser_error_multiple_definition(entity, HERE);
4506 bool must_be_constant = false;
4507 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4508 entity->base.parent_scope == file_scope) {
4509 must_be_constant = true;
4512 if (is_type_function(type)) {
4513 errorf(&entity->base.source_position,
4514 "function '%#T' is initialized like a variable",
4515 orig_type, entity->base.symbol);
4516 orig_type = type_error_type;
4519 parse_initializer_env_t env;
4520 env.type = orig_type;
4521 env.must_be_constant = must_be_constant;
4522 env.entity = entity;
4523 current_init_decl = entity;
4525 initializer_t *initializer = parse_initializer(&env);
4526 current_init_decl = NULL;
4528 if (entity->kind == ENTITY_VARIABLE) {
4529 /* §6.7.5:22 array initializers for arrays with unknown size
4530 * determine the array type size */
4531 declaration->type = env.type;
4532 entity->variable.initializer = initializer;
4536 /* parse rest of a declaration without any declarator */
4537 static void parse_anonymous_declaration_rest(
4538 const declaration_specifiers_t *specifiers)
4541 anonymous_entity = NULL;
4543 if (warning.other) {
4544 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4545 specifiers->thread_local) {
4546 warningf(&specifiers->source_position,
4547 "useless storage class in empty declaration");
4550 type_t *type = specifiers->type;
4551 switch (type->kind) {
4552 case TYPE_COMPOUND_STRUCT:
4553 case TYPE_COMPOUND_UNION: {
4554 if (type->compound.compound->base.symbol == NULL) {
4555 warningf(&specifiers->source_position,
4556 "unnamed struct/union that defines no instances");
4565 warningf(&specifiers->source_position, "empty declaration");
4571 static void check_variable_type_complete(entity_t *ent)
4573 if (ent->kind != ENTITY_VARIABLE)
4576 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4577 * type for the object shall be complete [...] */
4578 declaration_t *decl = &ent->declaration;
4579 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4580 decl->storage_class == STORAGE_CLASS_STATIC)
4583 type_t *const orig_type = decl->type;
4584 type_t *const type = skip_typeref(orig_type);
4585 if (!is_type_incomplete(type))
4588 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4589 * are given length one. */
4590 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4591 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4595 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4596 orig_type, ent->base.symbol);
4600 static void parse_declaration_rest(entity_t *ndeclaration,
4601 const declaration_specifiers_t *specifiers,
4602 parsed_declaration_func finished_declaration,
4603 declarator_flags_t flags)
4605 add_anchor_token(';');
4606 add_anchor_token(',');
4608 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4610 if (token.type == '=') {
4611 parse_init_declarator_rest(entity);
4612 } else if (entity->kind == ENTITY_VARIABLE) {
4613 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4614 * [...] where the extern specifier is explicitly used. */
4615 declaration_t *decl = &entity->declaration;
4616 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4617 type_t *type = decl->type;
4618 if (is_type_reference(skip_typeref(type))) {
4619 errorf(&entity->base.source_position,
4620 "reference '%#T' must be initialized",
4621 type, entity->base.symbol);
4626 check_variable_type_complete(entity);
4631 add_anchor_token('=');
4632 ndeclaration = parse_declarator(specifiers, flags);
4633 rem_anchor_token('=');
4635 expect(';', end_error);
4638 anonymous_entity = NULL;
4639 rem_anchor_token(';');
4640 rem_anchor_token(',');
4643 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4645 symbol_t *symbol = entity->base.symbol;
4646 if (symbol == NULL) {
4647 errorf(HERE, "anonymous declaration not valid as function parameter");
4651 assert(entity->base.namespc == NAMESPACE_NORMAL);
4652 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4653 if (previous_entity == NULL
4654 || previous_entity->base.parent_scope != current_scope) {
4655 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4660 if (is_definition) {
4661 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4664 return record_entity(entity, false);
4667 static void parse_declaration(parsed_declaration_func finished_declaration,
4668 declarator_flags_t flags)
4670 declaration_specifiers_t specifiers;
4671 memset(&specifiers, 0, sizeof(specifiers));
4673 add_anchor_token(';');
4674 parse_declaration_specifiers(&specifiers);
4675 rem_anchor_token(';');
4677 if (token.type == ';') {
4678 parse_anonymous_declaration_rest(&specifiers);
4680 entity_t *entity = parse_declarator(&specifiers, flags);
4681 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4686 static type_t *get_default_promoted_type(type_t *orig_type)
4688 type_t *result = orig_type;
4690 type_t *type = skip_typeref(orig_type);
4691 if (is_type_integer(type)) {
4692 result = promote_integer(type);
4693 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4694 result = type_double;
4700 static void parse_kr_declaration_list(entity_t *entity)
4702 if (entity->kind != ENTITY_FUNCTION)
4705 type_t *type = skip_typeref(entity->declaration.type);
4706 assert(is_type_function(type));
4707 if (!type->function.kr_style_parameters)
4710 add_anchor_token('{');
4712 /* push function parameters */
4713 size_t const top = environment_top();
4714 scope_t *old_scope = scope_push(&entity->function.parameters);
4716 entity_t *parameter = entity->function.parameters.entities;
4717 for ( ; parameter != NULL; parameter = parameter->base.next) {
4718 assert(parameter->base.parent_scope == NULL);
4719 parameter->base.parent_scope = current_scope;
4720 environment_push(parameter);
4723 /* parse declaration list */
4725 switch (token.type) {
4727 case T___extension__:
4728 /* This covers symbols, which are no type, too, and results in
4729 * better error messages. The typical cases are misspelled type
4730 * names and missing includes. */
4732 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4740 /* pop function parameters */
4741 assert(current_scope == &entity->function.parameters);
4742 scope_pop(old_scope);
4743 environment_pop_to(top);
4745 /* update function type */
4746 type_t *new_type = duplicate_type(type);
4748 function_parameter_t *parameters = NULL;
4749 function_parameter_t **anchor = ¶meters;
4751 /* did we have an earlier prototype? */
4752 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4753 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4756 function_parameter_t *proto_parameter = NULL;
4757 if (proto_type != NULL) {
4758 type_t *proto_type_type = proto_type->declaration.type;
4759 proto_parameter = proto_type_type->function.parameters;
4760 /* If a K&R function definition has a variadic prototype earlier, then
4761 * make the function definition variadic, too. This should conform to
4762 * §6.7.5.3:15 and §6.9.1:8. */
4763 new_type->function.variadic = proto_type_type->function.variadic;
4765 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4767 new_type->function.unspecified_parameters = true;
4770 bool need_incompatible_warning = false;
4771 parameter = entity->function.parameters.entities;
4772 for (; parameter != NULL; parameter = parameter->base.next,
4774 proto_parameter == NULL ? NULL : proto_parameter->next) {
4775 if (parameter->kind != ENTITY_PARAMETER)
4778 type_t *parameter_type = parameter->declaration.type;
4779 if (parameter_type == NULL) {
4781 errorf(HERE, "no type specified for function parameter '%Y'",
4782 parameter->base.symbol);
4783 parameter_type = type_error_type;
4785 if (warning.implicit_int) {
4786 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4787 parameter->base.symbol);
4789 parameter_type = type_int;
4791 parameter->declaration.type = parameter_type;
4794 semantic_parameter_incomplete(parameter);
4796 /* we need the default promoted types for the function type */
4797 type_t *not_promoted = parameter_type;
4798 parameter_type = get_default_promoted_type(parameter_type);
4800 /* gcc special: if the type of the prototype matches the unpromoted
4801 * type don't promote */
4802 if (!strict_mode && proto_parameter != NULL) {
4803 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4804 type_t *promo_skip = skip_typeref(parameter_type);
4805 type_t *param_skip = skip_typeref(not_promoted);
4806 if (!types_compatible(proto_p_type, promo_skip)
4807 && types_compatible(proto_p_type, param_skip)) {
4809 need_incompatible_warning = true;
4810 parameter_type = not_promoted;
4813 function_parameter_t *const parameter
4814 = allocate_parameter(parameter_type);
4816 *anchor = parameter;
4817 anchor = ¶meter->next;
4820 new_type->function.parameters = parameters;
4821 new_type = identify_new_type(new_type);
4823 if (warning.other && need_incompatible_warning) {
4824 type_t *proto_type_type = proto_type->declaration.type;
4826 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4827 proto_type_type, proto_type->base.symbol,
4828 new_type, entity->base.symbol,
4829 &proto_type->base.source_position);
4832 entity->declaration.type = new_type;
4834 rem_anchor_token('{');
4837 static bool first_err = true;
4840 * When called with first_err set, prints the name of the current function,
4843 static void print_in_function(void)
4847 diagnosticf("%s: In function '%Y':\n",
4848 current_function->base.base.source_position.input_name,
4849 current_function->base.base.symbol);
4854 * Check if all labels are defined in the current function.
4855 * Check if all labels are used in the current function.
4857 static void check_labels(void)
4859 for (const goto_statement_t *goto_statement = goto_first;
4860 goto_statement != NULL;
4861 goto_statement = goto_statement->next) {
4862 /* skip computed gotos */
4863 if (goto_statement->expression != NULL)
4866 label_t *label = goto_statement->label;
4869 if (label->base.source_position.input_name == NULL) {
4870 print_in_function();
4871 errorf(&goto_statement->base.source_position,
4872 "label '%Y' used but not defined", label->base.symbol);
4876 if (warning.unused_label) {
4877 for (const label_statement_t *label_statement = label_first;
4878 label_statement != NULL;
4879 label_statement = label_statement->next) {
4880 label_t *label = label_statement->label;
4882 if (! label->used) {
4883 print_in_function();
4884 warningf(&label_statement->base.source_position,
4885 "label '%Y' defined but not used", label->base.symbol);
4891 static void warn_unused_entity(entity_t *entity, entity_t *last)
4893 entity_t const *const end = last != NULL ? last->base.next : NULL;
4894 for (; entity != end; entity = entity->base.next) {
4895 if (!is_declaration(entity))
4898 declaration_t *declaration = &entity->declaration;
4899 if (declaration->implicit)
4902 if (!declaration->used) {
4903 print_in_function();
4904 const char *what = get_entity_kind_name(entity->kind);
4905 warningf(&entity->base.source_position, "%s '%Y' is unused",
4906 what, entity->base.symbol);
4907 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4908 print_in_function();
4909 const char *what = get_entity_kind_name(entity->kind);
4910 warningf(&entity->base.source_position, "%s '%Y' is never read",
4911 what, entity->base.symbol);
4916 static void check_unused_variables(statement_t *const stmt, void *const env)
4920 switch (stmt->kind) {
4921 case STATEMENT_DECLARATION: {
4922 declaration_statement_t const *const decls = &stmt->declaration;
4923 warn_unused_entity(decls->declarations_begin,
4924 decls->declarations_end);
4929 warn_unused_entity(stmt->fors.scope.entities, NULL);
4938 * Check declarations of current_function for unused entities.
4940 static void check_declarations(void)
4942 if (warning.unused_parameter) {
4943 const scope_t *scope = ¤t_function->parameters;
4945 /* do not issue unused warnings for main */
4946 if (!is_sym_main(current_function->base.base.symbol)) {
4947 warn_unused_entity(scope->entities, NULL);
4950 if (warning.unused_variable) {
4951 walk_statements(current_function->statement, check_unused_variables,
4956 static int determine_truth(expression_t const* const cond)
4959 !is_constant_expression(cond) ? 0 :
4960 fold_constant_to_bool(cond) ? 1 :
4964 static void check_reachable(statement_t *);
4965 static bool reaches_end;
4967 static bool expression_returns(expression_t const *const expr)
4969 switch (expr->kind) {
4971 expression_t const *const func = expr->call.function;
4972 if (func->kind == EXPR_REFERENCE) {
4973 entity_t *entity = func->reference.entity;
4974 if (entity->kind == ENTITY_FUNCTION
4975 && entity->declaration.modifiers & DM_NORETURN)
4979 if (!expression_returns(func))
4982 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4983 if (!expression_returns(arg->expression))
4990 case EXPR_REFERENCE:
4991 case EXPR_REFERENCE_ENUM_VALUE:
4993 case EXPR_CHARACTER_CONSTANT:
4994 case EXPR_WIDE_CHARACTER_CONSTANT:
4995 case EXPR_STRING_LITERAL:
4996 case EXPR_WIDE_STRING_LITERAL:
4997 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4998 case EXPR_LABEL_ADDRESS:
4999 case EXPR_CLASSIFY_TYPE:
5000 case EXPR_SIZEOF: // TODO handle obscure VLA case
5003 case EXPR_BUILTIN_CONSTANT_P:
5004 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5009 case EXPR_STATEMENT: {
5010 bool old_reaches_end = reaches_end;
5011 reaches_end = false;
5012 check_reachable(expr->statement.statement);
5013 bool returns = reaches_end;
5014 reaches_end = old_reaches_end;
5018 case EXPR_CONDITIONAL:
5019 // TODO handle constant expression
5021 if (!expression_returns(expr->conditional.condition))
5024 if (expr->conditional.true_expression != NULL
5025 && expression_returns(expr->conditional.true_expression))
5028 return expression_returns(expr->conditional.false_expression);
5031 return expression_returns(expr->select.compound);
5033 case EXPR_ARRAY_ACCESS:
5035 expression_returns(expr->array_access.array_ref) &&
5036 expression_returns(expr->array_access.index);
5039 return expression_returns(expr->va_starte.ap);
5042 return expression_returns(expr->va_arge.ap);
5045 return expression_returns(expr->va_copye.src);
5047 EXPR_UNARY_CASES_MANDATORY
5048 return expression_returns(expr->unary.value);
5050 case EXPR_UNARY_THROW:
5054 // TODO handle constant lhs of && and ||
5056 expression_returns(expr->binary.left) &&
5057 expression_returns(expr->binary.right);
5063 panic("unhandled expression");
5066 static bool initializer_returns(initializer_t const *const init)
5068 switch (init->kind) {
5069 case INITIALIZER_VALUE:
5070 return expression_returns(init->value.value);
5072 case INITIALIZER_LIST: {
5073 initializer_t * const* i = init->list.initializers;
5074 initializer_t * const* const end = i + init->list.len;
5075 bool returns = true;
5076 for (; i != end; ++i) {
5077 if (!initializer_returns(*i))
5083 case INITIALIZER_STRING:
5084 case INITIALIZER_WIDE_STRING:
5085 case INITIALIZER_DESIGNATOR: // designators have no payload
5088 panic("unhandled initializer");
5091 static bool noreturn_candidate;
5093 static void check_reachable(statement_t *const stmt)
5095 if (stmt->base.reachable)
5097 if (stmt->kind != STATEMENT_DO_WHILE)
5098 stmt->base.reachable = true;
5100 statement_t *last = stmt;
5102 switch (stmt->kind) {
5103 case STATEMENT_INVALID:
5104 case STATEMENT_EMPTY:
5106 next = stmt->base.next;
5109 case STATEMENT_DECLARATION: {
5110 declaration_statement_t const *const decl = &stmt->declaration;
5111 entity_t const * ent = decl->declarations_begin;
5112 entity_t const *const last = decl->declarations_end;
5114 for (;; ent = ent->base.next) {
5115 if (ent->kind == ENTITY_VARIABLE &&
5116 ent->variable.initializer != NULL &&
5117 !initializer_returns(ent->variable.initializer)) {
5124 next = stmt->base.next;
5128 case STATEMENT_COMPOUND:
5129 next = stmt->compound.statements;
5131 next = stmt->base.next;
5134 case STATEMENT_RETURN: {
5135 expression_t const *const val = stmt->returns.value;
5136 if (val == NULL || expression_returns(val))
5137 noreturn_candidate = false;
5141 case STATEMENT_IF: {
5142 if_statement_t const *const ifs = &stmt->ifs;
5143 expression_t const *const cond = ifs->condition;
5145 if (!expression_returns(cond))
5148 int const val = determine_truth(cond);
5151 check_reachable(ifs->true_statement);
5156 if (ifs->false_statement != NULL) {
5157 check_reachable(ifs->false_statement);
5161 next = stmt->base.next;
5165 case STATEMENT_SWITCH: {
5166 switch_statement_t const *const switchs = &stmt->switchs;
5167 expression_t const *const expr = switchs->expression;
5169 if (!expression_returns(expr))
5172 if (is_constant_expression(expr)) {
5173 long const val = fold_constant_to_int(expr);
5174 case_label_statement_t * defaults = NULL;
5175 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5176 if (i->expression == NULL) {
5181 if (i->first_case <= val && val <= i->last_case) {
5182 check_reachable((statement_t*)i);
5187 if (defaults != NULL) {
5188 check_reachable((statement_t*)defaults);
5192 bool has_default = false;
5193 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5194 if (i->expression == NULL)
5197 check_reachable((statement_t*)i);
5204 next = stmt->base.next;
5208 case STATEMENT_EXPRESSION: {
5209 /* Check for noreturn function call */
5210 expression_t const *const expr = stmt->expression.expression;
5211 if (!expression_returns(expr))
5214 next = stmt->base.next;
5218 case STATEMENT_CONTINUE:
5219 for (statement_t *parent = stmt;;) {
5220 parent = parent->base.parent;
5221 if (parent == NULL) /* continue not within loop */
5225 switch (parent->kind) {
5226 case STATEMENT_WHILE: goto continue_while;
5227 case STATEMENT_DO_WHILE: goto continue_do_while;
5228 case STATEMENT_FOR: goto continue_for;
5234 case STATEMENT_BREAK:
5235 for (statement_t *parent = stmt;;) {
5236 parent = parent->base.parent;
5237 if (parent == NULL) /* break not within loop/switch */
5240 switch (parent->kind) {
5241 case STATEMENT_SWITCH:
5242 case STATEMENT_WHILE:
5243 case STATEMENT_DO_WHILE:
5246 next = parent->base.next;
5247 goto found_break_parent;
5255 case STATEMENT_GOTO:
5256 if (stmt->gotos.expression) {
5257 if (!expression_returns(stmt->gotos.expression))
5260 statement_t *parent = stmt->base.parent;
5261 if (parent == NULL) /* top level goto */
5265 next = stmt->gotos.label->statement;
5266 if (next == NULL) /* missing label */
5271 case STATEMENT_LABEL:
5272 next = stmt->label.statement;
5275 case STATEMENT_CASE_LABEL:
5276 next = stmt->case_label.statement;
5279 case STATEMENT_WHILE: {
5280 while_statement_t const *const whiles = &stmt->whiles;
5281 expression_t const *const cond = whiles->condition;
5283 if (!expression_returns(cond))
5286 int const val = determine_truth(cond);
5289 check_reachable(whiles->body);
5294 next = stmt->base.next;
5298 case STATEMENT_DO_WHILE:
5299 next = stmt->do_while.body;
5302 case STATEMENT_FOR: {
5303 for_statement_t *const fors = &stmt->fors;
5305 if (fors->condition_reachable)
5307 fors->condition_reachable = true;
5309 expression_t const *const cond = fors->condition;
5314 } else if (expression_returns(cond)) {
5315 val = determine_truth(cond);
5321 check_reachable(fors->body);
5326 next = stmt->base.next;
5330 case STATEMENT_MS_TRY: {
5331 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5332 check_reachable(ms_try->try_statement);
5333 next = ms_try->final_statement;
5337 case STATEMENT_LEAVE: {
5338 statement_t *parent = stmt;
5340 parent = parent->base.parent;
5341 if (parent == NULL) /* __leave not within __try */
5344 if (parent->kind == STATEMENT_MS_TRY) {
5346 next = parent->ms_try.final_statement;
5354 panic("invalid statement kind");
5357 while (next == NULL) {
5358 next = last->base.parent;
5360 noreturn_candidate = false;
5362 type_t *const type = skip_typeref(current_function->base.type);
5363 assert(is_type_function(type));
5364 type_t *const ret = skip_typeref(type->function.return_type);
5365 if (warning.return_type &&
5366 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5367 is_type_valid(ret) &&
5368 !is_sym_main(current_function->base.base.symbol)) {
5369 warningf(&stmt->base.source_position,
5370 "control reaches end of non-void function");
5375 switch (next->kind) {
5376 case STATEMENT_INVALID:
5377 case STATEMENT_EMPTY:
5378 case STATEMENT_DECLARATION:
5379 case STATEMENT_EXPRESSION:
5381 case STATEMENT_RETURN:
5382 case STATEMENT_CONTINUE:
5383 case STATEMENT_BREAK:
5384 case STATEMENT_GOTO:
5385 case STATEMENT_LEAVE:
5386 panic("invalid control flow in function");
5388 case STATEMENT_COMPOUND:
5389 if (next->compound.stmt_expr) {
5395 case STATEMENT_SWITCH:
5396 case STATEMENT_LABEL:
5397 case STATEMENT_CASE_LABEL:
5399 next = next->base.next;
5402 case STATEMENT_WHILE: {
5404 if (next->base.reachable)
5406 next->base.reachable = true;
5408 while_statement_t const *const whiles = &next->whiles;
5409 expression_t const *const cond = whiles->condition;
5411 if (!expression_returns(cond))
5414 int const val = determine_truth(cond);
5417 check_reachable(whiles->body);
5423 next = next->base.next;
5427 case STATEMENT_DO_WHILE: {
5429 if (next->base.reachable)
5431 next->base.reachable = true;
5433 do_while_statement_t const *const dw = &next->do_while;
5434 expression_t const *const cond = dw->condition;
5436 if (!expression_returns(cond))
5439 int const val = determine_truth(cond);
5442 check_reachable(dw->body);
5448 next = next->base.next;
5452 case STATEMENT_FOR: {
5454 for_statement_t *const fors = &next->fors;
5456 fors->step_reachable = true;
5458 if (fors->condition_reachable)
5460 fors->condition_reachable = true;
5462 expression_t const *const cond = fors->condition;
5467 } else if (expression_returns(cond)) {
5468 val = determine_truth(cond);
5474 check_reachable(fors->body);
5480 next = next->base.next;
5484 case STATEMENT_MS_TRY:
5486 next = next->ms_try.final_statement;
5491 check_reachable(next);
5494 static void check_unreachable(statement_t* const stmt, void *const env)
5498 switch (stmt->kind) {
5499 case STATEMENT_DO_WHILE:
5500 if (!stmt->base.reachable) {
5501 expression_t const *const cond = stmt->do_while.condition;
5502 if (determine_truth(cond) >= 0) {
5503 warningf(&cond->base.source_position,
5504 "condition of do-while-loop is unreachable");
5509 case STATEMENT_FOR: {
5510 for_statement_t const* const fors = &stmt->fors;
5512 // if init and step are unreachable, cond is unreachable, too
5513 if (!stmt->base.reachable && !fors->step_reachable) {
5514 warningf(&stmt->base.source_position, "statement is unreachable");
5516 if (!stmt->base.reachable && fors->initialisation != NULL) {
5517 warningf(&fors->initialisation->base.source_position,
5518 "initialisation of for-statement is unreachable");
5521 if (!fors->condition_reachable && fors->condition != NULL) {
5522 warningf(&fors->condition->base.source_position,
5523 "condition of for-statement is unreachable");
5526 if (!fors->step_reachable && fors->step != NULL) {
5527 warningf(&fors->step->base.source_position,
5528 "step of for-statement is unreachable");
5534 case STATEMENT_COMPOUND:
5535 if (stmt->compound.statements != NULL)
5537 goto warn_unreachable;
5539 case STATEMENT_DECLARATION: {
5540 /* Only warn if there is at least one declarator with an initializer.
5541 * This typically occurs in switch statements. */
5542 declaration_statement_t const *const decl = &stmt->declaration;
5543 entity_t const * ent = decl->declarations_begin;
5544 entity_t const *const last = decl->declarations_end;
5546 for (;; ent = ent->base.next) {
5547 if (ent->kind == ENTITY_VARIABLE &&
5548 ent->variable.initializer != NULL) {
5549 goto warn_unreachable;
5559 if (!stmt->base.reachable)
5560 warningf(&stmt->base.source_position, "statement is unreachable");
5565 static void parse_external_declaration(void)
5567 /* function-definitions and declarations both start with declaration
5569 declaration_specifiers_t specifiers;
5570 memset(&specifiers, 0, sizeof(specifiers));
5572 add_anchor_token(';');
5573 parse_declaration_specifiers(&specifiers);
5574 rem_anchor_token(';');
5576 /* must be a declaration */
5577 if (token.type == ';') {
5578 parse_anonymous_declaration_rest(&specifiers);
5582 add_anchor_token(',');
5583 add_anchor_token('=');
5584 add_anchor_token(';');
5585 add_anchor_token('{');
5587 /* declarator is common to both function-definitions and declarations */
5588 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5590 rem_anchor_token('{');
5591 rem_anchor_token(';');
5592 rem_anchor_token('=');
5593 rem_anchor_token(',');
5595 /* must be a declaration */
5596 switch (token.type) {
5600 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5605 /* must be a function definition */
5606 parse_kr_declaration_list(ndeclaration);
5608 if (token.type != '{') {
5609 parse_error_expected("while parsing function definition", '{', NULL);
5610 eat_until_matching_token(';');
5614 assert(is_declaration(ndeclaration));
5615 type_t *const orig_type = ndeclaration->declaration.type;
5616 type_t * type = skip_typeref(orig_type);
5618 if (!is_type_function(type)) {
5619 if (is_type_valid(type)) {
5620 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5621 type, ndeclaration->base.symbol);
5625 } else if (is_typeref(orig_type)) {
5627 errorf(&ndeclaration->base.source_position,
5628 "type of function definition '%#T' is a typedef",
5629 orig_type, ndeclaration->base.symbol);
5632 if (warning.aggregate_return &&
5633 is_type_compound(skip_typeref(type->function.return_type))) {
5634 warningf(HERE, "function '%Y' returns an aggregate",
5635 ndeclaration->base.symbol);
5637 if (warning.traditional && !type->function.unspecified_parameters) {
5638 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5639 ndeclaration->base.symbol);
5641 if (warning.old_style_definition && type->function.unspecified_parameters) {
5642 warningf(HERE, "old-style function definition '%Y'",
5643 ndeclaration->base.symbol);
5646 /* §6.7.5.3:14 a function definition with () means no
5647 * parameters (and not unspecified parameters) */
5648 if (type->function.unspecified_parameters &&
5649 type->function.parameters == NULL) {
5650 type_t *copy = duplicate_type(type);
5651 copy->function.unspecified_parameters = false;
5652 type = identify_new_type(copy);
5654 ndeclaration->declaration.type = type;
5657 entity_t *const entity = record_entity(ndeclaration, true);
5658 assert(entity->kind == ENTITY_FUNCTION);
5659 assert(ndeclaration->kind == ENTITY_FUNCTION);
5661 function_t *function = &entity->function;
5662 if (ndeclaration != entity) {
5663 function->parameters = ndeclaration->function.parameters;
5665 assert(is_declaration(entity));
5666 type = skip_typeref(entity->declaration.type);
5668 /* push function parameters and switch scope */
5669 size_t const top = environment_top();
5670 scope_t *old_scope = scope_push(&function->parameters);
5672 entity_t *parameter = function->parameters.entities;
5673 for (; parameter != NULL; parameter = parameter->base.next) {
5674 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5675 parameter->base.parent_scope = current_scope;
5677 assert(parameter->base.parent_scope == NULL
5678 || parameter->base.parent_scope == current_scope);
5679 parameter->base.parent_scope = current_scope;
5680 if (parameter->base.symbol == NULL) {
5681 errorf(¶meter->base.source_position, "parameter name omitted");
5684 environment_push(parameter);
5687 if (function->statement != NULL) {
5688 parser_error_multiple_definition(entity, HERE);
5691 /* parse function body */
5692 int label_stack_top = label_top();
5693 function_t *old_current_function = current_function;
5694 entity_t *old_current_entity = current_entity;
5695 current_function = function;
5696 current_entity = (entity_t*) function;
5697 current_parent = NULL;
5700 goto_anchor = &goto_first;
5702 label_anchor = &label_first;
5704 statement_t *const body = parse_compound_statement(false);
5705 function->statement = body;
5708 check_declarations();
5709 if (warning.return_type ||
5710 warning.unreachable_code ||
5711 (warning.missing_noreturn
5712 && !(function->base.modifiers & DM_NORETURN))) {
5713 noreturn_candidate = true;
5714 check_reachable(body);
5715 if (warning.unreachable_code)
5716 walk_statements(body, check_unreachable, NULL);
5717 if (warning.missing_noreturn &&
5718 noreturn_candidate &&
5719 !(function->base.modifiers & DM_NORETURN)) {
5720 warningf(&body->base.source_position,
5721 "function '%#T' is candidate for attribute 'noreturn'",
5722 type, entity->base.symbol);
5726 assert(current_parent == NULL);
5727 assert(current_function == function);
5728 assert(current_entity == (entity_t*) function);
5729 current_entity = old_current_entity;
5730 current_function = old_current_function;
5731 label_pop_to(label_stack_top);
5734 assert(current_scope == &function->parameters);
5735 scope_pop(old_scope);
5736 environment_pop_to(top);
5739 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5740 source_position_t *source_position,
5741 const symbol_t *symbol)
5743 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5745 type->bitfield.base_type = base_type;
5746 type->bitfield.size_expression = size;
5749 type_t *skipped_type = skip_typeref(base_type);
5750 if (!is_type_integer(skipped_type)) {
5751 errorf(HERE, "bitfield base type '%T' is not an integer type",
5755 bit_size = get_type_size(base_type) * 8;
5758 if (is_constant_expression(size)) {
5759 long v = fold_constant_to_int(size);
5760 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5763 errorf(source_position, "negative width in bit-field '%Y'",
5765 } else if (v == 0 && symbol != NULL) {
5766 errorf(source_position, "zero width for bit-field '%Y'",
5768 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5769 errorf(source_position, "width of '%Y' exceeds its type",
5772 type->bitfield.bit_size = v;
5779 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5781 entity_t *iter = compound->members.entities;
5782 for (; iter != NULL; iter = iter->base.next) {
5783 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5786 if (iter->base.symbol == symbol) {
5788 } else if (iter->base.symbol == NULL) {
5789 /* search in anonymous structs and unions */
5790 type_t *type = skip_typeref(iter->declaration.type);
5791 if (is_type_compound(type)) {
5792 if (find_compound_entry(type->compound.compound, symbol)
5803 static void check_deprecated(const source_position_t *source_position,
5804 const entity_t *entity)
5806 if (!warning.deprecated_declarations)
5808 if (!is_declaration(entity))
5810 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5813 char const *const prefix = get_entity_kind_name(entity->kind);
5814 const char *deprecated_string
5815 = get_deprecated_string(entity->declaration.attributes);
5816 if (deprecated_string != NULL) {
5817 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5818 prefix, entity->base.symbol, &entity->base.source_position,
5821 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5822 entity->base.symbol, &entity->base.source_position);
5827 static expression_t *create_select(const source_position_t *pos,
5829 type_qualifiers_t qualifiers,
5832 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5834 check_deprecated(pos, entry);
5836 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5837 select->select.compound = addr;
5838 select->select.compound_entry = entry;
5840 type_t *entry_type = entry->declaration.type;
5841 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5843 /* we always do the auto-type conversions; the & and sizeof parser contains
5844 * code to revert this! */
5845 select->base.type = automatic_type_conversion(res_type);
5846 if (res_type->kind == TYPE_BITFIELD) {
5847 select->base.type = res_type->bitfield.base_type;
5854 * Find entry with symbol in compound. Search anonymous structs and unions and
5855 * creates implicit select expressions for them.
5856 * Returns the adress for the innermost compound.
5858 static expression_t *find_create_select(const source_position_t *pos,
5860 type_qualifiers_t qualifiers,
5861 compound_t *compound, symbol_t *symbol)
5863 entity_t *iter = compound->members.entities;
5864 for (; iter != NULL; iter = iter->base.next) {
5865 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5868 symbol_t *iter_symbol = iter->base.symbol;
5869 if (iter_symbol == NULL) {
5870 type_t *type = iter->declaration.type;
5871 if (type->kind != TYPE_COMPOUND_STRUCT
5872 && type->kind != TYPE_COMPOUND_UNION)
5875 compound_t *sub_compound = type->compound.compound;
5877 if (find_compound_entry(sub_compound, symbol) == NULL)
5880 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5881 sub_addr->base.source_position = *pos;
5882 sub_addr->select.implicit = true;
5883 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5887 if (iter_symbol == symbol) {
5888 return create_select(pos, addr, qualifiers, iter);
5895 static void parse_compound_declarators(compound_t *compound,
5896 const declaration_specifiers_t *specifiers)
5901 if (token.type == ':') {
5902 source_position_t source_position = *HERE;
5905 type_t *base_type = specifiers->type;
5906 expression_t *size = parse_constant_expression();
5908 type_t *type = make_bitfield_type(base_type, size,
5909 &source_position, NULL);
5911 attribute_t *attributes = parse_attributes(NULL);
5912 attribute_t **anchor = &attributes;
5913 while (*anchor != NULL)
5914 anchor = &(*anchor)->next;
5915 *anchor = specifiers->attributes;
5917 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5918 entity->base.namespc = NAMESPACE_NORMAL;
5919 entity->base.source_position = source_position;
5920 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5921 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5922 entity->declaration.type = type;
5923 entity->declaration.attributes = attributes;
5925 if (attributes != NULL) {
5926 handle_entity_attributes(attributes, entity);
5928 append_entity(&compound->members, entity);
5930 entity = parse_declarator(specifiers,
5931 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5932 if (entity->kind == ENTITY_TYPEDEF) {
5933 errorf(&entity->base.source_position,
5934 "typedef not allowed as compound member");
5936 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5938 /* make sure we don't define a symbol multiple times */
5939 symbol_t *symbol = entity->base.symbol;
5940 if (symbol != NULL) {
5941 entity_t *prev = find_compound_entry(compound, symbol);
5943 errorf(&entity->base.source_position,
5944 "multiple declarations of symbol '%Y' (declared %P)",
5945 symbol, &prev->base.source_position);
5949 if (token.type == ':') {
5950 source_position_t source_position = *HERE;
5952 expression_t *size = parse_constant_expression();
5954 type_t *type = entity->declaration.type;
5955 type_t *bitfield_type = make_bitfield_type(type, size,
5956 &source_position, entity->base.symbol);
5958 attribute_t *attributes = parse_attributes(NULL);
5959 entity->declaration.type = bitfield_type;
5960 handle_entity_attributes(attributes, entity);
5962 type_t *orig_type = entity->declaration.type;
5963 type_t *type = skip_typeref(orig_type);
5964 if (is_type_function(type)) {
5965 errorf(&entity->base.source_position,
5966 "compound member '%Y' must not have function type '%T'",
5967 entity->base.symbol, orig_type);
5968 } else if (is_type_incomplete(type)) {
5969 /* §6.7.2.1:16 flexible array member */
5970 if (!is_type_array(type) ||
5971 token.type != ';' ||
5972 look_ahead(1)->type != '}') {
5973 errorf(&entity->base.source_position,
5974 "compound member '%Y' has incomplete type '%T'",
5975 entity->base.symbol, orig_type);
5980 append_entity(&compound->members, entity);
5983 } while (next_if(','));
5984 expect(';', end_error);
5987 anonymous_entity = NULL;
5990 static void parse_compound_type_entries(compound_t *compound)
5993 add_anchor_token('}');
5995 while (token.type != '}') {
5996 if (token.type == T_EOF) {
5997 errorf(HERE, "EOF while parsing struct");
6000 declaration_specifiers_t specifiers;
6001 memset(&specifiers, 0, sizeof(specifiers));
6002 parse_declaration_specifiers(&specifiers);
6004 parse_compound_declarators(compound, &specifiers);
6006 rem_anchor_token('}');
6010 compound->complete = true;
6013 static type_t *parse_typename(void)
6015 declaration_specifiers_t specifiers;
6016 memset(&specifiers, 0, sizeof(specifiers));
6017 parse_declaration_specifiers(&specifiers);
6018 if (specifiers.storage_class != STORAGE_CLASS_NONE
6019 || specifiers.thread_local) {
6020 /* TODO: improve error message, user does probably not know what a
6021 * storage class is...
6023 errorf(HERE, "typename may not have a storage class");
6026 type_t *result = parse_abstract_declarator(specifiers.type);
6034 typedef expression_t* (*parse_expression_function)(void);
6035 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6037 typedef struct expression_parser_function_t expression_parser_function_t;
6038 struct expression_parser_function_t {
6039 parse_expression_function parser;
6040 precedence_t infix_precedence;
6041 parse_expression_infix_function infix_parser;
6044 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6047 * Prints an error message if an expression was expected but not read
6049 static expression_t *expected_expression_error(void)
6051 /* skip the error message if the error token was read */
6052 if (token.type != T_ERROR) {
6053 errorf(HERE, "expected expression, got token %K", &token);
6057 return create_invalid_expression();
6061 * Parse a string constant.
6063 static expression_t *parse_string_const(void)
6066 if (token.type == T_STRING_LITERAL) {
6067 string_t res = token.v.string;
6069 while (token.type == T_STRING_LITERAL) {
6070 res = concat_strings(&res, &token.v.string);
6073 if (token.type != T_WIDE_STRING_LITERAL) {
6074 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6075 /* note: that we use type_char_ptr here, which is already the
6076 * automatic converted type. revert_automatic_type_conversion
6077 * will construct the array type */
6078 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6079 cnst->string.value = res;
6083 wres = concat_string_wide_string(&res, &token.v.wide_string);
6085 wres = token.v.wide_string;
6090 switch (token.type) {
6091 case T_WIDE_STRING_LITERAL:
6092 wres = concat_wide_strings(&wres, &token.v.wide_string);
6095 case T_STRING_LITERAL:
6096 wres = concat_wide_string_string(&wres, &token.v.string);
6100 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6101 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6102 cnst->wide_string.value = wres;
6111 * Parse a boolean constant.
6113 static expression_t *parse_bool_const(bool value)
6115 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6116 cnst->base.type = type_bool;
6117 cnst->conste.v.int_value = value;
6125 * Parse an integer constant.
6127 static expression_t *parse_int_const(void)
6129 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6130 cnst->base.type = token.datatype;
6131 cnst->conste.v.int_value = token.v.intvalue;
6139 * Parse a character constant.
6141 static expression_t *parse_character_constant(void)
6143 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6144 cnst->base.type = token.datatype;
6145 cnst->conste.v.character = token.v.string;
6147 if (cnst->conste.v.character.size != 1) {
6149 errorf(HERE, "more than 1 character in character constant");
6150 } else if (warning.multichar) {
6151 warningf(HERE, "multi-character character constant");
6160 * Parse a wide character constant.
6162 static expression_t *parse_wide_character_constant(void)
6164 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6165 cnst->base.type = token.datatype;
6166 cnst->conste.v.wide_character = token.v.wide_string;
6168 if (cnst->conste.v.wide_character.size != 1) {
6170 errorf(HERE, "more than 1 character in character constant");
6171 } else if (warning.multichar) {
6172 warningf(HERE, "multi-character character constant");
6181 * Parse a float constant.
6183 static expression_t *parse_float_const(void)
6185 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6186 cnst->base.type = token.datatype;
6187 cnst->conste.v.float_value = token.v.floatvalue;
6194 static entity_t *create_implicit_function(symbol_t *symbol,
6195 const source_position_t *source_position)
6197 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6198 ntype->function.return_type = type_int;
6199 ntype->function.unspecified_parameters = true;
6200 ntype->function.linkage = LINKAGE_C;
6201 type_t *type = identify_new_type(ntype);
6203 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6204 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6205 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6206 entity->declaration.type = type;
6207 entity->declaration.implicit = true;
6208 entity->base.symbol = symbol;
6209 entity->base.source_position = *source_position;
6211 if (current_scope != NULL) {
6212 bool strict_prototypes_old = warning.strict_prototypes;
6213 warning.strict_prototypes = false;
6214 record_entity(entity, false);
6215 warning.strict_prototypes = strict_prototypes_old;
6222 * Creates a return_type (func)(argument_type) function type if not
6225 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6226 type_t *argument_type2)
6228 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6229 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6230 parameter1->next = parameter2;
6232 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6233 type->function.return_type = return_type;
6234 type->function.parameters = parameter1;
6236 return identify_new_type(type);
6240 * Creates a return_type (func)(argument_type) function type if not
6243 * @param return_type the return type
6244 * @param argument_type the argument type
6246 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6248 function_parameter_t *const parameter = allocate_parameter(argument_type);
6250 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6251 type->function.return_type = return_type;
6252 type->function.parameters = parameter;
6254 return identify_new_type(type);
6258 * Creates a return_type (func)(argument_type, ...) function type if not
6261 * @param return_type the return type
6262 * @param argument_type the argument type
6264 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6266 function_parameter_t *const parameter = allocate_parameter(argument_type);
6268 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6269 type->function.return_type = return_type;
6270 type->function.parameters = parameter;
6271 type->function.variadic = true;
6273 return identify_new_type(type);
6277 * Creates a return_type (func)(void) function type if not
6280 * @param return_type the return type
6282 static type_t *make_function_0_type(type_t *return_type)
6284 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6285 type->function.return_type = return_type;
6286 type->function.parameters = NULL;
6288 return identify_new_type(type);
6292 * Creates a NO_RETURN return_type (func)(void) function type if not
6295 * @param return_type the return type
6297 static type_t *make_function_0_type_noreturn(type_t *return_type)
6299 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6300 type->function.return_type = return_type;
6301 type->function.parameters = NULL;
6302 type->function.modifiers |= DM_NORETURN;
6303 return identify_new_type(type);
6307 * Performs automatic type cast as described in §6.3.2.1.
6309 * @param orig_type the original type
6311 static type_t *automatic_type_conversion(type_t *orig_type)
6313 type_t *type = skip_typeref(orig_type);
6314 if (is_type_array(type)) {
6315 array_type_t *array_type = &type->array;
6316 type_t *element_type = array_type->element_type;
6317 unsigned qualifiers = array_type->base.qualifiers;
6319 return make_pointer_type(element_type, qualifiers);
6322 if (is_type_function(type)) {
6323 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6330 * reverts the automatic casts of array to pointer types and function
6331 * to function-pointer types as defined §6.3.2.1
6333 type_t *revert_automatic_type_conversion(const expression_t *expression)
6335 switch (expression->kind) {
6336 case EXPR_REFERENCE: {
6337 entity_t *entity = expression->reference.entity;
6338 if (is_declaration(entity)) {
6339 return entity->declaration.type;
6340 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6341 return entity->enum_value.enum_type;
6343 panic("no declaration or enum in reference");
6348 entity_t *entity = expression->select.compound_entry;
6349 assert(is_declaration(entity));
6350 type_t *type = entity->declaration.type;
6351 return get_qualified_type(type,
6352 expression->base.type->base.qualifiers);
6355 case EXPR_UNARY_DEREFERENCE: {
6356 const expression_t *const value = expression->unary.value;
6357 type_t *const type = skip_typeref(value->base.type);
6358 if (!is_type_pointer(type))
6359 return type_error_type;
6360 return type->pointer.points_to;
6363 case EXPR_ARRAY_ACCESS: {
6364 const expression_t *array_ref = expression->array_access.array_ref;
6365 type_t *type_left = skip_typeref(array_ref->base.type);
6366 if (!is_type_pointer(type_left))
6367 return type_error_type;
6368 return type_left->pointer.points_to;
6371 case EXPR_STRING_LITERAL: {
6372 size_t size = expression->string.value.size;
6373 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6376 case EXPR_WIDE_STRING_LITERAL: {
6377 size_t size = expression->wide_string.value.size;
6378 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6381 case EXPR_COMPOUND_LITERAL:
6382 return expression->compound_literal.type;
6385 return expression->base.type;
6390 * Find an entity matching a symbol in a scope.
6391 * Uses current scope if scope is NULL
6393 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6394 namespace_tag_t namespc)
6396 if (scope == NULL) {
6397 return get_entity(symbol, namespc);
6400 /* we should optimize here, if scope grows above a certain size we should
6401 construct a hashmap here... */
6402 entity_t *entity = scope->entities;
6403 for ( ; entity != NULL; entity = entity->base.next) {
6404 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6411 static entity_t *parse_qualified_identifier(void)
6413 /* namespace containing the symbol */
6415 source_position_t pos;
6416 const scope_t *lookup_scope = NULL;
6418 if (next_if(T_COLONCOLON))
6419 lookup_scope = &unit->scope;
6423 if (token.type != T_IDENTIFIER) {
6424 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6425 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6427 symbol = token.v.symbol;
6432 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6434 if (!next_if(T_COLONCOLON))
6437 switch (entity->kind) {
6438 case ENTITY_NAMESPACE:
6439 lookup_scope = &entity->namespacee.members;
6444 lookup_scope = &entity->compound.members;
6447 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6448 symbol, get_entity_kind_name(entity->kind));
6453 if (entity == NULL) {
6454 if (!strict_mode && token.type == '(') {
6455 /* an implicitly declared function */
6456 if (warning.error_implicit_function_declaration) {
6457 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6458 } else if (warning.implicit_function_declaration) {
6459 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6462 entity = create_implicit_function(symbol, &pos);
6464 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6465 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6472 /* skip further qualifications */
6473 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6475 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6478 static expression_t *parse_reference(void)
6480 entity_t *entity = parse_qualified_identifier();
6483 if (is_declaration(entity)) {
6484 orig_type = entity->declaration.type;
6485 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6486 orig_type = entity->enum_value.enum_type;
6488 panic("expected declaration or enum value in reference");
6491 /* we always do the auto-type conversions; the & and sizeof parser contains
6492 * code to revert this! */
6493 type_t *type = automatic_type_conversion(orig_type);
6495 expression_kind_t kind = EXPR_REFERENCE;
6496 if (entity->kind == ENTITY_ENUM_VALUE)
6497 kind = EXPR_REFERENCE_ENUM_VALUE;
6499 expression_t *expression = allocate_expression_zero(kind);
6500 expression->reference.entity = entity;
6501 expression->base.type = type;
6503 /* this declaration is used */
6504 if (is_declaration(entity)) {
6505 entity->declaration.used = true;
6508 if (entity->base.parent_scope != file_scope
6509 && (current_function != NULL
6510 && entity->base.parent_scope->depth < current_function->parameters.depth)
6511 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6512 if (entity->kind == ENTITY_VARIABLE) {
6513 /* access of a variable from an outer function */
6514 entity->variable.address_taken = true;
6515 } else if (entity->kind == ENTITY_PARAMETER) {
6516 entity->parameter.address_taken = true;
6518 current_function->need_closure = true;
6521 check_deprecated(HERE, entity);
6523 if (warning.init_self && entity == current_init_decl && !in_type_prop
6524 && entity->kind == ENTITY_VARIABLE) {
6525 current_init_decl = NULL;
6526 warningf(HERE, "variable '%#T' is initialized by itself",
6527 entity->declaration.type, entity->base.symbol);
6533 static bool semantic_cast(expression_t *cast)
6535 expression_t *expression = cast->unary.value;
6536 type_t *orig_dest_type = cast->base.type;
6537 type_t *orig_type_right = expression->base.type;
6538 type_t const *dst_type = skip_typeref(orig_dest_type);
6539 type_t const *src_type = skip_typeref(orig_type_right);
6540 source_position_t const *pos = &cast->base.source_position;
6542 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6543 if (dst_type == type_void)
6546 /* only integer and pointer can be casted to pointer */
6547 if (is_type_pointer(dst_type) &&
6548 !is_type_pointer(src_type) &&
6549 !is_type_integer(src_type) &&
6550 is_type_valid(src_type)) {
6551 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6555 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6556 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6560 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6561 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6565 if (warning.cast_qual &&
6566 is_type_pointer(src_type) &&
6567 is_type_pointer(dst_type)) {
6568 type_t *src = skip_typeref(src_type->pointer.points_to);
6569 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6570 unsigned missing_qualifiers =
6571 src->base.qualifiers & ~dst->base.qualifiers;
6572 if (missing_qualifiers != 0) {
6574 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6575 missing_qualifiers, orig_type_right);
6581 static expression_t *parse_compound_literal(type_t *type)
6583 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6585 parse_initializer_env_t env;
6588 env.must_be_constant = false;
6589 initializer_t *initializer = parse_initializer(&env);
6592 expression->compound_literal.initializer = initializer;
6593 expression->compound_literal.type = type;
6594 expression->base.type = automatic_type_conversion(type);
6600 * Parse a cast expression.
6602 static expression_t *parse_cast(void)
6604 add_anchor_token(')');
6606 source_position_t source_position = token.source_position;
6608 type_t *type = parse_typename();
6610 rem_anchor_token(')');
6611 expect(')', end_error);
6613 if (token.type == '{') {
6614 return parse_compound_literal(type);
6617 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6618 cast->base.source_position = source_position;
6620 expression_t *value = parse_sub_expression(PREC_CAST);
6621 cast->base.type = type;
6622 cast->unary.value = value;
6624 if (! semantic_cast(cast)) {
6625 /* TODO: record the error in the AST. else it is impossible to detect it */
6630 return create_invalid_expression();
6634 * Parse a statement expression.
6636 static expression_t *parse_statement_expression(void)
6638 add_anchor_token(')');
6640 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6642 statement_t *statement = parse_compound_statement(true);
6643 statement->compound.stmt_expr = true;
6644 expression->statement.statement = statement;
6646 /* find last statement and use its type */
6647 type_t *type = type_void;
6648 const statement_t *stmt = statement->compound.statements;
6650 while (stmt->base.next != NULL)
6651 stmt = stmt->base.next;
6653 if (stmt->kind == STATEMENT_EXPRESSION) {
6654 type = stmt->expression.expression->base.type;
6656 } else if (warning.other) {
6657 warningf(&expression->base.source_position, "empty statement expression ({})");
6659 expression->base.type = type;
6661 rem_anchor_token(')');
6662 expect(')', end_error);
6669 * Parse a parenthesized expression.
6671 static expression_t *parse_parenthesized_expression(void)
6675 switch (token.type) {
6677 /* gcc extension: a statement expression */
6678 return parse_statement_expression();
6682 return parse_cast();
6684 if (is_typedef_symbol(token.v.symbol)) {
6685 return parse_cast();
6689 add_anchor_token(')');
6690 expression_t *result = parse_expression();
6691 result->base.parenthesized = true;
6692 rem_anchor_token(')');
6693 expect(')', end_error);
6699 static expression_t *parse_function_keyword(void)
6703 if (current_function == NULL) {
6704 errorf(HERE, "'__func__' used outside of a function");
6707 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6708 expression->base.type = type_char_ptr;
6709 expression->funcname.kind = FUNCNAME_FUNCTION;
6716 static expression_t *parse_pretty_function_keyword(void)
6718 if (current_function == NULL) {
6719 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6722 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6723 expression->base.type = type_char_ptr;
6724 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6726 eat(T___PRETTY_FUNCTION__);
6731 static expression_t *parse_funcsig_keyword(void)
6733 if (current_function == NULL) {
6734 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6737 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6738 expression->base.type = type_char_ptr;
6739 expression->funcname.kind = FUNCNAME_FUNCSIG;
6746 static expression_t *parse_funcdname_keyword(void)
6748 if (current_function == NULL) {
6749 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6752 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6753 expression->base.type = type_char_ptr;
6754 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6756 eat(T___FUNCDNAME__);
6761 static designator_t *parse_designator(void)
6763 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6764 result->source_position = *HERE;
6766 if (token.type != T_IDENTIFIER) {
6767 parse_error_expected("while parsing member designator",
6768 T_IDENTIFIER, NULL);
6771 result->symbol = token.v.symbol;
6774 designator_t *last_designator = result;
6777 if (token.type != T_IDENTIFIER) {
6778 parse_error_expected("while parsing member designator",
6779 T_IDENTIFIER, NULL);
6782 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6783 designator->source_position = *HERE;
6784 designator->symbol = token.v.symbol;
6787 last_designator->next = designator;
6788 last_designator = designator;
6792 add_anchor_token(']');
6793 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6794 designator->source_position = *HERE;
6795 designator->array_index = parse_expression();
6796 rem_anchor_token(']');
6797 expect(']', end_error);
6798 if (designator->array_index == NULL) {
6802 last_designator->next = designator;
6803 last_designator = designator;
6815 * Parse the __builtin_offsetof() expression.
6817 static expression_t *parse_offsetof(void)
6819 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6820 expression->base.type = type_size_t;
6822 eat(T___builtin_offsetof);
6824 expect('(', end_error);
6825 add_anchor_token(',');
6826 type_t *type = parse_typename();
6827 rem_anchor_token(',');
6828 expect(',', end_error);
6829 add_anchor_token(')');
6830 designator_t *designator = parse_designator();
6831 rem_anchor_token(')');
6832 expect(')', end_error);
6834 expression->offsetofe.type = type;
6835 expression->offsetofe.designator = designator;
6838 memset(&path, 0, sizeof(path));
6839 path.top_type = type;
6840 path.path = NEW_ARR_F(type_path_entry_t, 0);
6842 descend_into_subtype(&path);
6844 if (!walk_designator(&path, designator, true)) {
6845 return create_invalid_expression();
6848 DEL_ARR_F(path.path);
6852 return create_invalid_expression();
6856 * Parses a _builtin_va_start() expression.
6858 static expression_t *parse_va_start(void)
6860 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6862 eat(T___builtin_va_start);
6864 expect('(', end_error);
6865 add_anchor_token(',');
6866 expression->va_starte.ap = parse_assignment_expression();
6867 rem_anchor_token(',');
6868 expect(',', end_error);
6869 expression_t *const expr = parse_assignment_expression();
6870 if (expr->kind == EXPR_REFERENCE) {
6871 entity_t *const entity = expr->reference.entity;
6872 if (!current_function->base.type->function.variadic) {
6873 errorf(&expr->base.source_position,
6874 "'va_start' used in non-variadic function");
6875 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6876 entity->base.next != NULL ||
6877 entity->kind != ENTITY_PARAMETER) {
6878 errorf(&expr->base.source_position,
6879 "second argument of 'va_start' must be last parameter of the current function");
6881 expression->va_starte.parameter = &entity->variable;
6883 expect(')', end_error);
6886 expect(')', end_error);
6888 return create_invalid_expression();
6892 * Parses a __builtin_va_arg() expression.
6894 static expression_t *parse_va_arg(void)
6896 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6898 eat(T___builtin_va_arg);
6900 expect('(', end_error);
6902 ap.expression = parse_assignment_expression();
6903 expression->va_arge.ap = ap.expression;
6904 check_call_argument(type_valist, &ap, 1);
6906 expect(',', end_error);
6907 expression->base.type = parse_typename();
6908 expect(')', end_error);
6912 return create_invalid_expression();
6916 * Parses a __builtin_va_copy() expression.
6918 static expression_t *parse_va_copy(void)
6920 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6922 eat(T___builtin_va_copy);
6924 expect('(', end_error);
6925 expression_t *dst = parse_assignment_expression();
6926 assign_error_t error = semantic_assign(type_valist, dst);
6927 report_assign_error(error, type_valist, dst, "call argument 1",
6928 &dst->base.source_position);
6929 expression->va_copye.dst = dst;
6931 expect(',', end_error);
6933 call_argument_t src;
6934 src.expression = parse_assignment_expression();
6935 check_call_argument(type_valist, &src, 2);
6936 expression->va_copye.src = src.expression;
6937 expect(')', end_error);
6941 return create_invalid_expression();
6945 * Parses a __builtin_constant_p() expression.
6947 static expression_t *parse_builtin_constant(void)
6949 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6951 eat(T___builtin_constant_p);
6953 expect('(', end_error);
6954 add_anchor_token(')');
6955 expression->builtin_constant.value = parse_assignment_expression();
6956 rem_anchor_token(')');
6957 expect(')', end_error);
6958 expression->base.type = type_int;
6962 return create_invalid_expression();
6966 * Parses a __builtin_types_compatible_p() expression.
6968 static expression_t *parse_builtin_types_compatible(void)
6970 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6972 eat(T___builtin_types_compatible_p);
6974 expect('(', end_error);
6975 add_anchor_token(')');
6976 add_anchor_token(',');
6977 expression->builtin_types_compatible.left = parse_typename();
6978 rem_anchor_token(',');
6979 expect(',', end_error);
6980 expression->builtin_types_compatible.right = parse_typename();
6981 rem_anchor_token(')');
6982 expect(')', end_error);
6983 expression->base.type = type_int;
6987 return create_invalid_expression();
6991 * Parses a __builtin_is_*() compare expression.
6993 static expression_t *parse_compare_builtin(void)
6995 expression_t *expression;
6997 switch (token.type) {
6998 case T___builtin_isgreater:
6999 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7001 case T___builtin_isgreaterequal:
7002 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7004 case T___builtin_isless:
7005 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7007 case T___builtin_islessequal:
7008 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7010 case T___builtin_islessgreater:
7011 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7013 case T___builtin_isunordered:
7014 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7017 internal_errorf(HERE, "invalid compare builtin found");
7019 expression->base.source_position = *HERE;
7022 expect('(', end_error);
7023 expression->binary.left = parse_assignment_expression();
7024 expect(',', end_error);
7025 expression->binary.right = parse_assignment_expression();
7026 expect(')', end_error);
7028 type_t *const orig_type_left = expression->binary.left->base.type;
7029 type_t *const orig_type_right = expression->binary.right->base.type;
7031 type_t *const type_left = skip_typeref(orig_type_left);
7032 type_t *const type_right = skip_typeref(orig_type_right);
7033 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7034 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7035 type_error_incompatible("invalid operands in comparison",
7036 &expression->base.source_position, orig_type_left, orig_type_right);
7039 semantic_comparison(&expression->binary);
7044 return create_invalid_expression();
7048 * Parses a MS assume() expression.
7050 static expression_t *parse_assume(void)
7052 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7056 expect('(', end_error);
7057 add_anchor_token(')');
7058 expression->unary.value = parse_assignment_expression();
7059 rem_anchor_token(')');
7060 expect(')', end_error);
7062 expression->base.type = type_void;
7065 return create_invalid_expression();
7069 * Return the declaration for a given label symbol or create a new one.
7071 * @param symbol the symbol of the label
7073 static label_t *get_label(symbol_t *symbol)
7076 assert(current_function != NULL);
7078 label = get_entity(symbol, NAMESPACE_LABEL);
7079 /* if we found a local label, we already created the declaration */
7080 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7081 if (label->base.parent_scope != current_scope) {
7082 assert(label->base.parent_scope->depth < current_scope->depth);
7083 current_function->goto_to_outer = true;
7085 return &label->label;
7088 label = get_entity(symbol, NAMESPACE_LABEL);
7089 /* if we found a label in the same function, then we already created the
7092 && label->base.parent_scope == ¤t_function->parameters) {
7093 return &label->label;
7096 /* otherwise we need to create a new one */
7097 label = allocate_entity_zero(ENTITY_LABEL);
7098 label->base.namespc = NAMESPACE_LABEL;
7099 label->base.symbol = symbol;
7103 return &label->label;
7107 * Parses a GNU && label address expression.
7109 static expression_t *parse_label_address(void)
7111 source_position_t source_position = token.source_position;
7113 if (token.type != T_IDENTIFIER) {
7114 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7117 symbol_t *symbol = token.v.symbol;
7120 label_t *label = get_label(symbol);
7122 label->address_taken = true;
7124 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7125 expression->base.source_position = source_position;
7127 /* label address is threaten as a void pointer */
7128 expression->base.type = type_void_ptr;
7129 expression->label_address.label = label;
7132 return create_invalid_expression();
7136 * Parse a microsoft __noop expression.
7138 static expression_t *parse_noop_expression(void)
7140 /* the result is a (int)0 */
7141 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7142 cnst->base.type = type_int;
7143 cnst->conste.v.int_value = 0;
7144 cnst->conste.is_ms_noop = true;
7148 if (token.type == '(') {
7149 /* parse arguments */
7151 add_anchor_token(')');
7152 add_anchor_token(',');
7154 if (token.type != ')') do {
7155 (void)parse_assignment_expression();
7156 } while (next_if(','));
7158 rem_anchor_token(',');
7159 rem_anchor_token(')');
7160 expect(')', end_error);
7167 * Parses a primary expression.
7169 static expression_t *parse_primary_expression(void)
7171 switch (token.type) {
7172 case T_false: return parse_bool_const(false);
7173 case T_true: return parse_bool_const(true);
7174 case T_INTEGER: return parse_int_const();
7175 case T_CHARACTER_CONSTANT: return parse_character_constant();
7176 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7177 case T_FLOATINGPOINT: return parse_float_const();
7178 case T_STRING_LITERAL:
7179 case T_WIDE_STRING_LITERAL: return parse_string_const();
7180 case T___FUNCTION__:
7181 case T___func__: return parse_function_keyword();
7182 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7183 case T___FUNCSIG__: return parse_funcsig_keyword();
7184 case T___FUNCDNAME__: return parse_funcdname_keyword();
7185 case T___builtin_offsetof: return parse_offsetof();
7186 case T___builtin_va_start: return parse_va_start();
7187 case T___builtin_va_arg: return parse_va_arg();
7188 case T___builtin_va_copy: return parse_va_copy();
7189 case T___builtin_isgreater:
7190 case T___builtin_isgreaterequal:
7191 case T___builtin_isless:
7192 case T___builtin_islessequal:
7193 case T___builtin_islessgreater:
7194 case T___builtin_isunordered: return parse_compare_builtin();
7195 case T___builtin_constant_p: return parse_builtin_constant();
7196 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7197 case T__assume: return parse_assume();
7200 return parse_label_address();
7203 case '(': return parse_parenthesized_expression();
7204 case T___noop: return parse_noop_expression();
7206 /* Gracefully handle type names while parsing expressions. */
7208 return parse_reference();
7210 if (!is_typedef_symbol(token.v.symbol)) {
7211 return parse_reference();
7215 source_position_t const pos = *HERE;
7216 type_t const *const type = parse_typename();
7217 errorf(&pos, "encountered type '%T' while parsing expression", type);
7218 return create_invalid_expression();
7222 errorf(HERE, "unexpected token %K, expected an expression", &token);
7223 return create_invalid_expression();
7227 * Check if the expression has the character type and issue a warning then.
7229 static void check_for_char_index_type(const expression_t *expression)
7231 type_t *const type = expression->base.type;
7232 const type_t *const base_type = skip_typeref(type);
7234 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7235 warning.char_subscripts) {
7236 warningf(&expression->base.source_position,
7237 "array subscript has type '%T'", type);
7241 static expression_t *parse_array_expression(expression_t *left)
7243 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7246 add_anchor_token(']');
7248 expression_t *inside = parse_expression();
7250 type_t *const orig_type_left = left->base.type;
7251 type_t *const orig_type_inside = inside->base.type;
7253 type_t *const type_left = skip_typeref(orig_type_left);
7254 type_t *const type_inside = skip_typeref(orig_type_inside);
7256 type_t *return_type;
7257 array_access_expression_t *array_access = &expression->array_access;
7258 if (is_type_pointer(type_left)) {
7259 return_type = type_left->pointer.points_to;
7260 array_access->array_ref = left;
7261 array_access->index = inside;
7262 check_for_char_index_type(inside);
7263 } else if (is_type_pointer(type_inside)) {
7264 return_type = type_inside->pointer.points_to;
7265 array_access->array_ref = inside;
7266 array_access->index = left;
7267 array_access->flipped = true;
7268 check_for_char_index_type(left);
7270 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7272 "array access on object with non-pointer types '%T', '%T'",
7273 orig_type_left, orig_type_inside);
7275 return_type = type_error_type;
7276 array_access->array_ref = left;
7277 array_access->index = inside;
7280 expression->base.type = automatic_type_conversion(return_type);
7282 rem_anchor_token(']');
7283 expect(']', end_error);
7288 static expression_t *parse_typeprop(expression_kind_t const kind)
7290 expression_t *tp_expression = allocate_expression_zero(kind);
7291 tp_expression->base.type = type_size_t;
7293 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7295 /* we only refer to a type property, mark this case */
7296 bool old = in_type_prop;
7297 in_type_prop = true;
7300 expression_t *expression;
7301 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7303 add_anchor_token(')');
7304 orig_type = parse_typename();
7305 rem_anchor_token(')');
7306 expect(')', end_error);
7308 if (token.type == '{') {
7309 /* It was not sizeof(type) after all. It is sizeof of an expression
7310 * starting with a compound literal */
7311 expression = parse_compound_literal(orig_type);
7312 goto typeprop_expression;
7315 expression = parse_sub_expression(PREC_UNARY);
7317 typeprop_expression:
7318 tp_expression->typeprop.tp_expression = expression;
7320 orig_type = revert_automatic_type_conversion(expression);
7321 expression->base.type = orig_type;
7324 tp_expression->typeprop.type = orig_type;
7325 type_t const* const type = skip_typeref(orig_type);
7326 char const* const wrong_type =
7327 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7328 is_type_incomplete(type) ? "incomplete" :
7329 type->kind == TYPE_FUNCTION ? "function designator" :
7330 type->kind == TYPE_BITFIELD ? "bitfield" :
7332 if (wrong_type != NULL) {
7333 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7334 errorf(&tp_expression->base.source_position,
7335 "operand of %s expression must not be of %s type '%T'",
7336 what, wrong_type, orig_type);
7341 return tp_expression;
7344 static expression_t *parse_sizeof(void)
7346 return parse_typeprop(EXPR_SIZEOF);
7349 static expression_t *parse_alignof(void)
7351 return parse_typeprop(EXPR_ALIGNOF);
7354 static expression_t *parse_select_expression(expression_t *addr)
7356 assert(token.type == '.' || token.type == T_MINUSGREATER);
7357 bool select_left_arrow = (token.type == T_MINUSGREATER);
7360 if (token.type != T_IDENTIFIER) {
7361 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7362 return create_invalid_expression();
7364 symbol_t *symbol = token.v.symbol;
7367 type_t *const orig_type = addr->base.type;
7368 type_t *const type = skip_typeref(orig_type);
7371 bool saw_error = false;
7372 if (is_type_pointer(type)) {
7373 if (!select_left_arrow) {
7375 "request for member '%Y' in something not a struct or union, but '%T'",
7379 type_left = skip_typeref(type->pointer.points_to);
7381 if (select_left_arrow && is_type_valid(type)) {
7382 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7388 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7389 type_left->kind != TYPE_COMPOUND_UNION) {
7391 if (is_type_valid(type_left) && !saw_error) {
7393 "request for member '%Y' in something not a struct or union, but '%T'",
7396 return create_invalid_expression();
7399 compound_t *compound = type_left->compound.compound;
7400 if (!compound->complete) {
7401 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7403 return create_invalid_expression();
7406 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7407 expression_t *result
7408 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7410 if (result == NULL) {
7411 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7412 return create_invalid_expression();
7418 static void check_call_argument(type_t *expected_type,
7419 call_argument_t *argument, unsigned pos)
7421 type_t *expected_type_skip = skip_typeref(expected_type);
7422 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7423 expression_t *arg_expr = argument->expression;
7424 type_t *arg_type = skip_typeref(arg_expr->base.type);
7426 /* handle transparent union gnu extension */
7427 if (is_type_union(expected_type_skip)
7428 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7429 compound_t *union_decl = expected_type_skip->compound.compound;
7430 type_t *best_type = NULL;
7431 entity_t *entry = union_decl->members.entities;
7432 for ( ; entry != NULL; entry = entry->base.next) {
7433 assert(is_declaration(entry));
7434 type_t *decl_type = entry->declaration.type;
7435 error = semantic_assign(decl_type, arg_expr);
7436 if (error == ASSIGN_ERROR_INCOMPATIBLE
7437 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7440 if (error == ASSIGN_SUCCESS) {
7441 best_type = decl_type;
7442 } else if (best_type == NULL) {
7443 best_type = decl_type;
7447 if (best_type != NULL) {
7448 expected_type = best_type;
7452 error = semantic_assign(expected_type, arg_expr);
7453 argument->expression = create_implicit_cast(arg_expr, expected_type);
7455 if (error != ASSIGN_SUCCESS) {
7456 /* report exact scope in error messages (like "in argument 3") */
7458 snprintf(buf, sizeof(buf), "call argument %u", pos);
7459 report_assign_error(error, expected_type, arg_expr, buf,
7460 &arg_expr->base.source_position);
7461 } else if (warning.traditional || warning.conversion) {
7462 type_t *const promoted_type = get_default_promoted_type(arg_type);
7463 if (!types_compatible(expected_type_skip, promoted_type) &&
7464 !types_compatible(expected_type_skip, type_void_ptr) &&
7465 !types_compatible(type_void_ptr, promoted_type)) {
7466 /* Deliberately show the skipped types in this warning */
7467 warningf(&arg_expr->base.source_position,
7468 "passing call argument %u as '%T' rather than '%T' due to prototype",
7469 pos, expected_type_skip, promoted_type);
7475 * Handle the semantic restrictions of builtin calls
7477 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7478 switch (call->function->reference.entity->function.btk) {
7479 case bk_gnu_builtin_return_address:
7480 case bk_gnu_builtin_frame_address: {
7481 /* argument must be constant */
7482 call_argument_t *argument = call->arguments;
7484 if (! is_constant_expression(argument->expression)) {
7485 errorf(&call->base.source_position,
7486 "argument of '%Y' must be a constant expression",
7487 call->function->reference.entity->base.symbol);
7491 case bk_gnu_builtin_prefetch: {
7492 /* second and third argument must be constant if existent */
7493 call_argument_t *rw = call->arguments->next;
7494 call_argument_t *locality = NULL;
7497 if (! is_constant_expression(rw->expression)) {
7498 errorf(&call->base.source_position,
7499 "second argument of '%Y' must be a constant expression",
7500 call->function->reference.entity->base.symbol);
7502 locality = rw->next;
7504 if (locality != NULL) {
7505 if (! is_constant_expression(locality->expression)) {
7506 errorf(&call->base.source_position,
7507 "third argument of '%Y' must be a constant expression",
7508 call->function->reference.entity->base.symbol);
7510 locality = rw->next;
7520 * Parse a call expression, ie. expression '( ... )'.
7522 * @param expression the function address
7524 static expression_t *parse_call_expression(expression_t *expression)
7526 expression_t *result = allocate_expression_zero(EXPR_CALL);
7527 call_expression_t *call = &result->call;
7528 call->function = expression;
7530 type_t *const orig_type = expression->base.type;
7531 type_t *const type = skip_typeref(orig_type);
7533 function_type_t *function_type = NULL;
7534 if (is_type_pointer(type)) {
7535 type_t *const to_type = skip_typeref(type->pointer.points_to);
7537 if (is_type_function(to_type)) {
7538 function_type = &to_type->function;
7539 call->base.type = function_type->return_type;
7543 if (function_type == NULL && is_type_valid(type)) {
7545 "called object '%E' (type '%T') is not a pointer to a function",
7546 expression, orig_type);
7549 /* parse arguments */
7551 add_anchor_token(')');
7552 add_anchor_token(',');
7554 if (token.type != ')') {
7555 call_argument_t **anchor = &call->arguments;
7557 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7558 argument->expression = parse_assignment_expression();
7561 anchor = &argument->next;
7562 } while (next_if(','));
7564 rem_anchor_token(',');
7565 rem_anchor_token(')');
7566 expect(')', end_error);
7568 if (function_type == NULL)
7571 /* check type and count of call arguments */
7572 function_parameter_t *parameter = function_type->parameters;
7573 call_argument_t *argument = call->arguments;
7574 if (!function_type->unspecified_parameters) {
7575 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7576 parameter = parameter->next, argument = argument->next) {
7577 check_call_argument(parameter->type, argument, ++pos);
7580 if (parameter != NULL) {
7581 errorf(HERE, "too few arguments to function '%E'", expression);
7582 } else if (argument != NULL && !function_type->variadic) {
7583 errorf(HERE, "too many arguments to function '%E'", expression);
7587 /* do default promotion for other arguments */
7588 for (; argument != NULL; argument = argument->next) {
7589 type_t *type = argument->expression->base.type;
7591 type = get_default_promoted_type(type);
7593 argument->expression
7594 = create_implicit_cast(argument->expression, type);
7597 check_format(&result->call);
7599 if (warning.aggregate_return &&
7600 is_type_compound(skip_typeref(function_type->return_type))) {
7601 warningf(&result->base.source_position,
7602 "function call has aggregate value");
7605 if (call->function->kind == EXPR_REFERENCE) {
7606 reference_expression_t *reference = &call->function->reference;
7607 if (reference->entity->kind == ENTITY_FUNCTION &&
7608 reference->entity->function.btk != bk_none)
7609 handle_builtin_argument_restrictions(call);
7616 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7618 static bool same_compound_type(const type_t *type1, const type_t *type2)
7621 is_type_compound(type1) &&
7622 type1->kind == type2->kind &&
7623 type1->compound.compound == type2->compound.compound;
7626 static expression_t const *get_reference_address(expression_t const *expr)
7628 bool regular_take_address = true;
7630 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7631 expr = expr->unary.value;
7633 regular_take_address = false;
7636 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7639 expr = expr->unary.value;
7642 if (expr->kind != EXPR_REFERENCE)
7645 /* special case for functions which are automatically converted to a
7646 * pointer to function without an extra TAKE_ADDRESS operation */
7647 if (!regular_take_address &&
7648 expr->reference.entity->kind != ENTITY_FUNCTION) {
7655 static void warn_reference_address_as_bool(expression_t const* expr)
7657 if (!warning.address)
7660 expr = get_reference_address(expr);
7662 warningf(&expr->base.source_position,
7663 "the address of '%Y' will always evaluate as 'true'",
7664 expr->reference.entity->base.symbol);
7668 static void warn_assignment_in_condition(const expression_t *const expr)
7670 if (!warning.parentheses)
7672 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7674 if (expr->base.parenthesized)
7676 warningf(&expr->base.source_position,
7677 "suggest parentheses around assignment used as truth value");
7680 static void semantic_condition(expression_t const *const expr,
7681 char const *const context)
7683 type_t *const type = skip_typeref(expr->base.type);
7684 if (is_type_scalar(type)) {
7685 warn_reference_address_as_bool(expr);
7686 warn_assignment_in_condition(expr);
7687 } else if (is_type_valid(type)) {
7688 errorf(&expr->base.source_position,
7689 "%s must have scalar type", context);
7694 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7696 * @param expression the conditional expression
7698 static expression_t *parse_conditional_expression(expression_t *expression)
7700 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7702 conditional_expression_t *conditional = &result->conditional;
7703 conditional->condition = expression;
7706 add_anchor_token(':');
7708 /* §6.5.15:2 The first operand shall have scalar type. */
7709 semantic_condition(expression, "condition of conditional operator");
7711 expression_t *true_expression = expression;
7712 bool gnu_cond = false;
7713 if (GNU_MODE && token.type == ':') {
7716 true_expression = parse_expression();
7718 rem_anchor_token(':');
7719 expect(':', end_error);
7721 expression_t *false_expression =
7722 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7724 type_t *const orig_true_type = true_expression->base.type;
7725 type_t *const orig_false_type = false_expression->base.type;
7726 type_t *const true_type = skip_typeref(orig_true_type);
7727 type_t *const false_type = skip_typeref(orig_false_type);
7730 type_t *result_type;
7731 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7732 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7733 /* ISO/IEC 14882:1998(E) §5.16:2 */
7734 if (true_expression->kind == EXPR_UNARY_THROW) {
7735 result_type = false_type;
7736 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7737 result_type = true_type;
7739 if (warning.other && (
7740 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7741 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7743 warningf(&conditional->base.source_position,
7744 "ISO C forbids conditional expression with only one void side");
7746 result_type = type_void;
7748 } else if (is_type_arithmetic(true_type)
7749 && is_type_arithmetic(false_type)) {
7750 result_type = semantic_arithmetic(true_type, false_type);
7752 true_expression = create_implicit_cast(true_expression, result_type);
7753 false_expression = create_implicit_cast(false_expression, result_type);
7755 conditional->true_expression = true_expression;
7756 conditional->false_expression = false_expression;
7757 conditional->base.type = result_type;
7758 } else if (same_compound_type(true_type, false_type)) {
7759 /* just take 1 of the 2 types */
7760 result_type = true_type;
7761 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7762 type_t *pointer_type;
7764 expression_t *other_expression;
7765 if (is_type_pointer(true_type) &&
7766 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7767 pointer_type = true_type;
7768 other_type = false_type;
7769 other_expression = false_expression;
7771 pointer_type = false_type;
7772 other_type = true_type;
7773 other_expression = true_expression;
7776 if (is_null_pointer_constant(other_expression)) {
7777 result_type = pointer_type;
7778 } else if (is_type_pointer(other_type)) {
7779 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7780 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7783 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7784 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7786 } else if (types_compatible(get_unqualified_type(to1),
7787 get_unqualified_type(to2))) {
7790 if (warning.other) {
7791 warningf(&conditional->base.source_position,
7792 "pointer types '%T' and '%T' in conditional expression are incompatible",
7793 true_type, false_type);
7798 type_t *const type =
7799 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7800 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7801 } else if (is_type_integer(other_type)) {
7802 if (warning.other) {
7803 warningf(&conditional->base.source_position,
7804 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7806 result_type = pointer_type;
7808 if (is_type_valid(other_type)) {
7809 type_error_incompatible("while parsing conditional",
7810 &expression->base.source_position, true_type, false_type);
7812 result_type = type_error_type;
7815 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7816 type_error_incompatible("while parsing conditional",
7817 &conditional->base.source_position, true_type,
7820 result_type = type_error_type;
7823 conditional->true_expression
7824 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7825 conditional->false_expression
7826 = create_implicit_cast(false_expression, result_type);
7827 conditional->base.type = result_type;
7832 * Parse an extension expression.
7834 static expression_t *parse_extension(void)
7836 eat(T___extension__);
7838 bool old_gcc_extension = in_gcc_extension;
7839 in_gcc_extension = true;
7840 expression_t *expression = parse_sub_expression(PREC_UNARY);
7841 in_gcc_extension = old_gcc_extension;
7846 * Parse a __builtin_classify_type() expression.
7848 static expression_t *parse_builtin_classify_type(void)
7850 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7851 result->base.type = type_int;
7853 eat(T___builtin_classify_type);
7855 expect('(', end_error);
7856 add_anchor_token(')');
7857 expression_t *expression = parse_expression();
7858 rem_anchor_token(')');
7859 expect(')', end_error);
7860 result->classify_type.type_expression = expression;
7864 return create_invalid_expression();
7868 * Parse a delete expression
7869 * ISO/IEC 14882:1998(E) §5.3.5
7871 static expression_t *parse_delete(void)
7873 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7874 result->base.type = type_void;
7879 result->kind = EXPR_UNARY_DELETE_ARRAY;
7880 expect(']', end_error);
7884 expression_t *const value = parse_sub_expression(PREC_CAST);
7885 result->unary.value = value;
7887 type_t *const type = skip_typeref(value->base.type);
7888 if (!is_type_pointer(type)) {
7889 if (is_type_valid(type)) {
7890 errorf(&value->base.source_position,
7891 "operand of delete must have pointer type");
7893 } else if (warning.other &&
7894 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7895 warningf(&value->base.source_position,
7896 "deleting 'void*' is undefined");
7903 * Parse a throw expression
7904 * ISO/IEC 14882:1998(E) §15:1
7906 static expression_t *parse_throw(void)
7908 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7909 result->base.type = type_void;
7913 expression_t *value = NULL;
7914 switch (token.type) {
7916 value = parse_assignment_expression();
7917 /* ISO/IEC 14882:1998(E) §15.1:3 */
7918 type_t *const orig_type = value->base.type;
7919 type_t *const type = skip_typeref(orig_type);
7920 if (is_type_incomplete(type)) {
7921 errorf(&value->base.source_position,
7922 "cannot throw object of incomplete type '%T'", orig_type);
7923 } else if (is_type_pointer(type)) {
7924 type_t *const points_to = skip_typeref(type->pointer.points_to);
7925 if (is_type_incomplete(points_to) &&
7926 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7927 errorf(&value->base.source_position,
7928 "cannot throw pointer to incomplete type '%T'", orig_type);
7936 result->unary.value = value;
7941 static bool check_pointer_arithmetic(const source_position_t *source_position,
7942 type_t *pointer_type,
7943 type_t *orig_pointer_type)
7945 type_t *points_to = pointer_type->pointer.points_to;
7946 points_to = skip_typeref(points_to);
7948 if (is_type_incomplete(points_to)) {
7949 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7950 errorf(source_position,
7951 "arithmetic with pointer to incomplete type '%T' not allowed",
7954 } else if (warning.pointer_arith) {
7955 warningf(source_position,
7956 "pointer of type '%T' used in arithmetic",
7959 } else if (is_type_function(points_to)) {
7961 errorf(source_position,
7962 "arithmetic with pointer to function type '%T' not allowed",
7965 } else if (warning.pointer_arith) {
7966 warningf(source_position,
7967 "pointer to a function '%T' used in arithmetic",
7974 static bool is_lvalue(const expression_t *expression)
7976 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7977 switch (expression->kind) {
7978 case EXPR_ARRAY_ACCESS:
7979 case EXPR_COMPOUND_LITERAL:
7980 case EXPR_REFERENCE:
7982 case EXPR_UNARY_DEREFERENCE:
7986 type_t *type = skip_typeref(expression->base.type);
7988 /* ISO/IEC 14882:1998(E) §3.10:3 */
7989 is_type_reference(type) ||
7990 /* Claim it is an lvalue, if the type is invalid. There was a parse
7991 * error before, which maybe prevented properly recognizing it as
7993 !is_type_valid(type);
7998 static void semantic_incdec(unary_expression_t *expression)
8000 type_t *const orig_type = expression->value->base.type;
8001 type_t *const type = skip_typeref(orig_type);
8002 if (is_type_pointer(type)) {
8003 if (!check_pointer_arithmetic(&expression->base.source_position,
8007 } else if (!is_type_real(type) && is_type_valid(type)) {
8008 /* TODO: improve error message */
8009 errorf(&expression->base.source_position,
8010 "operation needs an arithmetic or pointer type");
8013 if (!is_lvalue(expression->value)) {
8014 /* TODO: improve error message */
8015 errorf(&expression->base.source_position, "lvalue required as operand");
8017 expression->base.type = orig_type;
8020 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8022 type_t *const orig_type = expression->value->base.type;
8023 type_t *const type = skip_typeref(orig_type);
8024 if (!is_type_arithmetic(type)) {
8025 if (is_type_valid(type)) {
8026 /* TODO: improve error message */
8027 errorf(&expression->base.source_position,
8028 "operation needs an arithmetic type");
8033 expression->base.type = orig_type;
8036 static void semantic_unexpr_plus(unary_expression_t *expression)
8038 semantic_unexpr_arithmetic(expression);
8039 if (warning.traditional)
8040 warningf(&expression->base.source_position,
8041 "traditional C rejects the unary plus operator");
8044 static void semantic_not(unary_expression_t *expression)
8046 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8047 semantic_condition(expression->value, "operand of !");
8048 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8051 static void semantic_unexpr_integer(unary_expression_t *expression)
8053 type_t *const orig_type = expression->value->base.type;
8054 type_t *const type = skip_typeref(orig_type);
8055 if (!is_type_integer(type)) {
8056 if (is_type_valid(type)) {
8057 errorf(&expression->base.source_position,
8058 "operand of ~ must be of integer type");
8063 expression->base.type = orig_type;
8066 static void semantic_dereference(unary_expression_t *expression)
8068 type_t *const orig_type = expression->value->base.type;
8069 type_t *const type = skip_typeref(orig_type);
8070 if (!is_type_pointer(type)) {
8071 if (is_type_valid(type)) {
8072 errorf(&expression->base.source_position,
8073 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8078 type_t *result_type = type->pointer.points_to;
8079 result_type = automatic_type_conversion(result_type);
8080 expression->base.type = result_type;
8084 * Record that an address is taken (expression represents an lvalue).
8086 * @param expression the expression
8087 * @param may_be_register if true, the expression might be an register
8089 static void set_address_taken(expression_t *expression, bool may_be_register)
8091 if (expression->kind != EXPR_REFERENCE)
8094 entity_t *const entity = expression->reference.entity;
8096 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8099 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8100 && !may_be_register) {
8101 errorf(&expression->base.source_position,
8102 "address of register %s '%Y' requested",
8103 get_entity_kind_name(entity->kind), entity->base.symbol);
8106 if (entity->kind == ENTITY_VARIABLE) {
8107 entity->variable.address_taken = true;
8109 assert(entity->kind == ENTITY_PARAMETER);
8110 entity->parameter.address_taken = true;
8115 * Check the semantic of the address taken expression.
8117 static void semantic_take_addr(unary_expression_t *expression)
8119 expression_t *value = expression->value;
8120 value->base.type = revert_automatic_type_conversion(value);
8122 type_t *orig_type = value->base.type;
8123 type_t *type = skip_typeref(orig_type);
8124 if (!is_type_valid(type))
8128 if (!is_lvalue(value)) {
8129 errorf(&expression->base.source_position, "'&' requires an lvalue");
8131 if (type->kind == TYPE_BITFIELD) {
8132 errorf(&expression->base.source_position,
8133 "'&' not allowed on object with bitfield type '%T'",
8137 set_address_taken(value, false);
8139 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8142 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8143 static expression_t *parse_##unexpression_type(void) \
8145 expression_t *unary_expression \
8146 = allocate_expression_zero(unexpression_type); \
8148 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8150 sfunc(&unary_expression->unary); \
8152 return unary_expression; \
8155 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8156 semantic_unexpr_arithmetic)
8157 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8158 semantic_unexpr_plus)
8159 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8161 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8162 semantic_dereference)
8163 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8165 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8166 semantic_unexpr_integer)
8167 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8169 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8172 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8174 static expression_t *parse_##unexpression_type(expression_t *left) \
8176 expression_t *unary_expression \
8177 = allocate_expression_zero(unexpression_type); \
8179 unary_expression->unary.value = left; \
8181 sfunc(&unary_expression->unary); \
8183 return unary_expression; \
8186 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8187 EXPR_UNARY_POSTFIX_INCREMENT,
8189 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8190 EXPR_UNARY_POSTFIX_DECREMENT,
8193 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8195 /* TODO: handle complex + imaginary types */
8197 type_left = get_unqualified_type(type_left);
8198 type_right = get_unqualified_type(type_right);
8200 /* §6.3.1.8 Usual arithmetic conversions */
8201 if (type_left == type_long_double || type_right == type_long_double) {
8202 return type_long_double;
8203 } else if (type_left == type_double || type_right == type_double) {
8205 } else if (type_left == type_float || type_right == type_float) {
8209 type_left = promote_integer(type_left);
8210 type_right = promote_integer(type_right);
8212 if (type_left == type_right)
8215 bool const signed_left = is_type_signed(type_left);
8216 bool const signed_right = is_type_signed(type_right);
8217 int const rank_left = get_rank(type_left);
8218 int const rank_right = get_rank(type_right);
8220 if (signed_left == signed_right)
8221 return rank_left >= rank_right ? type_left : type_right;
8230 u_rank = rank_right;
8231 u_type = type_right;
8233 s_rank = rank_right;
8234 s_type = type_right;
8239 if (u_rank >= s_rank)
8242 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8244 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8245 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8249 case ATOMIC_TYPE_INT: return type_unsigned_int;
8250 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8251 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8253 default: panic("invalid atomic type");
8258 * Check the semantic restrictions for a binary expression.
8260 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8262 expression_t *const left = expression->left;
8263 expression_t *const right = expression->right;
8264 type_t *const orig_type_left = left->base.type;
8265 type_t *const orig_type_right = right->base.type;
8266 type_t *const type_left = skip_typeref(orig_type_left);
8267 type_t *const type_right = skip_typeref(orig_type_right);
8269 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8270 /* TODO: improve error message */
8271 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8272 errorf(&expression->base.source_position,
8273 "operation needs arithmetic types");
8278 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8279 expression->left = create_implicit_cast(left, arithmetic_type);
8280 expression->right = create_implicit_cast(right, arithmetic_type);
8281 expression->base.type = arithmetic_type;
8284 static void warn_div_by_zero(binary_expression_t const *const expression)
8286 if (!warning.div_by_zero ||
8287 !is_type_integer(expression->base.type))
8290 expression_t const *const right = expression->right;
8291 /* The type of the right operand can be different for /= */
8292 if (is_type_integer(right->base.type) &&
8293 is_constant_expression(right) &&
8294 !fold_constant_to_bool(right)) {
8295 warningf(&expression->base.source_position, "division by zero");
8300 * Check the semantic restrictions for a div/mod expression.
8302 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8304 semantic_binexpr_arithmetic(expression);
8305 warn_div_by_zero(expression);
8308 static void warn_addsub_in_shift(const expression_t *const expr)
8310 if (expr->base.parenthesized)
8314 switch (expr->kind) {
8315 case EXPR_BINARY_ADD: op = '+'; break;
8316 case EXPR_BINARY_SUB: op = '-'; break;
8320 warningf(&expr->base.source_position,
8321 "suggest parentheses around '%c' inside shift", op);
8324 static bool semantic_shift(binary_expression_t *expression)
8326 expression_t *const left = expression->left;
8327 expression_t *const right = expression->right;
8328 type_t *const orig_type_left = left->base.type;
8329 type_t *const orig_type_right = right->base.type;
8330 type_t * type_left = skip_typeref(orig_type_left);
8331 type_t * type_right = skip_typeref(orig_type_right);
8333 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8334 /* TODO: improve error message */
8335 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8336 errorf(&expression->base.source_position,
8337 "operands of shift operation must have integer types");
8342 type_left = promote_integer(type_left);
8344 if (is_constant_expression(right)) {
8345 long count = fold_constant_to_int(right);
8347 warningf(&right->base.source_position,
8348 "shift count must be non-negative");
8349 } else if ((unsigned long)count >=
8350 get_atomic_type_size(type_left->atomic.akind) * 8) {
8351 warningf(&right->base.source_position,
8352 "shift count must be less than type width");
8356 type_right = promote_integer(type_right);
8357 expression->right = create_implicit_cast(right, type_right);
8362 static void semantic_shift_op(binary_expression_t *expression)
8364 expression_t *const left = expression->left;
8365 expression_t *const right = expression->right;
8367 if (!semantic_shift(expression))
8370 if (warning.parentheses) {
8371 warn_addsub_in_shift(left);
8372 warn_addsub_in_shift(right);
8375 type_t *const orig_type_left = left->base.type;
8376 type_t * type_left = skip_typeref(orig_type_left);
8378 type_left = promote_integer(type_left);
8379 expression->left = create_implicit_cast(left, type_left);
8380 expression->base.type = type_left;
8383 static void semantic_add(binary_expression_t *expression)
8385 expression_t *const left = expression->left;
8386 expression_t *const right = expression->right;
8387 type_t *const orig_type_left = left->base.type;
8388 type_t *const orig_type_right = right->base.type;
8389 type_t *const type_left = skip_typeref(orig_type_left);
8390 type_t *const type_right = skip_typeref(orig_type_right);
8393 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8394 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8395 expression->left = create_implicit_cast(left, arithmetic_type);
8396 expression->right = create_implicit_cast(right, arithmetic_type);
8397 expression->base.type = arithmetic_type;
8398 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8399 check_pointer_arithmetic(&expression->base.source_position,
8400 type_left, orig_type_left);
8401 expression->base.type = type_left;
8402 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8403 check_pointer_arithmetic(&expression->base.source_position,
8404 type_right, orig_type_right);
8405 expression->base.type = type_right;
8406 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8407 errorf(&expression->base.source_position,
8408 "invalid operands to binary + ('%T', '%T')",
8409 orig_type_left, orig_type_right);
8413 static void semantic_sub(binary_expression_t *expression)
8415 expression_t *const left = expression->left;
8416 expression_t *const right = expression->right;
8417 type_t *const orig_type_left = left->base.type;
8418 type_t *const orig_type_right = right->base.type;
8419 type_t *const type_left = skip_typeref(orig_type_left);
8420 type_t *const type_right = skip_typeref(orig_type_right);
8421 source_position_t const *const pos = &expression->base.source_position;
8424 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8425 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8426 expression->left = create_implicit_cast(left, arithmetic_type);
8427 expression->right = create_implicit_cast(right, arithmetic_type);
8428 expression->base.type = arithmetic_type;
8429 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8430 check_pointer_arithmetic(&expression->base.source_position,
8431 type_left, orig_type_left);
8432 expression->base.type = type_left;
8433 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8434 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8435 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8436 if (!types_compatible(unqual_left, unqual_right)) {
8438 "subtracting pointers to incompatible types '%T' and '%T'",
8439 orig_type_left, orig_type_right);
8440 } else if (!is_type_object(unqual_left)) {
8441 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8442 errorf(pos, "subtracting pointers to non-object types '%T'",
8444 } else if (warning.other) {
8445 warningf(pos, "subtracting pointers to void");
8448 expression->base.type = type_ptrdiff_t;
8449 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8450 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8451 orig_type_left, orig_type_right);
8455 static void warn_string_literal_address(expression_t const* expr)
8457 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8458 expr = expr->unary.value;
8459 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8461 expr = expr->unary.value;
8464 if (expr->kind == EXPR_STRING_LITERAL ||
8465 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8466 warningf(&expr->base.source_position,
8467 "comparison with string literal results in unspecified behaviour");
8471 static void warn_comparison_in_comparison(const expression_t *const expr)
8473 if (expr->base.parenthesized)
8475 switch (expr->base.kind) {
8476 case EXPR_BINARY_LESS:
8477 case EXPR_BINARY_GREATER:
8478 case EXPR_BINARY_LESSEQUAL:
8479 case EXPR_BINARY_GREATEREQUAL:
8480 case EXPR_BINARY_NOTEQUAL:
8481 case EXPR_BINARY_EQUAL:
8482 warningf(&expr->base.source_position,
8483 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8490 static bool maybe_negative(expression_t const *const expr)
8493 !is_constant_expression(expr) ||
8494 fold_constant_to_int(expr) < 0;
8498 * Check the semantics of comparison expressions.
8500 * @param expression The expression to check.
8502 static void semantic_comparison(binary_expression_t *expression)
8504 expression_t *left = expression->left;
8505 expression_t *right = expression->right;
8507 if (warning.address) {
8508 warn_string_literal_address(left);
8509 warn_string_literal_address(right);
8511 expression_t const* const func_left = get_reference_address(left);
8512 if (func_left != NULL && is_null_pointer_constant(right)) {
8513 warningf(&expression->base.source_position,
8514 "the address of '%Y' will never be NULL",
8515 func_left->reference.entity->base.symbol);
8518 expression_t const* const func_right = get_reference_address(right);
8519 if (func_right != NULL && is_null_pointer_constant(right)) {
8520 warningf(&expression->base.source_position,
8521 "the address of '%Y' will never be NULL",
8522 func_right->reference.entity->base.symbol);
8526 if (warning.parentheses) {
8527 warn_comparison_in_comparison(left);
8528 warn_comparison_in_comparison(right);
8531 type_t *orig_type_left = left->base.type;
8532 type_t *orig_type_right = right->base.type;
8533 type_t *type_left = skip_typeref(orig_type_left);
8534 type_t *type_right = skip_typeref(orig_type_right);
8536 /* TODO non-arithmetic types */
8537 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8538 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8540 /* test for signed vs unsigned compares */
8541 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8542 bool const signed_left = is_type_signed(type_left);
8543 bool const signed_right = is_type_signed(type_right);
8544 if (signed_left != signed_right) {
8545 /* FIXME long long needs better const folding magic */
8546 /* TODO check whether constant value can be represented by other type */
8547 if ((signed_left && maybe_negative(left)) ||
8548 (signed_right && maybe_negative(right))) {
8549 warningf(&expression->base.source_position,
8550 "comparison between signed and unsigned");
8555 expression->left = create_implicit_cast(left, arithmetic_type);
8556 expression->right = create_implicit_cast(right, arithmetic_type);
8557 expression->base.type = arithmetic_type;
8558 if (warning.float_equal &&
8559 (expression->base.kind == EXPR_BINARY_EQUAL ||
8560 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8561 is_type_float(arithmetic_type)) {
8562 warningf(&expression->base.source_position,
8563 "comparing floating point with == or != is unsafe");
8565 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8566 /* TODO check compatibility */
8567 } else if (is_type_pointer(type_left)) {
8568 expression->right = create_implicit_cast(right, type_left);
8569 } else if (is_type_pointer(type_right)) {
8570 expression->left = create_implicit_cast(left, type_right);
8571 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8572 type_error_incompatible("invalid operands in comparison",
8573 &expression->base.source_position,
8574 type_left, type_right);
8576 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8580 * Checks if a compound type has constant fields.
8582 static bool has_const_fields(const compound_type_t *type)
8584 compound_t *compound = type->compound;
8585 entity_t *entry = compound->members.entities;
8587 for (; entry != NULL; entry = entry->base.next) {
8588 if (!is_declaration(entry))
8591 const type_t *decl_type = skip_typeref(entry->declaration.type);
8592 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8599 static bool is_valid_assignment_lhs(expression_t const* const left)
8601 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8602 type_t *const type_left = skip_typeref(orig_type_left);
8604 if (!is_lvalue(left)) {
8605 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8610 if (left->kind == EXPR_REFERENCE
8611 && left->reference.entity->kind == ENTITY_FUNCTION) {
8612 errorf(HERE, "cannot assign to function '%E'", left);
8616 if (is_type_array(type_left)) {
8617 errorf(HERE, "cannot assign to array '%E'", left);
8620 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8621 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8625 if (is_type_incomplete(type_left)) {
8626 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8627 left, orig_type_left);
8630 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8631 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8632 left, orig_type_left);
8639 static void semantic_arithmetic_assign(binary_expression_t *expression)
8641 expression_t *left = expression->left;
8642 expression_t *right = expression->right;
8643 type_t *orig_type_left = left->base.type;
8644 type_t *orig_type_right = right->base.type;
8646 if (!is_valid_assignment_lhs(left))
8649 type_t *type_left = skip_typeref(orig_type_left);
8650 type_t *type_right = skip_typeref(orig_type_right);
8652 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8653 /* TODO: improve error message */
8654 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8655 errorf(&expression->base.source_position,
8656 "operation needs arithmetic types");
8661 /* combined instructions are tricky. We can't create an implicit cast on
8662 * the left side, because we need the uncasted form for the store.
8663 * The ast2firm pass has to know that left_type must be right_type
8664 * for the arithmetic operation and create a cast by itself */
8665 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8666 expression->right = create_implicit_cast(right, arithmetic_type);
8667 expression->base.type = type_left;
8670 static void semantic_divmod_assign(binary_expression_t *expression)
8672 semantic_arithmetic_assign(expression);
8673 warn_div_by_zero(expression);
8676 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8678 expression_t *const left = expression->left;
8679 expression_t *const right = expression->right;
8680 type_t *const orig_type_left = left->base.type;
8681 type_t *const orig_type_right = right->base.type;
8682 type_t *const type_left = skip_typeref(orig_type_left);
8683 type_t *const type_right = skip_typeref(orig_type_right);
8685 if (!is_valid_assignment_lhs(left))
8688 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8689 /* combined instructions are tricky. We can't create an implicit cast on
8690 * the left side, because we need the uncasted form for the store.
8691 * The ast2firm pass has to know that left_type must be right_type
8692 * for the arithmetic operation and create a cast by itself */
8693 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8694 expression->right = create_implicit_cast(right, arithmetic_type);
8695 expression->base.type = type_left;
8696 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8697 check_pointer_arithmetic(&expression->base.source_position,
8698 type_left, orig_type_left);
8699 expression->base.type = type_left;
8700 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8701 errorf(&expression->base.source_position,
8702 "incompatible types '%T' and '%T' in assignment",
8703 orig_type_left, orig_type_right);
8707 static void semantic_integer_assign(binary_expression_t *expression)
8709 expression_t *left = expression->left;
8710 expression_t *right = expression->right;
8711 type_t *orig_type_left = left->base.type;
8712 type_t *orig_type_right = right->base.type;
8714 if (!is_valid_assignment_lhs(left))
8717 type_t *type_left = skip_typeref(orig_type_left);
8718 type_t *type_right = skip_typeref(orig_type_right);
8720 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8721 /* TODO: improve error message */
8722 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8723 errorf(&expression->base.source_position,
8724 "operation needs integer types");
8729 /* combined instructions are tricky. We can't create an implicit cast on
8730 * the left side, because we need the uncasted form for the store.
8731 * The ast2firm pass has to know that left_type must be right_type
8732 * for the arithmetic operation and create a cast by itself */
8733 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8734 expression->right = create_implicit_cast(right, arithmetic_type);
8735 expression->base.type = type_left;
8738 static void semantic_shift_assign(binary_expression_t *expression)
8740 expression_t *left = expression->left;
8742 if (!is_valid_assignment_lhs(left))
8745 if (!semantic_shift(expression))
8748 expression->base.type = skip_typeref(left->base.type);
8751 static void warn_logical_and_within_or(const expression_t *const expr)
8753 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8755 if (expr->base.parenthesized)
8757 warningf(&expr->base.source_position,
8758 "suggest parentheses around && within ||");
8762 * Check the semantic restrictions of a logical expression.
8764 static void semantic_logical_op(binary_expression_t *expression)
8766 /* §6.5.13:2 Each of the operands shall have scalar type.
8767 * §6.5.14:2 Each of the operands shall have scalar type. */
8768 semantic_condition(expression->left, "left operand of logical operator");
8769 semantic_condition(expression->right, "right operand of logical operator");
8770 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8771 warning.parentheses) {
8772 warn_logical_and_within_or(expression->left);
8773 warn_logical_and_within_or(expression->right);
8775 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8779 * Check the semantic restrictions of a binary assign expression.
8781 static void semantic_binexpr_assign(binary_expression_t *expression)
8783 expression_t *left = expression->left;
8784 type_t *orig_type_left = left->base.type;
8786 if (!is_valid_assignment_lhs(left))
8789 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8790 report_assign_error(error, orig_type_left, expression->right,
8791 "assignment", &left->base.source_position);
8792 expression->right = create_implicit_cast(expression->right, orig_type_left);
8793 expression->base.type = orig_type_left;
8797 * Determine if the outermost operation (or parts thereof) of the given
8798 * expression has no effect in order to generate a warning about this fact.
8799 * Therefore in some cases this only examines some of the operands of the
8800 * expression (see comments in the function and examples below).
8802 * f() + 23; // warning, because + has no effect
8803 * x || f(); // no warning, because x controls execution of f()
8804 * x ? y : f(); // warning, because y has no effect
8805 * (void)x; // no warning to be able to suppress the warning
8806 * This function can NOT be used for an "expression has definitely no effect"-
8808 static bool expression_has_effect(const expression_t *const expr)
8810 switch (expr->kind) {
8811 case EXPR_UNKNOWN: break;
8812 case EXPR_INVALID: return true; /* do NOT warn */
8813 case EXPR_REFERENCE: return false;
8814 case EXPR_REFERENCE_ENUM_VALUE: return false;
8815 /* suppress the warning for microsoft __noop operations */
8816 case EXPR_CONST: return expr->conste.is_ms_noop;
8817 case EXPR_CHARACTER_CONSTANT: return false;
8818 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8819 case EXPR_STRING_LITERAL: return false;
8820 case EXPR_WIDE_STRING_LITERAL: return false;
8821 case EXPR_LABEL_ADDRESS: return false;
8824 const call_expression_t *const call = &expr->call;
8825 if (call->function->kind != EXPR_REFERENCE)
8828 switch (call->function->reference.entity->function.btk) {
8829 /* FIXME: which builtins have no effect? */
8830 default: return true;
8834 /* Generate the warning if either the left or right hand side of a
8835 * conditional expression has no effect */
8836 case EXPR_CONDITIONAL: {
8837 conditional_expression_t const *const cond = &expr->conditional;
8838 expression_t const *const t = cond->true_expression;
8840 (t == NULL || expression_has_effect(t)) &&
8841 expression_has_effect(cond->false_expression);
8844 case EXPR_SELECT: return false;
8845 case EXPR_ARRAY_ACCESS: return false;
8846 case EXPR_SIZEOF: return false;
8847 case EXPR_CLASSIFY_TYPE: return false;
8848 case EXPR_ALIGNOF: return false;
8850 case EXPR_FUNCNAME: return false;
8851 case EXPR_BUILTIN_CONSTANT_P: return false;
8852 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8853 case EXPR_OFFSETOF: return false;
8854 case EXPR_VA_START: return true;
8855 case EXPR_VA_ARG: return true;
8856 case EXPR_VA_COPY: return true;
8857 case EXPR_STATEMENT: return true; // TODO
8858 case EXPR_COMPOUND_LITERAL: return false;
8860 case EXPR_UNARY_NEGATE: return false;
8861 case EXPR_UNARY_PLUS: return false;
8862 case EXPR_UNARY_BITWISE_NEGATE: return false;
8863 case EXPR_UNARY_NOT: return false;
8864 case EXPR_UNARY_DEREFERENCE: return false;
8865 case EXPR_UNARY_TAKE_ADDRESS: return false;
8866 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8867 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8868 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8869 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8871 /* Treat void casts as if they have an effect in order to being able to
8872 * suppress the warning */
8873 case EXPR_UNARY_CAST: {
8874 type_t *const type = skip_typeref(expr->base.type);
8875 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8878 case EXPR_UNARY_CAST_IMPLICIT: return true;
8879 case EXPR_UNARY_ASSUME: return true;
8880 case EXPR_UNARY_DELETE: return true;
8881 case EXPR_UNARY_DELETE_ARRAY: return true;
8882 case EXPR_UNARY_THROW: return true;
8884 case EXPR_BINARY_ADD: return false;
8885 case EXPR_BINARY_SUB: return false;
8886 case EXPR_BINARY_MUL: return false;
8887 case EXPR_BINARY_DIV: return false;
8888 case EXPR_BINARY_MOD: return false;
8889 case EXPR_BINARY_EQUAL: return false;
8890 case EXPR_BINARY_NOTEQUAL: return false;
8891 case EXPR_BINARY_LESS: return false;
8892 case EXPR_BINARY_LESSEQUAL: return false;
8893 case EXPR_BINARY_GREATER: return false;
8894 case EXPR_BINARY_GREATEREQUAL: return false;
8895 case EXPR_BINARY_BITWISE_AND: return false;
8896 case EXPR_BINARY_BITWISE_OR: return false;
8897 case EXPR_BINARY_BITWISE_XOR: return false;
8898 case EXPR_BINARY_SHIFTLEFT: return false;
8899 case EXPR_BINARY_SHIFTRIGHT: return false;
8900 case EXPR_BINARY_ASSIGN: return true;
8901 case EXPR_BINARY_MUL_ASSIGN: return true;
8902 case EXPR_BINARY_DIV_ASSIGN: return true;
8903 case EXPR_BINARY_MOD_ASSIGN: return true;
8904 case EXPR_BINARY_ADD_ASSIGN: return true;
8905 case EXPR_BINARY_SUB_ASSIGN: return true;
8906 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8907 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8908 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8909 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8910 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8912 /* Only examine the right hand side of && and ||, because the left hand
8913 * side already has the effect of controlling the execution of the right
8915 case EXPR_BINARY_LOGICAL_AND:
8916 case EXPR_BINARY_LOGICAL_OR:
8917 /* Only examine the right hand side of a comma expression, because the left
8918 * hand side has a separate warning */
8919 case EXPR_BINARY_COMMA:
8920 return expression_has_effect(expr->binary.right);
8922 case EXPR_BINARY_ISGREATER: return false;
8923 case EXPR_BINARY_ISGREATEREQUAL: return false;
8924 case EXPR_BINARY_ISLESS: return false;
8925 case EXPR_BINARY_ISLESSEQUAL: return false;
8926 case EXPR_BINARY_ISLESSGREATER: return false;
8927 case EXPR_BINARY_ISUNORDERED: return false;
8930 internal_errorf(HERE, "unexpected expression");
8933 static void semantic_comma(binary_expression_t *expression)
8935 if (warning.unused_value) {
8936 const expression_t *const left = expression->left;
8937 if (!expression_has_effect(left)) {
8938 warningf(&left->base.source_position,
8939 "left-hand operand of comma expression has no effect");
8942 expression->base.type = expression->right->base.type;
8946 * @param prec_r precedence of the right operand
8948 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8949 static expression_t *parse_##binexpression_type(expression_t *left) \
8951 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8952 binexpr->binary.left = left; \
8955 expression_t *right = parse_sub_expression(prec_r); \
8957 binexpr->binary.right = right; \
8958 sfunc(&binexpr->binary); \
8963 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8964 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8965 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8966 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8967 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8968 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8969 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8970 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8971 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8972 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8973 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8974 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8975 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8976 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8977 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8978 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8979 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8980 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8981 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8982 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8983 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8984 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8985 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8986 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8987 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8988 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8989 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8990 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8991 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8992 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8995 static expression_t *parse_sub_expression(precedence_t precedence)
8997 if (token.type < 0) {
8998 return expected_expression_error();
9001 expression_parser_function_t *parser
9002 = &expression_parsers[token.type];
9003 source_position_t source_position = token.source_position;
9006 if (parser->parser != NULL) {
9007 left = parser->parser();
9009 left = parse_primary_expression();
9011 assert(left != NULL);
9012 left->base.source_position = source_position;
9015 if (token.type < 0) {
9016 return expected_expression_error();
9019 parser = &expression_parsers[token.type];
9020 if (parser->infix_parser == NULL)
9022 if (parser->infix_precedence < precedence)
9025 left = parser->infix_parser(left);
9027 assert(left != NULL);
9028 assert(left->kind != EXPR_UNKNOWN);
9029 left->base.source_position = source_position;
9036 * Parse an expression.
9038 static expression_t *parse_expression(void)
9040 return parse_sub_expression(PREC_EXPRESSION);
9044 * Register a parser for a prefix-like operator.
9046 * @param parser the parser function
9047 * @param token_type the token type of the prefix token
9049 static void register_expression_parser(parse_expression_function parser,
9052 expression_parser_function_t *entry = &expression_parsers[token_type];
9054 if (entry->parser != NULL) {
9055 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9056 panic("trying to register multiple expression parsers for a token");
9058 entry->parser = parser;
9062 * Register a parser for an infix operator with given precedence.
9064 * @param parser the parser function
9065 * @param token_type the token type of the infix operator
9066 * @param precedence the precedence of the operator
9068 static void register_infix_parser(parse_expression_infix_function parser,
9069 int token_type, precedence_t precedence)
9071 expression_parser_function_t *entry = &expression_parsers[token_type];
9073 if (entry->infix_parser != NULL) {
9074 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9075 panic("trying to register multiple infix expression parsers for a "
9078 entry->infix_parser = parser;
9079 entry->infix_precedence = precedence;
9083 * Initialize the expression parsers.
9085 static void init_expression_parsers(void)
9087 memset(&expression_parsers, 0, sizeof(expression_parsers));
9089 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9090 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9091 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9092 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9093 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9094 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9095 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9096 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9097 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9098 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9099 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9100 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9101 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9102 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9103 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9104 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9105 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9106 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9107 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9108 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9109 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9110 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9111 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9112 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9113 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9114 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9115 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9116 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9117 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9118 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9119 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9120 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9121 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9122 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9123 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9124 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9125 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9127 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9128 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9129 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9130 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9131 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9132 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9133 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9134 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9135 register_expression_parser(parse_sizeof, T_sizeof);
9136 register_expression_parser(parse_alignof, T___alignof__);
9137 register_expression_parser(parse_extension, T___extension__);
9138 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9139 register_expression_parser(parse_delete, T_delete);
9140 register_expression_parser(parse_throw, T_throw);
9144 * Parse a asm statement arguments specification.
9146 static asm_argument_t *parse_asm_arguments(bool is_out)
9148 asm_argument_t *result = NULL;
9149 asm_argument_t **anchor = &result;
9151 while (token.type == T_STRING_LITERAL || token.type == '[') {
9152 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9153 memset(argument, 0, sizeof(argument[0]));
9156 if (token.type != T_IDENTIFIER) {
9157 parse_error_expected("while parsing asm argument",
9158 T_IDENTIFIER, NULL);
9161 argument->symbol = token.v.symbol;
9163 expect(']', end_error);
9166 argument->constraints = parse_string_literals();
9167 expect('(', end_error);
9168 add_anchor_token(')');
9169 expression_t *expression = parse_expression();
9170 rem_anchor_token(')');
9172 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9173 * change size or type representation (e.g. int -> long is ok, but
9174 * int -> float is not) */
9175 if (expression->kind == EXPR_UNARY_CAST) {
9176 type_t *const type = expression->base.type;
9177 type_kind_t const kind = type->kind;
9178 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9181 if (kind == TYPE_ATOMIC) {
9182 atomic_type_kind_t const akind = type->atomic.akind;
9183 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9184 size = get_atomic_type_size(akind);
9186 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9187 size = get_atomic_type_size(get_intptr_kind());
9191 expression_t *const value = expression->unary.value;
9192 type_t *const value_type = value->base.type;
9193 type_kind_t const value_kind = value_type->kind;
9195 unsigned value_flags;
9196 unsigned value_size;
9197 if (value_kind == TYPE_ATOMIC) {
9198 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9199 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9200 value_size = get_atomic_type_size(value_akind);
9201 } else if (value_kind == TYPE_POINTER) {
9202 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9203 value_size = get_atomic_type_size(get_intptr_kind());
9208 if (value_flags != flags || value_size != size)
9212 } while (expression->kind == EXPR_UNARY_CAST);
9216 if (!is_lvalue(expression)) {
9217 errorf(&expression->base.source_position,
9218 "asm output argument is not an lvalue");
9221 if (argument->constraints.begin[0] == '+')
9222 mark_vars_read(expression, NULL);
9224 mark_vars_read(expression, NULL);
9226 argument->expression = expression;
9227 expect(')', end_error);
9229 set_address_taken(expression, true);
9232 anchor = &argument->next;
9244 * Parse a asm statement clobber specification.
9246 static asm_clobber_t *parse_asm_clobbers(void)
9248 asm_clobber_t *result = NULL;
9249 asm_clobber_t **anchor = &result;
9251 while (token.type == T_STRING_LITERAL) {
9252 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9253 clobber->clobber = parse_string_literals();
9256 anchor = &clobber->next;
9266 * Parse an asm statement.
9268 static statement_t *parse_asm_statement(void)
9270 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9271 asm_statement_t *asm_statement = &statement->asms;
9275 if (next_if(T_volatile))
9276 asm_statement->is_volatile = true;
9278 expect('(', end_error);
9279 add_anchor_token(')');
9280 add_anchor_token(':');
9281 asm_statement->asm_text = parse_string_literals();
9283 if (!next_if(':')) {
9284 rem_anchor_token(':');
9288 asm_statement->outputs = parse_asm_arguments(true);
9289 if (!next_if(':')) {
9290 rem_anchor_token(':');
9294 asm_statement->inputs = parse_asm_arguments(false);
9295 if (!next_if(':')) {
9296 rem_anchor_token(':');
9299 rem_anchor_token(':');
9301 asm_statement->clobbers = parse_asm_clobbers();
9304 rem_anchor_token(')');
9305 expect(')', end_error);
9306 expect(';', end_error);
9308 if (asm_statement->outputs == NULL) {
9309 /* GCC: An 'asm' instruction without any output operands will be treated
9310 * identically to a volatile 'asm' instruction. */
9311 asm_statement->is_volatile = true;
9316 return create_invalid_statement();
9320 * Parse a case statement.
9322 static statement_t *parse_case_statement(void)
9324 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9325 source_position_t *const pos = &statement->base.source_position;
9329 expression_t *const expression = parse_expression();
9330 statement->case_label.expression = expression;
9331 if (!is_constant_expression(expression)) {
9332 /* This check does not prevent the error message in all cases of an
9333 * prior error while parsing the expression. At least it catches the
9334 * common case of a mistyped enum entry. */
9335 if (is_type_valid(skip_typeref(expression->base.type))) {
9336 errorf(pos, "case label does not reduce to an integer constant");
9338 statement->case_label.is_bad = true;
9340 long const val = fold_constant_to_int(expression);
9341 statement->case_label.first_case = val;
9342 statement->case_label.last_case = val;
9346 if (next_if(T_DOTDOTDOT)) {
9347 expression_t *const end_range = parse_expression();
9348 statement->case_label.end_range = end_range;
9349 if (!is_constant_expression(end_range)) {
9350 /* This check does not prevent the error message in all cases of an
9351 * prior error while parsing the expression. At least it catches the
9352 * common case of a mistyped enum entry. */
9353 if (is_type_valid(skip_typeref(end_range->base.type))) {
9354 errorf(pos, "case range does not reduce to an integer constant");
9356 statement->case_label.is_bad = true;
9358 long const val = fold_constant_to_int(end_range);
9359 statement->case_label.last_case = val;
9361 if (warning.other && val < statement->case_label.first_case) {
9362 statement->case_label.is_empty_range = true;
9363 warningf(pos, "empty range specified");
9369 PUSH_PARENT(statement);
9371 expect(':', end_error);
9374 if (current_switch != NULL) {
9375 if (! statement->case_label.is_bad) {
9376 /* Check for duplicate case values */
9377 case_label_statement_t *c = &statement->case_label;
9378 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9379 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9382 if (c->last_case < l->first_case || c->first_case > l->last_case)
9385 errorf(pos, "duplicate case value (previously used %P)",
9386 &l->base.source_position);
9390 /* link all cases into the switch statement */
9391 if (current_switch->last_case == NULL) {
9392 current_switch->first_case = &statement->case_label;
9394 current_switch->last_case->next = &statement->case_label;
9396 current_switch->last_case = &statement->case_label;
9398 errorf(pos, "case label not within a switch statement");
9401 statement_t *const inner_stmt = parse_statement();
9402 statement->case_label.statement = inner_stmt;
9403 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9404 errorf(&inner_stmt->base.source_position, "declaration after case label");
9412 * Parse a default statement.
9414 static statement_t *parse_default_statement(void)
9416 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9420 PUSH_PARENT(statement);
9422 expect(':', end_error);
9423 if (current_switch != NULL) {
9424 const case_label_statement_t *def_label = current_switch->default_label;
9425 if (def_label != NULL) {
9426 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9427 &def_label->base.source_position);
9429 current_switch->default_label = &statement->case_label;
9431 /* link all cases into the switch statement */
9432 if (current_switch->last_case == NULL) {
9433 current_switch->first_case = &statement->case_label;
9435 current_switch->last_case->next = &statement->case_label;
9437 current_switch->last_case = &statement->case_label;
9440 errorf(&statement->base.source_position,
9441 "'default' label not within a switch statement");
9444 statement_t *const inner_stmt = parse_statement();
9445 statement->case_label.statement = inner_stmt;
9446 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9447 errorf(&inner_stmt->base.source_position, "declaration after default label");
9454 return create_invalid_statement();
9458 * Parse a label statement.
9460 static statement_t *parse_label_statement(void)
9462 assert(token.type == T_IDENTIFIER);
9463 symbol_t *symbol = token.v.symbol;
9464 label_t *label = get_label(symbol);
9466 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9467 statement->label.label = label;
9471 PUSH_PARENT(statement);
9473 /* if statement is already set then the label is defined twice,
9474 * otherwise it was just mentioned in a goto/local label declaration so far
9476 if (label->statement != NULL) {
9477 errorf(HERE, "duplicate label '%Y' (declared %P)",
9478 symbol, &label->base.source_position);
9480 label->base.source_position = token.source_position;
9481 label->statement = statement;
9486 if (token.type == '}') {
9487 /* TODO only warn? */
9488 if (warning.other && false) {
9489 warningf(HERE, "label at end of compound statement");
9490 statement->label.statement = create_empty_statement();
9492 errorf(HERE, "label at end of compound statement");
9493 statement->label.statement = create_invalid_statement();
9495 } else if (token.type == ';') {
9496 /* Eat an empty statement here, to avoid the warning about an empty
9497 * statement after a label. label:; is commonly used to have a label
9498 * before a closing brace. */
9499 statement->label.statement = create_empty_statement();
9502 statement_t *const inner_stmt = parse_statement();
9503 statement->label.statement = inner_stmt;
9504 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9505 errorf(&inner_stmt->base.source_position, "declaration after label");
9509 /* remember the labels in a list for later checking */
9510 *label_anchor = &statement->label;
9511 label_anchor = &statement->label.next;
9518 * Parse an if statement.
9520 static statement_t *parse_if(void)
9522 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9526 PUSH_PARENT(statement);
9528 add_anchor_token('{');
9530 expect('(', end_error);
9531 add_anchor_token(')');
9532 expression_t *const expr = parse_expression();
9533 statement->ifs.condition = expr;
9534 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9536 semantic_condition(expr, "condition of 'if'-statment");
9537 mark_vars_read(expr, NULL);
9538 rem_anchor_token(')');
9539 expect(')', end_error);
9542 rem_anchor_token('{');
9544 add_anchor_token(T_else);
9545 statement_t *const true_stmt = parse_statement();
9546 statement->ifs.true_statement = true_stmt;
9547 rem_anchor_token(T_else);
9549 if (next_if(T_else)) {
9550 statement->ifs.false_statement = parse_statement();
9551 } else if (warning.parentheses &&
9552 true_stmt->kind == STATEMENT_IF &&
9553 true_stmt->ifs.false_statement != NULL) {
9554 warningf(&true_stmt->base.source_position,
9555 "suggest explicit braces to avoid ambiguous 'else'");
9563 * Check that all enums are handled in a switch.
9565 * @param statement the switch statement to check
9567 static void check_enum_cases(const switch_statement_t *statement)
9569 const type_t *type = skip_typeref(statement->expression->base.type);
9570 if (! is_type_enum(type))
9572 const enum_type_t *enumt = &type->enumt;
9574 /* if we have a default, no warnings */
9575 if (statement->default_label != NULL)
9578 /* FIXME: calculation of value should be done while parsing */
9579 /* TODO: quadratic algorithm here. Change to an n log n one */
9580 long last_value = -1;
9581 const entity_t *entry = enumt->enume->base.next;
9582 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9583 entry = entry->base.next) {
9584 const expression_t *expression = entry->enum_value.value;
9585 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9587 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9588 if (l->expression == NULL)
9590 if (l->first_case <= value && value <= l->last_case) {
9596 warningf(&statement->base.source_position,
9597 "enumeration value '%Y' not handled in switch",
9598 entry->base.symbol);
9605 * Parse a switch statement.
9607 static statement_t *parse_switch(void)
9609 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9613 PUSH_PARENT(statement);
9615 expect('(', end_error);
9616 add_anchor_token(')');
9617 expression_t *const expr = parse_expression();
9618 mark_vars_read(expr, NULL);
9619 type_t * type = skip_typeref(expr->base.type);
9620 if (is_type_integer(type)) {
9621 type = promote_integer(type);
9622 if (warning.traditional) {
9623 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9624 warningf(&expr->base.source_position,
9625 "'%T' switch expression not converted to '%T' in ISO C",
9629 } else if (is_type_valid(type)) {
9630 errorf(&expr->base.source_position,
9631 "switch quantity is not an integer, but '%T'", type);
9632 type = type_error_type;
9634 statement->switchs.expression = create_implicit_cast(expr, type);
9635 expect(')', end_error);
9636 rem_anchor_token(')');
9638 switch_statement_t *rem = current_switch;
9639 current_switch = &statement->switchs;
9640 statement->switchs.body = parse_statement();
9641 current_switch = rem;
9643 if (warning.switch_default &&
9644 statement->switchs.default_label == NULL) {
9645 warningf(&statement->base.source_position, "switch has no default case");
9647 if (warning.switch_enum)
9648 check_enum_cases(&statement->switchs);
9654 return create_invalid_statement();
9657 static statement_t *parse_loop_body(statement_t *const loop)
9659 statement_t *const rem = current_loop;
9660 current_loop = loop;
9662 statement_t *const body = parse_statement();
9669 * Parse a while statement.
9671 static statement_t *parse_while(void)
9673 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9677 PUSH_PARENT(statement);
9679 expect('(', end_error);
9680 add_anchor_token(')');
9681 expression_t *const cond = parse_expression();
9682 statement->whiles.condition = cond;
9683 /* §6.8.5:2 The controlling expression of an iteration statement shall
9684 * have scalar type. */
9685 semantic_condition(cond, "condition of 'while'-statement");
9686 mark_vars_read(cond, NULL);
9687 rem_anchor_token(')');
9688 expect(')', end_error);
9690 statement->whiles.body = parse_loop_body(statement);
9696 return create_invalid_statement();
9700 * Parse a do statement.
9702 static statement_t *parse_do(void)
9704 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9708 PUSH_PARENT(statement);
9710 add_anchor_token(T_while);
9711 statement->do_while.body = parse_loop_body(statement);
9712 rem_anchor_token(T_while);
9714 expect(T_while, end_error);
9715 expect('(', end_error);
9716 add_anchor_token(')');
9717 expression_t *const cond = parse_expression();
9718 statement->do_while.condition = cond;
9719 /* §6.8.5:2 The controlling expression of an iteration statement shall
9720 * have scalar type. */
9721 semantic_condition(cond, "condition of 'do-while'-statement");
9722 mark_vars_read(cond, NULL);
9723 rem_anchor_token(')');
9724 expect(')', end_error);
9725 expect(';', end_error);
9731 return create_invalid_statement();
9735 * Parse a for statement.
9737 static statement_t *parse_for(void)
9739 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9743 expect('(', end_error1);
9744 add_anchor_token(')');
9746 PUSH_PARENT(statement);
9748 size_t const top = environment_top();
9749 scope_t *old_scope = scope_push(&statement->fors.scope);
9751 bool old_gcc_extension = in_gcc_extension;
9752 while (next_if(T___extension__)) {
9753 in_gcc_extension = true;
9757 } else if (is_declaration_specifier(&token, false)) {
9758 parse_declaration(record_entity, DECL_FLAGS_NONE);
9760 add_anchor_token(';');
9761 expression_t *const init = parse_expression();
9762 statement->fors.initialisation = init;
9763 mark_vars_read(init, ENT_ANY);
9764 if (warning.unused_value && !expression_has_effect(init)) {
9765 warningf(&init->base.source_position,
9766 "initialisation of 'for'-statement has no effect");
9768 rem_anchor_token(';');
9769 expect(';', end_error2);
9771 in_gcc_extension = old_gcc_extension;
9773 if (token.type != ';') {
9774 add_anchor_token(';');
9775 expression_t *const cond = parse_expression();
9776 statement->fors.condition = cond;
9777 /* §6.8.5:2 The controlling expression of an iteration statement
9778 * shall have scalar type. */
9779 semantic_condition(cond, "condition of 'for'-statement");
9780 mark_vars_read(cond, NULL);
9781 rem_anchor_token(';');
9783 expect(';', end_error2);
9784 if (token.type != ')') {
9785 expression_t *const step = parse_expression();
9786 statement->fors.step = step;
9787 mark_vars_read(step, ENT_ANY);
9788 if (warning.unused_value && !expression_has_effect(step)) {
9789 warningf(&step->base.source_position,
9790 "step of 'for'-statement has no effect");
9793 expect(')', end_error2);
9794 rem_anchor_token(')');
9795 statement->fors.body = parse_loop_body(statement);
9797 assert(current_scope == &statement->fors.scope);
9798 scope_pop(old_scope);
9799 environment_pop_to(top);
9806 rem_anchor_token(')');
9807 assert(current_scope == &statement->fors.scope);
9808 scope_pop(old_scope);
9809 environment_pop_to(top);
9813 return create_invalid_statement();
9817 * Parse a goto statement.
9819 static statement_t *parse_goto(void)
9821 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9824 if (GNU_MODE && next_if('*')) {
9825 expression_t *expression = parse_expression();
9826 mark_vars_read(expression, NULL);
9828 /* Argh: although documentation says the expression must be of type void*,
9829 * gcc accepts anything that can be casted into void* without error */
9830 type_t *type = expression->base.type;
9832 if (type != type_error_type) {
9833 if (!is_type_pointer(type) && !is_type_integer(type)) {
9834 errorf(&expression->base.source_position,
9835 "cannot convert to a pointer type");
9836 } else if (warning.other && type != type_void_ptr) {
9837 warningf(&expression->base.source_position,
9838 "type of computed goto expression should be 'void*' not '%T'", type);
9840 expression = create_implicit_cast(expression, type_void_ptr);
9843 statement->gotos.expression = expression;
9844 } else if (token.type == T_IDENTIFIER) {
9845 symbol_t *symbol = token.v.symbol;
9847 statement->gotos.label = get_label(symbol);
9850 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9852 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9857 /* remember the goto's in a list for later checking */
9858 *goto_anchor = &statement->gotos;
9859 goto_anchor = &statement->gotos.next;
9861 expect(';', end_error);
9865 return create_invalid_statement();
9869 * Parse a continue statement.
9871 static statement_t *parse_continue(void)
9873 if (current_loop == NULL) {
9874 errorf(HERE, "continue statement not within loop");
9877 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9880 expect(';', end_error);
9887 * Parse a break statement.
9889 static statement_t *parse_break(void)
9891 if (current_switch == NULL && current_loop == NULL) {
9892 errorf(HERE, "break statement not within loop or switch");
9895 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9898 expect(';', end_error);
9905 * Parse a __leave statement.
9907 static statement_t *parse_leave_statement(void)
9909 if (current_try == NULL) {
9910 errorf(HERE, "__leave statement not within __try");
9913 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9916 expect(';', end_error);
9923 * Check if a given entity represents a local variable.
9925 static bool is_local_variable(const entity_t *entity)
9927 if (entity->kind != ENTITY_VARIABLE)
9930 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9931 case STORAGE_CLASS_AUTO:
9932 case STORAGE_CLASS_REGISTER: {
9933 const type_t *type = skip_typeref(entity->declaration.type);
9934 if (is_type_function(type)) {
9946 * Check if a given expression represents a local variable.
9948 static bool expression_is_local_variable(const expression_t *expression)
9950 if (expression->base.kind != EXPR_REFERENCE) {
9953 const entity_t *entity = expression->reference.entity;
9954 return is_local_variable(entity);
9958 * Check if a given expression represents a local variable and
9959 * return its declaration then, else return NULL.
9961 entity_t *expression_is_variable(const expression_t *expression)
9963 if (expression->base.kind != EXPR_REFERENCE) {
9966 entity_t *entity = expression->reference.entity;
9967 if (entity->kind != ENTITY_VARIABLE)
9974 * Parse a return statement.
9976 static statement_t *parse_return(void)
9980 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9982 expression_t *return_value = NULL;
9983 if (token.type != ';') {
9984 return_value = parse_expression();
9985 mark_vars_read(return_value, NULL);
9988 const type_t *const func_type = skip_typeref(current_function->base.type);
9989 assert(is_type_function(func_type));
9990 type_t *const return_type = skip_typeref(func_type->function.return_type);
9992 source_position_t const *const pos = &statement->base.source_position;
9993 if (return_value != NULL) {
9994 type_t *return_value_type = skip_typeref(return_value->base.type);
9996 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9997 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9998 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9999 /* Only warn in C mode, because GCC does the same */
10000 if (c_mode & _CXX || strict_mode) {
10002 "'return' with a value, in function returning 'void'");
10003 } else if (warning.other) {
10005 "'return' with a value, in function returning 'void'");
10007 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10008 /* Only warn in C mode, because GCC does the same */
10011 "'return' with expression in function returning 'void'");
10012 } else if (warning.other) {
10014 "'return' with expression in function returning 'void'");
10018 assign_error_t error = semantic_assign(return_type, return_value);
10019 report_assign_error(error, return_type, return_value, "'return'",
10022 return_value = create_implicit_cast(return_value, return_type);
10023 /* check for returning address of a local var */
10024 if (warning.other && return_value != NULL
10025 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10026 const expression_t *expression = return_value->unary.value;
10027 if (expression_is_local_variable(expression)) {
10028 warningf(pos, "function returns address of local variable");
10031 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10032 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10033 if (c_mode & _CXX || strict_mode) {
10035 "'return' without value, in function returning non-void");
10038 "'return' without value, in function returning non-void");
10041 statement->returns.value = return_value;
10043 expect(';', end_error);
10050 * Parse a declaration statement.
10052 static statement_t *parse_declaration_statement(void)
10054 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10056 entity_t *before = current_scope->last_entity;
10058 parse_external_declaration();
10060 parse_declaration(record_entity, DECL_FLAGS_NONE);
10063 declaration_statement_t *const decl = &statement->declaration;
10064 entity_t *const begin =
10065 before != NULL ? before->base.next : current_scope->entities;
10066 decl->declarations_begin = begin;
10067 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10073 * Parse an expression statement, ie. expr ';'.
10075 static statement_t *parse_expression_statement(void)
10077 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10079 expression_t *const expr = parse_expression();
10080 statement->expression.expression = expr;
10081 mark_vars_read(expr, ENT_ANY);
10083 expect(';', end_error);
10090 * Parse a microsoft __try { } __finally { } or
10091 * __try{ } __except() { }
10093 static statement_t *parse_ms_try_statment(void)
10095 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10098 PUSH_PARENT(statement);
10100 ms_try_statement_t *rem = current_try;
10101 current_try = &statement->ms_try;
10102 statement->ms_try.try_statement = parse_compound_statement(false);
10107 if (next_if(T___except)) {
10108 expect('(', end_error);
10109 add_anchor_token(')');
10110 expression_t *const expr = parse_expression();
10111 mark_vars_read(expr, NULL);
10112 type_t * type = skip_typeref(expr->base.type);
10113 if (is_type_integer(type)) {
10114 type = promote_integer(type);
10115 } else if (is_type_valid(type)) {
10116 errorf(&expr->base.source_position,
10117 "__expect expression is not an integer, but '%T'", type);
10118 type = type_error_type;
10120 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10121 rem_anchor_token(')');
10122 expect(')', end_error);
10123 statement->ms_try.final_statement = parse_compound_statement(false);
10124 } else if (next_if(T__finally)) {
10125 statement->ms_try.final_statement = parse_compound_statement(false);
10127 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10128 return create_invalid_statement();
10132 return create_invalid_statement();
10135 static statement_t *parse_empty_statement(void)
10137 if (warning.empty_statement) {
10138 warningf(HERE, "statement is empty");
10140 statement_t *const statement = create_empty_statement();
10145 static statement_t *parse_local_label_declaration(void)
10147 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10151 entity_t *begin = NULL, *end = NULL;
10154 if (token.type != T_IDENTIFIER) {
10155 parse_error_expected("while parsing local label declaration",
10156 T_IDENTIFIER, NULL);
10159 symbol_t *symbol = token.v.symbol;
10160 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10161 if (entity != NULL && entity->base.parent_scope == current_scope) {
10162 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10163 symbol, &entity->base.source_position);
10165 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10167 entity->base.parent_scope = current_scope;
10168 entity->base.namespc = NAMESPACE_LABEL;
10169 entity->base.source_position = token.source_position;
10170 entity->base.symbol = symbol;
10173 end->base.next = entity;
10178 environment_push(entity);
10181 } while (next_if(','));
10184 statement->declaration.declarations_begin = begin;
10185 statement->declaration.declarations_end = end;
10189 static void parse_namespace_definition(void)
10193 entity_t *entity = NULL;
10194 symbol_t *symbol = NULL;
10196 if (token.type == T_IDENTIFIER) {
10197 symbol = token.v.symbol;
10200 entity = get_entity(symbol, NAMESPACE_NORMAL);
10202 && entity->kind != ENTITY_NAMESPACE
10203 && entity->base.parent_scope == current_scope) {
10204 if (!is_error_entity(entity)) {
10205 error_redefined_as_different_kind(&token.source_position,
10206 entity, ENTITY_NAMESPACE);
10212 if (entity == NULL) {
10213 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10214 entity->base.symbol = symbol;
10215 entity->base.source_position = token.source_position;
10216 entity->base.namespc = NAMESPACE_NORMAL;
10217 entity->base.parent_scope = current_scope;
10220 if (token.type == '=') {
10221 /* TODO: parse namespace alias */
10222 panic("namespace alias definition not supported yet");
10225 environment_push(entity);
10226 append_entity(current_scope, entity);
10228 size_t const top = environment_top();
10229 scope_t *old_scope = scope_push(&entity->namespacee.members);
10231 entity_t *old_current_entity = current_entity;
10232 current_entity = entity;
10234 expect('{', end_error);
10236 expect('}', end_error);
10239 assert(current_scope == &entity->namespacee.members);
10240 assert(current_entity == entity);
10241 current_entity = old_current_entity;
10242 scope_pop(old_scope);
10243 environment_pop_to(top);
10247 * Parse a statement.
10248 * There's also parse_statement() which additionally checks for
10249 * "statement has no effect" warnings
10251 static statement_t *intern_parse_statement(void)
10253 statement_t *statement = NULL;
10255 /* declaration or statement */
10256 add_anchor_token(';');
10257 switch (token.type) {
10258 case T_IDENTIFIER: {
10259 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10260 if (la1_type == ':') {
10261 statement = parse_label_statement();
10262 } else if (is_typedef_symbol(token.v.symbol)) {
10263 statement = parse_declaration_statement();
10265 /* it's an identifier, the grammar says this must be an
10266 * expression statement. However it is common that users mistype
10267 * declaration types, so we guess a bit here to improve robustness
10268 * for incorrect programs */
10269 switch (la1_type) {
10272 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10273 goto expression_statment;
10278 statement = parse_declaration_statement();
10282 expression_statment:
10283 statement = parse_expression_statement();
10290 case T___extension__:
10291 /* This can be a prefix to a declaration or an expression statement.
10292 * We simply eat it now and parse the rest with tail recursion. */
10293 while (next_if(T___extension__)) {}
10294 bool old_gcc_extension = in_gcc_extension;
10295 in_gcc_extension = true;
10296 statement = intern_parse_statement();
10297 in_gcc_extension = old_gcc_extension;
10301 statement = parse_declaration_statement();
10305 statement = parse_local_label_declaration();
10308 case ';': statement = parse_empty_statement(); break;
10309 case '{': statement = parse_compound_statement(false); break;
10310 case T___leave: statement = parse_leave_statement(); break;
10311 case T___try: statement = parse_ms_try_statment(); break;
10312 case T_asm: statement = parse_asm_statement(); break;
10313 case T_break: statement = parse_break(); break;
10314 case T_case: statement = parse_case_statement(); break;
10315 case T_continue: statement = parse_continue(); break;
10316 case T_default: statement = parse_default_statement(); break;
10317 case T_do: statement = parse_do(); break;
10318 case T_for: statement = parse_for(); break;
10319 case T_goto: statement = parse_goto(); break;
10320 case T_if: statement = parse_if(); break;
10321 case T_return: statement = parse_return(); break;
10322 case T_switch: statement = parse_switch(); break;
10323 case T_while: statement = parse_while(); break;
10326 statement = parse_expression_statement();
10330 errorf(HERE, "unexpected token %K while parsing statement", &token);
10331 statement = create_invalid_statement();
10336 rem_anchor_token(';');
10338 assert(statement != NULL
10339 && statement->base.source_position.input_name != NULL);
10345 * parse a statement and emits "statement has no effect" warning if needed
10346 * (This is really a wrapper around intern_parse_statement with check for 1
10347 * single warning. It is needed, because for statement expressions we have
10348 * to avoid the warning on the last statement)
10350 static statement_t *parse_statement(void)
10352 statement_t *statement = intern_parse_statement();
10354 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10355 expression_t *expression = statement->expression.expression;
10356 if (!expression_has_effect(expression)) {
10357 warningf(&expression->base.source_position,
10358 "statement has no effect");
10366 * Parse a compound statement.
10368 static statement_t *parse_compound_statement(bool inside_expression_statement)
10370 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10372 PUSH_PARENT(statement);
10375 add_anchor_token('}');
10376 /* tokens, which can start a statement */
10377 /* TODO MS, __builtin_FOO */
10378 add_anchor_token('!');
10379 add_anchor_token('&');
10380 add_anchor_token('(');
10381 add_anchor_token('*');
10382 add_anchor_token('+');
10383 add_anchor_token('-');
10384 add_anchor_token('{');
10385 add_anchor_token('~');
10386 add_anchor_token(T_CHARACTER_CONSTANT);
10387 add_anchor_token(T_COLONCOLON);
10388 add_anchor_token(T_FLOATINGPOINT);
10389 add_anchor_token(T_IDENTIFIER);
10390 add_anchor_token(T_INTEGER);
10391 add_anchor_token(T_MINUSMINUS);
10392 add_anchor_token(T_PLUSPLUS);
10393 add_anchor_token(T_STRING_LITERAL);
10394 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10395 add_anchor_token(T_WIDE_STRING_LITERAL);
10396 add_anchor_token(T__Bool);
10397 add_anchor_token(T__Complex);
10398 add_anchor_token(T__Imaginary);
10399 add_anchor_token(T___FUNCTION__);
10400 add_anchor_token(T___PRETTY_FUNCTION__);
10401 add_anchor_token(T___alignof__);
10402 add_anchor_token(T___attribute__);
10403 add_anchor_token(T___builtin_va_start);
10404 add_anchor_token(T___extension__);
10405 add_anchor_token(T___func__);
10406 add_anchor_token(T___imag__);
10407 add_anchor_token(T___label__);
10408 add_anchor_token(T___real__);
10409 add_anchor_token(T___thread);
10410 add_anchor_token(T_asm);
10411 add_anchor_token(T_auto);
10412 add_anchor_token(T_bool);
10413 add_anchor_token(T_break);
10414 add_anchor_token(T_case);
10415 add_anchor_token(T_char);
10416 add_anchor_token(T_class);
10417 add_anchor_token(T_const);
10418 add_anchor_token(T_const_cast);
10419 add_anchor_token(T_continue);
10420 add_anchor_token(T_default);
10421 add_anchor_token(T_delete);
10422 add_anchor_token(T_double);
10423 add_anchor_token(T_do);
10424 add_anchor_token(T_dynamic_cast);
10425 add_anchor_token(T_enum);
10426 add_anchor_token(T_extern);
10427 add_anchor_token(T_false);
10428 add_anchor_token(T_float);
10429 add_anchor_token(T_for);
10430 add_anchor_token(T_goto);
10431 add_anchor_token(T_if);
10432 add_anchor_token(T_inline);
10433 add_anchor_token(T_int);
10434 add_anchor_token(T_long);
10435 add_anchor_token(T_new);
10436 add_anchor_token(T_operator);
10437 add_anchor_token(T_register);
10438 add_anchor_token(T_reinterpret_cast);
10439 add_anchor_token(T_restrict);
10440 add_anchor_token(T_return);
10441 add_anchor_token(T_short);
10442 add_anchor_token(T_signed);
10443 add_anchor_token(T_sizeof);
10444 add_anchor_token(T_static);
10445 add_anchor_token(T_static_cast);
10446 add_anchor_token(T_struct);
10447 add_anchor_token(T_switch);
10448 add_anchor_token(T_template);
10449 add_anchor_token(T_this);
10450 add_anchor_token(T_throw);
10451 add_anchor_token(T_true);
10452 add_anchor_token(T_try);
10453 add_anchor_token(T_typedef);
10454 add_anchor_token(T_typeid);
10455 add_anchor_token(T_typename);
10456 add_anchor_token(T_typeof);
10457 add_anchor_token(T_union);
10458 add_anchor_token(T_unsigned);
10459 add_anchor_token(T_using);
10460 add_anchor_token(T_void);
10461 add_anchor_token(T_volatile);
10462 add_anchor_token(T_wchar_t);
10463 add_anchor_token(T_while);
10465 size_t const top = environment_top();
10466 scope_t *old_scope = scope_push(&statement->compound.scope);
10468 statement_t **anchor = &statement->compound.statements;
10469 bool only_decls_so_far = true;
10470 while (token.type != '}') {
10471 if (token.type == T_EOF) {
10472 errorf(&statement->base.source_position,
10473 "EOF while parsing compound statement");
10476 statement_t *sub_statement = intern_parse_statement();
10477 if (is_invalid_statement(sub_statement)) {
10478 /* an error occurred. if we are at an anchor, return */
10484 if (warning.declaration_after_statement) {
10485 if (sub_statement->kind != STATEMENT_DECLARATION) {
10486 only_decls_so_far = false;
10487 } else if (!only_decls_so_far) {
10488 warningf(&sub_statement->base.source_position,
10489 "ISO C90 forbids mixed declarations and code");
10493 *anchor = sub_statement;
10495 while (sub_statement->base.next != NULL)
10496 sub_statement = sub_statement->base.next;
10498 anchor = &sub_statement->base.next;
10502 /* look over all statements again to produce no effect warnings */
10503 if (warning.unused_value) {
10504 statement_t *sub_statement = statement->compound.statements;
10505 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10506 if (sub_statement->kind != STATEMENT_EXPRESSION)
10508 /* don't emit a warning for the last expression in an expression
10509 * statement as it has always an effect */
10510 if (inside_expression_statement && sub_statement->base.next == NULL)
10513 expression_t *expression = sub_statement->expression.expression;
10514 if (!expression_has_effect(expression)) {
10515 warningf(&expression->base.source_position,
10516 "statement has no effect");
10522 rem_anchor_token(T_while);
10523 rem_anchor_token(T_wchar_t);
10524 rem_anchor_token(T_volatile);
10525 rem_anchor_token(T_void);
10526 rem_anchor_token(T_using);
10527 rem_anchor_token(T_unsigned);
10528 rem_anchor_token(T_union);
10529 rem_anchor_token(T_typeof);
10530 rem_anchor_token(T_typename);
10531 rem_anchor_token(T_typeid);
10532 rem_anchor_token(T_typedef);
10533 rem_anchor_token(T_try);
10534 rem_anchor_token(T_true);
10535 rem_anchor_token(T_throw);
10536 rem_anchor_token(T_this);
10537 rem_anchor_token(T_template);
10538 rem_anchor_token(T_switch);
10539 rem_anchor_token(T_struct);
10540 rem_anchor_token(T_static_cast);
10541 rem_anchor_token(T_static);
10542 rem_anchor_token(T_sizeof);
10543 rem_anchor_token(T_signed);
10544 rem_anchor_token(T_short);
10545 rem_anchor_token(T_return);
10546 rem_anchor_token(T_restrict);
10547 rem_anchor_token(T_reinterpret_cast);
10548 rem_anchor_token(T_register);
10549 rem_anchor_token(T_operator);
10550 rem_anchor_token(T_new);
10551 rem_anchor_token(T_long);
10552 rem_anchor_token(T_int);
10553 rem_anchor_token(T_inline);
10554 rem_anchor_token(T_if);
10555 rem_anchor_token(T_goto);
10556 rem_anchor_token(T_for);
10557 rem_anchor_token(T_float);
10558 rem_anchor_token(T_false);
10559 rem_anchor_token(T_extern);
10560 rem_anchor_token(T_enum);
10561 rem_anchor_token(T_dynamic_cast);
10562 rem_anchor_token(T_do);
10563 rem_anchor_token(T_double);
10564 rem_anchor_token(T_delete);
10565 rem_anchor_token(T_default);
10566 rem_anchor_token(T_continue);
10567 rem_anchor_token(T_const_cast);
10568 rem_anchor_token(T_const);
10569 rem_anchor_token(T_class);
10570 rem_anchor_token(T_char);
10571 rem_anchor_token(T_case);
10572 rem_anchor_token(T_break);
10573 rem_anchor_token(T_bool);
10574 rem_anchor_token(T_auto);
10575 rem_anchor_token(T_asm);
10576 rem_anchor_token(T___thread);
10577 rem_anchor_token(T___real__);
10578 rem_anchor_token(T___label__);
10579 rem_anchor_token(T___imag__);
10580 rem_anchor_token(T___func__);
10581 rem_anchor_token(T___extension__);
10582 rem_anchor_token(T___builtin_va_start);
10583 rem_anchor_token(T___attribute__);
10584 rem_anchor_token(T___alignof__);
10585 rem_anchor_token(T___PRETTY_FUNCTION__);
10586 rem_anchor_token(T___FUNCTION__);
10587 rem_anchor_token(T__Imaginary);
10588 rem_anchor_token(T__Complex);
10589 rem_anchor_token(T__Bool);
10590 rem_anchor_token(T_WIDE_STRING_LITERAL);
10591 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10592 rem_anchor_token(T_STRING_LITERAL);
10593 rem_anchor_token(T_PLUSPLUS);
10594 rem_anchor_token(T_MINUSMINUS);
10595 rem_anchor_token(T_INTEGER);
10596 rem_anchor_token(T_IDENTIFIER);
10597 rem_anchor_token(T_FLOATINGPOINT);
10598 rem_anchor_token(T_COLONCOLON);
10599 rem_anchor_token(T_CHARACTER_CONSTANT);
10600 rem_anchor_token('~');
10601 rem_anchor_token('{');
10602 rem_anchor_token('-');
10603 rem_anchor_token('+');
10604 rem_anchor_token('*');
10605 rem_anchor_token('(');
10606 rem_anchor_token('&');
10607 rem_anchor_token('!');
10608 rem_anchor_token('}');
10609 assert(current_scope == &statement->compound.scope);
10610 scope_pop(old_scope);
10611 environment_pop_to(top);
10618 * Check for unused global static functions and variables
10620 static void check_unused_globals(void)
10622 if (!warning.unused_function && !warning.unused_variable)
10625 for (const entity_t *entity = file_scope->entities; entity != NULL;
10626 entity = entity->base.next) {
10627 if (!is_declaration(entity))
10630 const declaration_t *declaration = &entity->declaration;
10631 if (declaration->used ||
10632 declaration->modifiers & DM_UNUSED ||
10633 declaration->modifiers & DM_USED ||
10634 declaration->storage_class != STORAGE_CLASS_STATIC)
10637 type_t *const type = declaration->type;
10639 if (entity->kind == ENTITY_FUNCTION) {
10640 /* inhibit warning for static inline functions */
10641 if (entity->function.is_inline)
10644 s = entity->function.statement != NULL ? "defined" : "declared";
10649 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10650 type, declaration->base.symbol, s);
10654 static void parse_global_asm(void)
10656 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10659 expect('(', end_error);
10661 statement->asms.asm_text = parse_string_literals();
10662 statement->base.next = unit->global_asm;
10663 unit->global_asm = statement;
10665 expect(')', end_error);
10666 expect(';', end_error);
10671 static void parse_linkage_specification(void)
10674 assert(token.type == T_STRING_LITERAL);
10676 const char *linkage = parse_string_literals().begin;
10678 linkage_kind_t old_linkage = current_linkage;
10679 linkage_kind_t new_linkage;
10680 if (strcmp(linkage, "C") == 0) {
10681 new_linkage = LINKAGE_C;
10682 } else if (strcmp(linkage, "C++") == 0) {
10683 new_linkage = LINKAGE_CXX;
10685 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10686 new_linkage = LINKAGE_INVALID;
10688 current_linkage = new_linkage;
10690 if (next_if('{')) {
10692 expect('}', end_error);
10698 assert(current_linkage == new_linkage);
10699 current_linkage = old_linkage;
10702 static void parse_external(void)
10704 switch (token.type) {
10705 DECLARATION_START_NO_EXTERN
10707 case T___extension__:
10708 /* tokens below are for implicit int */
10709 case '&': /* & x; -> int& x; (and error later, because C++ has no
10711 case '*': /* * x; -> int* x; */
10712 case '(': /* (x); -> int (x); */
10713 parse_external_declaration();
10717 if (look_ahead(1)->type == T_STRING_LITERAL) {
10718 parse_linkage_specification();
10720 parse_external_declaration();
10725 parse_global_asm();
10729 parse_namespace_definition();
10733 if (!strict_mode) {
10735 warningf(HERE, "stray ';' outside of function");
10742 errorf(HERE, "stray %K outside of function", &token);
10743 if (token.type == '(' || token.type == '{' || token.type == '[')
10744 eat_until_matching_token(token.type);
10750 static void parse_externals(void)
10752 add_anchor_token('}');
10753 add_anchor_token(T_EOF);
10756 unsigned char token_anchor_copy[T_LAST_TOKEN];
10757 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10760 while (token.type != T_EOF && token.type != '}') {
10762 bool anchor_leak = false;
10763 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10764 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10766 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10767 anchor_leak = true;
10770 if (in_gcc_extension) {
10771 errorf(HERE, "Leaked __extension__");
10772 anchor_leak = true;
10782 rem_anchor_token(T_EOF);
10783 rem_anchor_token('}');
10787 * Parse a translation unit.
10789 static void parse_translation_unit(void)
10791 add_anchor_token(T_EOF);
10796 if (token.type == T_EOF)
10799 errorf(HERE, "stray %K outside of function", &token);
10800 if (token.type == '(' || token.type == '{' || token.type == '[')
10801 eat_until_matching_token(token.type);
10809 * @return the translation unit or NULL if errors occurred.
10811 void start_parsing(void)
10813 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10814 label_stack = NEW_ARR_F(stack_entry_t, 0);
10815 diagnostic_count = 0;
10819 print_to_file(stderr);
10821 assert(unit == NULL);
10822 unit = allocate_ast_zero(sizeof(unit[0]));
10824 assert(file_scope == NULL);
10825 file_scope = &unit->scope;
10827 assert(current_scope == NULL);
10828 scope_push(&unit->scope);
10830 create_gnu_builtins();
10832 create_microsoft_intrinsics();
10835 translation_unit_t *finish_parsing(void)
10837 assert(current_scope == &unit->scope);
10840 assert(file_scope == &unit->scope);
10841 check_unused_globals();
10844 DEL_ARR_F(environment_stack);
10845 DEL_ARR_F(label_stack);
10847 translation_unit_t *result = unit;
10852 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10853 * are given length one. */
10854 static void complete_incomplete_arrays(void)
10856 size_t n = ARR_LEN(incomplete_arrays);
10857 for (size_t i = 0; i != n; ++i) {
10858 declaration_t *const decl = incomplete_arrays[i];
10859 type_t *const orig_type = decl->type;
10860 type_t *const type = skip_typeref(orig_type);
10862 if (!is_type_incomplete(type))
10865 if (warning.other) {
10866 warningf(&decl->base.source_position,
10867 "array '%#T' assumed to have one element",
10868 orig_type, decl->base.symbol);
10871 type_t *const new_type = duplicate_type(type);
10872 new_type->array.size_constant = true;
10873 new_type->array.has_implicit_size = true;
10874 new_type->array.size = 1;
10876 type_t *const result = identify_new_type(new_type);
10878 decl->type = result;
10882 void prepare_main_collect2(entity_t *entity)
10884 // create call to __main
10885 symbol_t *symbol = symbol_table_insert("__main");
10886 entity_t *subsubmain_ent
10887 = create_implicit_function(symbol, &builtin_source_position);
10889 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10890 type_t *ftype = subsubmain_ent->declaration.type;
10891 ref->base.source_position = builtin_source_position;
10892 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10893 ref->reference.entity = subsubmain_ent;
10895 expression_t *call = allocate_expression_zero(EXPR_CALL);
10896 call->base.source_position = builtin_source_position;
10897 call->base.type = type_void;
10898 call->call.function = ref;
10900 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10901 expr_statement->base.source_position = builtin_source_position;
10902 expr_statement->expression.expression = call;
10904 statement_t *statement = entity->function.statement;
10905 assert(statement->kind == STATEMENT_COMPOUND);
10906 compound_statement_t *compounds = &statement->compound;
10908 expr_statement->base.next = compounds->statements;
10909 compounds->statements = expr_statement;
10914 lookahead_bufpos = 0;
10915 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10918 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10919 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10920 parse_translation_unit();
10921 complete_incomplete_arrays();
10922 DEL_ARR_F(incomplete_arrays);
10923 incomplete_arrays = NULL;
10927 * create a builtin function.
10929 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10931 symbol_t *symbol = symbol_table_insert(name);
10932 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10933 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10934 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10935 entity->declaration.type = function_type;
10936 entity->declaration.implicit = true;
10937 entity->base.symbol = symbol;
10938 entity->base.source_position = builtin_source_position;
10940 entity->function.btk = kind;
10942 record_entity(entity, /*is_definition=*/false);
10948 * Create predefined gnu builtins.
10950 static void create_gnu_builtins(void)
10952 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10954 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10955 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10956 GNU_BUILTIN(huge_valf, make_function_0_type(type_float));
10957 GNU_BUILTIN(huge_vall, make_function_0_type(type_long_double));
10958 GNU_BUILTIN(inf, make_function_0_type(type_double));
10959 GNU_BUILTIN(inff, make_function_0_type(type_float));
10960 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
10961 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
10962 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
10963 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
10964 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
10965 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
10966 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10967 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10968 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
10969 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
10970 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
10971 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
10972 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
10973 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
10974 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
10980 * Create predefined MS intrinsics.
10982 static void create_microsoft_intrinsics(void)
10984 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
10986 /* intrinsics for all architectures */
10987 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10988 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10989 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
10990 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
10991 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
10992 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
10993 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
10995 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
10996 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
10997 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
10998 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11001 MS_BUILTIN(_enable, make_function_0_type(type_void));
11002 MS_BUILTIN(_disable, make_function_0_type(type_void));
11003 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11004 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11005 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11006 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11007 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11008 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11009 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11010 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11011 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11012 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11013 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11015 if (machine_size <= 32) {
11016 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11017 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11019 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11020 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11027 * Initialize the parser.
11029 void init_parser(void)
11031 sym_anonymous = symbol_table_insert("<anonymous>");
11033 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11035 init_expression_parsers();
11036 obstack_init(&temp_obst);
11038 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11039 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11043 * Terminate the parser.
11045 void exit_parser(void)
11047 obstack_free(&temp_obst, NULL);