2 * This file is part of cparser.
3 * Copyright (C) 2007-2008 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
41 #include "adt/bitfiddle.h"
42 #include "adt/error.h"
43 #include "adt/array.h"
45 //#define PRINT_TOKENS
46 #define MAX_LOOKAHEAD 1
51 entity_namespace_t namespc;
54 typedef struct declaration_specifiers_t declaration_specifiers_t;
55 struct declaration_specifiers_t {
56 source_position_t source_position;
57 storage_class_t storage_class;
58 unsigned char alignment; /**< Alignment, 0 if not set. */
60 bool thread_local : 1; /**< GCC __thread */
61 attribute_t *attributes; /**< list of attributes */
66 * An environment for parsing initializers (and compound literals).
68 typedef struct parse_initializer_env_t {
69 type_t *type; /**< the type of the initializer. In case of an
70 array type with unspecified size this gets
71 adjusted to the actual size. */
72 entity_t *entity; /**< the variable that is initialized if any */
73 bool must_be_constant;
74 } parse_initializer_env_t;
76 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
78 /** The current token. */
80 /** The lookahead ring-buffer. */
81 static token_t lookahead_buffer[MAX_LOOKAHEAD];
82 /** Position of the next token in the lookahead buffer. */
83 static size_t lookahead_bufpos;
84 static stack_entry_t *environment_stack = NULL;
85 static stack_entry_t *label_stack = NULL;
86 static scope_t *file_scope = NULL;
87 static scope_t *current_scope = NULL;
88 /** Point to the current function declaration if inside a function. */
89 static function_t *current_function = NULL;
90 static entity_t *current_init_decl = NULL;
91 static switch_statement_t *current_switch = NULL;
92 static statement_t *current_loop = NULL;
93 static statement_t *current_parent = NULL;
94 static ms_try_statement_t *current_try = NULL;
95 static linkage_kind_t current_linkage = LINKAGE_INVALID;
96 static goto_statement_t *goto_first = NULL;
97 static goto_statement_t **goto_anchor = NULL;
98 static label_statement_t *label_first = NULL;
99 static label_statement_t **label_anchor = NULL;
100 /** current translation unit. */
101 static translation_unit_t *unit = NULL;
102 /** true if we are in a type property context (evaluation only for type. */
103 static bool in_type_prop = false;
104 /** true in we are in a __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
111 #define PUSH_PARENT(stmt) \
112 statement_t *const prev_parent = current_parent; \
113 ((void)(current_parent = (stmt)))
114 #define POP_PARENT ((void)(current_parent = prev_parent))
116 /** special symbol used for anonymous entities. */
117 static const symbol_t *sym_anonymous = NULL;
119 /** The token anchor set */
120 static unsigned char token_anchor_set[T_LAST_TOKEN];
122 /** The current source position. */
123 #define HERE (&token.source_position)
125 /** true if we are in GCC mode. */
126 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
128 static statement_t *parse_compound_statement(bool inside_expression_statement);
129 static statement_t *parse_statement(void);
131 static expression_t *parse_sub_expression(precedence_t);
132 static expression_t *parse_expression(void);
133 static type_t *parse_typename(void);
134 static void parse_externals(void);
135 static void parse_external(void);
137 static void parse_compound_type_entries(compound_t *compound_declaration);
139 static void check_call_argument(type_t *expected_type,
140 call_argument_t *argument, unsigned pos);
142 typedef enum declarator_flags_t {
144 DECL_MAY_BE_ABSTRACT = 1U << 0,
145 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
146 DECL_IS_PARAMETER = 1U << 2
147 } declarator_flags_t;
149 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
150 declarator_flags_t flags);
152 static entity_t *record_entity(entity_t *entity, bool is_definition);
154 static void semantic_comparison(binary_expression_t *expression);
156 static void create_gnu_builtins(void);
157 static void create_microsoft_intrinsics(void);
159 #define STORAGE_CLASSES \
160 STORAGE_CLASSES_NO_EXTERN \
163 #define STORAGE_CLASSES_NO_EXTERN \
170 #define TYPE_QUALIFIERS \
175 case T__forceinline: \
176 case T___attribute__:
178 #define COMPLEX_SPECIFIERS \
180 #define IMAGINARY_SPECIFIERS \
183 #define TYPE_SPECIFIERS \
185 case T___builtin_va_list: \
210 #define DECLARATION_START \
215 #define DECLARATION_START_NO_EXTERN \
216 STORAGE_CLASSES_NO_EXTERN \
220 #define TYPENAME_START \
224 #define EXPRESSION_START \
233 case T_CHARACTER_CONSTANT: \
234 case T_FLOATINGPOINT: \
238 case T_STRING_LITERAL: \
239 case T_WIDE_CHARACTER_CONSTANT: \
240 case T_WIDE_STRING_LITERAL: \
241 case T___FUNCDNAME__: \
242 case T___FUNCSIG__: \
243 case T___FUNCTION__: \
244 case T___PRETTY_FUNCTION__: \
245 case T___alignof__: \
246 case T___builtin_classify_type: \
247 case T___builtin_constant_p: \
248 case T___builtin_isgreater: \
249 case T___builtin_isgreaterequal: \
250 case T___builtin_isless: \
251 case T___builtin_islessequal: \
252 case T___builtin_islessgreater: \
253 case T___builtin_isunordered: \
254 case T___builtin_offsetof: \
255 case T___builtin_va_arg: \
256 case T___builtin_va_start: \
257 case T___builtin_va_copy: \
268 * Allocate an AST node with given size and
269 * initialize all fields with zero.
271 static void *allocate_ast_zero(size_t size)
273 void *res = allocate_ast(size);
274 memset(res, 0, size);
279 * Returns the size of an entity node.
281 * @param kind the entity kind
283 static size_t get_entity_struct_size(entity_kind_t kind)
285 static const size_t sizes[] = {
286 [ENTITY_VARIABLE] = sizeof(variable_t),
287 [ENTITY_PARAMETER] = sizeof(parameter_t),
288 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
289 [ENTITY_FUNCTION] = sizeof(function_t),
290 [ENTITY_TYPEDEF] = sizeof(typedef_t),
291 [ENTITY_STRUCT] = sizeof(compound_t),
292 [ENTITY_UNION] = sizeof(compound_t),
293 [ENTITY_ENUM] = sizeof(enum_t),
294 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
295 [ENTITY_LABEL] = sizeof(label_t),
296 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
297 [ENTITY_NAMESPACE] = sizeof(namespace_t)
299 assert(kind < lengthof(sizes));
300 assert(sizes[kind] != 0);
305 * Allocate an entity of given kind and initialize all
308 * @param kind the kind of the entity to allocate
310 static entity_t *allocate_entity_zero(entity_kind_t kind)
312 size_t size = get_entity_struct_size(kind);
313 entity_t *entity = allocate_ast_zero(size);
319 * Returns the size of a statement node.
321 * @param kind the statement kind
323 static size_t get_statement_struct_size(statement_kind_t kind)
325 static const size_t sizes[] = {
326 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
327 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
328 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
329 [STATEMENT_RETURN] = sizeof(return_statement_t),
330 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
331 [STATEMENT_IF] = sizeof(if_statement_t),
332 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
333 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
334 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
335 [STATEMENT_BREAK] = sizeof(statement_base_t),
336 [STATEMENT_GOTO] = sizeof(goto_statement_t),
337 [STATEMENT_LABEL] = sizeof(label_statement_t),
338 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
339 [STATEMENT_WHILE] = sizeof(while_statement_t),
340 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
341 [STATEMENT_FOR] = sizeof(for_statement_t),
342 [STATEMENT_ASM] = sizeof(asm_statement_t),
343 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
344 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
346 assert(kind < lengthof(sizes));
347 assert(sizes[kind] != 0);
352 * Returns the size of an expression node.
354 * @param kind the expression kind
356 static size_t get_expression_struct_size(expression_kind_t kind)
358 static const size_t sizes[] = {
359 [EXPR_INVALID] = sizeof(expression_base_t),
360 [EXPR_REFERENCE] = sizeof(reference_expression_t),
361 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
362 [EXPR_CONST] = sizeof(const_expression_t),
363 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
364 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
365 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
366 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
367 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
368 [EXPR_CALL] = sizeof(call_expression_t),
369 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
370 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
371 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
372 [EXPR_SELECT] = sizeof(select_expression_t),
373 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
374 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
375 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
376 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
377 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
378 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
379 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
380 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
381 [EXPR_VA_START] = sizeof(va_start_expression_t),
382 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
383 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
384 [EXPR_STATEMENT] = sizeof(statement_expression_t),
385 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
387 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
388 return sizes[EXPR_UNARY_FIRST];
390 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
391 return sizes[EXPR_BINARY_FIRST];
393 assert(kind < lengthof(sizes));
394 assert(sizes[kind] != 0);
399 * Allocate a statement node of given kind and initialize all
400 * fields with zero. Sets its source position to the position
401 * of the current token.
403 static statement_t *allocate_statement_zero(statement_kind_t kind)
405 size_t size = get_statement_struct_size(kind);
406 statement_t *res = allocate_ast_zero(size);
408 res->base.kind = kind;
409 res->base.parent = current_parent;
410 res->base.source_position = token.source_position;
415 * Allocate an expression node of given kind and initialize all
418 * @param kind the kind of the expression to allocate
420 static expression_t *allocate_expression_zero(expression_kind_t kind)
422 size_t size = get_expression_struct_size(kind);
423 expression_t *res = allocate_ast_zero(size);
425 res->base.kind = kind;
426 res->base.type = type_error_type;
427 res->base.source_position = token.source_position;
432 * Creates a new invalid expression at the source position
433 * of the current token.
435 static expression_t *create_invalid_expression(void)
437 return allocate_expression_zero(EXPR_INVALID);
441 * Creates a new invalid statement.
443 static statement_t *create_invalid_statement(void)
445 return allocate_statement_zero(STATEMENT_INVALID);
449 * Allocate a new empty statement.
451 static statement_t *create_empty_statement(void)
453 return allocate_statement_zero(STATEMENT_EMPTY);
457 * Returns the size of a type node.
459 * @param kind the type kind
461 static size_t get_type_struct_size(type_kind_t kind)
463 static const size_t sizes[] = {
464 [TYPE_ATOMIC] = sizeof(atomic_type_t),
465 [TYPE_COMPLEX] = sizeof(complex_type_t),
466 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
467 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
468 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
469 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
470 [TYPE_ENUM] = sizeof(enum_type_t),
471 [TYPE_FUNCTION] = sizeof(function_type_t),
472 [TYPE_POINTER] = sizeof(pointer_type_t),
473 [TYPE_ARRAY] = sizeof(array_type_t),
474 [TYPE_BUILTIN] = sizeof(builtin_type_t),
475 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
476 [TYPE_TYPEOF] = sizeof(typeof_type_t),
478 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
479 assert(kind <= TYPE_TYPEOF);
480 assert(sizes[kind] != 0);
485 * Allocate a type node of given kind and initialize all
488 * @param kind type kind to allocate
490 static type_t *allocate_type_zero(type_kind_t kind)
492 size_t size = get_type_struct_size(kind);
493 type_t *res = obstack_alloc(type_obst, size);
494 memset(res, 0, size);
495 res->base.kind = kind;
500 static function_parameter_t *allocate_parameter(type_t *const type)
502 function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
503 memset(param, 0, sizeof(*param));
509 * Returns the size of an initializer node.
511 * @param kind the initializer kind
513 static size_t get_initializer_size(initializer_kind_t kind)
515 static const size_t sizes[] = {
516 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
517 [INITIALIZER_STRING] = sizeof(initializer_string_t),
518 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
519 [INITIALIZER_LIST] = sizeof(initializer_list_t),
520 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
522 assert(kind < lengthof(sizes));
523 assert(sizes[kind] != 0);
528 * Allocate an initializer node of given kind and initialize all
531 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
533 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
540 * Returns the index of the top element of the environment stack.
542 static size_t environment_top(void)
544 return ARR_LEN(environment_stack);
548 * Returns the index of the top element of the global label stack.
550 static size_t label_top(void)
552 return ARR_LEN(label_stack);
556 * Return the next token.
558 static inline void next_token(void)
560 token = lookahead_buffer[lookahead_bufpos];
561 lookahead_buffer[lookahead_bufpos] = lexer_token;
564 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
567 print_token(stderr, &token);
568 fprintf(stderr, "\n");
573 * Return the next token with a given lookahead.
575 static inline const token_t *look_ahead(size_t num)
577 assert(0 < num && num <= MAX_LOOKAHEAD);
578 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
579 return &lookahead_buffer[pos];
583 * Adds a token type to the token type anchor set (a multi-set).
585 static void add_anchor_token(int token_type)
587 assert(0 <= token_type && token_type < T_LAST_TOKEN);
588 ++token_anchor_set[token_type];
592 * Set the number of tokens types of the given type
593 * to zero and return the old count.
595 static int save_and_reset_anchor_state(int token_type)
597 assert(0 <= token_type && token_type < T_LAST_TOKEN);
598 int count = token_anchor_set[token_type];
599 token_anchor_set[token_type] = 0;
604 * Restore the number of token types to the given count.
606 static void restore_anchor_state(int token_type, int count)
608 assert(0 <= token_type && token_type < T_LAST_TOKEN);
609 token_anchor_set[token_type] = count;
613 * Remove a token type from the token type anchor set (a multi-set).
615 static void rem_anchor_token(int token_type)
617 assert(0 <= token_type && token_type < T_LAST_TOKEN);
618 assert(token_anchor_set[token_type] != 0);
619 --token_anchor_set[token_type];
623 * Return true if the token type of the current token is
626 static bool at_anchor(void)
630 return token_anchor_set[token.type];
634 * Eat tokens until a matching token type is found.
636 static void eat_until_matching_token(int type)
640 case '(': end_token = ')'; break;
641 case '{': end_token = '}'; break;
642 case '[': end_token = ']'; break;
643 default: end_token = type; break;
646 unsigned parenthesis_count = 0;
647 unsigned brace_count = 0;
648 unsigned bracket_count = 0;
649 while (token.type != end_token ||
650 parenthesis_count != 0 ||
652 bracket_count != 0) {
653 switch (token.type) {
655 case '(': ++parenthesis_count; break;
656 case '{': ++brace_count; break;
657 case '[': ++bracket_count; break;
660 if (parenthesis_count > 0)
670 if (bracket_count > 0)
673 if (token.type == end_token &&
674 parenthesis_count == 0 &&
688 * Eat input tokens until an anchor is found.
690 static void eat_until_anchor(void)
692 while (token_anchor_set[token.type] == 0) {
693 if (token.type == '(' || token.type == '{' || token.type == '[')
694 eat_until_matching_token(token.type);
700 * Eat a whole block from input tokens.
702 static void eat_block(void)
704 eat_until_matching_token('{');
705 if (token.type == '}')
709 #define eat(token_type) (assert(token.type == (token_type)), next_token())
712 * Report a parse error because an expected token was not found.
715 #if defined __GNUC__ && __GNUC__ >= 4
716 __attribute__((sentinel))
718 void parse_error_expected(const char *message, ...)
720 if (message != NULL) {
721 errorf(HERE, "%s", message);
724 va_start(ap, message);
725 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
730 * Report an incompatible type.
732 static void type_error_incompatible(const char *msg,
733 const source_position_t *source_position, type_t *type1, type_t *type2)
735 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
740 * Expect the current token is the expected token.
741 * If not, generate an error, eat the current statement,
742 * and goto the end_error label.
744 #define expect(expected, error_label) \
746 if (UNLIKELY(token.type != (expected))) { \
747 parse_error_expected(NULL, (expected), NULL); \
748 add_anchor_token(expected); \
749 eat_until_anchor(); \
750 if (token.type == expected) \
752 rem_anchor_token(expected); \
759 * Push a given scope on the scope stack and make it the
762 static scope_t *scope_push(scope_t *new_scope)
764 if (current_scope != NULL) {
765 new_scope->depth = current_scope->depth + 1;
768 scope_t *old_scope = current_scope;
769 current_scope = new_scope;
774 * Pop the current scope from the scope stack.
776 static void scope_pop(scope_t *old_scope)
778 current_scope = old_scope;
782 * Search an entity by its symbol in a given namespace.
784 static entity_t *get_entity(const symbol_t *const symbol,
785 namespace_tag_t namespc)
787 entity_t *entity = symbol->entity;
788 for (; entity != NULL; entity = entity->base.symbol_next) {
789 if (entity->base.namespc == namespc)
796 /* §6.2.3:1 24) There is only one name space for tags even though three are
798 static entity_t *get_tag(symbol_t const *const symbol,
799 entity_kind_tag_t const kind)
801 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
802 if (entity != NULL && entity->kind != kind) {
804 "'%Y' defined as wrong kind of tag (previous definition %P)",
805 symbol, &entity->base.source_position);
812 * pushs an entity on the environment stack and links the corresponding symbol
815 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
817 symbol_t *symbol = entity->base.symbol;
818 entity_namespace_t namespc = entity->base.namespc;
819 assert(namespc != NAMESPACE_INVALID);
821 /* replace/add entity into entity list of the symbol */
824 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
829 /* replace an entry? */
830 if (iter->base.namespc == namespc) {
831 entity->base.symbol_next = iter->base.symbol_next;
837 /* remember old declaration */
839 entry.symbol = symbol;
840 entry.old_entity = iter;
841 entry.namespc = namespc;
842 ARR_APP1(stack_entry_t, *stack_ptr, entry);
846 * Push an entity on the environment stack.
848 static void environment_push(entity_t *entity)
850 assert(entity->base.source_position.input_name != NULL);
851 assert(entity->base.parent_scope != NULL);
852 stack_push(&environment_stack, entity);
856 * Push a declaration on the global label stack.
858 * @param declaration the declaration
860 static void label_push(entity_t *label)
862 /* we abuse the parameters scope as parent for the labels */
863 label->base.parent_scope = ¤t_function->parameters;
864 stack_push(&label_stack, label);
868 * pops symbols from the environment stack until @p new_top is the top element
870 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
872 stack_entry_t *stack = *stack_ptr;
873 size_t top = ARR_LEN(stack);
876 assert(new_top <= top);
880 for (i = top; i > new_top; --i) {
881 stack_entry_t *entry = &stack[i - 1];
883 entity_t *old_entity = entry->old_entity;
884 symbol_t *symbol = entry->symbol;
885 entity_namespace_t namespc = entry->namespc;
887 /* replace with old_entity/remove */
890 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
892 assert(iter != NULL);
893 /* replace an entry? */
894 if (iter->base.namespc == namespc)
898 /* restore definition from outer scopes (if there was one) */
899 if (old_entity != NULL) {
900 old_entity->base.symbol_next = iter->base.symbol_next;
901 *anchor = old_entity;
903 /* remove entry from list */
904 *anchor = iter->base.symbol_next;
908 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
912 * Pop all entries from the environment stack until the new_top
915 * @param new_top the new stack top
917 static void environment_pop_to(size_t new_top)
919 stack_pop_to(&environment_stack, new_top);
923 * Pop all entries from the global label stack until the new_top
926 * @param new_top the new stack top
928 static void label_pop_to(size_t new_top)
930 stack_pop_to(&label_stack, new_top);
933 static int get_akind_rank(atomic_type_kind_t akind)
939 * Return the type rank for an atomic type.
941 static int get_rank(const type_t *type)
943 assert(!is_typeref(type));
944 if (type->kind == TYPE_ENUM)
945 return get_akind_rank(type->enumt.akind);
947 assert(type->kind == TYPE_ATOMIC);
948 return get_akind_rank(type->atomic.akind);
952 * §6.3.1.1:2 Do integer promotion for a given type.
954 * @param type the type to promote
955 * @return the promoted type
957 static type_t *promote_integer(type_t *type)
959 if (type->kind == TYPE_BITFIELD)
960 type = type->bitfield.base_type;
962 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
969 * Create a cast expression.
971 * @param expression the expression to cast
972 * @param dest_type the destination type
974 static expression_t *create_cast_expression(expression_t *expression,
977 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
979 cast->unary.value = expression;
980 cast->base.type = dest_type;
986 * Check if a given expression represents a null pointer constant.
988 * @param expression the expression to check
990 static bool is_null_pointer_constant(const expression_t *expression)
992 /* skip void* cast */
993 if (expression->kind == EXPR_UNARY_CAST ||
994 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
995 type_t *const type = skip_typeref(expression->base.type);
996 if (types_compatible(type, type_void_ptr))
997 expression = expression->unary.value;
1000 type_t *const type = skip_typeref(expression->base.type);
1002 is_type_integer(type) &&
1003 is_constant_expression(expression) &&
1004 !fold_constant_to_bool(expression);
1008 * Create an implicit cast expression.
1010 * @param expression the expression to cast
1011 * @param dest_type the destination type
1013 static expression_t *create_implicit_cast(expression_t *expression,
1016 type_t *const source_type = expression->base.type;
1018 if (source_type == dest_type)
1021 return create_cast_expression(expression, dest_type);
1024 typedef enum assign_error_t {
1026 ASSIGN_ERROR_INCOMPATIBLE,
1027 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1028 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1029 ASSIGN_WARNING_POINTER_FROM_INT,
1030 ASSIGN_WARNING_INT_FROM_POINTER
1033 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1034 const expression_t *const right,
1035 const char *context,
1036 const source_position_t *source_position)
1038 type_t *const orig_type_right = right->base.type;
1039 type_t *const type_left = skip_typeref(orig_type_left);
1040 type_t *const type_right = skip_typeref(orig_type_right);
1043 case ASSIGN_SUCCESS:
1045 case ASSIGN_ERROR_INCOMPATIBLE:
1046 errorf(source_position,
1047 "destination type '%T' in %s is incompatible with type '%T'",
1048 orig_type_left, context, orig_type_right);
1051 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1052 if (warning.other) {
1053 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1054 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1056 /* the left type has all qualifiers from the right type */
1057 unsigned missing_qualifiers
1058 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1059 warningf(source_position,
1060 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1061 orig_type_left, context, orig_type_right, missing_qualifiers);
1066 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1067 if (warning.other) {
1068 warningf(source_position,
1069 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1070 orig_type_left, context, right, orig_type_right);
1074 case ASSIGN_WARNING_POINTER_FROM_INT:
1075 if (warning.other) {
1076 warningf(source_position,
1077 "%s makes pointer '%T' from integer '%T' without a cast",
1078 context, orig_type_left, orig_type_right);
1082 case ASSIGN_WARNING_INT_FROM_POINTER:
1083 if (warning.other) {
1084 warningf(source_position,
1085 "%s makes integer '%T' from pointer '%T' without a cast",
1086 context, orig_type_left, orig_type_right);
1091 panic("invalid error value");
1095 /** Implements the rules from §6.5.16.1 */
1096 static assign_error_t semantic_assign(type_t *orig_type_left,
1097 const expression_t *const right)
1099 type_t *const orig_type_right = right->base.type;
1100 type_t *const type_left = skip_typeref(orig_type_left);
1101 type_t *const type_right = skip_typeref(orig_type_right);
1103 if (is_type_pointer(type_left)) {
1104 if (is_null_pointer_constant(right)) {
1105 return ASSIGN_SUCCESS;
1106 } else if (is_type_pointer(type_right)) {
1107 type_t *points_to_left
1108 = skip_typeref(type_left->pointer.points_to);
1109 type_t *points_to_right
1110 = skip_typeref(type_right->pointer.points_to);
1111 assign_error_t res = ASSIGN_SUCCESS;
1113 /* the left type has all qualifiers from the right type */
1114 unsigned missing_qualifiers
1115 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1116 if (missing_qualifiers != 0) {
1117 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1120 points_to_left = get_unqualified_type(points_to_left);
1121 points_to_right = get_unqualified_type(points_to_right);
1123 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1126 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1127 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1128 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1131 if (!types_compatible(points_to_left, points_to_right)) {
1132 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1136 } else if (is_type_integer(type_right)) {
1137 return ASSIGN_WARNING_POINTER_FROM_INT;
1139 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1140 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1141 && is_type_pointer(type_right))) {
1142 return ASSIGN_SUCCESS;
1143 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1144 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1145 type_t *const unqual_type_left = get_unqualified_type(type_left);
1146 type_t *const unqual_type_right = get_unqualified_type(type_right);
1147 if (types_compatible(unqual_type_left, unqual_type_right)) {
1148 return ASSIGN_SUCCESS;
1150 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1151 return ASSIGN_WARNING_INT_FROM_POINTER;
1154 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1155 return ASSIGN_SUCCESS;
1157 return ASSIGN_ERROR_INCOMPATIBLE;
1160 static expression_t *parse_constant_expression(void)
1162 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1164 if (!is_constant_expression(result)) {
1165 errorf(&result->base.source_position,
1166 "expression '%E' is not constant", result);
1172 static expression_t *parse_assignment_expression(void)
1174 return parse_sub_expression(PREC_ASSIGNMENT);
1177 static string_t parse_string_literals(void)
1179 assert(token.type == T_STRING_LITERAL);
1180 string_t result = token.v.string;
1184 while (token.type == T_STRING_LITERAL) {
1185 result = concat_strings(&result, &token.v.string);
1193 * compare two string, ignoring double underscores on the second.
1195 static int strcmp_underscore(const char *s1, const char *s2)
1197 if (s2[0] == '_' && s2[1] == '_') {
1198 size_t len2 = strlen(s2);
1199 size_t len1 = strlen(s1);
1200 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1201 return strncmp(s1, s2+2, len2-4);
1205 return strcmp(s1, s2);
1208 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1210 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1211 attribute->kind = kind;
1216 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1219 * __attribute__ ( ( attribute-list ) )
1223 * attribute_list , attrib
1228 * any-word ( identifier )
1229 * any-word ( identifier , nonempty-expr-list )
1230 * any-word ( expr-list )
1232 * where the "identifier" must not be declared as a type, and
1233 * "any-word" may be any identifier (including one declared as a
1234 * type), a reserved word storage class specifier, type specifier or
1235 * type qualifier. ??? This still leaves out most reserved keywords
1236 * (following the old parser), shouldn't we include them, and why not
1237 * allow identifiers declared as types to start the arguments?
1239 * Matze: this all looks confusing and little systematic, so we're even less
1240 * strict and parse any list of things which are identifiers or
1241 * (assignment-)expressions.
1243 static attribute_argument_t *parse_attribute_arguments(void)
1245 if (token.type == ')')
1248 attribute_argument_t *first = NULL;
1249 attribute_argument_t *last = NULL;
1251 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1253 /* is it an identifier */
1254 if (token.type == T_IDENTIFIER
1255 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1256 symbol_t *symbol = token.v.symbol;
1257 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1258 argument->v.symbol = symbol;
1261 /* must be an expression */
1262 expression_t *expression = parse_assignment_expression();
1264 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1265 argument->v.expression = expression;
1268 /* append argument */
1272 last->next = argument;
1276 if (token.type == ',') {
1280 expect(')', end_error);
1291 static attribute_t *parse_attribute_asm(void)
1295 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1297 expect('(', end_error);
1298 attribute->a.arguments = parse_attribute_arguments();
1305 static symbol_t *get_symbol_from_token(void)
1307 switch(token.type) {
1309 return token.v.symbol;
1338 /* maybe we need more tokens ... add them on demand */
1339 return get_token_symbol(&token);
1345 static attribute_t *parse_attribute_gnu_single(void)
1347 /* parse "any-word" */
1348 symbol_t *symbol = get_symbol_from_token();
1349 if (symbol == NULL) {
1350 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1354 const char *name = symbol->string;
1357 attribute_kind_t kind;
1358 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1359 const char *attribute_name = get_attribute_name(kind);
1360 if (attribute_name != NULL
1361 && strcmp_underscore(attribute_name, name) == 0)
1365 if (kind >= ATTRIBUTE_GNU_LAST) {
1366 if (warning.attribute) {
1367 warningf(HERE, "unknown attribute '%s' ignored", name);
1369 /* TODO: we should still save the attribute in the list... */
1370 kind = ATTRIBUTE_UNKNOWN;
1373 attribute_t *attribute = allocate_attribute_zero(kind);
1375 /* parse arguments */
1376 if (token.type == '(') {
1378 attribute->a.arguments = parse_attribute_arguments();
1387 static attribute_t *parse_attribute_gnu(void)
1389 attribute_t *first = NULL;
1390 attribute_t *last = NULL;
1392 eat(T___attribute__);
1393 expect('(', end_error);
1394 expect('(', end_error);
1396 if (token.type == ')') {
1398 expect(')', end_error);
1403 attribute_t *attribute = parse_attribute_gnu_single();
1404 if (attribute == NULL)
1410 last->next = attribute;
1414 if (token.type == ')') {
1418 expect(',', end_error);
1420 expect(')', end_error);
1426 /** Parse attributes. */
1427 static attribute_t *parse_attributes(attribute_t *first)
1429 attribute_t *last = first;
1432 while (last->next != NULL)
1436 attribute_t *attribute;
1437 switch (token.type) {
1438 case T___attribute__:
1439 attribute = parse_attribute_gnu();
1443 attribute = parse_attribute_asm();
1448 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1453 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1456 case T__forceinline:
1458 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1463 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1468 /* TODO record modifier */
1470 warningf(HERE, "Ignoring declaration modifier %K", &token);
1471 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1481 last->next = attribute;
1487 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1489 static entity_t *determine_lhs_ent(expression_t *const expr,
1492 switch (expr->kind) {
1493 case EXPR_REFERENCE: {
1494 entity_t *const entity = expr->reference.entity;
1495 /* we should only find variables as lvalues... */
1496 if (entity->base.kind != ENTITY_VARIABLE
1497 && entity->base.kind != ENTITY_PARAMETER)
1503 case EXPR_ARRAY_ACCESS: {
1504 expression_t *const ref = expr->array_access.array_ref;
1505 entity_t * ent = NULL;
1506 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1507 ent = determine_lhs_ent(ref, lhs_ent);
1510 mark_vars_read(expr->select.compound, lhs_ent);
1512 mark_vars_read(expr->array_access.index, lhs_ent);
1517 if (is_type_compound(skip_typeref(expr->base.type))) {
1518 return determine_lhs_ent(expr->select.compound, lhs_ent);
1520 mark_vars_read(expr->select.compound, lhs_ent);
1525 case EXPR_UNARY_DEREFERENCE: {
1526 expression_t *const val = expr->unary.value;
1527 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1529 return determine_lhs_ent(val->unary.value, lhs_ent);
1531 mark_vars_read(val, NULL);
1537 mark_vars_read(expr, NULL);
1542 #define ENT_ANY ((entity_t*)-1)
1545 * Mark declarations, which are read. This is used to detect variables, which
1549 * x is not marked as "read", because it is only read to calculate its own new
1553 * x and y are not detected as "not read", because multiple variables are
1556 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1558 switch (expr->kind) {
1559 case EXPR_REFERENCE: {
1560 entity_t *const entity = expr->reference.entity;
1561 if (entity->kind != ENTITY_VARIABLE
1562 && entity->kind != ENTITY_PARAMETER)
1565 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1566 if (entity->kind == ENTITY_VARIABLE) {
1567 entity->variable.read = true;
1569 entity->parameter.read = true;
1576 // TODO respect pure/const
1577 mark_vars_read(expr->call.function, NULL);
1578 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1579 mark_vars_read(arg->expression, NULL);
1583 case EXPR_CONDITIONAL:
1584 // TODO lhs_decl should depend on whether true/false have an effect
1585 mark_vars_read(expr->conditional.condition, NULL);
1586 if (expr->conditional.true_expression != NULL)
1587 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1588 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1592 if (lhs_ent == ENT_ANY
1593 && !is_type_compound(skip_typeref(expr->base.type)))
1595 mark_vars_read(expr->select.compound, lhs_ent);
1598 case EXPR_ARRAY_ACCESS: {
1599 expression_t *const ref = expr->array_access.array_ref;
1600 mark_vars_read(ref, lhs_ent);
1601 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1602 mark_vars_read(expr->array_access.index, lhs_ent);
1607 mark_vars_read(expr->va_arge.ap, lhs_ent);
1611 mark_vars_read(expr->va_copye.src, lhs_ent);
1614 case EXPR_UNARY_CAST:
1615 /* Special case: Use void cast to mark a variable as "read" */
1616 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1621 case EXPR_UNARY_THROW:
1622 if (expr->unary.value == NULL)
1625 case EXPR_UNARY_DEREFERENCE:
1626 case EXPR_UNARY_DELETE:
1627 case EXPR_UNARY_DELETE_ARRAY:
1628 if (lhs_ent == ENT_ANY)
1632 case EXPR_UNARY_NEGATE:
1633 case EXPR_UNARY_PLUS:
1634 case EXPR_UNARY_BITWISE_NEGATE:
1635 case EXPR_UNARY_NOT:
1636 case EXPR_UNARY_TAKE_ADDRESS:
1637 case EXPR_UNARY_POSTFIX_INCREMENT:
1638 case EXPR_UNARY_POSTFIX_DECREMENT:
1639 case EXPR_UNARY_PREFIX_INCREMENT:
1640 case EXPR_UNARY_PREFIX_DECREMENT:
1641 case EXPR_UNARY_CAST_IMPLICIT:
1642 case EXPR_UNARY_ASSUME:
1644 mark_vars_read(expr->unary.value, lhs_ent);
1647 case EXPR_BINARY_ADD:
1648 case EXPR_BINARY_SUB:
1649 case EXPR_BINARY_MUL:
1650 case EXPR_BINARY_DIV:
1651 case EXPR_BINARY_MOD:
1652 case EXPR_BINARY_EQUAL:
1653 case EXPR_BINARY_NOTEQUAL:
1654 case EXPR_BINARY_LESS:
1655 case EXPR_BINARY_LESSEQUAL:
1656 case EXPR_BINARY_GREATER:
1657 case EXPR_BINARY_GREATEREQUAL:
1658 case EXPR_BINARY_BITWISE_AND:
1659 case EXPR_BINARY_BITWISE_OR:
1660 case EXPR_BINARY_BITWISE_XOR:
1661 case EXPR_BINARY_LOGICAL_AND:
1662 case EXPR_BINARY_LOGICAL_OR:
1663 case EXPR_BINARY_SHIFTLEFT:
1664 case EXPR_BINARY_SHIFTRIGHT:
1665 case EXPR_BINARY_COMMA:
1666 case EXPR_BINARY_ISGREATER:
1667 case EXPR_BINARY_ISGREATEREQUAL:
1668 case EXPR_BINARY_ISLESS:
1669 case EXPR_BINARY_ISLESSEQUAL:
1670 case EXPR_BINARY_ISLESSGREATER:
1671 case EXPR_BINARY_ISUNORDERED:
1672 mark_vars_read(expr->binary.left, lhs_ent);
1673 mark_vars_read(expr->binary.right, lhs_ent);
1676 case EXPR_BINARY_ASSIGN:
1677 case EXPR_BINARY_MUL_ASSIGN:
1678 case EXPR_BINARY_DIV_ASSIGN:
1679 case EXPR_BINARY_MOD_ASSIGN:
1680 case EXPR_BINARY_ADD_ASSIGN:
1681 case EXPR_BINARY_SUB_ASSIGN:
1682 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1683 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1684 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1685 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1686 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1687 if (lhs_ent == ENT_ANY)
1689 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1690 mark_vars_read(expr->binary.right, lhs_ent);
1695 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1701 case EXPR_CHARACTER_CONSTANT:
1702 case EXPR_WIDE_CHARACTER_CONSTANT:
1703 case EXPR_STRING_LITERAL:
1704 case EXPR_WIDE_STRING_LITERAL:
1705 case EXPR_COMPOUND_LITERAL: // TODO init?
1707 case EXPR_CLASSIFY_TYPE:
1710 case EXPR_BUILTIN_CONSTANT_P:
1711 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1713 case EXPR_STATEMENT: // TODO
1714 case EXPR_LABEL_ADDRESS:
1715 case EXPR_REFERENCE_ENUM_VALUE:
1719 panic("unhandled expression");
1722 static designator_t *parse_designation(void)
1724 designator_t *result = NULL;
1725 designator_t *last = NULL;
1728 designator_t *designator;
1729 switch (token.type) {
1731 designator = allocate_ast_zero(sizeof(designator[0]));
1732 designator->source_position = token.source_position;
1734 add_anchor_token(']');
1735 designator->array_index = parse_constant_expression();
1736 rem_anchor_token(']');
1737 expect(']', end_error);
1740 designator = allocate_ast_zero(sizeof(designator[0]));
1741 designator->source_position = token.source_position;
1743 if (token.type != T_IDENTIFIER) {
1744 parse_error_expected("while parsing designator",
1745 T_IDENTIFIER, NULL);
1748 designator->symbol = token.v.symbol;
1752 expect('=', end_error);
1756 assert(designator != NULL);
1758 last->next = designator;
1760 result = designator;
1768 static initializer_t *initializer_from_string(array_type_t *type,
1769 const string_t *const string)
1771 /* TODO: check len vs. size of array type */
1774 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1775 initializer->string.string = *string;
1780 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1781 wide_string_t *const string)
1783 /* TODO: check len vs. size of array type */
1786 initializer_t *const initializer =
1787 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1788 initializer->wide_string.string = *string;
1794 * Build an initializer from a given expression.
1796 static initializer_t *initializer_from_expression(type_t *orig_type,
1797 expression_t *expression)
1799 /* TODO check that expression is a constant expression */
1801 /* §6.7.8.14/15 char array may be initialized by string literals */
1802 type_t *type = skip_typeref(orig_type);
1803 type_t *expr_type_orig = expression->base.type;
1804 type_t *expr_type = skip_typeref(expr_type_orig);
1805 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1806 array_type_t *const array_type = &type->array;
1807 type_t *const element_type = skip_typeref(array_type->element_type);
1809 if (element_type->kind == TYPE_ATOMIC) {
1810 atomic_type_kind_t akind = element_type->atomic.akind;
1811 switch (expression->kind) {
1812 case EXPR_STRING_LITERAL:
1813 if (akind == ATOMIC_TYPE_CHAR
1814 || akind == ATOMIC_TYPE_SCHAR
1815 || akind == ATOMIC_TYPE_UCHAR) {
1816 return initializer_from_string(array_type,
1817 &expression->string.value);
1821 case EXPR_WIDE_STRING_LITERAL: {
1822 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1823 if (get_unqualified_type(element_type) == bare_wchar_type) {
1824 return initializer_from_wide_string(array_type,
1825 &expression->wide_string.value);
1836 assign_error_t error = semantic_assign(type, expression);
1837 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1839 report_assign_error(error, type, expression, "initializer",
1840 &expression->base.source_position);
1842 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1844 if (type->kind == TYPE_BITFIELD) {
1845 type = type->bitfield.base_type;
1848 result->value.value = create_implicit_cast(expression, type);
1854 * Checks if a given expression can be used as an constant initializer.
1856 static bool is_initializer_constant(const expression_t *expression)
1858 return is_constant_expression(expression)
1859 || is_address_constant(expression);
1863 * Parses an scalar initializer.
1865 * §6.7.8.11; eat {} without warning
1867 static initializer_t *parse_scalar_initializer(type_t *type,
1868 bool must_be_constant)
1870 /* there might be extra {} hierarchies */
1872 if (token.type == '{') {
1874 warningf(HERE, "extra curly braces around scalar initializer");
1878 } while (token.type == '{');
1881 expression_t *expression = parse_assignment_expression();
1882 mark_vars_read(expression, NULL);
1883 if (must_be_constant && !is_initializer_constant(expression)) {
1884 errorf(&expression->base.source_position,
1885 "Initialisation expression '%E' is not constant",
1889 initializer_t *initializer = initializer_from_expression(type, expression);
1891 if (initializer == NULL) {
1892 errorf(&expression->base.source_position,
1893 "expression '%E' (type '%T') doesn't match expected type '%T'",
1894 expression, expression->base.type, type);
1899 bool additional_warning_displayed = false;
1900 while (braces > 0) {
1901 if (token.type == ',') {
1904 if (token.type != '}') {
1905 if (!additional_warning_displayed && warning.other) {
1906 warningf(HERE, "additional elements in scalar initializer");
1907 additional_warning_displayed = true;
1918 * An entry in the type path.
1920 typedef struct type_path_entry_t type_path_entry_t;
1921 struct type_path_entry_t {
1922 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1924 size_t index; /**< For array types: the current index. */
1925 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1930 * A type path expression a position inside compound or array types.
1932 typedef struct type_path_t type_path_t;
1933 struct type_path_t {
1934 type_path_entry_t *path; /**< An flexible array containing the current path. */
1935 type_t *top_type; /**< type of the element the path points */
1936 size_t max_index; /**< largest index in outermost array */
1940 * Prints a type path for debugging.
1942 static __attribute__((unused)) void debug_print_type_path(
1943 const type_path_t *path)
1945 size_t len = ARR_LEN(path->path);
1947 for (size_t i = 0; i < len; ++i) {
1948 const type_path_entry_t *entry = & path->path[i];
1950 type_t *type = skip_typeref(entry->type);
1951 if (is_type_compound(type)) {
1952 /* in gcc mode structs can have no members */
1953 if (entry->v.compound_entry == NULL) {
1957 fprintf(stderr, ".%s",
1958 entry->v.compound_entry->base.symbol->string);
1959 } else if (is_type_array(type)) {
1960 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1962 fprintf(stderr, "-INVALID-");
1965 if (path->top_type != NULL) {
1966 fprintf(stderr, " (");
1967 print_type(path->top_type);
1968 fprintf(stderr, ")");
1973 * Return the top type path entry, ie. in a path
1974 * (type).a.b returns the b.
1976 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1978 size_t len = ARR_LEN(path->path);
1980 return &path->path[len-1];
1984 * Enlarge the type path by an (empty) element.
1986 static type_path_entry_t *append_to_type_path(type_path_t *path)
1988 size_t len = ARR_LEN(path->path);
1989 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1991 type_path_entry_t *result = & path->path[len];
1992 memset(result, 0, sizeof(result[0]));
1997 * Descending into a sub-type. Enter the scope of the current top_type.
1999 static void descend_into_subtype(type_path_t *path)
2001 type_t *orig_top_type = path->top_type;
2002 type_t *top_type = skip_typeref(orig_top_type);
2004 type_path_entry_t *top = append_to_type_path(path);
2005 top->type = top_type;
2007 if (is_type_compound(top_type)) {
2008 compound_t *compound = top_type->compound.compound;
2009 entity_t *entry = compound->members.entities;
2011 if (entry != NULL) {
2012 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2013 top->v.compound_entry = &entry->declaration;
2014 path->top_type = entry->declaration.type;
2016 path->top_type = NULL;
2018 } else if (is_type_array(top_type)) {
2020 path->top_type = top_type->array.element_type;
2022 assert(!is_type_valid(top_type));
2027 * Pop an entry from the given type path, ie. returning from
2028 * (type).a.b to (type).a
2030 static void ascend_from_subtype(type_path_t *path)
2032 type_path_entry_t *top = get_type_path_top(path);
2034 path->top_type = top->type;
2036 size_t len = ARR_LEN(path->path);
2037 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2041 * Pop entries from the given type path until the given
2042 * path level is reached.
2044 static void ascend_to(type_path_t *path, size_t top_path_level)
2046 size_t len = ARR_LEN(path->path);
2048 while (len > top_path_level) {
2049 ascend_from_subtype(path);
2050 len = ARR_LEN(path->path);
2054 static bool walk_designator(type_path_t *path, const designator_t *designator,
2055 bool used_in_offsetof)
2057 for (; designator != NULL; designator = designator->next) {
2058 type_path_entry_t *top = get_type_path_top(path);
2059 type_t *orig_type = top->type;
2061 type_t *type = skip_typeref(orig_type);
2063 if (designator->symbol != NULL) {
2064 symbol_t *symbol = designator->symbol;
2065 if (!is_type_compound(type)) {
2066 if (is_type_valid(type)) {
2067 errorf(&designator->source_position,
2068 "'.%Y' designator used for non-compound type '%T'",
2072 top->type = type_error_type;
2073 top->v.compound_entry = NULL;
2074 orig_type = type_error_type;
2076 compound_t *compound = type->compound.compound;
2077 entity_t *iter = compound->members.entities;
2078 for (; iter != NULL; iter = iter->base.next) {
2079 if (iter->base.symbol == symbol) {
2084 errorf(&designator->source_position,
2085 "'%T' has no member named '%Y'", orig_type, symbol);
2088 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2089 if (used_in_offsetof) {
2090 type_t *real_type = skip_typeref(iter->declaration.type);
2091 if (real_type->kind == TYPE_BITFIELD) {
2092 errorf(&designator->source_position,
2093 "offsetof designator '%Y' may not specify bitfield",
2099 top->type = orig_type;
2100 top->v.compound_entry = &iter->declaration;
2101 orig_type = iter->declaration.type;
2104 expression_t *array_index = designator->array_index;
2105 assert(designator->array_index != NULL);
2107 if (!is_type_array(type)) {
2108 if (is_type_valid(type)) {
2109 errorf(&designator->source_position,
2110 "[%E] designator used for non-array type '%T'",
2111 array_index, orig_type);
2116 long index = fold_constant_to_int(array_index);
2117 if (!used_in_offsetof) {
2119 errorf(&designator->source_position,
2120 "array index [%E] must be positive", array_index);
2121 } else if (type->array.size_constant) {
2122 long array_size = type->array.size;
2123 if (index >= array_size) {
2124 errorf(&designator->source_position,
2125 "designator [%E] (%d) exceeds array size %d",
2126 array_index, index, array_size);
2131 top->type = orig_type;
2132 top->v.index = (size_t) index;
2133 orig_type = type->array.element_type;
2135 path->top_type = orig_type;
2137 if (designator->next != NULL) {
2138 descend_into_subtype(path);
2147 static void advance_current_object(type_path_t *path, size_t top_path_level)
2149 type_path_entry_t *top = get_type_path_top(path);
2151 type_t *type = skip_typeref(top->type);
2152 if (is_type_union(type)) {
2153 /* in unions only the first element is initialized */
2154 top->v.compound_entry = NULL;
2155 } else if (is_type_struct(type)) {
2156 declaration_t *entry = top->v.compound_entry;
2158 entity_t *next_entity = entry->base.next;
2159 if (next_entity != NULL) {
2160 assert(is_declaration(next_entity));
2161 entry = &next_entity->declaration;
2166 top->v.compound_entry = entry;
2167 if (entry != NULL) {
2168 path->top_type = entry->type;
2171 } else if (is_type_array(type)) {
2172 assert(is_type_array(type));
2176 if (!type->array.size_constant || top->v.index < type->array.size) {
2180 assert(!is_type_valid(type));
2184 /* we're past the last member of the current sub-aggregate, try if we
2185 * can ascend in the type hierarchy and continue with another subobject */
2186 size_t len = ARR_LEN(path->path);
2188 if (len > top_path_level) {
2189 ascend_from_subtype(path);
2190 advance_current_object(path, top_path_level);
2192 path->top_type = NULL;
2197 * skip any {...} blocks until a closing bracket is reached.
2199 static void skip_initializers(void)
2201 if (token.type == '{')
2204 while (token.type != '}') {
2205 if (token.type == T_EOF)
2207 if (token.type == '{') {
2215 static initializer_t *create_empty_initializer(void)
2217 static initializer_t empty_initializer
2218 = { .list = { { INITIALIZER_LIST }, 0 } };
2219 return &empty_initializer;
2223 * Parse a part of an initialiser for a struct or union,
2225 static initializer_t *parse_sub_initializer(type_path_t *path,
2226 type_t *outer_type, size_t top_path_level,
2227 parse_initializer_env_t *env)
2229 if (token.type == '}') {
2230 /* empty initializer */
2231 return create_empty_initializer();
2234 type_t *orig_type = path->top_type;
2235 type_t *type = NULL;
2237 if (orig_type == NULL) {
2238 /* We are initializing an empty compound. */
2240 type = skip_typeref(orig_type);
2243 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2246 designator_t *designator = NULL;
2247 if (token.type == '.' || token.type == '[') {
2248 designator = parse_designation();
2249 goto finish_designator;
2250 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2251 /* GNU-style designator ("identifier: value") */
2252 designator = allocate_ast_zero(sizeof(designator[0]));
2253 designator->source_position = token.source_position;
2254 designator->symbol = token.v.symbol;
2259 /* reset path to toplevel, evaluate designator from there */
2260 ascend_to(path, top_path_level);
2261 if (!walk_designator(path, designator, false)) {
2262 /* can't continue after designation error */
2266 initializer_t *designator_initializer
2267 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2268 designator_initializer->designator.designator = designator;
2269 ARR_APP1(initializer_t*, initializers, designator_initializer);
2271 orig_type = path->top_type;
2272 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2277 if (token.type == '{') {
2278 if (type != NULL && is_type_scalar(type)) {
2279 sub = parse_scalar_initializer(type, env->must_be_constant);
2283 if (env->entity != NULL) {
2285 "extra brace group at end of initializer for '%Y'",
2286 env->entity->base.symbol);
2288 errorf(HERE, "extra brace group at end of initializer");
2291 descend_into_subtype(path);
2293 add_anchor_token('}');
2294 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2296 rem_anchor_token('}');
2299 ascend_from_subtype(path);
2300 expect('}', end_error);
2302 expect('}', end_error);
2303 goto error_parse_next;
2307 /* must be an expression */
2308 expression_t *expression = parse_assignment_expression();
2309 mark_vars_read(expression, NULL);
2311 if (env->must_be_constant && !is_initializer_constant(expression)) {
2312 errorf(&expression->base.source_position,
2313 "Initialisation expression '%E' is not constant",
2318 /* we are already outside, ... */
2319 type_t *const outer_type_skip = skip_typeref(outer_type);
2320 if (is_type_compound(outer_type_skip) &&
2321 !outer_type_skip->compound.compound->complete) {
2322 goto error_parse_next;
2327 /* handle { "string" } special case */
2328 if ((expression->kind == EXPR_STRING_LITERAL
2329 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2330 && outer_type != NULL) {
2331 sub = initializer_from_expression(outer_type, expression);
2333 if (token.type == ',') {
2336 if (token.type != '}' && warning.other) {
2337 warningf(HERE, "excessive elements in initializer for type '%T'",
2340 /* TODO: eat , ... */
2345 /* descend into subtypes until expression matches type */
2347 orig_type = path->top_type;
2348 type = skip_typeref(orig_type);
2350 sub = initializer_from_expression(orig_type, expression);
2354 if (!is_type_valid(type)) {
2357 if (is_type_scalar(type)) {
2358 errorf(&expression->base.source_position,
2359 "expression '%E' doesn't match expected type '%T'",
2360 expression, orig_type);
2364 descend_into_subtype(path);
2368 /* update largest index of top array */
2369 const type_path_entry_t *first = &path->path[0];
2370 type_t *first_type = first->type;
2371 first_type = skip_typeref(first_type);
2372 if (is_type_array(first_type)) {
2373 size_t index = first->v.index;
2374 if (index > path->max_index)
2375 path->max_index = index;
2379 /* append to initializers list */
2380 ARR_APP1(initializer_t*, initializers, sub);
2383 if (warning.other) {
2384 if (env->entity != NULL) {
2385 warningf(HERE, "excess elements in struct initializer for '%Y'",
2386 env->entity->base.symbol);
2388 warningf(HERE, "excess elements in struct initializer");
2394 if (token.type == '}') {
2397 expect(',', end_error);
2398 if (token.type == '}') {
2403 /* advance to the next declaration if we are not at the end */
2404 advance_current_object(path, top_path_level);
2405 orig_type = path->top_type;
2406 if (orig_type != NULL)
2407 type = skip_typeref(orig_type);
2413 size_t len = ARR_LEN(initializers);
2414 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2415 initializer_t *result = allocate_ast_zero(size);
2416 result->kind = INITIALIZER_LIST;
2417 result->list.len = len;
2418 memcpy(&result->list.initializers, initializers,
2419 len * sizeof(initializers[0]));
2421 DEL_ARR_F(initializers);
2422 ascend_to(path, top_path_level+1);
2427 skip_initializers();
2428 DEL_ARR_F(initializers);
2429 ascend_to(path, top_path_level+1);
2434 * Parses an initializer. Parsers either a compound literal
2435 * (env->declaration == NULL) or an initializer of a declaration.
2437 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2439 type_t *type = skip_typeref(env->type);
2440 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2441 initializer_t *result;
2443 if (is_type_scalar(type)) {
2444 result = parse_scalar_initializer(type, env->must_be_constant);
2445 } else if (token.type == '{') {
2449 memset(&path, 0, sizeof(path));
2450 path.top_type = env->type;
2451 path.path = NEW_ARR_F(type_path_entry_t, 0);
2453 descend_into_subtype(&path);
2455 add_anchor_token('}');
2456 result = parse_sub_initializer(&path, env->type, 1, env);
2457 rem_anchor_token('}');
2459 max_index = path.max_index;
2460 DEL_ARR_F(path.path);
2462 expect('}', end_error);
2464 /* parse_scalar_initializer() also works in this case: we simply
2465 * have an expression without {} around it */
2466 result = parse_scalar_initializer(type, env->must_be_constant);
2469 /* §6.7.8:22 array initializers for arrays with unknown size determine
2470 * the array type size */
2471 if (is_type_array(type) && type->array.size_expression == NULL
2472 && result != NULL) {
2474 switch (result->kind) {
2475 case INITIALIZER_LIST:
2476 assert(max_index != 0xdeadbeaf);
2477 size = max_index + 1;
2480 case INITIALIZER_STRING:
2481 size = result->string.string.size;
2484 case INITIALIZER_WIDE_STRING:
2485 size = result->wide_string.string.size;
2488 case INITIALIZER_DESIGNATOR:
2489 case INITIALIZER_VALUE:
2490 /* can happen for parse errors */
2495 internal_errorf(HERE, "invalid initializer type");
2498 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2499 cnst->base.type = type_size_t;
2500 cnst->conste.v.int_value = size;
2502 type_t *new_type = duplicate_type(type);
2504 new_type->array.size_expression = cnst;
2505 new_type->array.size_constant = true;
2506 new_type->array.has_implicit_size = true;
2507 new_type->array.size = size;
2508 env->type = new_type;
2516 static void append_entity(scope_t *scope, entity_t *entity)
2518 if (scope->last_entity != NULL) {
2519 scope->last_entity->base.next = entity;
2521 scope->entities = entity;
2523 scope->last_entity = entity;
2527 static compound_t *parse_compound_type_specifier(bool is_struct)
2535 symbol_t *symbol = NULL;
2536 compound_t *compound = NULL;
2537 attribute_t *attributes = NULL;
2539 if (token.type == T___attribute__) {
2540 attributes = parse_attributes(NULL);
2543 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2544 if (token.type == T_IDENTIFIER) {
2545 /* the compound has a name, check if we have seen it already */
2546 symbol = token.v.symbol;
2549 entity_t *entity = get_tag(symbol, kind);
2550 if (entity != NULL) {
2551 compound = &entity->compound;
2552 if (compound->base.parent_scope != current_scope &&
2553 (token.type == '{' || token.type == ';')) {
2554 /* we're in an inner scope and have a definition. Shadow
2555 * existing definition in outer scope */
2557 } else if (compound->complete && token.type == '{') {
2558 assert(symbol != NULL);
2559 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2560 is_struct ? "struct" : "union", symbol,
2561 &compound->base.source_position);
2562 /* clear members in the hope to avoid further errors */
2563 compound->members.entities = NULL;
2566 } else if (token.type != '{') {
2568 parse_error_expected("while parsing struct type specifier",
2569 T_IDENTIFIER, '{', NULL);
2571 parse_error_expected("while parsing union type specifier",
2572 T_IDENTIFIER, '{', NULL);
2578 if (compound == NULL) {
2579 entity_t *entity = allocate_entity_zero(kind);
2580 compound = &entity->compound;
2582 compound->alignment = 1;
2583 compound->base.namespc = NAMESPACE_TAG;
2584 compound->base.source_position = token.source_position;
2585 compound->base.symbol = symbol;
2586 compound->base.parent_scope = current_scope;
2587 if (symbol != NULL) {
2588 environment_push(entity);
2590 append_entity(current_scope, entity);
2593 if (token.type == '{') {
2594 parse_compound_type_entries(compound);
2596 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2597 if (symbol == NULL) {
2598 assert(anonymous_entity == NULL);
2599 anonymous_entity = (entity_t*)compound;
2603 if (attributes != NULL) {
2604 handle_entity_attributes(attributes, (entity_t*) compound);
2610 static void parse_enum_entries(type_t *const enum_type)
2614 if (token.type == '}') {
2615 errorf(HERE, "empty enum not allowed");
2620 add_anchor_token('}');
2622 if (token.type != T_IDENTIFIER) {
2623 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2625 rem_anchor_token('}');
2629 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2630 entity->enum_value.enum_type = enum_type;
2631 entity->base.symbol = token.v.symbol;
2632 entity->base.source_position = token.source_position;
2635 if (token.type == '=') {
2637 expression_t *value = parse_constant_expression();
2639 value = create_implicit_cast(value, enum_type);
2640 entity->enum_value.value = value;
2645 record_entity(entity, false);
2647 if (token.type != ',')
2650 } while (token.type != '}');
2651 rem_anchor_token('}');
2653 expect('}', end_error);
2659 static type_t *parse_enum_specifier(void)
2665 if (token.type == T_IDENTIFIER) {
2666 symbol = token.v.symbol;
2669 entity = get_tag(symbol, ENTITY_ENUM);
2670 if (entity != NULL) {
2671 if (entity->base.parent_scope != current_scope &&
2672 (token.type == '{' || token.type == ';')) {
2673 /* we're in an inner scope and have a definition. Shadow
2674 * existing definition in outer scope */
2676 } else if (entity->enume.complete && token.type == '{') {
2677 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2678 symbol, &entity->base.source_position);
2681 } else if (token.type != '{') {
2682 parse_error_expected("while parsing enum type specifier",
2683 T_IDENTIFIER, '{', NULL);
2690 if (entity == NULL) {
2691 entity = allocate_entity_zero(ENTITY_ENUM);
2692 entity->base.namespc = NAMESPACE_TAG;
2693 entity->base.source_position = token.source_position;
2694 entity->base.symbol = symbol;
2695 entity->base.parent_scope = current_scope;
2698 type_t *const type = allocate_type_zero(TYPE_ENUM);
2699 type->enumt.enume = &entity->enume;
2700 type->enumt.akind = ATOMIC_TYPE_INT;
2702 if (token.type == '{') {
2703 if (symbol != NULL) {
2704 environment_push(entity);
2706 append_entity(current_scope, entity);
2707 entity->enume.complete = true;
2709 parse_enum_entries(type);
2710 parse_attributes(NULL);
2712 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2713 if (symbol == NULL) {
2714 assert(anonymous_entity == NULL);
2715 anonymous_entity = entity;
2717 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2718 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2726 * if a symbol is a typedef to another type, return true
2728 static bool is_typedef_symbol(symbol_t *symbol)
2730 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2731 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2734 static type_t *parse_typeof(void)
2740 expect('(', end_error);
2741 add_anchor_token(')');
2743 expression_t *expression = NULL;
2745 bool old_type_prop = in_type_prop;
2746 bool old_gcc_extension = in_gcc_extension;
2747 in_type_prop = true;
2749 while (token.type == T___extension__) {
2750 /* This can be a prefix to a typename or an expression. */
2752 in_gcc_extension = true;
2754 switch (token.type) {
2756 if (is_typedef_symbol(token.v.symbol)) {
2757 type = parse_typename();
2759 expression = parse_expression();
2760 type = revert_automatic_type_conversion(expression);
2765 type = parse_typename();
2769 expression = parse_expression();
2770 type = expression->base.type;
2773 in_type_prop = old_type_prop;
2774 in_gcc_extension = old_gcc_extension;
2776 rem_anchor_token(')');
2777 expect(')', end_error);
2779 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2780 typeof_type->typeoft.expression = expression;
2781 typeof_type->typeoft.typeof_type = type;
2788 typedef enum specifiers_t {
2789 SPECIFIER_SIGNED = 1 << 0,
2790 SPECIFIER_UNSIGNED = 1 << 1,
2791 SPECIFIER_LONG = 1 << 2,
2792 SPECIFIER_INT = 1 << 3,
2793 SPECIFIER_DOUBLE = 1 << 4,
2794 SPECIFIER_CHAR = 1 << 5,
2795 SPECIFIER_WCHAR_T = 1 << 6,
2796 SPECIFIER_SHORT = 1 << 7,
2797 SPECIFIER_LONG_LONG = 1 << 8,
2798 SPECIFIER_FLOAT = 1 << 9,
2799 SPECIFIER_BOOL = 1 << 10,
2800 SPECIFIER_VOID = 1 << 11,
2801 SPECIFIER_INT8 = 1 << 12,
2802 SPECIFIER_INT16 = 1 << 13,
2803 SPECIFIER_INT32 = 1 << 14,
2804 SPECIFIER_INT64 = 1 << 15,
2805 SPECIFIER_INT128 = 1 << 16,
2806 SPECIFIER_COMPLEX = 1 << 17,
2807 SPECIFIER_IMAGINARY = 1 << 18,
2810 static type_t *create_builtin_type(symbol_t *const symbol,
2811 type_t *const real_type)
2813 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2814 type->builtin.symbol = symbol;
2815 type->builtin.real_type = real_type;
2816 return identify_new_type(type);
2819 static type_t *get_typedef_type(symbol_t *symbol)
2821 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2822 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2825 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2826 type->typedeft.typedefe = &entity->typedefe;
2831 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2833 expect('(', end_error);
2835 attribute_property_argument_t *property
2836 = allocate_ast_zero(sizeof(*property));
2839 if (token.type != T_IDENTIFIER) {
2840 parse_error_expected("while parsing property declspec",
2841 T_IDENTIFIER, NULL);
2846 symbol_t *symbol = token.v.symbol;
2848 if (strcmp(symbol->string, "put") == 0) {
2850 } else if (strcmp(symbol->string, "get") == 0) {
2853 errorf(HERE, "expected put or get in property declspec");
2856 expect('=', end_error);
2857 if (token.type != T_IDENTIFIER) {
2858 parse_error_expected("while parsing property declspec",
2859 T_IDENTIFIER, NULL);
2863 property->put_symbol = token.v.symbol;
2865 property->get_symbol = token.v.symbol;
2868 if (token.type == ')')
2870 expect(',', end_error);
2873 attribute->a.property = property;
2875 expect(')', end_error);
2881 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2883 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2884 if (token.type == T_restrict) {
2885 kind = ATTRIBUTE_MS_RESTRICT;
2887 } else if (token.type == T_IDENTIFIER) {
2888 const char *name = token.v.symbol->string;
2890 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2892 const char *attribute_name = get_attribute_name(k);
2893 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2899 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2900 warningf(HERE, "unknown __declspec '%s' ignored", name);
2903 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2907 attribute_t *attribute = allocate_attribute_zero(kind);
2909 if (kind == ATTRIBUTE_MS_PROPERTY) {
2910 return parse_attribute_ms_property(attribute);
2913 /* parse arguments */
2914 if (token.type == '(') {
2916 attribute->a.arguments = parse_attribute_arguments();
2922 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2926 expect('(', end_error);
2928 if (token.type == ')') {
2933 add_anchor_token(')');
2935 attribute_t *last = first;
2938 while (last->next != NULL)
2942 attribute_t *attribute
2943 = parse_microsoft_extended_decl_modifier_single();
2944 if (attribute == NULL)
2950 last->next = attribute;
2954 if (token.type == ')') {
2957 expect(',', end_error);
2960 rem_anchor_token(')');
2961 expect(')', end_error);
2965 rem_anchor_token(')');
2969 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2971 entity_t *entity = allocate_entity_zero(kind);
2972 entity->base.source_position = *HERE;
2973 entity->base.symbol = symbol;
2974 if (is_declaration(entity)) {
2975 entity->declaration.type = type_error_type;
2976 entity->declaration.implicit = true;
2977 } else if (kind == ENTITY_TYPEDEF) {
2978 entity->typedefe.type = type_error_type;
2979 entity->typedefe.builtin = true;
2981 if (kind != ENTITY_COMPOUND_MEMBER)
2982 record_entity(entity, false);
2986 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2988 type_t *type = NULL;
2989 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2990 unsigned type_specifiers = 0;
2991 bool newtype = false;
2992 bool saw_error = false;
2993 bool old_gcc_extension = in_gcc_extension;
2995 specifiers->source_position = token.source_position;
2998 specifiers->attributes = parse_attributes(specifiers->attributes);
3000 switch (token.type) {
3002 #define MATCH_STORAGE_CLASS(token, class) \
3004 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3005 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3007 specifiers->storage_class = class; \
3008 if (specifiers->thread_local) \
3009 goto check_thread_storage_class; \
3013 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3014 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3015 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3016 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3017 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3020 specifiers->attributes
3021 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
3025 if (specifiers->thread_local) {
3026 errorf(HERE, "duplicate '__thread'");
3028 specifiers->thread_local = true;
3029 check_thread_storage_class:
3030 switch (specifiers->storage_class) {
3031 case STORAGE_CLASS_EXTERN:
3032 case STORAGE_CLASS_NONE:
3033 case STORAGE_CLASS_STATIC:
3037 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3038 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3039 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3040 wrong_thread_stoarge_class:
3041 errorf(HERE, "'__thread' used with '%s'", wrong);
3048 /* type qualifiers */
3049 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3051 qualifiers |= qualifier; \
3055 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3056 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3057 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3058 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3059 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3060 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3061 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3062 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3064 case T___extension__:
3066 in_gcc_extension = true;
3069 /* type specifiers */
3070 #define MATCH_SPECIFIER(token, specifier, name) \
3072 if (type_specifiers & specifier) { \
3073 errorf(HERE, "multiple " name " type specifiers given"); \
3075 type_specifiers |= specifier; \
3080 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3081 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3082 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3083 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3084 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3085 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3086 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3087 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3088 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3089 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3090 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3091 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3092 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3093 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3094 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3095 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3096 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3097 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3101 specifiers->is_inline = true;
3105 case T__forceinline:
3107 specifiers->modifiers |= DM_FORCEINLINE;
3112 if (type_specifiers & SPECIFIER_LONG_LONG) {
3113 errorf(HERE, "multiple type specifiers given");
3114 } else if (type_specifiers & SPECIFIER_LONG) {
3115 type_specifiers |= SPECIFIER_LONG_LONG;
3117 type_specifiers |= SPECIFIER_LONG;
3122 #define CHECK_DOUBLE_TYPE() \
3123 if ( type != NULL) \
3124 errorf(HERE, "multiple data types in declaration specifiers");
3127 CHECK_DOUBLE_TYPE();
3128 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3130 type->compound.compound = parse_compound_type_specifier(true);
3133 CHECK_DOUBLE_TYPE();
3134 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3135 type->compound.compound = parse_compound_type_specifier(false);
3138 CHECK_DOUBLE_TYPE();
3139 type = parse_enum_specifier();
3142 CHECK_DOUBLE_TYPE();
3143 type = parse_typeof();
3145 case T___builtin_va_list:
3146 CHECK_DOUBLE_TYPE();
3147 type = duplicate_type(type_valist);
3151 case T_IDENTIFIER: {
3152 /* only parse identifier if we haven't found a type yet */
3153 if (type != NULL || type_specifiers != 0) {
3154 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3155 * declaration, so it doesn't generate errors about expecting '(' or
3157 switch (look_ahead(1)->type) {
3164 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3168 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3173 goto finish_specifiers;
3177 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3178 if (typedef_type == NULL) {
3179 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3180 * declaration, so it doesn't generate 'implicit int' followed by more
3181 * errors later on. */
3182 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3188 errorf(HERE, "%K does not name a type", &token);
3191 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3193 type = allocate_type_zero(TYPE_TYPEDEF);
3194 type->typedeft.typedefe = &entity->typedefe;
3198 if (la1_type == '&' || la1_type == '*')
3199 goto finish_specifiers;
3204 goto finish_specifiers;
3209 type = typedef_type;
3213 /* function specifier */
3215 goto finish_specifiers;
3220 specifiers->attributes = parse_attributes(specifiers->attributes);
3222 in_gcc_extension = old_gcc_extension;
3224 if (type == NULL || (saw_error && type_specifiers != 0)) {
3225 atomic_type_kind_t atomic_type;
3227 /* match valid basic types */
3228 switch (type_specifiers) {
3229 case SPECIFIER_VOID:
3230 atomic_type = ATOMIC_TYPE_VOID;
3232 case SPECIFIER_WCHAR_T:
3233 atomic_type = ATOMIC_TYPE_WCHAR_T;
3235 case SPECIFIER_CHAR:
3236 atomic_type = ATOMIC_TYPE_CHAR;
3238 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3239 atomic_type = ATOMIC_TYPE_SCHAR;
3241 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3242 atomic_type = ATOMIC_TYPE_UCHAR;
3244 case SPECIFIER_SHORT:
3245 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3246 case SPECIFIER_SHORT | SPECIFIER_INT:
3247 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3248 atomic_type = ATOMIC_TYPE_SHORT;
3250 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3251 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3252 atomic_type = ATOMIC_TYPE_USHORT;
3255 case SPECIFIER_SIGNED:
3256 case SPECIFIER_SIGNED | SPECIFIER_INT:
3257 atomic_type = ATOMIC_TYPE_INT;
3259 case SPECIFIER_UNSIGNED:
3260 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3261 atomic_type = ATOMIC_TYPE_UINT;
3263 case SPECIFIER_LONG:
3264 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3265 case SPECIFIER_LONG | SPECIFIER_INT:
3266 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3267 atomic_type = ATOMIC_TYPE_LONG;
3269 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3270 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3271 atomic_type = ATOMIC_TYPE_ULONG;
3274 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3275 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3276 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3277 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3279 atomic_type = ATOMIC_TYPE_LONGLONG;
3280 goto warn_about_long_long;
3282 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3283 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3285 atomic_type = ATOMIC_TYPE_ULONGLONG;
3286 warn_about_long_long:
3287 if (warning.long_long) {
3288 warningf(&specifiers->source_position,
3289 "ISO C90 does not support 'long long'");
3293 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3294 atomic_type = unsigned_int8_type_kind;
3297 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3298 atomic_type = unsigned_int16_type_kind;
3301 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3302 atomic_type = unsigned_int32_type_kind;
3305 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3306 atomic_type = unsigned_int64_type_kind;
3309 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3310 atomic_type = unsigned_int128_type_kind;
3313 case SPECIFIER_INT8:
3314 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3315 atomic_type = int8_type_kind;
3318 case SPECIFIER_INT16:
3319 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3320 atomic_type = int16_type_kind;
3323 case SPECIFIER_INT32:
3324 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3325 atomic_type = int32_type_kind;
3328 case SPECIFIER_INT64:
3329 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3330 atomic_type = int64_type_kind;
3333 case SPECIFIER_INT128:
3334 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3335 atomic_type = int128_type_kind;
3338 case SPECIFIER_FLOAT:
3339 atomic_type = ATOMIC_TYPE_FLOAT;
3341 case SPECIFIER_DOUBLE:
3342 atomic_type = ATOMIC_TYPE_DOUBLE;
3344 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3345 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3347 case SPECIFIER_BOOL:
3348 atomic_type = ATOMIC_TYPE_BOOL;
3350 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3351 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3352 atomic_type = ATOMIC_TYPE_FLOAT;
3354 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3355 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3356 atomic_type = ATOMIC_TYPE_DOUBLE;
3358 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3359 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3360 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3363 /* invalid specifier combination, give an error message */
3364 if (type_specifiers == 0) {
3368 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3369 if (!(c_mode & _CXX) && !strict_mode) {
3370 if (warning.implicit_int) {
3371 warningf(HERE, "no type specifiers in declaration, using 'int'");
3373 atomic_type = ATOMIC_TYPE_INT;
3376 errorf(HERE, "no type specifiers given in declaration");
3378 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3379 (type_specifiers & SPECIFIER_UNSIGNED)) {
3380 errorf(HERE, "signed and unsigned specifiers given");
3381 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3382 errorf(HERE, "only integer types can be signed or unsigned");
3384 errorf(HERE, "multiple datatypes in declaration");
3389 if (type_specifiers & SPECIFIER_COMPLEX) {
3390 type = allocate_type_zero(TYPE_COMPLEX);
3391 type->complex.akind = atomic_type;
3392 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3393 type = allocate_type_zero(TYPE_IMAGINARY);
3394 type->imaginary.akind = atomic_type;
3396 type = allocate_type_zero(TYPE_ATOMIC);
3397 type->atomic.akind = atomic_type;
3400 } else if (type_specifiers != 0) {
3401 errorf(HERE, "multiple datatypes in declaration");
3404 /* FIXME: check type qualifiers here */
3405 type->base.qualifiers = qualifiers;
3408 type = identify_new_type(type);
3410 type = typehash_insert(type);
3413 if (specifiers->attributes != NULL)
3414 type = handle_type_attributes(specifiers->attributes, type);
3415 specifiers->type = type;
3419 specifiers->type = type_error_type;
3423 static type_qualifiers_t parse_type_qualifiers(void)
3425 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3428 switch (token.type) {
3429 /* type qualifiers */
3430 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3431 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3432 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3433 /* microsoft extended type modifiers */
3434 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3435 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3436 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3437 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3438 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3447 * Parses an K&R identifier list
3449 static void parse_identifier_list(scope_t *scope)
3452 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3453 entity->base.source_position = token.source_position;
3454 entity->base.namespc = NAMESPACE_NORMAL;
3455 entity->base.symbol = token.v.symbol;
3456 /* a K&R parameter has no type, yet */
3460 append_entity(scope, entity);
3462 if (token.type != ',') {
3466 } while (token.type == T_IDENTIFIER);
3469 static entity_t *parse_parameter(void)
3471 declaration_specifiers_t specifiers;
3472 memset(&specifiers, 0, sizeof(specifiers));
3474 parse_declaration_specifiers(&specifiers);
3476 entity_t *entity = parse_declarator(&specifiers,
3477 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3478 anonymous_entity = NULL;
3482 static void semantic_parameter_incomplete(const entity_t *entity)
3484 assert(entity->kind == ENTITY_PARAMETER);
3486 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3487 * list in a function declarator that is part of a
3488 * definition of that function shall not have
3489 * incomplete type. */
3490 type_t *type = skip_typeref(entity->declaration.type);
3491 if (is_type_incomplete(type)) {
3492 errorf(&entity->base.source_position,
3493 "parameter '%#T' has incomplete type",
3494 entity->declaration.type, entity->base.symbol);
3498 static bool has_parameters(void)
3500 /* func(void) is not a parameter */
3501 if (token.type == T_IDENTIFIER) {
3502 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3505 if (entity->kind != ENTITY_TYPEDEF)
3507 if (skip_typeref(entity->typedefe.type) != type_void)
3509 } else if (token.type != T_void) {
3512 if (look_ahead(1)->type != ')')
3519 * Parses function type parameters (and optionally creates variable_t entities
3520 * for them in a scope)
3522 static void parse_parameters(function_type_t *type, scope_t *scope)
3525 add_anchor_token(')');
3526 int saved_comma_state = save_and_reset_anchor_state(',');
3528 if (token.type == T_IDENTIFIER &&
3529 !is_typedef_symbol(token.v.symbol)) {
3530 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3531 if (la1_type == ',' || la1_type == ')') {
3532 type->kr_style_parameters = true;
3533 type->unspecified_parameters = true;
3534 parse_identifier_list(scope);
3535 goto parameters_finished;
3539 if (token.type == ')') {
3540 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3541 if (!(c_mode & _CXX))
3542 type->unspecified_parameters = true;
3543 goto parameters_finished;
3546 if (has_parameters()) {
3547 function_parameter_t **anchor = &type->parameters;
3549 switch (token.type) {
3552 type->variadic = true;
3553 goto parameters_finished;
3556 case T___extension__:
3559 entity_t *entity = parse_parameter();
3560 if (entity->kind == ENTITY_TYPEDEF) {
3561 errorf(&entity->base.source_position,
3562 "typedef not allowed as function parameter");
3565 assert(is_declaration(entity));
3567 semantic_parameter_incomplete(entity);
3569 function_parameter_t *const parameter =
3570 allocate_parameter(entity->declaration.type);
3572 if (scope != NULL) {
3573 append_entity(scope, entity);
3576 *anchor = parameter;
3577 anchor = ¶meter->next;
3582 goto parameters_finished;
3584 if (token.type != ',') {
3585 goto parameters_finished;
3592 parameters_finished:
3593 rem_anchor_token(')');
3594 expect(')', end_error);
3597 restore_anchor_state(',', saved_comma_state);
3600 typedef enum construct_type_kind_t {
3603 CONSTRUCT_REFERENCE,
3606 } construct_type_kind_t;
3608 typedef union construct_type_t construct_type_t;
3610 typedef struct construct_type_base_t {
3611 construct_type_kind_t kind;
3612 construct_type_t *next;
3613 } construct_type_base_t;
3615 typedef struct parsed_pointer_t {
3616 construct_type_base_t base;
3617 type_qualifiers_t type_qualifiers;
3618 variable_t *base_variable; /**< MS __based extension. */
3621 typedef struct parsed_reference_t {
3622 construct_type_base_t base;
3623 } parsed_reference_t;
3625 typedef struct construct_function_type_t {
3626 construct_type_base_t base;
3627 type_t *function_type;
3628 } construct_function_type_t;
3630 typedef struct parsed_array_t {
3631 construct_type_base_t base;
3632 type_qualifiers_t type_qualifiers;
3638 union construct_type_t {
3639 construct_type_kind_t kind;
3640 construct_type_base_t base;
3641 parsed_pointer_t pointer;
3642 parsed_reference_t reference;
3643 construct_function_type_t function;
3644 parsed_array_t array;
3647 static construct_type_t *parse_pointer_declarator(void)
3651 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3652 memset(pointer, 0, sizeof(pointer[0]));
3653 pointer->base.kind = CONSTRUCT_POINTER;
3654 pointer->type_qualifiers = parse_type_qualifiers();
3655 //pointer->base_variable = base_variable;
3657 return (construct_type_t*) pointer;
3660 static construct_type_t *parse_reference_declarator(void)
3664 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3665 parsed_reference_t *reference = &cons->reference;
3666 memset(reference, 0, sizeof(*reference));
3667 cons->kind = CONSTRUCT_REFERENCE;
3672 static construct_type_t *parse_array_declarator(void)
3675 add_anchor_token(']');
3677 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3678 parsed_array_t *array = &cons->array;
3679 memset(array, 0, sizeof(*array));
3680 cons->kind = CONSTRUCT_ARRAY;
3682 if (token.type == T_static) {
3683 array->is_static = true;
3687 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3688 if (type_qualifiers != 0) {
3689 if (token.type == T_static) {
3690 array->is_static = true;
3694 array->type_qualifiers = type_qualifiers;
3696 if (token.type == '*' && look_ahead(1)->type == ']') {
3697 array->is_variable = true;
3699 } else if (token.type != ']') {
3700 expression_t *const size = parse_assignment_expression();
3702 /* §6.7.5.2:1 Array size must have integer type */
3703 type_t *const orig_type = size->base.type;
3704 type_t *const type = skip_typeref(orig_type);
3705 if (!is_type_integer(type) && is_type_valid(type)) {
3706 errorf(&size->base.source_position,
3707 "array size '%E' must have integer type but has type '%T'",
3712 mark_vars_read(size, NULL);
3715 rem_anchor_token(']');
3716 expect(']', end_error);
3722 static construct_type_t *parse_function_declarator(scope_t *scope)
3724 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3725 function_type_t *ftype = &type->function;
3727 ftype->linkage = current_linkage;
3728 ftype->calling_convention = CC_CDECL;
3730 parse_parameters(ftype, scope);
3732 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3733 construct_function_type_t *function = &cons->function;
3734 memset(function, 0, sizeof(*function));
3735 cons->kind = CONSTRUCT_FUNCTION;
3736 function->function_type = type;
3741 typedef struct parse_declarator_env_t {
3742 bool may_be_abstract : 1;
3743 bool must_be_abstract : 1;
3744 decl_modifiers_t modifiers;
3746 source_position_t source_position;
3748 attribute_t *attributes;
3749 } parse_declarator_env_t;
3751 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3753 /* construct a single linked list of construct_type_t's which describe
3754 * how to construct the final declarator type */
3755 construct_type_t *first = NULL;
3756 construct_type_t **anchor = &first;
3758 env->attributes = parse_attributes(env->attributes);
3761 construct_type_t *type;
3762 //variable_t *based = NULL; /* MS __based extension */
3763 switch (token.type) {
3765 if (!(c_mode & _CXX))
3766 errorf(HERE, "references are only available for C++");
3767 type = parse_reference_declarator();
3772 source_position_t const pos = *HERE;
3774 expect('(', end_error);
3775 add_anchor_token(')');
3776 based = parse_microsoft_based();
3777 rem_anchor_token(')');
3778 expect(')', end_error);
3779 if (token.type != '*') {
3780 if (token.type == T__based) {
3781 errorf(&pos, "__based type modifier specified more than once");
3782 } else if (warning.other) {
3784 "__based does not precede a pointer declarator, ignored");
3789 panic("based currently disabled");
3795 type = parse_pointer_declarator();
3799 goto ptr_operator_end;
3803 anchor = &type->base.next;
3805 /* TODO: find out if this is correct */
3806 env->attributes = parse_attributes(env->attributes);
3811 modifiers |= env->modifiers;
3812 env->modifiers = modifiers;
3815 construct_type_t *inner_types = NULL;
3817 switch (token.type) {
3819 if (env->must_be_abstract) {
3820 errorf(HERE, "no identifier expected in typename");
3822 env->symbol = token.v.symbol;
3823 env->source_position = token.source_position;
3828 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3829 * interpreted as ``function with no parameter specification'', rather
3830 * than redundant parentheses around the omitted identifier. */
3831 if (look_ahead(1)->type != ')') {
3833 add_anchor_token(')');
3834 inner_types = parse_inner_declarator(env);
3835 if (inner_types != NULL) {
3836 /* All later declarators only modify the return type */
3837 env->must_be_abstract = true;
3839 rem_anchor_token(')');
3840 expect(')', end_error);
3844 if (env->may_be_abstract)
3846 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3851 construct_type_t **const p = anchor;
3854 construct_type_t *type;
3855 switch (token.type) {
3857 scope_t *scope = NULL;
3858 if (!env->must_be_abstract) {
3859 scope = &env->parameters;
3862 type = parse_function_declarator(scope);
3866 type = parse_array_declarator();
3869 goto declarator_finished;
3872 /* insert in the middle of the list (at p) */
3873 type->base.next = *p;
3876 anchor = &type->base.next;
3879 declarator_finished:
3880 /* append inner_types at the end of the list, we don't to set anchor anymore
3881 * as it's not needed anymore */
3882 *anchor = inner_types;
3889 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3891 construct_type_t *iter = construct_list;
3892 for (; iter != NULL; iter = iter->base.next) {
3893 switch (iter->kind) {
3894 case CONSTRUCT_INVALID:
3896 case CONSTRUCT_FUNCTION: {
3897 construct_function_type_t *function = &iter->function;
3898 type_t *function_type = function->function_type;
3900 function_type->function.return_type = type;
3902 type_t *skipped_return_type = skip_typeref(type);
3904 if (is_type_function(skipped_return_type)) {
3905 errorf(HERE, "function returning function is not allowed");
3906 } else if (is_type_array(skipped_return_type)) {
3907 errorf(HERE, "function returning array is not allowed");
3909 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3911 "type qualifiers in return type of function type are meaningless");
3915 /* The function type was constructed earlier. Freeing it here will
3916 * destroy other types. */
3917 type = typehash_insert(function_type);
3921 case CONSTRUCT_POINTER: {
3922 if (is_type_reference(skip_typeref(type)))
3923 errorf(HERE, "cannot declare a pointer to reference");
3925 parsed_pointer_t *pointer = &iter->pointer;
3926 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3930 case CONSTRUCT_REFERENCE:
3931 if (is_type_reference(skip_typeref(type)))
3932 errorf(HERE, "cannot declare a reference to reference");
3934 type = make_reference_type(type);
3937 case CONSTRUCT_ARRAY: {
3938 if (is_type_reference(skip_typeref(type)))
3939 errorf(HERE, "cannot declare an array of references");
3941 parsed_array_t *array = &iter->array;
3942 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3944 expression_t *size_expression = array->size;
3945 if (size_expression != NULL) {
3947 = create_implicit_cast(size_expression, type_size_t);
3950 array_type->base.qualifiers = array->type_qualifiers;
3951 array_type->array.element_type = type;
3952 array_type->array.is_static = array->is_static;
3953 array_type->array.is_variable = array->is_variable;
3954 array_type->array.size_expression = size_expression;
3956 if (size_expression != NULL) {
3957 if (is_constant_expression(size_expression)) {
3959 = fold_constant_to_int(size_expression);
3960 array_type->array.size = size;
3961 array_type->array.size_constant = true;
3962 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3963 * have a value greater than zero. */
3965 if (size < 0 || !GNU_MODE) {
3966 errorf(&size_expression->base.source_position,
3967 "size of array must be greater than zero");
3968 } else if (warning.other) {
3969 warningf(&size_expression->base.source_position,
3970 "zero length arrays are a GCC extension");
3974 array_type->array.is_vla = true;
3978 type_t *skipped_type = skip_typeref(type);
3980 if (is_type_incomplete(skipped_type)) {
3981 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3982 } else if (is_type_function(skipped_type)) {
3983 errorf(HERE, "array of functions is not allowed");
3985 type = identify_new_type(array_type);
3989 internal_errorf(HERE, "invalid type construction found");
3995 static type_t *automatic_type_conversion(type_t *orig_type);
3997 static type_t *semantic_parameter(const source_position_t *pos,
3999 const declaration_specifiers_t *specifiers,
4002 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4003 * shall be adjusted to ``qualified pointer to type'',
4005 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4006 * type'' shall be adjusted to ``pointer to function
4007 * returning type'', as in 6.3.2.1. */
4008 type = automatic_type_conversion(type);
4010 if (specifiers->is_inline && is_type_valid(type)) {
4011 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
4014 /* §6.9.1:6 The declarations in the declaration list shall contain
4015 * no storage-class specifier other than register and no
4016 * initializations. */
4017 if (specifiers->thread_local || (
4018 specifiers->storage_class != STORAGE_CLASS_NONE &&
4019 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4021 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
4024 /* delay test for incomplete type, because we might have (void)
4025 * which is legal but incomplete... */
4030 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4031 declarator_flags_t flags)
4033 parse_declarator_env_t env;
4034 memset(&env, 0, sizeof(env));
4035 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
4037 construct_type_t *construct_type = parse_inner_declarator(&env);
4039 construct_declarator_type(construct_type, specifiers->type);
4040 type_t *type = skip_typeref(orig_type);
4042 if (construct_type != NULL) {
4043 obstack_free(&temp_obst, construct_type);
4046 attribute_t *attributes = parse_attributes(env.attributes);
4047 /* append (shared) specifier attribute behind attributes of this
4049 if (attributes != NULL) {
4050 attribute_t *last = attributes;
4051 while (last->next != NULL)
4053 last->next = specifiers->attributes;
4055 attributes = specifiers->attributes;
4059 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4060 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4061 entity->base.symbol = env.symbol;
4062 entity->base.source_position = env.source_position;
4063 entity->typedefe.type = orig_type;
4065 if (anonymous_entity != NULL) {
4066 if (is_type_compound(type)) {
4067 assert(anonymous_entity->compound.alias == NULL);
4068 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4069 anonymous_entity->kind == ENTITY_UNION);
4070 anonymous_entity->compound.alias = entity;
4071 anonymous_entity = NULL;
4072 } else if (is_type_enum(type)) {
4073 assert(anonymous_entity->enume.alias == NULL);
4074 assert(anonymous_entity->kind == ENTITY_ENUM);
4075 anonymous_entity->enume.alias = entity;
4076 anonymous_entity = NULL;
4080 /* create a declaration type entity */
4081 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4082 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4084 if (env.symbol != NULL) {
4085 if (specifiers->is_inline && is_type_valid(type)) {
4086 errorf(&env.source_position,
4087 "compound member '%Y' declared 'inline'", env.symbol);
4090 if (specifiers->thread_local ||
4091 specifiers->storage_class != STORAGE_CLASS_NONE) {
4092 errorf(&env.source_position,
4093 "compound member '%Y' must have no storage class",
4097 } else if (flags & DECL_IS_PARAMETER) {
4098 orig_type = semantic_parameter(&env.source_position, orig_type,
4099 specifiers, env.symbol);
4101 entity = allocate_entity_zero(ENTITY_PARAMETER);
4102 } else if (is_type_function(type)) {
4103 entity = allocate_entity_zero(ENTITY_FUNCTION);
4105 entity->function.is_inline = specifiers->is_inline;
4106 entity->function.parameters = env.parameters;
4108 if (env.symbol != NULL) {
4109 /* this needs fixes for C++ */
4110 bool in_function_scope = current_function != NULL;
4112 if (specifiers->thread_local || (
4113 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4114 specifiers->storage_class != STORAGE_CLASS_NONE &&
4115 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4117 errorf(&env.source_position,
4118 "invalid storage class for function '%Y'", env.symbol);
4122 entity = allocate_entity_zero(ENTITY_VARIABLE);
4124 entity->variable.thread_local = specifiers->thread_local;
4126 if (env.symbol != NULL) {
4127 if (specifiers->is_inline && is_type_valid(type)) {
4128 errorf(&env.source_position,
4129 "variable '%Y' declared 'inline'", env.symbol);
4132 bool invalid_storage_class = false;
4133 if (current_scope == file_scope) {
4134 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4135 specifiers->storage_class != STORAGE_CLASS_NONE &&
4136 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4137 invalid_storage_class = true;
4140 if (specifiers->thread_local &&
4141 specifiers->storage_class == STORAGE_CLASS_NONE) {
4142 invalid_storage_class = true;
4145 if (invalid_storage_class) {
4146 errorf(&env.source_position,
4147 "invalid storage class for variable '%Y'", env.symbol);
4152 if (env.symbol != NULL) {
4153 entity->base.symbol = env.symbol;
4154 entity->base.source_position = env.source_position;
4156 entity->base.source_position = specifiers->source_position;
4158 entity->base.namespc = NAMESPACE_NORMAL;
4159 entity->declaration.type = orig_type;
4160 entity->declaration.alignment = get_type_alignment(orig_type);
4161 entity->declaration.modifiers = env.modifiers;
4162 entity->declaration.attributes = attributes;
4164 storage_class_t storage_class = specifiers->storage_class;
4165 entity->declaration.declared_storage_class = storage_class;
4167 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4168 storage_class = STORAGE_CLASS_AUTO;
4169 entity->declaration.storage_class = storage_class;
4172 if (attributes != NULL) {
4173 handle_entity_attributes(attributes, entity);
4179 static type_t *parse_abstract_declarator(type_t *base_type)
4181 parse_declarator_env_t env;
4182 memset(&env, 0, sizeof(env));
4183 env.may_be_abstract = true;
4184 env.must_be_abstract = true;
4186 construct_type_t *construct_type = parse_inner_declarator(&env);
4188 type_t *result = construct_declarator_type(construct_type, base_type);
4189 if (construct_type != NULL) {
4190 obstack_free(&temp_obst, construct_type);
4192 result = handle_type_attributes(env.attributes, result);
4198 * Check if the declaration of main is suspicious. main should be a
4199 * function with external linkage, returning int, taking either zero
4200 * arguments, two, or three arguments of appropriate types, ie.
4202 * int main([ int argc, char **argv [, char **env ] ]).
4204 * @param decl the declaration to check
4205 * @param type the function type of the declaration
4207 static void check_main(const entity_t *entity)
4209 const source_position_t *pos = &entity->base.source_position;
4210 if (entity->kind != ENTITY_FUNCTION) {
4211 warningf(pos, "'main' is not a function");
4215 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4216 warningf(pos, "'main' is normally a non-static function");
4219 type_t *type = skip_typeref(entity->declaration.type);
4220 assert(is_type_function(type));
4222 function_type_t *func_type = &type->function;
4223 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4224 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4225 func_type->return_type);
4227 const function_parameter_t *parm = func_type->parameters;
4229 type_t *const first_type = parm->type;
4230 if (!types_compatible(skip_typeref(first_type), type_int)) {
4232 "first argument of 'main' should be 'int', but is '%T'",
4237 type_t *const second_type = parm->type;
4238 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4239 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4243 type_t *const third_type = parm->type;
4244 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4245 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4249 goto warn_arg_count;
4253 warningf(pos, "'main' takes only zero, two or three arguments");
4259 * Check if a symbol is the equal to "main".
4261 static bool is_sym_main(const symbol_t *const sym)
4263 return strcmp(sym->string, "main") == 0;
4266 static void error_redefined_as_different_kind(const source_position_t *pos,
4267 const entity_t *old, entity_kind_t new_kind)
4269 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4270 get_entity_kind_name(old->kind), old->base.symbol,
4271 get_entity_kind_name(new_kind), &old->base.source_position);
4274 static bool is_error_entity(entity_t *const ent)
4276 if (is_declaration(ent)) {
4277 return is_type_valid(skip_typeref(ent->declaration.type));
4278 } else if (ent->kind == ENTITY_TYPEDEF) {
4279 return is_type_valid(skip_typeref(ent->typedefe.type));
4285 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4286 * for various problems that occur for multiple definitions
4288 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4290 const symbol_t *const symbol = entity->base.symbol;
4291 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4292 const source_position_t *pos = &entity->base.source_position;
4294 /* can happen in error cases */
4298 entity_t *const previous_entity = get_entity(symbol, namespc);
4299 /* pushing the same entity twice will break the stack structure */
4300 assert(previous_entity != entity);
4302 if (entity->kind == ENTITY_FUNCTION) {
4303 type_t *const orig_type = entity->declaration.type;
4304 type_t *const type = skip_typeref(orig_type);
4306 assert(is_type_function(type));
4307 if (type->function.unspecified_parameters &&
4308 warning.strict_prototypes &&
4309 previous_entity == NULL) {
4310 warningf(pos, "function declaration '%#T' is not a prototype",
4314 if (warning.main && current_scope == file_scope
4315 && is_sym_main(symbol)) {
4320 if (is_declaration(entity) &&
4321 warning.nested_externs &&
4322 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4323 current_scope != file_scope) {
4324 warningf(pos, "nested extern declaration of '%#T'",
4325 entity->declaration.type, symbol);
4328 if (previous_entity != NULL) {
4329 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4330 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4331 assert(previous_entity->kind == ENTITY_PARAMETER);
4333 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4334 entity->declaration.type, symbol,
4335 previous_entity->declaration.type, symbol,
4336 &previous_entity->base.source_position);
4340 if (previous_entity->base.parent_scope == current_scope) {
4341 if (previous_entity->kind != entity->kind) {
4342 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4343 error_redefined_as_different_kind(pos, previous_entity,
4348 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4349 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4350 symbol, &previous_entity->base.source_position);
4353 if (previous_entity->kind == ENTITY_TYPEDEF) {
4354 /* TODO: C++ allows this for exactly the same type */
4355 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4356 symbol, &previous_entity->base.source_position);
4360 /* at this point we should have only VARIABLES or FUNCTIONS */
4361 assert(is_declaration(previous_entity) && is_declaration(entity));
4363 declaration_t *const prev_decl = &previous_entity->declaration;
4364 declaration_t *const decl = &entity->declaration;
4366 /* can happen for K&R style declarations */
4367 if (prev_decl->type == NULL &&
4368 previous_entity->kind == ENTITY_PARAMETER &&
4369 entity->kind == ENTITY_PARAMETER) {
4370 prev_decl->type = decl->type;
4371 prev_decl->storage_class = decl->storage_class;
4372 prev_decl->declared_storage_class = decl->declared_storage_class;
4373 prev_decl->modifiers = decl->modifiers;
4374 return previous_entity;
4377 type_t *const orig_type = decl->type;
4378 assert(orig_type != NULL);
4379 type_t *const type = skip_typeref(orig_type);
4380 type_t *const prev_type = skip_typeref(prev_decl->type);
4382 if (!types_compatible(type, prev_type)) {
4384 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4385 orig_type, symbol, prev_decl->type, symbol,
4386 &previous_entity->base.source_position);
4388 unsigned old_storage_class = prev_decl->storage_class;
4389 if (warning.redundant_decls &&
4392 !(prev_decl->modifiers & DM_USED) &&
4393 !type->function.kr_style_parameters &&
4394 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4395 warningf(&previous_entity->base.source_position,
4396 "unnecessary static forward declaration for '%#T'",
4397 prev_decl->type, symbol);
4400 storage_class_t new_storage_class = decl->storage_class;
4402 /* pretend no storage class means extern for function
4403 * declarations (except if the previous declaration is neither
4404 * none nor extern) */
4405 if (entity->kind == ENTITY_FUNCTION) {
4406 /* the previous declaration could have unspecified parameters or
4407 * be a typedef, so use the new type */
4408 if (prev_type->function.unspecified_parameters || is_definition)
4409 prev_decl->type = type;
4411 switch (old_storage_class) {
4412 case STORAGE_CLASS_NONE:
4413 old_storage_class = STORAGE_CLASS_EXTERN;
4416 case STORAGE_CLASS_EXTERN:
4417 if (is_definition) {
4418 if (warning.missing_prototypes &&
4419 prev_type->function.unspecified_parameters &&
4420 !is_sym_main(symbol)) {
4421 warningf(pos, "no previous prototype for '%#T'",
4424 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4425 new_storage_class = STORAGE_CLASS_EXTERN;
4432 } else if (is_type_incomplete(prev_type)) {
4433 prev_decl->type = type;
4436 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4437 new_storage_class == STORAGE_CLASS_EXTERN) {
4438 warn_redundant_declaration:
4439 if (!is_definition &&
4440 warning.redundant_decls &&
4441 is_type_valid(prev_type) &&
4442 strcmp(previous_entity->base.source_position.input_name,
4443 "<builtin>") != 0) {
4445 "redundant declaration for '%Y' (declared %P)",
4446 symbol, &previous_entity->base.source_position);
4448 } else if (current_function == NULL) {
4449 if (old_storage_class != STORAGE_CLASS_STATIC &&
4450 new_storage_class == STORAGE_CLASS_STATIC) {
4452 "static declaration of '%Y' follows non-static declaration (declared %P)",
4453 symbol, &previous_entity->base.source_position);
4454 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4455 prev_decl->storage_class = STORAGE_CLASS_NONE;
4456 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4458 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4460 goto error_redeclaration;
4461 goto warn_redundant_declaration;
4463 } else if (is_type_valid(prev_type)) {
4464 if (old_storage_class == new_storage_class) {
4465 error_redeclaration:
4466 errorf(pos, "redeclaration of '%Y' (declared %P)",
4467 symbol, &previous_entity->base.source_position);
4470 "redeclaration of '%Y' with different linkage (declared %P)",
4471 symbol, &previous_entity->base.source_position);
4476 prev_decl->modifiers |= decl->modifiers;
4477 if (entity->kind == ENTITY_FUNCTION) {
4478 previous_entity->function.is_inline |= entity->function.is_inline;
4480 return previous_entity;
4483 if (warning.shadow) {
4484 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4485 get_entity_kind_name(entity->kind), symbol,
4486 get_entity_kind_name(previous_entity->kind),
4487 &previous_entity->base.source_position);
4491 if (entity->kind == ENTITY_FUNCTION) {
4492 if (is_definition &&
4493 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4494 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4495 warningf(pos, "no previous prototype for '%#T'",
4496 entity->declaration.type, symbol);
4497 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4498 warningf(pos, "no previous declaration for '%#T'",
4499 entity->declaration.type, symbol);
4502 } else if (warning.missing_declarations &&
4503 entity->kind == ENTITY_VARIABLE &&
4504 current_scope == file_scope) {
4505 declaration_t *declaration = &entity->declaration;
4506 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4507 warningf(pos, "no previous declaration for '%#T'",
4508 declaration->type, symbol);
4513 assert(entity->base.parent_scope == NULL);
4514 assert(current_scope != NULL);
4516 entity->base.parent_scope = current_scope;
4517 entity->base.namespc = NAMESPACE_NORMAL;
4518 environment_push(entity);
4519 append_entity(current_scope, entity);
4524 static void parser_error_multiple_definition(entity_t *entity,
4525 const source_position_t *source_position)
4527 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4528 entity->base.symbol, &entity->base.source_position);
4531 static bool is_declaration_specifier(const token_t *token,
4532 bool only_specifiers_qualifiers)
4534 switch (token->type) {
4539 return is_typedef_symbol(token->v.symbol);
4541 case T___extension__:
4543 return !only_specifiers_qualifiers;
4550 static void parse_init_declarator_rest(entity_t *entity)
4552 assert(is_declaration(entity));
4553 declaration_t *const declaration = &entity->declaration;
4557 type_t *orig_type = declaration->type;
4558 type_t *type = skip_typeref(orig_type);
4560 if (entity->kind == ENTITY_VARIABLE
4561 && entity->variable.initializer != NULL) {
4562 parser_error_multiple_definition(entity, HERE);
4565 bool must_be_constant = false;
4566 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4567 entity->base.parent_scope == file_scope) {
4568 must_be_constant = true;
4571 if (is_type_function(type)) {
4572 errorf(&entity->base.source_position,
4573 "function '%#T' is initialized like a variable",
4574 orig_type, entity->base.symbol);
4575 orig_type = type_error_type;
4578 parse_initializer_env_t env;
4579 env.type = orig_type;
4580 env.must_be_constant = must_be_constant;
4581 env.entity = entity;
4582 current_init_decl = entity;
4584 initializer_t *initializer = parse_initializer(&env);
4585 current_init_decl = NULL;
4587 if (entity->kind == ENTITY_VARIABLE) {
4588 /* §6.7.5:22 array initializers for arrays with unknown size
4589 * determine the array type size */
4590 declaration->type = env.type;
4591 entity->variable.initializer = initializer;
4595 /* parse rest of a declaration without any declarator */
4596 static void parse_anonymous_declaration_rest(
4597 const declaration_specifiers_t *specifiers)
4600 anonymous_entity = NULL;
4602 if (warning.other) {
4603 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4604 specifiers->thread_local) {
4605 warningf(&specifiers->source_position,
4606 "useless storage class in empty declaration");
4609 type_t *type = specifiers->type;
4610 switch (type->kind) {
4611 case TYPE_COMPOUND_STRUCT:
4612 case TYPE_COMPOUND_UNION: {
4613 if (type->compound.compound->base.symbol == NULL) {
4614 warningf(&specifiers->source_position,
4615 "unnamed struct/union that defines no instances");
4624 warningf(&specifiers->source_position, "empty declaration");
4630 static void check_variable_type_complete(entity_t *ent)
4632 if (ent->kind != ENTITY_VARIABLE)
4635 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4636 * type for the object shall be complete [...] */
4637 declaration_t *decl = &ent->declaration;
4638 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4639 decl->storage_class == STORAGE_CLASS_STATIC)
4642 type_t *const orig_type = decl->type;
4643 type_t *const type = skip_typeref(orig_type);
4644 if (!is_type_incomplete(type))
4647 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4648 * are given length one. */
4649 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4650 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4654 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4655 orig_type, ent->base.symbol);
4659 static void parse_declaration_rest(entity_t *ndeclaration,
4660 const declaration_specifiers_t *specifiers,
4661 parsed_declaration_func finished_declaration,
4662 declarator_flags_t flags)
4664 add_anchor_token(';');
4665 add_anchor_token(',');
4667 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4669 if (token.type == '=') {
4670 parse_init_declarator_rest(entity);
4671 } else if (entity->kind == ENTITY_VARIABLE) {
4672 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4673 * [...] where the extern specifier is explicitly used. */
4674 declaration_t *decl = &entity->declaration;
4675 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4676 type_t *type = decl->type;
4677 if (is_type_reference(skip_typeref(type))) {
4678 errorf(&entity->base.source_position,
4679 "reference '%#T' must be initialized",
4680 type, entity->base.symbol);
4685 check_variable_type_complete(entity);
4687 if (token.type != ',')
4691 add_anchor_token('=');
4692 ndeclaration = parse_declarator(specifiers, flags);
4693 rem_anchor_token('=');
4695 expect(';', end_error);
4698 anonymous_entity = NULL;
4699 rem_anchor_token(';');
4700 rem_anchor_token(',');
4703 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4705 symbol_t *symbol = entity->base.symbol;
4706 if (symbol == NULL) {
4707 errorf(HERE, "anonymous declaration not valid as function parameter");
4711 assert(entity->base.namespc == NAMESPACE_NORMAL);
4712 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4713 if (previous_entity == NULL
4714 || previous_entity->base.parent_scope != current_scope) {
4715 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4720 if (is_definition) {
4721 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4724 return record_entity(entity, false);
4727 static void parse_declaration(parsed_declaration_func finished_declaration,
4728 declarator_flags_t flags)
4730 declaration_specifiers_t specifiers;
4731 memset(&specifiers, 0, sizeof(specifiers));
4733 add_anchor_token(';');
4734 parse_declaration_specifiers(&specifiers);
4735 rem_anchor_token(';');
4737 if (token.type == ';') {
4738 parse_anonymous_declaration_rest(&specifiers);
4740 entity_t *entity = parse_declarator(&specifiers, flags);
4741 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4746 static type_t *get_default_promoted_type(type_t *orig_type)
4748 type_t *result = orig_type;
4750 type_t *type = skip_typeref(orig_type);
4751 if (is_type_integer(type)) {
4752 result = promote_integer(type);
4753 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4754 result = type_double;
4760 static void parse_kr_declaration_list(entity_t *entity)
4762 if (entity->kind != ENTITY_FUNCTION)
4765 type_t *type = skip_typeref(entity->declaration.type);
4766 assert(is_type_function(type));
4767 if (!type->function.kr_style_parameters)
4771 add_anchor_token('{');
4773 /* push function parameters */
4774 size_t const top = environment_top();
4775 scope_t *old_scope = scope_push(&entity->function.parameters);
4777 entity_t *parameter = entity->function.parameters.entities;
4778 for ( ; parameter != NULL; parameter = parameter->base.next) {
4779 assert(parameter->base.parent_scope == NULL);
4780 parameter->base.parent_scope = current_scope;
4781 environment_push(parameter);
4784 /* parse declaration list */
4786 switch (token.type) {
4788 case T___extension__:
4789 /* This covers symbols, which are no type, too, and results in
4790 * better error messages. The typical cases are misspelled type
4791 * names and missing includes. */
4793 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4801 /* pop function parameters */
4802 assert(current_scope == &entity->function.parameters);
4803 scope_pop(old_scope);
4804 environment_pop_to(top);
4806 /* update function type */
4807 type_t *new_type = duplicate_type(type);
4809 function_parameter_t *parameters = NULL;
4810 function_parameter_t **anchor = ¶meters;
4812 parameter = entity->function.parameters.entities;
4813 for (; parameter != NULL; parameter = parameter->base.next) {
4814 if (parameter->kind != ENTITY_PARAMETER)
4817 type_t *parameter_type = parameter->declaration.type;
4818 if (parameter_type == NULL) {
4820 errorf(HERE, "no type specified for function parameter '%Y'",
4821 parameter->base.symbol);
4822 parameter_type = type_error_type;
4824 if (warning.implicit_int) {
4825 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4826 parameter->base.symbol);
4828 parameter_type = type_int;
4830 parameter->declaration.type = parameter_type;
4833 semantic_parameter_incomplete(parameter);
4836 * we need the default promoted types for the function type
4838 parameter_type = get_default_promoted_type(parameter_type);
4840 function_parameter_t *const parameter =
4841 allocate_parameter(parameter_type);
4843 *anchor = parameter;
4844 anchor = ¶meter->next;
4847 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4849 new_type->function.parameters = parameters;
4850 new_type->function.unspecified_parameters = true;
4852 new_type = identify_new_type(new_type);
4854 entity->declaration.type = new_type;
4856 rem_anchor_token('{');
4859 static bool first_err = true;
4862 * When called with first_err set, prints the name of the current function,
4865 static void print_in_function(void)
4869 diagnosticf("%s: In function '%Y':\n",
4870 current_function->base.base.source_position.input_name,
4871 current_function->base.base.symbol);
4876 * Check if all labels are defined in the current function.
4877 * Check if all labels are used in the current function.
4879 static void check_labels(void)
4881 for (const goto_statement_t *goto_statement = goto_first;
4882 goto_statement != NULL;
4883 goto_statement = goto_statement->next) {
4884 /* skip computed gotos */
4885 if (goto_statement->expression != NULL)
4888 label_t *label = goto_statement->label;
4891 if (label->base.source_position.input_name == NULL) {
4892 print_in_function();
4893 errorf(&goto_statement->base.source_position,
4894 "label '%Y' used but not defined", label->base.symbol);
4898 if (warning.unused_label) {
4899 for (const label_statement_t *label_statement = label_first;
4900 label_statement != NULL;
4901 label_statement = label_statement->next) {
4902 label_t *label = label_statement->label;
4904 if (! label->used) {
4905 print_in_function();
4906 warningf(&label_statement->base.source_position,
4907 "label '%Y' defined but not used", label->base.symbol);
4913 static void warn_unused_entity(entity_t *entity, entity_t *last)
4915 entity_t const *const end = last != NULL ? last->base.next : NULL;
4916 for (; entity != end; entity = entity->base.next) {
4917 if (!is_declaration(entity))
4920 declaration_t *declaration = &entity->declaration;
4921 if (declaration->implicit)
4924 if (!declaration->used) {
4925 print_in_function();
4926 const char *what = get_entity_kind_name(entity->kind);
4927 warningf(&entity->base.source_position, "%s '%Y' is unused",
4928 what, entity->base.symbol);
4929 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4930 print_in_function();
4931 const char *what = get_entity_kind_name(entity->kind);
4932 warningf(&entity->base.source_position, "%s '%Y' is never read",
4933 what, entity->base.symbol);
4938 static void check_unused_variables(statement_t *const stmt, void *const env)
4942 switch (stmt->kind) {
4943 case STATEMENT_DECLARATION: {
4944 declaration_statement_t const *const decls = &stmt->declaration;
4945 warn_unused_entity(decls->declarations_begin,
4946 decls->declarations_end);
4951 warn_unused_entity(stmt->fors.scope.entities, NULL);
4960 * Check declarations of current_function for unused entities.
4962 static void check_declarations(void)
4964 if (warning.unused_parameter) {
4965 const scope_t *scope = ¤t_function->parameters;
4967 /* do not issue unused warnings for main */
4968 if (!is_sym_main(current_function->base.base.symbol)) {
4969 warn_unused_entity(scope->entities, NULL);
4972 if (warning.unused_variable) {
4973 walk_statements(current_function->statement, check_unused_variables,
4978 static int determine_truth(expression_t const* const cond)
4981 !is_constant_expression(cond) ? 0 :
4982 fold_constant_to_bool(cond) ? 1 :
4986 static void check_reachable(statement_t *);
4987 static bool reaches_end;
4989 static bool expression_returns(expression_t const *const expr)
4991 switch (expr->kind) {
4993 expression_t const *const func = expr->call.function;
4994 if (func->kind == EXPR_REFERENCE) {
4995 entity_t *entity = func->reference.entity;
4996 if (entity->kind == ENTITY_FUNCTION
4997 && entity->declaration.modifiers & DM_NORETURN)
5001 if (!expression_returns(func))
5004 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5005 if (!expression_returns(arg->expression))
5012 case EXPR_REFERENCE:
5013 case EXPR_REFERENCE_ENUM_VALUE:
5015 case EXPR_CHARACTER_CONSTANT:
5016 case EXPR_WIDE_CHARACTER_CONSTANT:
5017 case EXPR_STRING_LITERAL:
5018 case EXPR_WIDE_STRING_LITERAL:
5019 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5020 case EXPR_LABEL_ADDRESS:
5021 case EXPR_CLASSIFY_TYPE:
5022 case EXPR_SIZEOF: // TODO handle obscure VLA case
5025 case EXPR_BUILTIN_CONSTANT_P:
5026 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5031 case EXPR_STATEMENT: {
5032 bool old_reaches_end = reaches_end;
5033 reaches_end = false;
5034 check_reachable(expr->statement.statement);
5035 bool returns = reaches_end;
5036 reaches_end = old_reaches_end;
5040 case EXPR_CONDITIONAL:
5041 // TODO handle constant expression
5043 if (!expression_returns(expr->conditional.condition))
5046 if (expr->conditional.true_expression != NULL
5047 && expression_returns(expr->conditional.true_expression))
5050 return expression_returns(expr->conditional.false_expression);
5053 return expression_returns(expr->select.compound);
5055 case EXPR_ARRAY_ACCESS:
5057 expression_returns(expr->array_access.array_ref) &&
5058 expression_returns(expr->array_access.index);
5061 return expression_returns(expr->va_starte.ap);
5064 return expression_returns(expr->va_arge.ap);
5067 return expression_returns(expr->va_copye.src);
5069 EXPR_UNARY_CASES_MANDATORY
5070 return expression_returns(expr->unary.value);
5072 case EXPR_UNARY_THROW:
5076 // TODO handle constant lhs of && and ||
5078 expression_returns(expr->binary.left) &&
5079 expression_returns(expr->binary.right);
5085 panic("unhandled expression");
5088 static bool initializer_returns(initializer_t const *const init)
5090 switch (init->kind) {
5091 case INITIALIZER_VALUE:
5092 return expression_returns(init->value.value);
5094 case INITIALIZER_LIST: {
5095 initializer_t * const* i = init->list.initializers;
5096 initializer_t * const* const end = i + init->list.len;
5097 bool returns = true;
5098 for (; i != end; ++i) {
5099 if (!initializer_returns(*i))
5105 case INITIALIZER_STRING:
5106 case INITIALIZER_WIDE_STRING:
5107 case INITIALIZER_DESIGNATOR: // designators have no payload
5110 panic("unhandled initializer");
5113 static bool noreturn_candidate;
5115 static void check_reachable(statement_t *const stmt)
5117 if (stmt->base.reachable)
5119 if (stmt->kind != STATEMENT_DO_WHILE)
5120 stmt->base.reachable = true;
5122 statement_t *last = stmt;
5124 switch (stmt->kind) {
5125 case STATEMENT_INVALID:
5126 case STATEMENT_EMPTY:
5128 next = stmt->base.next;
5131 case STATEMENT_DECLARATION: {
5132 declaration_statement_t const *const decl = &stmt->declaration;
5133 entity_t const * ent = decl->declarations_begin;
5134 entity_t const *const last = decl->declarations_end;
5136 for (;; ent = ent->base.next) {
5137 if (ent->kind == ENTITY_VARIABLE &&
5138 ent->variable.initializer != NULL &&
5139 !initializer_returns(ent->variable.initializer)) {
5146 next = stmt->base.next;
5150 case STATEMENT_COMPOUND:
5151 next = stmt->compound.statements;
5153 next = stmt->base.next;
5156 case STATEMENT_RETURN: {
5157 expression_t const *const val = stmt->returns.value;
5158 if (val == NULL || expression_returns(val))
5159 noreturn_candidate = false;
5163 case STATEMENT_IF: {
5164 if_statement_t const *const ifs = &stmt->ifs;
5165 expression_t const *const cond = ifs->condition;
5167 if (!expression_returns(cond))
5170 int const val = determine_truth(cond);
5173 check_reachable(ifs->true_statement);
5178 if (ifs->false_statement != NULL) {
5179 check_reachable(ifs->false_statement);
5183 next = stmt->base.next;
5187 case STATEMENT_SWITCH: {
5188 switch_statement_t const *const switchs = &stmt->switchs;
5189 expression_t const *const expr = switchs->expression;
5191 if (!expression_returns(expr))
5194 if (is_constant_expression(expr)) {
5195 long const val = fold_constant_to_int(expr);
5196 case_label_statement_t * defaults = NULL;
5197 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5198 if (i->expression == NULL) {
5203 if (i->first_case <= val && val <= i->last_case) {
5204 check_reachable((statement_t*)i);
5209 if (defaults != NULL) {
5210 check_reachable((statement_t*)defaults);
5214 bool has_default = false;
5215 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5216 if (i->expression == NULL)
5219 check_reachable((statement_t*)i);
5226 next = stmt->base.next;
5230 case STATEMENT_EXPRESSION: {
5231 /* Check for noreturn function call */
5232 expression_t const *const expr = stmt->expression.expression;
5233 if (!expression_returns(expr))
5236 next = stmt->base.next;
5240 case STATEMENT_CONTINUE: {
5241 statement_t *parent = stmt;
5243 parent = parent->base.parent;
5244 if (parent == NULL) /* continue not within loop */
5248 switch (parent->kind) {
5249 case STATEMENT_WHILE: goto continue_while;
5250 case STATEMENT_DO_WHILE: goto continue_do_while;
5251 case STATEMENT_FOR: goto continue_for;
5258 case STATEMENT_BREAK: {
5259 statement_t *parent = stmt;
5261 parent = parent->base.parent;
5262 if (parent == NULL) /* break not within loop/switch */
5265 switch (parent->kind) {
5266 case STATEMENT_SWITCH:
5267 case STATEMENT_WHILE:
5268 case STATEMENT_DO_WHILE:
5271 next = parent->base.next;
5272 goto found_break_parent;
5281 case STATEMENT_GOTO:
5282 if (stmt->gotos.expression) {
5283 if (!expression_returns(stmt->gotos.expression))
5286 statement_t *parent = stmt->base.parent;
5287 if (parent == NULL) /* top level goto */
5291 next = stmt->gotos.label->statement;
5292 if (next == NULL) /* missing label */
5297 case STATEMENT_LABEL:
5298 next = stmt->label.statement;
5301 case STATEMENT_CASE_LABEL:
5302 next = stmt->case_label.statement;
5305 case STATEMENT_WHILE: {
5306 while_statement_t const *const whiles = &stmt->whiles;
5307 expression_t const *const cond = whiles->condition;
5309 if (!expression_returns(cond))
5312 int const val = determine_truth(cond);
5315 check_reachable(whiles->body);
5320 next = stmt->base.next;
5324 case STATEMENT_DO_WHILE:
5325 next = stmt->do_while.body;
5328 case STATEMENT_FOR: {
5329 for_statement_t *const fors = &stmt->fors;
5331 if (fors->condition_reachable)
5333 fors->condition_reachable = true;
5335 expression_t const *const cond = fors->condition;
5340 } else if (expression_returns(cond)) {
5341 val = determine_truth(cond);
5347 check_reachable(fors->body);
5352 next = stmt->base.next;
5356 case STATEMENT_MS_TRY: {
5357 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5358 check_reachable(ms_try->try_statement);
5359 next = ms_try->final_statement;
5363 case STATEMENT_LEAVE: {
5364 statement_t *parent = stmt;
5366 parent = parent->base.parent;
5367 if (parent == NULL) /* __leave not within __try */
5370 if (parent->kind == STATEMENT_MS_TRY) {
5372 next = parent->ms_try.final_statement;
5380 panic("invalid statement kind");
5383 while (next == NULL) {
5384 next = last->base.parent;
5386 noreturn_candidate = false;
5388 type_t *const type = skip_typeref(current_function->base.type);
5389 assert(is_type_function(type));
5390 type_t *const ret = skip_typeref(type->function.return_type);
5391 if (warning.return_type &&
5392 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5393 is_type_valid(ret) &&
5394 !is_sym_main(current_function->base.base.symbol)) {
5395 warningf(&stmt->base.source_position,
5396 "control reaches end of non-void function");
5401 switch (next->kind) {
5402 case STATEMENT_INVALID:
5403 case STATEMENT_EMPTY:
5404 case STATEMENT_DECLARATION:
5405 case STATEMENT_EXPRESSION:
5407 case STATEMENT_RETURN:
5408 case STATEMENT_CONTINUE:
5409 case STATEMENT_BREAK:
5410 case STATEMENT_GOTO:
5411 case STATEMENT_LEAVE:
5412 panic("invalid control flow in function");
5414 case STATEMENT_COMPOUND:
5415 if (next->compound.stmt_expr) {
5421 case STATEMENT_SWITCH:
5422 case STATEMENT_LABEL:
5423 case STATEMENT_CASE_LABEL:
5425 next = next->base.next;
5428 case STATEMENT_WHILE: {
5430 if (next->base.reachable)
5432 next->base.reachable = true;
5434 while_statement_t const *const whiles = &next->whiles;
5435 expression_t const *const cond = whiles->condition;
5437 if (!expression_returns(cond))
5440 int const val = determine_truth(cond);
5443 check_reachable(whiles->body);
5449 next = next->base.next;
5453 case STATEMENT_DO_WHILE: {
5455 if (next->base.reachable)
5457 next->base.reachable = true;
5459 do_while_statement_t const *const dw = &next->do_while;
5460 expression_t const *const cond = dw->condition;
5462 if (!expression_returns(cond))
5465 int const val = determine_truth(cond);
5468 check_reachable(dw->body);
5474 next = next->base.next;
5478 case STATEMENT_FOR: {
5480 for_statement_t *const fors = &next->fors;
5482 fors->step_reachable = true;
5484 if (fors->condition_reachable)
5486 fors->condition_reachable = true;
5488 expression_t const *const cond = fors->condition;
5493 } else if (expression_returns(cond)) {
5494 val = determine_truth(cond);
5500 check_reachable(fors->body);
5506 next = next->base.next;
5510 case STATEMENT_MS_TRY:
5512 next = next->ms_try.final_statement;
5517 check_reachable(next);
5520 static void check_unreachable(statement_t* const stmt, void *const env)
5524 switch (stmt->kind) {
5525 case STATEMENT_DO_WHILE:
5526 if (!stmt->base.reachable) {
5527 expression_t const *const cond = stmt->do_while.condition;
5528 if (determine_truth(cond) >= 0) {
5529 warningf(&cond->base.source_position,
5530 "condition of do-while-loop is unreachable");
5535 case STATEMENT_FOR: {
5536 for_statement_t const* const fors = &stmt->fors;
5538 // if init and step are unreachable, cond is unreachable, too
5539 if (!stmt->base.reachable && !fors->step_reachable) {
5540 warningf(&stmt->base.source_position, "statement is unreachable");
5542 if (!stmt->base.reachable && fors->initialisation != NULL) {
5543 warningf(&fors->initialisation->base.source_position,
5544 "initialisation of for-statement is unreachable");
5547 if (!fors->condition_reachable && fors->condition != NULL) {
5548 warningf(&fors->condition->base.source_position,
5549 "condition of for-statement is unreachable");
5552 if (!fors->step_reachable && fors->step != NULL) {
5553 warningf(&fors->step->base.source_position,
5554 "step of for-statement is unreachable");
5560 case STATEMENT_COMPOUND:
5561 if (stmt->compound.statements != NULL)
5563 goto warn_unreachable;
5565 case STATEMENT_DECLARATION: {
5566 /* Only warn if there is at least one declarator with an initializer.
5567 * This typically occurs in switch statements. */
5568 declaration_statement_t const *const decl = &stmt->declaration;
5569 entity_t const * ent = decl->declarations_begin;
5570 entity_t const *const last = decl->declarations_end;
5572 for (;; ent = ent->base.next) {
5573 if (ent->kind == ENTITY_VARIABLE &&
5574 ent->variable.initializer != NULL) {
5575 goto warn_unreachable;
5585 if (!stmt->base.reachable)
5586 warningf(&stmt->base.source_position, "statement is unreachable");
5591 static void parse_external_declaration(void)
5593 /* function-definitions and declarations both start with declaration
5595 declaration_specifiers_t specifiers;
5596 memset(&specifiers, 0, sizeof(specifiers));
5598 add_anchor_token(';');
5599 parse_declaration_specifiers(&specifiers);
5600 rem_anchor_token(';');
5602 /* must be a declaration */
5603 if (token.type == ';') {
5604 parse_anonymous_declaration_rest(&specifiers);
5608 add_anchor_token(',');
5609 add_anchor_token('=');
5610 add_anchor_token(';');
5611 add_anchor_token('{');
5613 /* declarator is common to both function-definitions and declarations */
5614 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5616 rem_anchor_token('{');
5617 rem_anchor_token(';');
5618 rem_anchor_token('=');
5619 rem_anchor_token(',');
5621 /* must be a declaration */
5622 switch (token.type) {
5626 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5631 /* must be a function definition */
5632 parse_kr_declaration_list(ndeclaration);
5634 if (token.type != '{') {
5635 parse_error_expected("while parsing function definition", '{', NULL);
5636 eat_until_matching_token(';');
5640 assert(is_declaration(ndeclaration));
5641 type_t *const orig_type = ndeclaration->declaration.type;
5642 type_t * type = skip_typeref(orig_type);
5644 if (!is_type_function(type)) {
5645 if (is_type_valid(type)) {
5646 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5647 type, ndeclaration->base.symbol);
5651 } else if (is_typeref(orig_type)) {
5653 errorf(&ndeclaration->base.source_position,
5654 "type of function definition '%#T' is a typedef",
5655 orig_type, ndeclaration->base.symbol);
5658 if (warning.aggregate_return &&
5659 is_type_compound(skip_typeref(type->function.return_type))) {
5660 warningf(HERE, "function '%Y' returns an aggregate",
5661 ndeclaration->base.symbol);
5663 if (warning.traditional && !type->function.unspecified_parameters) {
5664 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5665 ndeclaration->base.symbol);
5667 if (warning.old_style_definition && type->function.unspecified_parameters) {
5668 warningf(HERE, "old-style function definition '%Y'",
5669 ndeclaration->base.symbol);
5672 /* §6.7.5.3:14 a function definition with () means no
5673 * parameters (and not unspecified parameters) */
5674 if (type->function.unspecified_parameters &&
5675 type->function.parameters == NULL &&
5676 !type->function.kr_style_parameters) {
5677 type_t *copy = duplicate_type(type);
5678 copy->function.unspecified_parameters = false;
5679 type = identify_new_type(copy);
5681 ndeclaration->declaration.type = type;
5684 entity_t *const entity = record_entity(ndeclaration, true);
5685 assert(entity->kind == ENTITY_FUNCTION);
5686 assert(ndeclaration->kind == ENTITY_FUNCTION);
5688 function_t *function = &entity->function;
5689 if (ndeclaration != entity) {
5690 function->parameters = ndeclaration->function.parameters;
5692 assert(is_declaration(entity));
5693 type = skip_typeref(entity->declaration.type);
5695 /* push function parameters and switch scope */
5696 size_t const top = environment_top();
5697 scope_t *old_scope = scope_push(&function->parameters);
5699 entity_t *parameter = function->parameters.entities;
5700 for (; parameter != NULL; parameter = parameter->base.next) {
5701 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5702 parameter->base.parent_scope = current_scope;
5704 assert(parameter->base.parent_scope == NULL
5705 || parameter->base.parent_scope == current_scope);
5706 parameter->base.parent_scope = current_scope;
5707 if (parameter->base.symbol == NULL) {
5708 errorf(¶meter->base.source_position, "parameter name omitted");
5711 environment_push(parameter);
5714 if (function->statement != NULL) {
5715 parser_error_multiple_definition(entity, HERE);
5718 /* parse function body */
5719 int label_stack_top = label_top();
5720 function_t *old_current_function = current_function;
5721 current_function = function;
5722 current_parent = NULL;
5725 goto_anchor = &goto_first;
5727 label_anchor = &label_first;
5729 statement_t *const body = parse_compound_statement(false);
5730 function->statement = body;
5733 check_declarations();
5734 if (warning.return_type ||
5735 warning.unreachable_code ||
5736 (warning.missing_noreturn
5737 && !(function->base.modifiers & DM_NORETURN))) {
5738 noreturn_candidate = true;
5739 check_reachable(body);
5740 if (warning.unreachable_code)
5741 walk_statements(body, check_unreachable, NULL);
5742 if (warning.missing_noreturn &&
5743 noreturn_candidate &&
5744 !(function->base.modifiers & DM_NORETURN)) {
5745 warningf(&body->base.source_position,
5746 "function '%#T' is candidate for attribute 'noreturn'",
5747 type, entity->base.symbol);
5751 assert(current_parent == NULL);
5752 assert(current_function == function);
5753 current_function = old_current_function;
5754 label_pop_to(label_stack_top);
5757 assert(current_scope == &function->parameters);
5758 scope_pop(old_scope);
5759 environment_pop_to(top);
5762 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5763 source_position_t *source_position,
5764 const symbol_t *symbol)
5766 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5768 type->bitfield.base_type = base_type;
5769 type->bitfield.size_expression = size;
5772 type_t *skipped_type = skip_typeref(base_type);
5773 if (!is_type_integer(skipped_type)) {
5774 errorf(HERE, "bitfield base type '%T' is not an integer type",
5778 bit_size = get_type_size(base_type) * 8;
5781 if (is_constant_expression(size)) {
5782 long v = fold_constant_to_int(size);
5783 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5786 errorf(source_position, "negative width in bit-field '%Y'",
5788 } else if (v == 0 && symbol != NULL) {
5789 errorf(source_position, "zero width for bit-field '%Y'",
5791 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5792 errorf(source_position, "width of '%Y' exceeds its type",
5795 type->bitfield.bit_size = v;
5802 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5804 entity_t *iter = compound->members.entities;
5805 for (; iter != NULL; iter = iter->base.next) {
5806 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5809 if (iter->base.symbol == symbol) {
5811 } else if (iter->base.symbol == NULL) {
5812 /* search in anonymous structs and unions */
5813 type_t *type = skip_typeref(iter->declaration.type);
5814 if (is_type_compound(type)) {
5815 if (find_compound_entry(type->compound.compound, symbol)
5826 static void check_deprecated(const source_position_t *source_position,
5827 const entity_t *entity)
5829 if (!warning.deprecated_declarations)
5831 if (!is_declaration(entity))
5833 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5836 char const *const prefix = get_entity_kind_name(entity->kind);
5837 const char *deprecated_string
5838 = get_deprecated_string(entity->declaration.attributes);
5839 if (deprecated_string != NULL) {
5840 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5841 prefix, entity->base.symbol, &entity->base.source_position,
5844 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5845 entity->base.symbol, &entity->base.source_position);
5850 static expression_t *create_select(const source_position_t *pos,
5852 type_qualifiers_t qualifiers,
5855 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5857 check_deprecated(pos, entry);
5859 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5860 select->select.compound = addr;
5861 select->select.compound_entry = entry;
5863 type_t *entry_type = entry->declaration.type;
5864 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5866 /* we always do the auto-type conversions; the & and sizeof parser contains
5867 * code to revert this! */
5868 select->base.type = automatic_type_conversion(res_type);
5869 if (res_type->kind == TYPE_BITFIELD) {
5870 select->base.type = res_type->bitfield.base_type;
5877 * Find entry with symbol in compound. Search anonymous structs and unions and
5878 * creates implicit select expressions for them.
5879 * Returns the adress for the innermost compound.
5881 static expression_t *find_create_select(const source_position_t *pos,
5883 type_qualifiers_t qualifiers,
5884 compound_t *compound, symbol_t *symbol)
5886 entity_t *iter = compound->members.entities;
5887 for (; iter != NULL; iter = iter->base.next) {
5888 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5891 symbol_t *iter_symbol = iter->base.symbol;
5892 if (iter_symbol == NULL) {
5893 type_t *type = iter->declaration.type;
5894 if (type->kind != TYPE_COMPOUND_STRUCT
5895 && type->kind != TYPE_COMPOUND_UNION)
5898 compound_t *sub_compound = type->compound.compound;
5900 if (find_compound_entry(sub_compound, symbol) == NULL)
5903 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5904 sub_addr->base.source_position = *pos;
5905 sub_addr->select.implicit = true;
5906 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5910 if (iter_symbol == symbol) {
5911 return create_select(pos, addr, qualifiers, iter);
5918 static void parse_compound_declarators(compound_t *compound,
5919 const declaration_specifiers_t *specifiers)
5924 if (token.type == ':') {
5925 source_position_t source_position = *HERE;
5928 type_t *base_type = specifiers->type;
5929 expression_t *size = parse_constant_expression();
5931 type_t *type = make_bitfield_type(base_type, size,
5932 &source_position, NULL);
5934 attribute_t *attributes = parse_attributes(NULL);
5935 if (attributes != NULL) {
5936 attribute_t *last = attributes;
5937 while (last->next != NULL)
5939 last->next = specifiers->attributes;
5941 attributes = specifiers->attributes;
5944 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5945 entity->base.namespc = NAMESPACE_NORMAL;
5946 entity->base.source_position = source_position;
5947 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5948 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5949 entity->declaration.type = type;
5950 entity->declaration.attributes = attributes;
5952 if (attributes != NULL) {
5953 handle_entity_attributes(attributes, entity);
5955 append_entity(&compound->members, entity);
5957 entity = parse_declarator(specifiers,
5958 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5959 if (entity->kind == ENTITY_TYPEDEF) {
5960 errorf(&entity->base.source_position,
5961 "typedef not allowed as compound member");
5963 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5965 /* make sure we don't define a symbol multiple times */
5966 symbol_t *symbol = entity->base.symbol;
5967 if (symbol != NULL) {
5968 entity_t *prev = find_compound_entry(compound, symbol);
5970 errorf(&entity->base.source_position,
5971 "multiple declarations of symbol '%Y' (declared %P)",
5972 symbol, &prev->base.source_position);
5976 if (token.type == ':') {
5977 source_position_t source_position = *HERE;
5979 expression_t *size = parse_constant_expression();
5981 type_t *type = entity->declaration.type;
5982 type_t *bitfield_type = make_bitfield_type(type, size,
5983 &source_position, entity->base.symbol);
5985 attribute_t *attributes = parse_attributes(NULL);
5986 entity->declaration.type = bitfield_type;
5987 handle_entity_attributes(attributes, entity);
5989 type_t *orig_type = entity->declaration.type;
5990 type_t *type = skip_typeref(orig_type);
5991 if (is_type_function(type)) {
5992 errorf(&entity->base.source_position,
5993 "compound member '%Y' must not have function type '%T'",
5994 entity->base.symbol, orig_type);
5995 } else if (is_type_incomplete(type)) {
5996 /* §6.7.2.1:16 flexible array member */
5997 if (!is_type_array(type) ||
5998 token.type != ';' ||
5999 look_ahead(1)->type != '}') {
6000 errorf(&entity->base.source_position,
6001 "compound member '%Y' has incomplete type '%T'",
6002 entity->base.symbol, orig_type);
6007 append_entity(&compound->members, entity);
6011 if (token.type != ',')
6015 expect(';', end_error);
6018 anonymous_entity = NULL;
6021 static void parse_compound_type_entries(compound_t *compound)
6024 add_anchor_token('}');
6026 while (token.type != '}') {
6027 if (token.type == T_EOF) {
6028 errorf(HERE, "EOF while parsing struct");
6031 declaration_specifiers_t specifiers;
6032 memset(&specifiers, 0, sizeof(specifiers));
6033 parse_declaration_specifiers(&specifiers);
6035 parse_compound_declarators(compound, &specifiers);
6037 rem_anchor_token('}');
6041 compound->complete = true;
6044 static type_t *parse_typename(void)
6046 declaration_specifiers_t specifiers;
6047 memset(&specifiers, 0, sizeof(specifiers));
6048 parse_declaration_specifiers(&specifiers);
6049 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6050 specifiers.thread_local) {
6051 /* TODO: improve error message, user does probably not know what a
6052 * storage class is...
6054 errorf(HERE, "typename may not have a storage class");
6057 type_t *result = parse_abstract_declarator(specifiers.type);
6065 typedef expression_t* (*parse_expression_function)(void);
6066 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6068 typedef struct expression_parser_function_t expression_parser_function_t;
6069 struct expression_parser_function_t {
6070 parse_expression_function parser;
6071 precedence_t infix_precedence;
6072 parse_expression_infix_function infix_parser;
6075 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6078 * Prints an error message if an expression was expected but not read
6080 static expression_t *expected_expression_error(void)
6082 /* skip the error message if the error token was read */
6083 if (token.type != T_ERROR) {
6084 errorf(HERE, "expected expression, got token %K", &token);
6088 return create_invalid_expression();
6092 * Parse a string constant.
6094 static expression_t *parse_string_const(void)
6097 if (token.type == T_STRING_LITERAL) {
6098 string_t res = token.v.string;
6100 while (token.type == T_STRING_LITERAL) {
6101 res = concat_strings(&res, &token.v.string);
6104 if (token.type != T_WIDE_STRING_LITERAL) {
6105 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6106 /* note: that we use type_char_ptr here, which is already the
6107 * automatic converted type. revert_automatic_type_conversion
6108 * will construct the array type */
6109 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6110 cnst->string.value = res;
6114 wres = concat_string_wide_string(&res, &token.v.wide_string);
6116 wres = token.v.wide_string;
6121 switch (token.type) {
6122 case T_WIDE_STRING_LITERAL:
6123 wres = concat_wide_strings(&wres, &token.v.wide_string);
6126 case T_STRING_LITERAL:
6127 wres = concat_wide_string_string(&wres, &token.v.string);
6131 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6132 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6133 cnst->wide_string.value = wres;
6142 * Parse a boolean constant.
6144 static expression_t *parse_bool_const(bool value)
6146 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6147 cnst->base.type = type_bool;
6148 cnst->conste.v.int_value = value;
6156 * Parse an integer constant.
6158 static expression_t *parse_int_const(void)
6160 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6161 cnst->base.type = token.datatype;
6162 cnst->conste.v.int_value = token.v.intvalue;
6170 * Parse a character constant.
6172 static expression_t *parse_character_constant(void)
6174 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6175 cnst->base.type = token.datatype;
6176 cnst->conste.v.character = token.v.string;
6178 if (cnst->conste.v.character.size != 1) {
6180 errorf(HERE, "more than 1 character in character constant");
6181 } else if (warning.multichar) {
6182 warningf(HERE, "multi-character character constant");
6191 * Parse a wide character constant.
6193 static expression_t *parse_wide_character_constant(void)
6195 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6196 cnst->base.type = token.datatype;
6197 cnst->conste.v.wide_character = token.v.wide_string;
6199 if (cnst->conste.v.wide_character.size != 1) {
6201 errorf(HERE, "more than 1 character in character constant");
6202 } else if (warning.multichar) {
6203 warningf(HERE, "multi-character character constant");
6212 * Parse a float constant.
6214 static expression_t *parse_float_const(void)
6216 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6217 cnst->base.type = token.datatype;
6218 cnst->conste.v.float_value = token.v.floatvalue;
6225 static entity_t *create_implicit_function(symbol_t *symbol,
6226 const source_position_t *source_position)
6228 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6229 ntype->function.return_type = type_int;
6230 ntype->function.unspecified_parameters = true;
6231 ntype->function.linkage = LINKAGE_C;
6232 type_t *type = identify_new_type(ntype);
6234 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6235 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6236 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6237 entity->declaration.type = type;
6238 entity->declaration.implicit = true;
6239 entity->base.symbol = symbol;
6240 entity->base.source_position = *source_position;
6242 if (current_scope != NULL) {
6243 bool strict_prototypes_old = warning.strict_prototypes;
6244 warning.strict_prototypes = false;
6245 record_entity(entity, false);
6246 warning.strict_prototypes = strict_prototypes_old;
6253 * Creates a return_type (func)(argument_type) function type if not
6256 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6257 type_t *argument_type2)
6259 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6260 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6261 parameter1->next = parameter2;
6263 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6264 type->function.return_type = return_type;
6265 type->function.parameters = parameter1;
6267 return identify_new_type(type);
6271 * Creates a return_type (func)(argument_type) function type if not
6274 * @param return_type the return type
6275 * @param argument_type the argument type
6277 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6279 function_parameter_t *const parameter = allocate_parameter(argument_type);
6281 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6282 type->function.return_type = return_type;
6283 type->function.parameters = parameter;
6285 return identify_new_type(type);
6288 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6290 type_t *res = make_function_1_type(return_type, argument_type);
6291 res->function.variadic = 1;
6296 * Creates a return_type (func)(void) function type if not
6299 * @param return_type the return type
6301 static type_t *make_function_0_type(type_t *return_type)
6303 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6304 type->function.return_type = return_type;
6305 type->function.parameters = NULL;
6307 return identify_new_type(type);
6311 * Creates a NO_RETURN return_type (func)(void) function type if not
6314 * @param return_type the return type
6316 static type_t *make_function_0_type_noreturn(type_t *return_type)
6318 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6319 type->function.return_type = return_type;
6320 type->function.parameters = NULL;
6321 type->function.modifiers |= DM_NORETURN;
6322 return identify_new_type(type);
6326 * Performs automatic type cast as described in §6.3.2.1.
6328 * @param orig_type the original type
6330 static type_t *automatic_type_conversion(type_t *orig_type)
6332 type_t *type = skip_typeref(orig_type);
6333 if (is_type_array(type)) {
6334 array_type_t *array_type = &type->array;
6335 type_t *element_type = array_type->element_type;
6336 unsigned qualifiers = array_type->base.qualifiers;
6338 return make_pointer_type(element_type, qualifiers);
6341 if (is_type_function(type)) {
6342 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6349 * reverts the automatic casts of array to pointer types and function
6350 * to function-pointer types as defined §6.3.2.1
6352 type_t *revert_automatic_type_conversion(const expression_t *expression)
6354 switch (expression->kind) {
6355 case EXPR_REFERENCE: {
6356 entity_t *entity = expression->reference.entity;
6357 if (is_declaration(entity)) {
6358 return entity->declaration.type;
6359 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6360 return entity->enum_value.enum_type;
6362 panic("no declaration or enum in reference");
6367 entity_t *entity = expression->select.compound_entry;
6368 assert(is_declaration(entity));
6369 type_t *type = entity->declaration.type;
6370 return get_qualified_type(type,
6371 expression->base.type->base.qualifiers);
6374 case EXPR_UNARY_DEREFERENCE: {
6375 const expression_t *const value = expression->unary.value;
6376 type_t *const type = skip_typeref(value->base.type);
6377 if (!is_type_pointer(type))
6378 return type_error_type;
6379 return type->pointer.points_to;
6382 case EXPR_ARRAY_ACCESS: {
6383 const expression_t *array_ref = expression->array_access.array_ref;
6384 type_t *type_left = skip_typeref(array_ref->base.type);
6385 if (!is_type_pointer(type_left))
6386 return type_error_type;
6387 return type_left->pointer.points_to;
6390 case EXPR_STRING_LITERAL: {
6391 size_t size = expression->string.value.size;
6392 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6395 case EXPR_WIDE_STRING_LITERAL: {
6396 size_t size = expression->wide_string.value.size;
6397 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6400 case EXPR_COMPOUND_LITERAL:
6401 return expression->compound_literal.type;
6404 return expression->base.type;
6408 static expression_t *parse_reference(void)
6410 symbol_t *const symbol = token.v.symbol;
6412 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6414 if (entity == NULL) {
6415 if (!strict_mode && look_ahead(1)->type == '(') {
6416 /* an implicitly declared function */
6417 if (warning.error_implicit_function_declaration) {
6418 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6419 } else if (warning.implicit_function_declaration) {
6420 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6423 entity = create_implicit_function(symbol, HERE);
6425 errorf(HERE, "unknown identifier '%Y' found.", symbol);
6426 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6432 if (is_declaration(entity)) {
6433 orig_type = entity->declaration.type;
6434 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6435 orig_type = entity->enum_value.enum_type;
6437 panic("expected declaration or enum value in reference");
6440 /* we always do the auto-type conversions; the & and sizeof parser contains
6441 * code to revert this! */
6442 type_t *type = automatic_type_conversion(orig_type);
6444 expression_kind_t kind = EXPR_REFERENCE;
6445 if (entity->kind == ENTITY_ENUM_VALUE)
6446 kind = EXPR_REFERENCE_ENUM_VALUE;
6448 expression_t *expression = allocate_expression_zero(kind);
6449 expression->reference.entity = entity;
6450 expression->base.type = type;
6452 /* this declaration is used */
6453 if (is_declaration(entity)) {
6454 entity->declaration.used = true;
6457 if (entity->base.parent_scope != file_scope
6458 && (current_function != NULL && entity->base.parent_scope->depth < current_function->parameters.depth)
6459 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6460 if (entity->kind == ENTITY_VARIABLE) {
6461 /* access of a variable from an outer function */
6462 entity->variable.address_taken = true;
6463 } else if (entity->kind == ENTITY_PARAMETER) {
6464 entity->parameter.address_taken = true;
6466 current_function->need_closure = true;
6469 check_deprecated(HERE, entity);
6471 if (warning.init_self && entity == current_init_decl && !in_type_prop
6472 && entity->kind == ENTITY_VARIABLE) {
6473 current_init_decl = NULL;
6474 warningf(HERE, "variable '%#T' is initialized by itself",
6475 entity->declaration.type, entity->base.symbol);
6482 static bool semantic_cast(expression_t *cast)
6484 expression_t *expression = cast->unary.value;
6485 type_t *orig_dest_type = cast->base.type;
6486 type_t *orig_type_right = expression->base.type;
6487 type_t const *dst_type = skip_typeref(orig_dest_type);
6488 type_t const *src_type = skip_typeref(orig_type_right);
6489 source_position_t const *pos = &cast->base.source_position;
6491 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6492 if (dst_type == type_void)
6495 /* only integer and pointer can be casted to pointer */
6496 if (is_type_pointer(dst_type) &&
6497 !is_type_pointer(src_type) &&
6498 !is_type_integer(src_type) &&
6499 is_type_valid(src_type)) {
6500 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6504 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6505 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6509 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6510 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6514 if (warning.cast_qual &&
6515 is_type_pointer(src_type) &&
6516 is_type_pointer(dst_type)) {
6517 type_t *src = skip_typeref(src_type->pointer.points_to);
6518 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6519 unsigned missing_qualifiers =
6520 src->base.qualifiers & ~dst->base.qualifiers;
6521 if (missing_qualifiers != 0) {
6523 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6524 missing_qualifiers, orig_type_right);
6530 static expression_t *parse_compound_literal(type_t *type)
6532 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6534 parse_initializer_env_t env;
6537 env.must_be_constant = false;
6538 initializer_t *initializer = parse_initializer(&env);
6541 expression->compound_literal.initializer = initializer;
6542 expression->compound_literal.type = type;
6543 expression->base.type = automatic_type_conversion(type);
6549 * Parse a cast expression.
6551 static expression_t *parse_cast(void)
6553 add_anchor_token(')');
6555 source_position_t source_position = token.source_position;
6557 type_t *type = parse_typename();
6559 rem_anchor_token(')');
6560 expect(')', end_error);
6562 if (token.type == '{') {
6563 return parse_compound_literal(type);
6566 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6567 cast->base.source_position = source_position;
6569 expression_t *value = parse_sub_expression(PREC_CAST);
6570 cast->base.type = type;
6571 cast->unary.value = value;
6573 if (! semantic_cast(cast)) {
6574 /* TODO: record the error in the AST. else it is impossible to detect it */
6579 return create_invalid_expression();
6583 * Parse a statement expression.
6585 static expression_t *parse_statement_expression(void)
6587 add_anchor_token(')');
6589 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6591 statement_t *statement = parse_compound_statement(true);
6592 statement->compound.stmt_expr = true;
6593 expression->statement.statement = statement;
6595 /* find last statement and use its type */
6596 type_t *type = type_void;
6597 const statement_t *stmt = statement->compound.statements;
6599 while (stmt->base.next != NULL)
6600 stmt = stmt->base.next;
6602 if (stmt->kind == STATEMENT_EXPRESSION) {
6603 type = stmt->expression.expression->base.type;
6605 } else if (warning.other) {
6606 warningf(&expression->base.source_position, "empty statement expression ({})");
6608 expression->base.type = type;
6610 rem_anchor_token(')');
6611 expect(')', end_error);
6618 * Parse a parenthesized expression.
6620 static expression_t *parse_parenthesized_expression(void)
6624 switch (token.type) {
6626 /* gcc extension: a statement expression */
6627 return parse_statement_expression();
6631 return parse_cast();
6633 if (is_typedef_symbol(token.v.symbol)) {
6634 return parse_cast();
6638 add_anchor_token(')');
6639 expression_t *result = parse_expression();
6640 result->base.parenthesized = true;
6641 rem_anchor_token(')');
6642 expect(')', end_error);
6648 static expression_t *parse_function_keyword(void)
6652 if (current_function == NULL) {
6653 errorf(HERE, "'__func__' used outside of a function");
6656 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6657 expression->base.type = type_char_ptr;
6658 expression->funcname.kind = FUNCNAME_FUNCTION;
6665 static expression_t *parse_pretty_function_keyword(void)
6667 if (current_function == NULL) {
6668 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6671 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6672 expression->base.type = type_char_ptr;
6673 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6675 eat(T___PRETTY_FUNCTION__);
6680 static expression_t *parse_funcsig_keyword(void)
6682 if (current_function == NULL) {
6683 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6686 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6687 expression->base.type = type_char_ptr;
6688 expression->funcname.kind = FUNCNAME_FUNCSIG;
6695 static expression_t *parse_funcdname_keyword(void)
6697 if (current_function == NULL) {
6698 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6701 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6702 expression->base.type = type_char_ptr;
6703 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6705 eat(T___FUNCDNAME__);
6710 static designator_t *parse_designator(void)
6712 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6713 result->source_position = *HERE;
6715 if (token.type != T_IDENTIFIER) {
6716 parse_error_expected("while parsing member designator",
6717 T_IDENTIFIER, NULL);
6720 result->symbol = token.v.symbol;
6723 designator_t *last_designator = result;
6725 if (token.type == '.') {
6727 if (token.type != T_IDENTIFIER) {
6728 parse_error_expected("while parsing member designator",
6729 T_IDENTIFIER, NULL);
6732 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6733 designator->source_position = *HERE;
6734 designator->symbol = token.v.symbol;
6737 last_designator->next = designator;
6738 last_designator = designator;
6741 if (token.type == '[') {
6743 add_anchor_token(']');
6744 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6745 designator->source_position = *HERE;
6746 designator->array_index = parse_expression();
6747 rem_anchor_token(']');
6748 expect(']', end_error);
6749 if (designator->array_index == NULL) {
6753 last_designator->next = designator;
6754 last_designator = designator;
6766 * Parse the __builtin_offsetof() expression.
6768 static expression_t *parse_offsetof(void)
6770 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6771 expression->base.type = type_size_t;
6773 eat(T___builtin_offsetof);
6775 expect('(', end_error);
6776 add_anchor_token(',');
6777 type_t *type = parse_typename();
6778 rem_anchor_token(',');
6779 expect(',', end_error);
6780 add_anchor_token(')');
6781 designator_t *designator = parse_designator();
6782 rem_anchor_token(')');
6783 expect(')', end_error);
6785 expression->offsetofe.type = type;
6786 expression->offsetofe.designator = designator;
6789 memset(&path, 0, sizeof(path));
6790 path.top_type = type;
6791 path.path = NEW_ARR_F(type_path_entry_t, 0);
6793 descend_into_subtype(&path);
6795 if (!walk_designator(&path, designator, true)) {
6796 return create_invalid_expression();
6799 DEL_ARR_F(path.path);
6803 return create_invalid_expression();
6807 * Parses a _builtin_va_start() expression.
6809 static expression_t *parse_va_start(void)
6811 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6813 eat(T___builtin_va_start);
6815 expect('(', end_error);
6816 add_anchor_token(',');
6817 expression->va_starte.ap = parse_assignment_expression();
6818 rem_anchor_token(',');
6819 expect(',', end_error);
6820 expression_t *const expr = parse_assignment_expression();
6821 if (expr->kind == EXPR_REFERENCE) {
6822 entity_t *const entity = expr->reference.entity;
6823 if (entity->base.parent_scope != ¤t_function->parameters
6824 || entity->base.next != NULL
6825 || entity->kind != ENTITY_PARAMETER) {
6826 errorf(&expr->base.source_position,
6827 "second argument of 'va_start' must be last parameter of the current function");
6829 expression->va_starte.parameter = &entity->variable;
6831 expect(')', end_error);
6834 expect(')', end_error);
6836 return create_invalid_expression();
6840 * Parses a __builtin_va_arg() expression.
6842 static expression_t *parse_va_arg(void)
6844 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6846 eat(T___builtin_va_arg);
6848 expect('(', end_error);
6850 ap.expression = parse_assignment_expression();
6851 expression->va_arge.ap = ap.expression;
6852 check_call_argument(type_valist, &ap, 1);
6854 expect(',', end_error);
6855 expression->base.type = parse_typename();
6856 expect(')', end_error);
6860 return create_invalid_expression();
6864 * Parses a __builtin_va_copy() expression.
6866 static expression_t *parse_va_copy(void)
6868 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6870 eat(T___builtin_va_copy);
6872 expect('(', end_error);
6873 expression_t *dst = parse_assignment_expression();
6874 assign_error_t error = semantic_assign(type_valist, dst);
6875 report_assign_error(error, type_valist, dst, "call argument 1",
6876 &dst->base.source_position);
6877 expression->va_copye.dst = dst;
6879 expect(',', end_error);
6881 call_argument_t src;
6882 src.expression = parse_assignment_expression();
6883 check_call_argument(type_valist, &src, 2);
6884 expression->va_copye.src = src.expression;
6885 expect(')', end_error);
6889 return create_invalid_expression();
6893 * Parses a __builtin_constant_p() expression.
6895 static expression_t *parse_builtin_constant(void)
6897 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6899 eat(T___builtin_constant_p);
6901 expect('(', end_error);
6902 add_anchor_token(')');
6903 expression->builtin_constant.value = parse_assignment_expression();
6904 rem_anchor_token(')');
6905 expect(')', end_error);
6906 expression->base.type = type_int;
6910 return create_invalid_expression();
6914 * Parses a __builtin_types_compatible_p() expression.
6916 static expression_t *parse_builtin_types_compatible(void)
6918 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6920 eat(T___builtin_types_compatible_p);
6922 expect('(', end_error);
6923 add_anchor_token(')');
6924 add_anchor_token(',');
6925 expression->builtin_types_compatible.left = parse_typename();
6926 rem_anchor_token(',');
6927 expect(',', end_error);
6928 expression->builtin_types_compatible.right = parse_typename();
6929 rem_anchor_token(')');
6930 expect(')', end_error);
6931 expression->base.type = type_int;
6935 return create_invalid_expression();
6939 * Parses a __builtin_is_*() compare expression.
6941 static expression_t *parse_compare_builtin(void)
6943 expression_t *expression;
6945 switch (token.type) {
6946 case T___builtin_isgreater:
6947 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6949 case T___builtin_isgreaterequal:
6950 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6952 case T___builtin_isless:
6953 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6955 case T___builtin_islessequal:
6956 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6958 case T___builtin_islessgreater:
6959 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6961 case T___builtin_isunordered:
6962 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6965 internal_errorf(HERE, "invalid compare builtin found");
6967 expression->base.source_position = *HERE;
6970 expect('(', end_error);
6971 expression->binary.left = parse_assignment_expression();
6972 expect(',', end_error);
6973 expression->binary.right = parse_assignment_expression();
6974 expect(')', end_error);
6976 type_t *const orig_type_left = expression->binary.left->base.type;
6977 type_t *const orig_type_right = expression->binary.right->base.type;
6979 type_t *const type_left = skip_typeref(orig_type_left);
6980 type_t *const type_right = skip_typeref(orig_type_right);
6981 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6982 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6983 type_error_incompatible("invalid operands in comparison",
6984 &expression->base.source_position, orig_type_left, orig_type_right);
6987 semantic_comparison(&expression->binary);
6992 return create_invalid_expression();
6997 * Parses a __builtin_expect(, end_error) expression.
6999 static expression_t *parse_builtin_expect(void, end_error)
7001 expression_t *expression
7002 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7004 eat(T___builtin_expect);
7006 expect('(', end_error);
7007 expression->binary.left = parse_assignment_expression();
7008 expect(',', end_error);
7009 expression->binary.right = parse_constant_expression();
7010 expect(')', end_error);
7012 expression->base.type = expression->binary.left->base.type;
7016 return create_invalid_expression();
7021 * Parses a MS assume() expression.
7023 static expression_t *parse_assume(void)
7025 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7029 expect('(', end_error);
7030 add_anchor_token(')');
7031 expression->unary.value = parse_assignment_expression();
7032 rem_anchor_token(')');
7033 expect(')', end_error);
7035 expression->base.type = type_void;
7038 return create_invalid_expression();
7042 * Return the declaration for a given label symbol or create a new one.
7044 * @param symbol the symbol of the label
7046 static label_t *get_label(symbol_t *symbol)
7049 assert(current_function != NULL);
7051 label = get_entity(symbol, NAMESPACE_LABEL);
7052 /* if we found a local label, we already created the declaration */
7053 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7054 if (label->base.parent_scope != current_scope) {
7055 assert(label->base.parent_scope->depth < current_scope->depth);
7056 current_function->goto_to_outer = true;
7058 return &label->label;
7061 label = get_entity(symbol, NAMESPACE_LABEL);
7062 /* if we found a label in the same function, then we already created the
7065 && label->base.parent_scope == ¤t_function->parameters) {
7066 return &label->label;
7069 /* otherwise we need to create a new one */
7070 label = allocate_entity_zero(ENTITY_LABEL);
7071 label->base.namespc = NAMESPACE_LABEL;
7072 label->base.symbol = symbol;
7076 return &label->label;
7080 * Parses a GNU && label address expression.
7082 static expression_t *parse_label_address(void)
7084 source_position_t source_position = token.source_position;
7086 if (token.type != T_IDENTIFIER) {
7087 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7090 symbol_t *symbol = token.v.symbol;
7093 label_t *label = get_label(symbol);
7095 label->address_taken = true;
7097 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7098 expression->base.source_position = source_position;
7100 /* label address is threaten as a void pointer */
7101 expression->base.type = type_void_ptr;
7102 expression->label_address.label = label;
7105 return create_invalid_expression();
7109 * Parse a microsoft __noop expression.
7111 static expression_t *parse_noop_expression(void)
7113 /* the result is a (int)0 */
7114 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7115 cnst->base.type = type_int;
7116 cnst->conste.v.int_value = 0;
7117 cnst->conste.is_ms_noop = true;
7121 if (token.type == '(') {
7122 /* parse arguments */
7124 add_anchor_token(')');
7125 add_anchor_token(',');
7127 if (token.type != ')') {
7129 (void)parse_assignment_expression();
7130 if (token.type != ',')
7136 rem_anchor_token(',');
7137 rem_anchor_token(')');
7138 expect(')', end_error);
7145 * Parses a primary expression.
7147 static expression_t *parse_primary_expression(void)
7149 switch (token.type) {
7150 case T_false: return parse_bool_const(false);
7151 case T_true: return parse_bool_const(true);
7152 case T_INTEGER: return parse_int_const();
7153 case T_CHARACTER_CONSTANT: return parse_character_constant();
7154 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7155 case T_FLOATINGPOINT: return parse_float_const();
7156 case T_STRING_LITERAL:
7157 case T_WIDE_STRING_LITERAL: return parse_string_const();
7158 case T___FUNCTION__:
7159 case T___func__: return parse_function_keyword();
7160 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7161 case T___FUNCSIG__: return parse_funcsig_keyword();
7162 case T___FUNCDNAME__: return parse_funcdname_keyword();
7163 case T___builtin_offsetof: return parse_offsetof();
7164 case T___builtin_va_start: return parse_va_start();
7165 case T___builtin_va_arg: return parse_va_arg();
7166 case T___builtin_va_copy: return parse_va_copy();
7167 case T___builtin_isgreater:
7168 case T___builtin_isgreaterequal:
7169 case T___builtin_isless:
7170 case T___builtin_islessequal:
7171 case T___builtin_islessgreater:
7172 case T___builtin_isunordered: return parse_compare_builtin();
7173 case T___builtin_constant_p: return parse_builtin_constant();
7174 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7175 case T__assume: return parse_assume();
7178 return parse_label_address();
7181 case '(': return parse_parenthesized_expression();
7182 case T___noop: return parse_noop_expression();
7184 /* Gracefully handle type names while parsing expressions. */
7186 if (!is_typedef_symbol(token.v.symbol)) {
7187 return parse_reference();
7191 source_position_t const pos = *HERE;
7192 type_t const *const type = parse_typename();
7193 errorf(&pos, "encountered type '%T' while parsing expression", type);
7194 return create_invalid_expression();
7198 errorf(HERE, "unexpected token %K, expected an expression", &token);
7199 return create_invalid_expression();
7203 * Check if the expression has the character type and issue a warning then.
7205 static void check_for_char_index_type(const expression_t *expression)
7207 type_t *const type = expression->base.type;
7208 const type_t *const base_type = skip_typeref(type);
7210 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7211 warning.char_subscripts) {
7212 warningf(&expression->base.source_position,
7213 "array subscript has type '%T'", type);
7217 static expression_t *parse_array_expression(expression_t *left)
7219 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7222 add_anchor_token(']');
7224 expression_t *inside = parse_expression();
7226 type_t *const orig_type_left = left->base.type;
7227 type_t *const orig_type_inside = inside->base.type;
7229 type_t *const type_left = skip_typeref(orig_type_left);
7230 type_t *const type_inside = skip_typeref(orig_type_inside);
7232 type_t *return_type;
7233 array_access_expression_t *array_access = &expression->array_access;
7234 if (is_type_pointer(type_left)) {
7235 return_type = type_left->pointer.points_to;
7236 array_access->array_ref = left;
7237 array_access->index = inside;
7238 check_for_char_index_type(inside);
7239 } else if (is_type_pointer(type_inside)) {
7240 return_type = type_inside->pointer.points_to;
7241 array_access->array_ref = inside;
7242 array_access->index = left;
7243 array_access->flipped = true;
7244 check_for_char_index_type(left);
7246 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7248 "array access on object with non-pointer types '%T', '%T'",
7249 orig_type_left, orig_type_inside);
7251 return_type = type_error_type;
7252 array_access->array_ref = left;
7253 array_access->index = inside;
7256 expression->base.type = automatic_type_conversion(return_type);
7258 rem_anchor_token(']');
7259 expect(']', end_error);
7264 static expression_t *parse_typeprop(expression_kind_t const kind)
7266 expression_t *tp_expression = allocate_expression_zero(kind);
7267 tp_expression->base.type = type_size_t;
7269 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7271 /* we only refer to a type property, mark this case */
7272 bool old = in_type_prop;
7273 in_type_prop = true;
7276 expression_t *expression;
7277 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7279 add_anchor_token(')');
7280 orig_type = parse_typename();
7281 rem_anchor_token(')');
7282 expect(')', end_error);
7284 if (token.type == '{') {
7285 /* It was not sizeof(type) after all. It is sizeof of an expression
7286 * starting with a compound literal */
7287 expression = parse_compound_literal(orig_type);
7288 goto typeprop_expression;
7291 expression = parse_sub_expression(PREC_UNARY);
7293 typeprop_expression:
7294 tp_expression->typeprop.tp_expression = expression;
7296 orig_type = revert_automatic_type_conversion(expression);
7297 expression->base.type = orig_type;
7300 tp_expression->typeprop.type = orig_type;
7301 type_t const* const type = skip_typeref(orig_type);
7302 char const* const wrong_type =
7303 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7304 is_type_incomplete(type) ? "incomplete" :
7305 type->kind == TYPE_FUNCTION ? "function designator" :
7306 type->kind == TYPE_BITFIELD ? "bitfield" :
7308 if (wrong_type != NULL) {
7309 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7310 errorf(&tp_expression->base.source_position,
7311 "operand of %s expression must not be of %s type '%T'",
7312 what, wrong_type, orig_type);
7317 return tp_expression;
7320 static expression_t *parse_sizeof(void)
7322 return parse_typeprop(EXPR_SIZEOF);
7325 static expression_t *parse_alignof(void)
7327 return parse_typeprop(EXPR_ALIGNOF);
7330 static expression_t *parse_select_expression(expression_t *addr)
7332 assert(token.type == '.' || token.type == T_MINUSGREATER);
7333 bool select_left_arrow = (token.type == T_MINUSGREATER);
7336 if (token.type != T_IDENTIFIER) {
7337 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7338 return create_invalid_expression();
7340 symbol_t *symbol = token.v.symbol;
7343 type_t *const orig_type = addr->base.type;
7344 type_t *const type = skip_typeref(orig_type);
7347 bool saw_error = false;
7348 if (is_type_pointer(type)) {
7349 if (!select_left_arrow) {
7351 "request for member '%Y' in something not a struct or union, but '%T'",
7355 type_left = skip_typeref(type->pointer.points_to);
7357 if (select_left_arrow && is_type_valid(type)) {
7358 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7364 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7365 type_left->kind != TYPE_COMPOUND_UNION) {
7367 if (is_type_valid(type_left) && !saw_error) {
7369 "request for member '%Y' in something not a struct or union, but '%T'",
7372 return create_invalid_expression();
7375 compound_t *compound = type_left->compound.compound;
7376 if (!compound->complete) {
7377 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7379 return create_invalid_expression();
7382 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7383 expression_t *result
7384 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7386 if (result == NULL) {
7387 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7388 return create_invalid_expression();
7394 static void check_call_argument(type_t *expected_type,
7395 call_argument_t *argument, unsigned pos)
7397 type_t *expected_type_skip = skip_typeref(expected_type);
7398 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7399 expression_t *arg_expr = argument->expression;
7400 type_t *arg_type = skip_typeref(arg_expr->base.type);
7402 /* handle transparent union gnu extension */
7403 if (is_type_union(expected_type_skip)
7404 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7405 compound_t *union_decl = expected_type_skip->compound.compound;
7406 type_t *best_type = NULL;
7407 entity_t *entry = union_decl->members.entities;
7408 for ( ; entry != NULL; entry = entry->base.next) {
7409 assert(is_declaration(entry));
7410 type_t *decl_type = entry->declaration.type;
7411 error = semantic_assign(decl_type, arg_expr);
7412 if (error == ASSIGN_ERROR_INCOMPATIBLE
7413 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7416 if (error == ASSIGN_SUCCESS) {
7417 best_type = decl_type;
7418 } else if (best_type == NULL) {
7419 best_type = decl_type;
7423 if (best_type != NULL) {
7424 expected_type = best_type;
7428 error = semantic_assign(expected_type, arg_expr);
7429 argument->expression = create_implicit_cast(arg_expr, expected_type);
7431 if (error != ASSIGN_SUCCESS) {
7432 /* report exact scope in error messages (like "in argument 3") */
7434 snprintf(buf, sizeof(buf), "call argument %u", pos);
7435 report_assign_error(error, expected_type, arg_expr, buf,
7436 &arg_expr->base.source_position);
7437 } else if (warning.traditional || warning.conversion) {
7438 type_t *const promoted_type = get_default_promoted_type(arg_type);
7439 if (!types_compatible(expected_type_skip, promoted_type) &&
7440 !types_compatible(expected_type_skip, type_void_ptr) &&
7441 !types_compatible(type_void_ptr, promoted_type)) {
7442 /* Deliberately show the skipped types in this warning */
7443 warningf(&arg_expr->base.source_position,
7444 "passing call argument %u as '%T' rather than '%T' due to prototype",
7445 pos, expected_type_skip, promoted_type);
7451 * Handle the semantic restrictions of builtin calls
7453 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7454 switch (call->function->reference.entity->function.btk) {
7455 case bk_gnu_builtin_return_address:
7456 case bk_gnu_builtin_frame_address: {
7457 /* argument must be constant */
7458 call_argument_t *argument = call->arguments;
7460 if (! is_constant_expression(argument->expression)) {
7461 errorf(&call->base.source_position,
7462 "argument of '%Y' must be a constant expression",
7463 call->function->reference.entity->base.symbol);
7467 case bk_gnu_builtin_prefetch: {
7468 /* second and third argument must be constant if existent */
7469 call_argument_t *rw = call->arguments->next;
7470 call_argument_t *locality = NULL;
7473 if (! is_constant_expression(rw->expression)) {
7474 errorf(&call->base.source_position,
7475 "second argument of '%Y' must be a constant expression",
7476 call->function->reference.entity->base.symbol);
7478 locality = rw->next;
7480 if (locality != NULL) {
7481 if (! is_constant_expression(locality->expression)) {
7482 errorf(&call->base.source_position,
7483 "third argument of '%Y' must be a constant expression",
7484 call->function->reference.entity->base.symbol);
7486 locality = rw->next;
7496 * Parse a call expression, ie. expression '( ... )'.
7498 * @param expression the function address
7500 static expression_t *parse_call_expression(expression_t *expression)
7502 expression_t *result = allocate_expression_zero(EXPR_CALL);
7503 call_expression_t *call = &result->call;
7504 call->function = expression;
7506 type_t *const orig_type = expression->base.type;
7507 type_t *const type = skip_typeref(orig_type);
7509 function_type_t *function_type = NULL;
7510 if (is_type_pointer(type)) {
7511 type_t *const to_type = skip_typeref(type->pointer.points_to);
7513 if (is_type_function(to_type)) {
7514 function_type = &to_type->function;
7515 call->base.type = function_type->return_type;
7519 if (function_type == NULL && is_type_valid(type)) {
7521 "called object '%E' (type '%T') is not a pointer to a function",
7522 expression, orig_type);
7525 /* parse arguments */
7527 add_anchor_token(')');
7528 add_anchor_token(',');
7530 if (token.type != ')') {
7531 call_argument_t **anchor = &call->arguments;
7533 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7534 argument->expression = parse_assignment_expression();
7537 anchor = &argument->next;
7539 if (token.type != ',')
7544 rem_anchor_token(',');
7545 rem_anchor_token(')');
7546 expect(')', end_error);
7548 if (function_type == NULL)
7551 /* check type and count of call arguments */
7552 function_parameter_t *parameter = function_type->parameters;
7553 call_argument_t *argument = call->arguments;
7554 if (!function_type->unspecified_parameters) {
7555 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7556 parameter = parameter->next, argument = argument->next) {
7557 check_call_argument(parameter->type, argument, ++pos);
7560 if (parameter != NULL) {
7561 errorf(HERE, "too few arguments to function '%E'", expression);
7562 } else if (argument != NULL && !function_type->variadic) {
7563 errorf(HERE, "too many arguments to function '%E'", expression);
7567 /* do default promotion for other arguments */
7568 for (; argument != NULL; argument = argument->next) {
7569 type_t *type = argument->expression->base.type;
7571 type = get_default_promoted_type(type);
7573 argument->expression
7574 = create_implicit_cast(argument->expression, type);
7577 check_format(&result->call);
7579 if (warning.aggregate_return &&
7580 is_type_compound(skip_typeref(function_type->return_type))) {
7581 warningf(&result->base.source_position,
7582 "function call has aggregate value");
7585 if (call->function->kind == EXPR_REFERENCE) {
7586 reference_expression_t *reference = &call->function->reference;
7587 if (reference->entity->kind == ENTITY_FUNCTION &&
7588 reference->entity->function.btk != bk_none)
7589 handle_builtin_argument_restrictions(call);
7596 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7598 static bool same_compound_type(const type_t *type1, const type_t *type2)
7601 is_type_compound(type1) &&
7602 type1->kind == type2->kind &&
7603 type1->compound.compound == type2->compound.compound;
7606 static expression_t const *get_reference_address(expression_t const *expr)
7608 bool regular_take_address = true;
7610 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7611 expr = expr->unary.value;
7613 regular_take_address = false;
7616 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7619 expr = expr->unary.value;
7622 if (expr->kind != EXPR_REFERENCE)
7625 /* special case for functions which are automatically converted to a
7626 * pointer to function without an extra TAKE_ADDRESS operation */
7627 if (!regular_take_address &&
7628 expr->reference.entity->kind != ENTITY_FUNCTION) {
7635 static void warn_reference_address_as_bool(expression_t const* expr)
7637 if (!warning.address)
7640 expr = get_reference_address(expr);
7642 warningf(&expr->base.source_position,
7643 "the address of '%Y' will always evaluate as 'true'",
7644 expr->reference.entity->base.symbol);
7648 static void warn_assignment_in_condition(const expression_t *const expr)
7650 if (!warning.parentheses)
7652 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7654 if (expr->base.parenthesized)
7656 warningf(&expr->base.source_position,
7657 "suggest parentheses around assignment used as truth value");
7660 static void semantic_condition(expression_t const *const expr,
7661 char const *const context)
7663 type_t *const type = skip_typeref(expr->base.type);
7664 if (is_type_scalar(type)) {
7665 warn_reference_address_as_bool(expr);
7666 warn_assignment_in_condition(expr);
7667 } else if (is_type_valid(type)) {
7668 errorf(&expr->base.source_position,
7669 "%s must have scalar type", context);
7674 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7676 * @param expression the conditional expression
7678 static expression_t *parse_conditional_expression(expression_t *expression)
7680 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7682 conditional_expression_t *conditional = &result->conditional;
7683 conditional->condition = expression;
7686 add_anchor_token(':');
7688 /* §6.5.15:2 The first operand shall have scalar type. */
7689 semantic_condition(expression, "condition of conditional operator");
7691 expression_t *true_expression = expression;
7692 bool gnu_cond = false;
7693 if (GNU_MODE && token.type == ':') {
7696 true_expression = parse_expression();
7698 rem_anchor_token(':');
7699 expect(':', end_error);
7701 expression_t *false_expression =
7702 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7704 type_t *const orig_true_type = true_expression->base.type;
7705 type_t *const orig_false_type = false_expression->base.type;
7706 type_t *const true_type = skip_typeref(orig_true_type);
7707 type_t *const false_type = skip_typeref(orig_false_type);
7710 type_t *result_type;
7711 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7712 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7713 /* ISO/IEC 14882:1998(E) §5.16:2 */
7714 if (true_expression->kind == EXPR_UNARY_THROW) {
7715 result_type = false_type;
7716 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7717 result_type = true_type;
7719 if (warning.other && (
7720 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7721 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7723 warningf(&conditional->base.source_position,
7724 "ISO C forbids conditional expression with only one void side");
7726 result_type = type_void;
7728 } else if (is_type_arithmetic(true_type)
7729 && is_type_arithmetic(false_type)) {
7730 result_type = semantic_arithmetic(true_type, false_type);
7732 true_expression = create_implicit_cast(true_expression, result_type);
7733 false_expression = create_implicit_cast(false_expression, result_type);
7735 conditional->true_expression = true_expression;
7736 conditional->false_expression = false_expression;
7737 conditional->base.type = result_type;
7738 } else if (same_compound_type(true_type, false_type)) {
7739 /* just take 1 of the 2 types */
7740 result_type = true_type;
7741 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7742 type_t *pointer_type;
7744 expression_t *other_expression;
7745 if (is_type_pointer(true_type) &&
7746 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7747 pointer_type = true_type;
7748 other_type = false_type;
7749 other_expression = false_expression;
7751 pointer_type = false_type;
7752 other_type = true_type;
7753 other_expression = true_expression;
7756 if (is_null_pointer_constant(other_expression)) {
7757 result_type = pointer_type;
7758 } else if (is_type_pointer(other_type)) {
7759 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7760 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7763 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7764 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7766 } else if (types_compatible(get_unqualified_type(to1),
7767 get_unqualified_type(to2))) {
7770 if (warning.other) {
7771 warningf(&conditional->base.source_position,
7772 "pointer types '%T' and '%T' in conditional expression are incompatible",
7773 true_type, false_type);
7778 type_t *const type =
7779 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7780 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7781 } else if (is_type_integer(other_type)) {
7782 if (warning.other) {
7783 warningf(&conditional->base.source_position,
7784 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7786 result_type = pointer_type;
7788 if (is_type_valid(other_type)) {
7789 type_error_incompatible("while parsing conditional",
7790 &expression->base.source_position, true_type, false_type);
7792 result_type = type_error_type;
7795 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7796 type_error_incompatible("while parsing conditional",
7797 &conditional->base.source_position, true_type,
7800 result_type = type_error_type;
7803 conditional->true_expression
7804 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7805 conditional->false_expression
7806 = create_implicit_cast(false_expression, result_type);
7807 conditional->base.type = result_type;
7812 * Parse an extension expression.
7814 static expression_t *parse_extension(void)
7816 eat(T___extension__);
7818 bool old_gcc_extension = in_gcc_extension;
7819 in_gcc_extension = true;
7820 expression_t *expression = parse_sub_expression(PREC_UNARY);
7821 in_gcc_extension = old_gcc_extension;
7826 * Parse a __builtin_classify_type() expression.
7828 static expression_t *parse_builtin_classify_type(void)
7830 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7831 result->base.type = type_int;
7833 eat(T___builtin_classify_type);
7835 expect('(', end_error);
7836 add_anchor_token(')');
7837 expression_t *expression = parse_expression();
7838 rem_anchor_token(')');
7839 expect(')', end_error);
7840 result->classify_type.type_expression = expression;
7844 return create_invalid_expression();
7848 * Parse a delete expression
7849 * ISO/IEC 14882:1998(E) §5.3.5
7851 static expression_t *parse_delete(void)
7853 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7854 result->base.type = type_void;
7858 if (token.type == '[') {
7860 result->kind = EXPR_UNARY_DELETE_ARRAY;
7861 expect(']', end_error);
7865 expression_t *const value = parse_sub_expression(PREC_CAST);
7866 result->unary.value = value;
7868 type_t *const type = skip_typeref(value->base.type);
7869 if (!is_type_pointer(type)) {
7870 if (is_type_valid(type)) {
7871 errorf(&value->base.source_position,
7872 "operand of delete must have pointer type");
7874 } else if (warning.other &&
7875 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7876 warningf(&value->base.source_position,
7877 "deleting 'void*' is undefined");
7884 * Parse a throw expression
7885 * ISO/IEC 14882:1998(E) §15:1
7887 static expression_t *parse_throw(void)
7889 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7890 result->base.type = type_void;
7894 expression_t *value = NULL;
7895 switch (token.type) {
7897 value = parse_assignment_expression();
7898 /* ISO/IEC 14882:1998(E) §15.1:3 */
7899 type_t *const orig_type = value->base.type;
7900 type_t *const type = skip_typeref(orig_type);
7901 if (is_type_incomplete(type)) {
7902 errorf(&value->base.source_position,
7903 "cannot throw object of incomplete type '%T'", orig_type);
7904 } else if (is_type_pointer(type)) {
7905 type_t *const points_to = skip_typeref(type->pointer.points_to);
7906 if (is_type_incomplete(points_to) &&
7907 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7908 errorf(&value->base.source_position,
7909 "cannot throw pointer to incomplete type '%T'", orig_type);
7917 result->unary.value = value;
7922 static bool check_pointer_arithmetic(const source_position_t *source_position,
7923 type_t *pointer_type,
7924 type_t *orig_pointer_type)
7926 type_t *points_to = pointer_type->pointer.points_to;
7927 points_to = skip_typeref(points_to);
7929 if (is_type_incomplete(points_to)) {
7930 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7931 errorf(source_position,
7932 "arithmetic with pointer to incomplete type '%T' not allowed",
7935 } else if (warning.pointer_arith) {
7936 warningf(source_position,
7937 "pointer of type '%T' used in arithmetic",
7940 } else if (is_type_function(points_to)) {
7942 errorf(source_position,
7943 "arithmetic with pointer to function type '%T' not allowed",
7946 } else if (warning.pointer_arith) {
7947 warningf(source_position,
7948 "pointer to a function '%T' used in arithmetic",
7955 static bool is_lvalue(const expression_t *expression)
7957 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7958 switch (expression->kind) {
7959 case EXPR_ARRAY_ACCESS:
7960 case EXPR_COMPOUND_LITERAL:
7961 case EXPR_REFERENCE:
7963 case EXPR_UNARY_DEREFERENCE:
7967 type_t *type = skip_typeref(expression->base.type);
7969 /* ISO/IEC 14882:1998(E) §3.10:3 */
7970 is_type_reference(type) ||
7971 /* Claim it is an lvalue, if the type is invalid. There was a parse
7972 * error before, which maybe prevented properly recognizing it as
7974 !is_type_valid(type);
7979 static void semantic_incdec(unary_expression_t *expression)
7981 type_t *const orig_type = expression->value->base.type;
7982 type_t *const type = skip_typeref(orig_type);
7983 if (is_type_pointer(type)) {
7984 if (!check_pointer_arithmetic(&expression->base.source_position,
7988 } else if (!is_type_real(type) && is_type_valid(type)) {
7989 /* TODO: improve error message */
7990 errorf(&expression->base.source_position,
7991 "operation needs an arithmetic or pointer type");
7994 if (!is_lvalue(expression->value)) {
7995 /* TODO: improve error message */
7996 errorf(&expression->base.source_position, "lvalue required as operand");
7998 expression->base.type = orig_type;
8001 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8003 type_t *const orig_type = expression->value->base.type;
8004 type_t *const type = skip_typeref(orig_type);
8005 if (!is_type_arithmetic(type)) {
8006 if (is_type_valid(type)) {
8007 /* TODO: improve error message */
8008 errorf(&expression->base.source_position,
8009 "operation needs an arithmetic type");
8014 expression->base.type = orig_type;
8017 static void semantic_unexpr_plus(unary_expression_t *expression)
8019 semantic_unexpr_arithmetic(expression);
8020 if (warning.traditional)
8021 warningf(&expression->base.source_position,
8022 "traditional C rejects the unary plus operator");
8025 static void semantic_not(unary_expression_t *expression)
8027 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8028 semantic_condition(expression->value, "operand of !");
8029 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8032 static void semantic_unexpr_integer(unary_expression_t *expression)
8034 type_t *const orig_type = expression->value->base.type;
8035 type_t *const type = skip_typeref(orig_type);
8036 if (!is_type_integer(type)) {
8037 if (is_type_valid(type)) {
8038 errorf(&expression->base.source_position,
8039 "operand of ~ must be of integer type");
8044 expression->base.type = orig_type;
8047 static void semantic_dereference(unary_expression_t *expression)
8049 type_t *const orig_type = expression->value->base.type;
8050 type_t *const type = skip_typeref(orig_type);
8051 if (!is_type_pointer(type)) {
8052 if (is_type_valid(type)) {
8053 errorf(&expression->base.source_position,
8054 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8059 type_t *result_type = type->pointer.points_to;
8060 result_type = automatic_type_conversion(result_type);
8061 expression->base.type = result_type;
8065 * Record that an address is taken (expression represents an lvalue).
8067 * @param expression the expression
8068 * @param may_be_register if true, the expression might be an register
8070 static void set_address_taken(expression_t *expression, bool may_be_register)
8072 if (expression->kind != EXPR_REFERENCE)
8075 entity_t *const entity = expression->reference.entity;
8077 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8080 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8081 && !may_be_register) {
8082 errorf(&expression->base.source_position,
8083 "address of register %s '%Y' requested",
8084 get_entity_kind_name(entity->kind), entity->base.symbol);
8087 if (entity->kind == ENTITY_VARIABLE) {
8088 entity->variable.address_taken = true;
8090 assert(entity->kind == ENTITY_PARAMETER);
8091 entity->parameter.address_taken = true;
8096 * Check the semantic of the address taken expression.
8098 static void semantic_take_addr(unary_expression_t *expression)
8100 expression_t *value = expression->value;
8101 value->base.type = revert_automatic_type_conversion(value);
8103 type_t *orig_type = value->base.type;
8104 type_t *type = skip_typeref(orig_type);
8105 if (!is_type_valid(type))
8109 if (!is_lvalue(value)) {
8110 errorf(&expression->base.source_position, "'&' requires an lvalue");
8112 if (type->kind == TYPE_BITFIELD) {
8113 errorf(&expression->base.source_position,
8114 "'&' not allowed on object with bitfield type '%T'",
8118 set_address_taken(value, false);
8120 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8123 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8124 static expression_t *parse_##unexpression_type(void) \
8126 expression_t *unary_expression \
8127 = allocate_expression_zero(unexpression_type); \
8129 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8131 sfunc(&unary_expression->unary); \
8133 return unary_expression; \
8136 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8137 semantic_unexpr_arithmetic)
8138 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8139 semantic_unexpr_plus)
8140 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8142 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8143 semantic_dereference)
8144 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8146 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8147 semantic_unexpr_integer)
8148 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8150 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8153 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8155 static expression_t *parse_##unexpression_type(expression_t *left) \
8157 expression_t *unary_expression \
8158 = allocate_expression_zero(unexpression_type); \
8160 unary_expression->unary.value = left; \
8162 sfunc(&unary_expression->unary); \
8164 return unary_expression; \
8167 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8168 EXPR_UNARY_POSTFIX_INCREMENT,
8170 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8171 EXPR_UNARY_POSTFIX_DECREMENT,
8174 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8176 /* TODO: handle complex + imaginary types */
8178 type_left = get_unqualified_type(type_left);
8179 type_right = get_unqualified_type(type_right);
8181 /* §6.3.1.8 Usual arithmetic conversions */
8182 if (type_left == type_long_double || type_right == type_long_double) {
8183 return type_long_double;
8184 } else if (type_left == type_double || type_right == type_double) {
8186 } else if (type_left == type_float || type_right == type_float) {
8190 type_left = promote_integer(type_left);
8191 type_right = promote_integer(type_right);
8193 if (type_left == type_right)
8196 bool const signed_left = is_type_signed(type_left);
8197 bool const signed_right = is_type_signed(type_right);
8198 int const rank_left = get_rank(type_left);
8199 int const rank_right = get_rank(type_right);
8201 if (signed_left == signed_right)
8202 return rank_left >= rank_right ? type_left : type_right;
8211 u_rank = rank_right;
8212 u_type = type_right;
8214 s_rank = rank_right;
8215 s_type = type_right;
8220 if (u_rank >= s_rank)
8223 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8225 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8226 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8230 case ATOMIC_TYPE_INT: return type_unsigned_int;
8231 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8232 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8234 default: panic("invalid atomic type");
8239 * Check the semantic restrictions for a binary expression.
8241 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8243 expression_t *const left = expression->left;
8244 expression_t *const right = expression->right;
8245 type_t *const orig_type_left = left->base.type;
8246 type_t *const orig_type_right = right->base.type;
8247 type_t *const type_left = skip_typeref(orig_type_left);
8248 type_t *const type_right = skip_typeref(orig_type_right);
8250 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8251 /* TODO: improve error message */
8252 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8253 errorf(&expression->base.source_position,
8254 "operation needs arithmetic types");
8259 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8260 expression->left = create_implicit_cast(left, arithmetic_type);
8261 expression->right = create_implicit_cast(right, arithmetic_type);
8262 expression->base.type = arithmetic_type;
8265 static void warn_div_by_zero(binary_expression_t const *const expression)
8267 if (!warning.div_by_zero ||
8268 !is_type_integer(expression->base.type))
8271 expression_t const *const right = expression->right;
8272 /* The type of the right operand can be different for /= */
8273 if (is_type_integer(right->base.type) &&
8274 is_constant_expression(right) &&
8275 !fold_constant_to_bool(right)) {
8276 warningf(&expression->base.source_position, "division by zero");
8281 * Check the semantic restrictions for a div/mod expression.
8283 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8285 semantic_binexpr_arithmetic(expression);
8286 warn_div_by_zero(expression);
8289 static void warn_addsub_in_shift(const expression_t *const expr)
8291 if (expr->base.parenthesized)
8295 switch (expr->kind) {
8296 case EXPR_BINARY_ADD: op = '+'; break;
8297 case EXPR_BINARY_SUB: op = '-'; break;
8301 warningf(&expr->base.source_position,
8302 "suggest parentheses around '%c' inside shift", op);
8305 static bool semantic_shift(binary_expression_t *expression)
8307 expression_t *const left = expression->left;
8308 expression_t *const right = expression->right;
8309 type_t *const orig_type_left = left->base.type;
8310 type_t *const orig_type_right = right->base.type;
8311 type_t * type_left = skip_typeref(orig_type_left);
8312 type_t * type_right = skip_typeref(orig_type_right);
8314 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8315 /* TODO: improve error message */
8316 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8317 errorf(&expression->base.source_position,
8318 "operands of shift operation must have integer types");
8323 type_left = promote_integer(type_left);
8325 if (is_constant_expression(right)) {
8326 long count = fold_constant_to_int(right);
8328 warningf(&right->base.source_position,
8329 "shift count must be non-negative");
8330 } else if ((unsigned long)count >=
8331 get_atomic_type_size(type_left->atomic.akind) * 8) {
8332 warningf(&right->base.source_position,
8333 "shift count must be less than type width");
8337 type_right = promote_integer(type_right);
8338 expression->right = create_implicit_cast(right, type_right);
8343 static void semantic_shift_op(binary_expression_t *expression)
8345 expression_t *const left = expression->left;
8346 expression_t *const right = expression->right;
8348 if (!semantic_shift(expression))
8351 if (warning.parentheses) {
8352 warn_addsub_in_shift(left);
8353 warn_addsub_in_shift(right);
8356 type_t *const orig_type_left = left->base.type;
8357 type_t * type_left = skip_typeref(orig_type_left);
8359 type_left = promote_integer(type_left);
8360 expression->left = create_implicit_cast(left, type_left);
8361 expression->base.type = type_left;
8364 static void semantic_add(binary_expression_t *expression)
8366 expression_t *const left = expression->left;
8367 expression_t *const right = expression->right;
8368 type_t *const orig_type_left = left->base.type;
8369 type_t *const orig_type_right = right->base.type;
8370 type_t *const type_left = skip_typeref(orig_type_left);
8371 type_t *const type_right = skip_typeref(orig_type_right);
8374 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8375 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8376 expression->left = create_implicit_cast(left, arithmetic_type);
8377 expression->right = create_implicit_cast(right, arithmetic_type);
8378 expression->base.type = arithmetic_type;
8379 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8380 check_pointer_arithmetic(&expression->base.source_position,
8381 type_left, orig_type_left);
8382 expression->base.type = type_left;
8383 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8384 check_pointer_arithmetic(&expression->base.source_position,
8385 type_right, orig_type_right);
8386 expression->base.type = type_right;
8387 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8388 errorf(&expression->base.source_position,
8389 "invalid operands to binary + ('%T', '%T')",
8390 orig_type_left, orig_type_right);
8394 static void semantic_sub(binary_expression_t *expression)
8396 expression_t *const left = expression->left;
8397 expression_t *const right = expression->right;
8398 type_t *const orig_type_left = left->base.type;
8399 type_t *const orig_type_right = right->base.type;
8400 type_t *const type_left = skip_typeref(orig_type_left);
8401 type_t *const type_right = skip_typeref(orig_type_right);
8402 source_position_t const *const pos = &expression->base.source_position;
8405 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8406 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8407 expression->left = create_implicit_cast(left, arithmetic_type);
8408 expression->right = create_implicit_cast(right, arithmetic_type);
8409 expression->base.type = arithmetic_type;
8410 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8411 check_pointer_arithmetic(&expression->base.source_position,
8412 type_left, orig_type_left);
8413 expression->base.type = type_left;
8414 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8415 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8416 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8417 if (!types_compatible(unqual_left, unqual_right)) {
8419 "subtracting pointers to incompatible types '%T' and '%T'",
8420 orig_type_left, orig_type_right);
8421 } else if (!is_type_object(unqual_left)) {
8422 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8423 errorf(pos, "subtracting pointers to non-object types '%T'",
8425 } else if (warning.other) {
8426 warningf(pos, "subtracting pointers to void");
8429 expression->base.type = type_ptrdiff_t;
8430 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8431 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8432 orig_type_left, orig_type_right);
8436 static void warn_string_literal_address(expression_t const* expr)
8438 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8439 expr = expr->unary.value;
8440 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8442 expr = expr->unary.value;
8445 if (expr->kind == EXPR_STRING_LITERAL ||
8446 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8447 warningf(&expr->base.source_position,
8448 "comparison with string literal results in unspecified behaviour");
8452 static void warn_comparison_in_comparison(const expression_t *const expr)
8454 if (expr->base.parenthesized)
8456 switch (expr->base.kind) {
8457 case EXPR_BINARY_LESS:
8458 case EXPR_BINARY_GREATER:
8459 case EXPR_BINARY_LESSEQUAL:
8460 case EXPR_BINARY_GREATEREQUAL:
8461 case EXPR_BINARY_NOTEQUAL:
8462 case EXPR_BINARY_EQUAL:
8463 warningf(&expr->base.source_position,
8464 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8471 static bool maybe_negative(expression_t const *const expr)
8474 !is_constant_expression(expr) ||
8475 fold_constant_to_int(expr) < 0;
8479 * Check the semantics of comparison expressions.
8481 * @param expression The expression to check.
8483 static void semantic_comparison(binary_expression_t *expression)
8485 expression_t *left = expression->left;
8486 expression_t *right = expression->right;
8488 if (warning.address) {
8489 warn_string_literal_address(left);
8490 warn_string_literal_address(right);
8492 expression_t const* const func_left = get_reference_address(left);
8493 if (func_left != NULL && is_null_pointer_constant(right)) {
8494 warningf(&expression->base.source_position,
8495 "the address of '%Y' will never be NULL",
8496 func_left->reference.entity->base.symbol);
8499 expression_t const* const func_right = get_reference_address(right);
8500 if (func_right != NULL && is_null_pointer_constant(right)) {
8501 warningf(&expression->base.source_position,
8502 "the address of '%Y' will never be NULL",
8503 func_right->reference.entity->base.symbol);
8507 if (warning.parentheses) {
8508 warn_comparison_in_comparison(left);
8509 warn_comparison_in_comparison(right);
8512 type_t *orig_type_left = left->base.type;
8513 type_t *orig_type_right = right->base.type;
8514 type_t *type_left = skip_typeref(orig_type_left);
8515 type_t *type_right = skip_typeref(orig_type_right);
8517 /* TODO non-arithmetic types */
8518 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8519 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8521 /* test for signed vs unsigned compares */
8522 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8523 bool const signed_left = is_type_signed(type_left);
8524 bool const signed_right = is_type_signed(type_right);
8525 if (signed_left != signed_right) {
8526 /* FIXME long long needs better const folding magic */
8527 /* TODO check whether constant value can be represented by other type */
8528 if ((signed_left && maybe_negative(left)) ||
8529 (signed_right && maybe_negative(right))) {
8530 warningf(&expression->base.source_position,
8531 "comparison between signed and unsigned");
8536 expression->left = create_implicit_cast(left, arithmetic_type);
8537 expression->right = create_implicit_cast(right, arithmetic_type);
8538 expression->base.type = arithmetic_type;
8539 if (warning.float_equal &&
8540 (expression->base.kind == EXPR_BINARY_EQUAL ||
8541 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8542 is_type_float(arithmetic_type)) {
8543 warningf(&expression->base.source_position,
8544 "comparing floating point with == or != is unsafe");
8546 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8547 /* TODO check compatibility */
8548 } else if (is_type_pointer(type_left)) {
8549 expression->right = create_implicit_cast(right, type_left);
8550 } else if (is_type_pointer(type_right)) {
8551 expression->left = create_implicit_cast(left, type_right);
8552 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8553 type_error_incompatible("invalid operands in comparison",
8554 &expression->base.source_position,
8555 type_left, type_right);
8557 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8561 * Checks if a compound type has constant fields.
8563 static bool has_const_fields(const compound_type_t *type)
8565 compound_t *compound = type->compound;
8566 entity_t *entry = compound->members.entities;
8568 for (; entry != NULL; entry = entry->base.next) {
8569 if (!is_declaration(entry))
8572 const type_t *decl_type = skip_typeref(entry->declaration.type);
8573 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8580 static bool is_valid_assignment_lhs(expression_t const* const left)
8582 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8583 type_t *const type_left = skip_typeref(orig_type_left);
8585 if (!is_lvalue(left)) {
8586 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8591 if (left->kind == EXPR_REFERENCE
8592 && left->reference.entity->kind == ENTITY_FUNCTION) {
8593 errorf(HERE, "cannot assign to function '%E'", left);
8597 if (is_type_array(type_left)) {
8598 errorf(HERE, "cannot assign to array '%E'", left);
8601 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8602 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8606 if (is_type_incomplete(type_left)) {
8607 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8608 left, orig_type_left);
8611 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8612 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8613 left, orig_type_left);
8620 static void semantic_arithmetic_assign(binary_expression_t *expression)
8622 expression_t *left = expression->left;
8623 expression_t *right = expression->right;
8624 type_t *orig_type_left = left->base.type;
8625 type_t *orig_type_right = right->base.type;
8627 if (!is_valid_assignment_lhs(left))
8630 type_t *type_left = skip_typeref(orig_type_left);
8631 type_t *type_right = skip_typeref(orig_type_right);
8633 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8634 /* TODO: improve error message */
8635 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8636 errorf(&expression->base.source_position,
8637 "operation needs arithmetic types");
8642 /* combined instructions are tricky. We can't create an implicit cast on
8643 * the left side, because we need the uncasted form for the store.
8644 * The ast2firm pass has to know that left_type must be right_type
8645 * for the arithmetic operation and create a cast by itself */
8646 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8647 expression->right = create_implicit_cast(right, arithmetic_type);
8648 expression->base.type = type_left;
8651 static void semantic_divmod_assign(binary_expression_t *expression)
8653 semantic_arithmetic_assign(expression);
8654 warn_div_by_zero(expression);
8657 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8659 expression_t *const left = expression->left;
8660 expression_t *const right = expression->right;
8661 type_t *const orig_type_left = left->base.type;
8662 type_t *const orig_type_right = right->base.type;
8663 type_t *const type_left = skip_typeref(orig_type_left);
8664 type_t *const type_right = skip_typeref(orig_type_right);
8666 if (!is_valid_assignment_lhs(left))
8669 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8670 /* combined instructions are tricky. We can't create an implicit cast on
8671 * the left side, because we need the uncasted form for the store.
8672 * The ast2firm pass has to know that left_type must be right_type
8673 * for the arithmetic operation and create a cast by itself */
8674 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8675 expression->right = create_implicit_cast(right, arithmetic_type);
8676 expression->base.type = type_left;
8677 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8678 check_pointer_arithmetic(&expression->base.source_position,
8679 type_left, orig_type_left);
8680 expression->base.type = type_left;
8681 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8682 errorf(&expression->base.source_position,
8683 "incompatible types '%T' and '%T' in assignment",
8684 orig_type_left, orig_type_right);
8688 static void semantic_integer_assign(binary_expression_t *expression)
8690 expression_t *left = expression->left;
8691 expression_t *right = expression->right;
8692 type_t *orig_type_left = left->base.type;
8693 type_t *orig_type_right = right->base.type;
8695 if (!is_valid_assignment_lhs(left))
8698 type_t *type_left = skip_typeref(orig_type_left);
8699 type_t *type_right = skip_typeref(orig_type_right);
8701 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8702 /* TODO: improve error message */
8703 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8704 errorf(&expression->base.source_position,
8705 "operation needs integer types");
8710 /* combined instructions are tricky. We can't create an implicit cast on
8711 * the left side, because we need the uncasted form for the store.
8712 * The ast2firm pass has to know that left_type must be right_type
8713 * for the arithmetic operation and create a cast by itself */
8714 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8715 expression->right = create_implicit_cast(right, arithmetic_type);
8716 expression->base.type = type_left;
8719 static void semantic_shift_assign(binary_expression_t *expression)
8721 expression_t *left = expression->left;
8723 if (!is_valid_assignment_lhs(left))
8726 if (!semantic_shift(expression))
8729 expression->base.type = skip_typeref(left->base.type);
8732 static void warn_logical_and_within_or(const expression_t *const expr)
8734 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8736 if (expr->base.parenthesized)
8738 warningf(&expr->base.source_position,
8739 "suggest parentheses around && within ||");
8743 * Check the semantic restrictions of a logical expression.
8745 static void semantic_logical_op(binary_expression_t *expression)
8747 /* §6.5.13:2 Each of the operands shall have scalar type.
8748 * §6.5.14:2 Each of the operands shall have scalar type. */
8749 semantic_condition(expression->left, "left operand of logical operator");
8750 semantic_condition(expression->right, "right operand of logical operator");
8751 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8752 warning.parentheses) {
8753 warn_logical_and_within_or(expression->left);
8754 warn_logical_and_within_or(expression->right);
8756 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8760 * Check the semantic restrictions of a binary assign expression.
8762 static void semantic_binexpr_assign(binary_expression_t *expression)
8764 expression_t *left = expression->left;
8765 type_t *orig_type_left = left->base.type;
8767 if (!is_valid_assignment_lhs(left))
8770 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8771 report_assign_error(error, orig_type_left, expression->right,
8772 "assignment", &left->base.source_position);
8773 expression->right = create_implicit_cast(expression->right, orig_type_left);
8774 expression->base.type = orig_type_left;
8778 * Determine if the outermost operation (or parts thereof) of the given
8779 * expression has no effect in order to generate a warning about this fact.
8780 * Therefore in some cases this only examines some of the operands of the
8781 * expression (see comments in the function and examples below).
8783 * f() + 23; // warning, because + has no effect
8784 * x || f(); // no warning, because x controls execution of f()
8785 * x ? y : f(); // warning, because y has no effect
8786 * (void)x; // no warning to be able to suppress the warning
8787 * This function can NOT be used for an "expression has definitely no effect"-
8789 static bool expression_has_effect(const expression_t *const expr)
8791 switch (expr->kind) {
8792 case EXPR_UNKNOWN: break;
8793 case EXPR_INVALID: return true; /* do NOT warn */
8794 case EXPR_REFERENCE: return false;
8795 case EXPR_REFERENCE_ENUM_VALUE: return false;
8796 /* suppress the warning for microsoft __noop operations */
8797 case EXPR_CONST: return expr->conste.is_ms_noop;
8798 case EXPR_CHARACTER_CONSTANT: return false;
8799 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8800 case EXPR_STRING_LITERAL: return false;
8801 case EXPR_WIDE_STRING_LITERAL: return false;
8802 case EXPR_LABEL_ADDRESS: return false;
8805 const call_expression_t *const call = &expr->call;
8806 if (call->function->kind != EXPR_REFERENCE)
8809 switch (call->function->reference.entity->function.btk) {
8810 /* FIXME: which builtins have no effect? */
8811 default: return true;
8815 /* Generate the warning if either the left or right hand side of a
8816 * conditional expression has no effect */
8817 case EXPR_CONDITIONAL: {
8818 conditional_expression_t const *const cond = &expr->conditional;
8819 expression_t const *const t = cond->true_expression;
8821 (t == NULL || expression_has_effect(t)) &&
8822 expression_has_effect(cond->false_expression);
8825 case EXPR_SELECT: return false;
8826 case EXPR_ARRAY_ACCESS: return false;
8827 case EXPR_SIZEOF: return false;
8828 case EXPR_CLASSIFY_TYPE: return false;
8829 case EXPR_ALIGNOF: return false;
8831 case EXPR_FUNCNAME: return false;
8832 case EXPR_BUILTIN_CONSTANT_P: return false;
8833 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8834 case EXPR_OFFSETOF: return false;
8835 case EXPR_VA_START: return true;
8836 case EXPR_VA_ARG: return true;
8837 case EXPR_VA_COPY: return true;
8838 case EXPR_STATEMENT: return true; // TODO
8839 case EXPR_COMPOUND_LITERAL: return false;
8841 case EXPR_UNARY_NEGATE: return false;
8842 case EXPR_UNARY_PLUS: return false;
8843 case EXPR_UNARY_BITWISE_NEGATE: return false;
8844 case EXPR_UNARY_NOT: return false;
8845 case EXPR_UNARY_DEREFERENCE: return false;
8846 case EXPR_UNARY_TAKE_ADDRESS: return false;
8847 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8848 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8849 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8850 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8852 /* Treat void casts as if they have an effect in order to being able to
8853 * suppress the warning */
8854 case EXPR_UNARY_CAST: {
8855 type_t *const type = skip_typeref(expr->base.type);
8856 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8859 case EXPR_UNARY_CAST_IMPLICIT: return true;
8860 case EXPR_UNARY_ASSUME: return true;
8861 case EXPR_UNARY_DELETE: return true;
8862 case EXPR_UNARY_DELETE_ARRAY: return true;
8863 case EXPR_UNARY_THROW: return true;
8865 case EXPR_BINARY_ADD: return false;
8866 case EXPR_BINARY_SUB: return false;
8867 case EXPR_BINARY_MUL: return false;
8868 case EXPR_BINARY_DIV: return false;
8869 case EXPR_BINARY_MOD: return false;
8870 case EXPR_BINARY_EQUAL: return false;
8871 case EXPR_BINARY_NOTEQUAL: return false;
8872 case EXPR_BINARY_LESS: return false;
8873 case EXPR_BINARY_LESSEQUAL: return false;
8874 case EXPR_BINARY_GREATER: return false;
8875 case EXPR_BINARY_GREATEREQUAL: return false;
8876 case EXPR_BINARY_BITWISE_AND: return false;
8877 case EXPR_BINARY_BITWISE_OR: return false;
8878 case EXPR_BINARY_BITWISE_XOR: return false;
8879 case EXPR_BINARY_SHIFTLEFT: return false;
8880 case EXPR_BINARY_SHIFTRIGHT: return false;
8881 case EXPR_BINARY_ASSIGN: return true;
8882 case EXPR_BINARY_MUL_ASSIGN: return true;
8883 case EXPR_BINARY_DIV_ASSIGN: return true;
8884 case EXPR_BINARY_MOD_ASSIGN: return true;
8885 case EXPR_BINARY_ADD_ASSIGN: return true;
8886 case EXPR_BINARY_SUB_ASSIGN: return true;
8887 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8888 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8889 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8890 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8891 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8893 /* Only examine the right hand side of && and ||, because the left hand
8894 * side already has the effect of controlling the execution of the right
8896 case EXPR_BINARY_LOGICAL_AND:
8897 case EXPR_BINARY_LOGICAL_OR:
8898 /* Only examine the right hand side of a comma expression, because the left
8899 * hand side has a separate warning */
8900 case EXPR_BINARY_COMMA:
8901 return expression_has_effect(expr->binary.right);
8903 case EXPR_BINARY_ISGREATER: return false;
8904 case EXPR_BINARY_ISGREATEREQUAL: return false;
8905 case EXPR_BINARY_ISLESS: return false;
8906 case EXPR_BINARY_ISLESSEQUAL: return false;
8907 case EXPR_BINARY_ISLESSGREATER: return false;
8908 case EXPR_BINARY_ISUNORDERED: return false;
8911 internal_errorf(HERE, "unexpected expression");
8914 static void semantic_comma(binary_expression_t *expression)
8916 if (warning.unused_value) {
8917 const expression_t *const left = expression->left;
8918 if (!expression_has_effect(left)) {
8919 warningf(&left->base.source_position,
8920 "left-hand operand of comma expression has no effect");
8923 expression->base.type = expression->right->base.type;
8927 * @param prec_r precedence of the right operand
8929 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8930 static expression_t *parse_##binexpression_type(expression_t *left) \
8932 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8933 binexpr->binary.left = left; \
8936 expression_t *right = parse_sub_expression(prec_r); \
8938 binexpr->binary.right = right; \
8939 sfunc(&binexpr->binary); \
8944 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8945 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8946 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8947 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8948 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8949 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8950 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8951 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8952 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8953 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8954 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8955 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8956 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8957 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8958 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8959 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8960 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8961 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8962 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8963 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8964 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8965 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8966 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8967 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8968 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8969 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8970 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8971 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8972 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8973 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8976 static expression_t *parse_sub_expression(precedence_t precedence)
8978 if (token.type < 0) {
8979 return expected_expression_error();
8982 expression_parser_function_t *parser
8983 = &expression_parsers[token.type];
8984 source_position_t source_position = token.source_position;
8987 if (parser->parser != NULL) {
8988 left = parser->parser();
8990 left = parse_primary_expression();
8992 assert(left != NULL);
8993 left->base.source_position = source_position;
8996 if (token.type < 0) {
8997 return expected_expression_error();
9000 parser = &expression_parsers[token.type];
9001 if (parser->infix_parser == NULL)
9003 if (parser->infix_precedence < precedence)
9006 left = parser->infix_parser(left);
9008 assert(left != NULL);
9009 assert(left->kind != EXPR_UNKNOWN);
9010 left->base.source_position = source_position;
9017 * Parse an expression.
9019 static expression_t *parse_expression(void)
9021 return parse_sub_expression(PREC_EXPRESSION);
9025 * Register a parser for a prefix-like operator.
9027 * @param parser the parser function
9028 * @param token_type the token type of the prefix token
9030 static void register_expression_parser(parse_expression_function parser,
9033 expression_parser_function_t *entry = &expression_parsers[token_type];
9035 if (entry->parser != NULL) {
9036 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9037 panic("trying to register multiple expression parsers for a token");
9039 entry->parser = parser;
9043 * Register a parser for an infix operator with given precedence.
9045 * @param parser the parser function
9046 * @param token_type the token type of the infix operator
9047 * @param precedence the precedence of the operator
9049 static void register_infix_parser(parse_expression_infix_function parser,
9050 int token_type, precedence_t precedence)
9052 expression_parser_function_t *entry = &expression_parsers[token_type];
9054 if (entry->infix_parser != NULL) {
9055 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9056 panic("trying to register multiple infix expression parsers for a "
9059 entry->infix_parser = parser;
9060 entry->infix_precedence = precedence;
9064 * Initialize the expression parsers.
9066 static void init_expression_parsers(void)
9068 memset(&expression_parsers, 0, sizeof(expression_parsers));
9070 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9071 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9072 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9073 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9074 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9075 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9076 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9077 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9078 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9079 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9080 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9081 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9082 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9083 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9084 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9085 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9086 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9087 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9088 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9089 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9090 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9091 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9092 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9093 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9094 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9095 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9096 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9097 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9098 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9099 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9100 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9101 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9102 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9103 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9104 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9105 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9106 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9108 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9109 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9110 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9111 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9112 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9113 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9114 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9115 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9116 register_expression_parser(parse_sizeof, T_sizeof);
9117 register_expression_parser(parse_alignof, T___alignof__);
9118 register_expression_parser(parse_extension, T___extension__);
9119 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9120 register_expression_parser(parse_delete, T_delete);
9121 register_expression_parser(parse_throw, T_throw);
9125 * Parse a asm statement arguments specification.
9127 static asm_argument_t *parse_asm_arguments(bool is_out)
9129 asm_argument_t *result = NULL;
9130 asm_argument_t **anchor = &result;
9132 while (token.type == T_STRING_LITERAL || token.type == '[') {
9133 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9134 memset(argument, 0, sizeof(argument[0]));
9136 if (token.type == '[') {
9138 if (token.type != T_IDENTIFIER) {
9139 parse_error_expected("while parsing asm argument",
9140 T_IDENTIFIER, NULL);
9143 argument->symbol = token.v.symbol;
9145 expect(']', end_error);
9148 argument->constraints = parse_string_literals();
9149 expect('(', end_error);
9150 add_anchor_token(')');
9151 expression_t *expression = parse_expression();
9152 rem_anchor_token(')');
9154 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9155 * change size or type representation (e.g. int -> long is ok, but
9156 * int -> float is not) */
9157 if (expression->kind == EXPR_UNARY_CAST) {
9158 type_t *const type = expression->base.type;
9159 type_kind_t const kind = type->kind;
9160 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9163 if (kind == TYPE_ATOMIC) {
9164 atomic_type_kind_t const akind = type->atomic.akind;
9165 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9166 size = get_atomic_type_size(akind);
9168 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9169 size = get_atomic_type_size(get_intptr_kind());
9173 expression_t *const value = expression->unary.value;
9174 type_t *const value_type = value->base.type;
9175 type_kind_t const value_kind = value_type->kind;
9177 unsigned value_flags;
9178 unsigned value_size;
9179 if (value_kind == TYPE_ATOMIC) {
9180 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9181 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9182 value_size = get_atomic_type_size(value_akind);
9183 } else if (value_kind == TYPE_POINTER) {
9184 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9185 value_size = get_atomic_type_size(get_intptr_kind());
9190 if (value_flags != flags || value_size != size)
9194 } while (expression->kind == EXPR_UNARY_CAST);
9198 if (!is_lvalue(expression)) {
9199 errorf(&expression->base.source_position,
9200 "asm output argument is not an lvalue");
9203 if (argument->constraints.begin[0] == '+')
9204 mark_vars_read(expression, NULL);
9206 mark_vars_read(expression, NULL);
9208 argument->expression = expression;
9209 expect(')', end_error);
9211 set_address_taken(expression, true);
9214 anchor = &argument->next;
9216 if (token.type != ',')
9227 * Parse a asm statement clobber specification.
9229 static asm_clobber_t *parse_asm_clobbers(void)
9231 asm_clobber_t *result = NULL;
9232 asm_clobber_t *last = NULL;
9234 while (token.type == T_STRING_LITERAL) {
9235 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9236 clobber->clobber = parse_string_literals();
9239 last->next = clobber;
9245 if (token.type != ',')
9254 * Parse an asm statement.
9256 static statement_t *parse_asm_statement(void)
9258 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9259 asm_statement_t *asm_statement = &statement->asms;
9263 if (token.type == T_volatile) {
9265 asm_statement->is_volatile = true;
9268 expect('(', end_error);
9269 add_anchor_token(')');
9270 add_anchor_token(':');
9271 asm_statement->asm_text = parse_string_literals();
9273 if (token.type != ':') {
9274 rem_anchor_token(':');
9279 asm_statement->outputs = parse_asm_arguments(true);
9280 if (token.type != ':') {
9281 rem_anchor_token(':');
9286 asm_statement->inputs = parse_asm_arguments(false);
9287 if (token.type != ':') {
9288 rem_anchor_token(':');
9291 rem_anchor_token(':');
9294 asm_statement->clobbers = parse_asm_clobbers();
9297 rem_anchor_token(')');
9298 expect(')', end_error);
9299 expect(';', end_error);
9301 if (asm_statement->outputs == NULL) {
9302 /* GCC: An 'asm' instruction without any output operands will be treated
9303 * identically to a volatile 'asm' instruction. */
9304 asm_statement->is_volatile = true;
9309 return create_invalid_statement();
9313 * Parse a case statement.
9315 static statement_t *parse_case_statement(void)
9317 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9318 source_position_t *const pos = &statement->base.source_position;
9322 expression_t *const expression = parse_expression();
9323 statement->case_label.expression = expression;
9324 if (!is_constant_expression(expression)) {
9325 /* This check does not prevent the error message in all cases of an
9326 * prior error while parsing the expression. At least it catches the
9327 * common case of a mistyped enum entry. */
9328 if (is_type_valid(skip_typeref(expression->base.type))) {
9329 errorf(pos, "case label does not reduce to an integer constant");
9331 statement->case_label.is_bad = true;
9333 long const val = fold_constant_to_int(expression);
9334 statement->case_label.first_case = val;
9335 statement->case_label.last_case = val;
9339 if (token.type == T_DOTDOTDOT) {
9341 expression_t *const end_range = parse_expression();
9342 statement->case_label.end_range = end_range;
9343 if (!is_constant_expression(end_range)) {
9344 /* This check does not prevent the error message in all cases of an
9345 * prior error while parsing the expression. At least it catches the
9346 * common case of a mistyped enum entry. */
9347 if (is_type_valid(skip_typeref(end_range->base.type))) {
9348 errorf(pos, "case range does not reduce to an integer constant");
9350 statement->case_label.is_bad = true;
9352 long const val = fold_constant_to_int(end_range);
9353 statement->case_label.last_case = val;
9355 if (warning.other && val < statement->case_label.first_case) {
9356 statement->case_label.is_empty_range = true;
9357 warningf(pos, "empty range specified");
9363 PUSH_PARENT(statement);
9365 expect(':', end_error);
9368 if (current_switch != NULL) {
9369 if (! statement->case_label.is_bad) {
9370 /* Check for duplicate case values */
9371 case_label_statement_t *c = &statement->case_label;
9372 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9373 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9376 if (c->last_case < l->first_case || c->first_case > l->last_case)
9379 errorf(pos, "duplicate case value (previously used %P)",
9380 &l->base.source_position);
9384 /* link all cases into the switch statement */
9385 if (current_switch->last_case == NULL) {
9386 current_switch->first_case = &statement->case_label;
9388 current_switch->last_case->next = &statement->case_label;
9390 current_switch->last_case = &statement->case_label;
9392 errorf(pos, "case label not within a switch statement");
9395 statement_t *const inner_stmt = parse_statement();
9396 statement->case_label.statement = inner_stmt;
9397 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9398 errorf(&inner_stmt->base.source_position, "declaration after case label");
9406 * Parse a default statement.
9408 static statement_t *parse_default_statement(void)
9410 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9414 PUSH_PARENT(statement);
9416 expect(':', end_error);
9417 if (current_switch != NULL) {
9418 const case_label_statement_t *def_label = current_switch->default_label;
9419 if (def_label != NULL) {
9420 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9421 &def_label->base.source_position);
9423 current_switch->default_label = &statement->case_label;
9425 /* link all cases into the switch statement */
9426 if (current_switch->last_case == NULL) {
9427 current_switch->first_case = &statement->case_label;
9429 current_switch->last_case->next = &statement->case_label;
9431 current_switch->last_case = &statement->case_label;
9434 errorf(&statement->base.source_position,
9435 "'default' label not within a switch statement");
9438 statement_t *const inner_stmt = parse_statement();
9439 statement->case_label.statement = inner_stmt;
9440 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9441 errorf(&inner_stmt->base.source_position, "declaration after default label");
9448 return create_invalid_statement();
9452 * Parse a label statement.
9454 static statement_t *parse_label_statement(void)
9456 assert(token.type == T_IDENTIFIER);
9457 symbol_t *symbol = token.v.symbol;
9458 label_t *label = get_label(symbol);
9460 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9461 statement->label.label = label;
9465 PUSH_PARENT(statement);
9467 /* if statement is already set then the label is defined twice,
9468 * otherwise it was just mentioned in a goto/local label declaration so far
9470 if (label->statement != NULL) {
9471 errorf(HERE, "duplicate label '%Y' (declared %P)",
9472 symbol, &label->base.source_position);
9474 label->base.source_position = token.source_position;
9475 label->statement = statement;
9480 if (token.type == '}') {
9481 /* TODO only warn? */
9482 if (warning.other && false) {
9483 warningf(HERE, "label at end of compound statement");
9484 statement->label.statement = create_empty_statement();
9486 errorf(HERE, "label at end of compound statement");
9487 statement->label.statement = create_invalid_statement();
9489 } else if (token.type == ';') {
9490 /* Eat an empty statement here, to avoid the warning about an empty
9491 * statement after a label. label:; is commonly used to have a label
9492 * before a closing brace. */
9493 statement->label.statement = create_empty_statement();
9496 statement_t *const inner_stmt = parse_statement();
9497 statement->label.statement = inner_stmt;
9498 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9499 errorf(&inner_stmt->base.source_position, "declaration after label");
9503 /* remember the labels in a list for later checking */
9504 *label_anchor = &statement->label;
9505 label_anchor = &statement->label.next;
9512 * Parse an if statement.
9514 static statement_t *parse_if(void)
9516 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9520 PUSH_PARENT(statement);
9522 add_anchor_token('{');
9524 expect('(', end_error);
9525 add_anchor_token(')');
9526 expression_t *const expr = parse_expression();
9527 statement->ifs.condition = expr;
9528 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9530 semantic_condition(expr, "condition of 'if'-statment");
9531 mark_vars_read(expr, NULL);
9532 rem_anchor_token(')');
9533 expect(')', end_error);
9536 rem_anchor_token('{');
9538 add_anchor_token(T_else);
9539 statement_t *const true_stmt = parse_statement();
9540 statement->ifs.true_statement = true_stmt;
9541 rem_anchor_token(T_else);
9543 if (token.type == T_else) {
9545 statement->ifs.false_statement = parse_statement();
9546 } else if (warning.parentheses &&
9547 true_stmt->kind == STATEMENT_IF &&
9548 true_stmt->ifs.false_statement != NULL) {
9549 warningf(&true_stmt->base.source_position,
9550 "suggest explicit braces to avoid ambiguous 'else'");
9558 * Check that all enums are handled in a switch.
9560 * @param statement the switch statement to check
9562 static void check_enum_cases(const switch_statement_t *statement)
9564 const type_t *type = skip_typeref(statement->expression->base.type);
9565 if (! is_type_enum(type))
9567 const enum_type_t *enumt = &type->enumt;
9569 /* if we have a default, no warnings */
9570 if (statement->default_label != NULL)
9573 /* FIXME: calculation of value should be done while parsing */
9574 /* TODO: quadratic algorithm here. Change to an n log n one */
9575 long last_value = -1;
9576 const entity_t *entry = enumt->enume->base.next;
9577 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9578 entry = entry->base.next) {
9579 const expression_t *expression = entry->enum_value.value;
9580 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9582 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9583 if (l->expression == NULL)
9585 if (l->first_case <= value && value <= l->last_case) {
9591 warningf(&statement->base.source_position,
9592 "enumeration value '%Y' not handled in switch",
9593 entry->base.symbol);
9600 * Parse a switch statement.
9602 static statement_t *parse_switch(void)
9604 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9608 PUSH_PARENT(statement);
9610 expect('(', end_error);
9611 add_anchor_token(')');
9612 expression_t *const expr = parse_expression();
9613 mark_vars_read(expr, NULL);
9614 type_t * type = skip_typeref(expr->base.type);
9615 if (is_type_integer(type)) {
9616 type = promote_integer(type);
9617 if (warning.traditional) {
9618 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9619 warningf(&expr->base.source_position,
9620 "'%T' switch expression not converted to '%T' in ISO C",
9624 } else if (is_type_valid(type)) {
9625 errorf(&expr->base.source_position,
9626 "switch quantity is not an integer, but '%T'", type);
9627 type = type_error_type;
9629 statement->switchs.expression = create_implicit_cast(expr, type);
9630 expect(')', end_error);
9631 rem_anchor_token(')');
9633 switch_statement_t *rem = current_switch;
9634 current_switch = &statement->switchs;
9635 statement->switchs.body = parse_statement();
9636 current_switch = rem;
9638 if (warning.switch_default &&
9639 statement->switchs.default_label == NULL) {
9640 warningf(&statement->base.source_position, "switch has no default case");
9642 if (warning.switch_enum)
9643 check_enum_cases(&statement->switchs);
9649 return create_invalid_statement();
9652 static statement_t *parse_loop_body(statement_t *const loop)
9654 statement_t *const rem = current_loop;
9655 current_loop = loop;
9657 statement_t *const body = parse_statement();
9664 * Parse a while statement.
9666 static statement_t *parse_while(void)
9668 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9672 PUSH_PARENT(statement);
9674 expect('(', end_error);
9675 add_anchor_token(')');
9676 expression_t *const cond = parse_expression();
9677 statement->whiles.condition = cond;
9678 /* §6.8.5:2 The controlling expression of an iteration statement shall
9679 * have scalar type. */
9680 semantic_condition(cond, "condition of 'while'-statement");
9681 mark_vars_read(cond, NULL);
9682 rem_anchor_token(')');
9683 expect(')', end_error);
9685 statement->whiles.body = parse_loop_body(statement);
9691 return create_invalid_statement();
9695 * Parse a do statement.
9697 static statement_t *parse_do(void)
9699 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9703 PUSH_PARENT(statement);
9705 add_anchor_token(T_while);
9706 statement->do_while.body = parse_loop_body(statement);
9707 rem_anchor_token(T_while);
9709 expect(T_while, end_error);
9710 expect('(', end_error);
9711 add_anchor_token(')');
9712 expression_t *const cond = parse_expression();
9713 statement->do_while.condition = cond;
9714 /* §6.8.5:2 The controlling expression of an iteration statement shall
9715 * have scalar type. */
9716 semantic_condition(cond, "condition of 'do-while'-statement");
9717 mark_vars_read(cond, NULL);
9718 rem_anchor_token(')');
9719 expect(')', end_error);
9720 expect(';', end_error);
9726 return create_invalid_statement();
9730 * Parse a for statement.
9732 static statement_t *parse_for(void)
9734 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9738 expect('(', end_error1);
9739 add_anchor_token(')');
9741 PUSH_PARENT(statement);
9743 size_t const top = environment_top();
9744 scope_t *old_scope = scope_push(&statement->fors.scope);
9746 bool old_gcc_extension = in_gcc_extension;
9747 while (token.type == T___extension__) {
9749 in_gcc_extension = true;
9752 if (token.type == ';') {
9754 } else if (is_declaration_specifier(&token, false)) {
9755 parse_declaration(record_entity, DECL_FLAGS_NONE);
9757 add_anchor_token(';');
9758 expression_t *const init = parse_expression();
9759 statement->fors.initialisation = init;
9760 mark_vars_read(init, ENT_ANY);
9761 if (warning.unused_value && !expression_has_effect(init)) {
9762 warningf(&init->base.source_position,
9763 "initialisation of 'for'-statement has no effect");
9765 rem_anchor_token(';');
9766 expect(';', end_error2);
9768 in_gcc_extension = old_gcc_extension;
9770 if (token.type != ';') {
9771 add_anchor_token(';');
9772 expression_t *const cond = parse_expression();
9773 statement->fors.condition = cond;
9774 /* §6.8.5:2 The controlling expression of an iteration statement
9775 * shall have scalar type. */
9776 semantic_condition(cond, "condition of 'for'-statement");
9777 mark_vars_read(cond, NULL);
9778 rem_anchor_token(';');
9780 expect(';', end_error2);
9781 if (token.type != ')') {
9782 expression_t *const step = parse_expression();
9783 statement->fors.step = step;
9784 mark_vars_read(step, ENT_ANY);
9785 if (warning.unused_value && !expression_has_effect(step)) {
9786 warningf(&step->base.source_position,
9787 "step of 'for'-statement has no effect");
9790 expect(')', end_error2);
9791 rem_anchor_token(')');
9792 statement->fors.body = parse_loop_body(statement);
9794 assert(current_scope == &statement->fors.scope);
9795 scope_pop(old_scope);
9796 environment_pop_to(top);
9803 rem_anchor_token(')');
9804 assert(current_scope == &statement->fors.scope);
9805 scope_pop(old_scope);
9806 environment_pop_to(top);
9810 return create_invalid_statement();
9814 * Parse a goto statement.
9816 static statement_t *parse_goto(void)
9818 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9821 if (GNU_MODE && token.type == '*') {
9823 expression_t *expression = parse_expression();
9824 mark_vars_read(expression, NULL);
9826 /* Argh: although documentation says the expression must be of type void*,
9827 * gcc accepts anything that can be casted into void* without error */
9828 type_t *type = expression->base.type;
9830 if (type != type_error_type) {
9831 if (!is_type_pointer(type) && !is_type_integer(type)) {
9832 errorf(&expression->base.source_position,
9833 "cannot convert to a pointer type");
9834 } else if (warning.other && type != type_void_ptr) {
9835 warningf(&expression->base.source_position,
9836 "type of computed goto expression should be 'void*' not '%T'", type);
9838 expression = create_implicit_cast(expression, type_void_ptr);
9841 statement->gotos.expression = expression;
9842 } else if (token.type == T_IDENTIFIER) {
9843 symbol_t *symbol = token.v.symbol;
9845 statement->gotos.label = get_label(symbol);
9848 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9850 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9855 /* remember the goto's in a list for later checking */
9856 *goto_anchor = &statement->gotos;
9857 goto_anchor = &statement->gotos.next;
9859 expect(';', end_error);
9863 return create_invalid_statement();
9867 * Parse a continue statement.
9869 static statement_t *parse_continue(void)
9871 if (current_loop == NULL) {
9872 errorf(HERE, "continue statement not within loop");
9875 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9878 expect(';', end_error);
9885 * Parse a break statement.
9887 static statement_t *parse_break(void)
9889 if (current_switch == NULL && current_loop == NULL) {
9890 errorf(HERE, "break statement not within loop or switch");
9893 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9896 expect(';', end_error);
9903 * Parse a __leave statement.
9905 static statement_t *parse_leave_statement(void)
9907 if (current_try == NULL) {
9908 errorf(HERE, "__leave statement not within __try");
9911 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9914 expect(';', end_error);
9921 * Check if a given entity represents a local variable.
9923 static bool is_local_variable(const entity_t *entity)
9925 if (entity->kind != ENTITY_VARIABLE)
9928 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9929 case STORAGE_CLASS_AUTO:
9930 case STORAGE_CLASS_REGISTER: {
9931 const type_t *type = skip_typeref(entity->declaration.type);
9932 if (is_type_function(type)) {
9944 * Check if a given expression represents a local variable.
9946 static bool expression_is_local_variable(const expression_t *expression)
9948 if (expression->base.kind != EXPR_REFERENCE) {
9951 const entity_t *entity = expression->reference.entity;
9952 return is_local_variable(entity);
9956 * Check if a given expression represents a local variable and
9957 * return its declaration then, else return NULL.
9959 entity_t *expression_is_variable(const expression_t *expression)
9961 if (expression->base.kind != EXPR_REFERENCE) {
9964 entity_t *entity = expression->reference.entity;
9965 if (entity->kind != ENTITY_VARIABLE)
9972 * Parse a return statement.
9974 static statement_t *parse_return(void)
9978 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9980 expression_t *return_value = NULL;
9981 if (token.type != ';') {
9982 return_value = parse_expression();
9983 mark_vars_read(return_value, NULL);
9986 const type_t *const func_type = skip_typeref(current_function->base.type);
9987 assert(is_type_function(func_type));
9988 type_t *const return_type = skip_typeref(func_type->function.return_type);
9990 source_position_t const *const pos = &statement->base.source_position;
9991 if (return_value != NULL) {
9992 type_t *return_value_type = skip_typeref(return_value->base.type);
9994 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9995 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9996 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9997 /* Only warn in C mode, because GCC does the same */
9998 if (c_mode & _CXX || strict_mode) {
10000 "'return' with a value, in function returning 'void'");
10001 } else if (warning.other) {
10003 "'return' with a value, in function returning 'void'");
10005 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10006 /* Only warn in C mode, because GCC does the same */
10009 "'return' with expression in function returning 'void'");
10010 } else if (warning.other) {
10012 "'return' with expression in function returning 'void'");
10016 assign_error_t error = semantic_assign(return_type, return_value);
10017 report_assign_error(error, return_type, return_value, "'return'",
10020 return_value = create_implicit_cast(return_value, return_type);
10021 /* check for returning address of a local var */
10022 if (warning.other && return_value != NULL
10023 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10024 const expression_t *expression = return_value->unary.value;
10025 if (expression_is_local_variable(expression)) {
10026 warningf(pos, "function returns address of local variable");
10029 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10030 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10031 if (c_mode & _CXX || strict_mode) {
10033 "'return' without value, in function returning non-void");
10036 "'return' without value, in function returning non-void");
10039 statement->returns.value = return_value;
10041 expect(';', end_error);
10048 * Parse a declaration statement.
10050 static statement_t *parse_declaration_statement(void)
10052 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10054 entity_t *before = current_scope->last_entity;
10056 parse_external_declaration();
10058 parse_declaration(record_entity, DECL_FLAGS_NONE);
10061 declaration_statement_t *const decl = &statement->declaration;
10062 entity_t *const begin =
10063 before != NULL ? before->base.next : current_scope->entities;
10064 decl->declarations_begin = begin;
10065 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10071 * Parse an expression statement, ie. expr ';'.
10073 static statement_t *parse_expression_statement(void)
10075 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10077 expression_t *const expr = parse_expression();
10078 statement->expression.expression = expr;
10079 mark_vars_read(expr, ENT_ANY);
10081 expect(';', end_error);
10088 * Parse a microsoft __try { } __finally { } or
10089 * __try{ } __except() { }
10091 static statement_t *parse_ms_try_statment(void)
10093 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10096 PUSH_PARENT(statement);
10098 ms_try_statement_t *rem = current_try;
10099 current_try = &statement->ms_try;
10100 statement->ms_try.try_statement = parse_compound_statement(false);
10105 if (token.type == T___except) {
10107 expect('(', end_error);
10108 add_anchor_token(')');
10109 expression_t *const expr = parse_expression();
10110 mark_vars_read(expr, NULL);
10111 type_t * type = skip_typeref(expr->base.type);
10112 if (is_type_integer(type)) {
10113 type = promote_integer(type);
10114 } else if (is_type_valid(type)) {
10115 errorf(&expr->base.source_position,
10116 "__expect expression is not an integer, but '%T'", type);
10117 type = type_error_type;
10119 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10120 rem_anchor_token(')');
10121 expect(')', end_error);
10122 statement->ms_try.final_statement = parse_compound_statement(false);
10123 } else if (token.type == 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);
10182 if (token.type != ',')
10188 statement->declaration.declarations_begin = begin;
10189 statement->declaration.declarations_end = end;
10193 static void parse_namespace_definition(void)
10197 entity_t *entity = NULL;
10198 symbol_t *symbol = NULL;
10200 if (token.type == T_IDENTIFIER) {
10201 symbol = token.v.symbol;
10204 entity = get_entity(symbol, NAMESPACE_NORMAL);
10205 if (entity != NULL &&
10206 entity->kind != ENTITY_NAMESPACE &&
10207 entity->base.parent_scope == current_scope) {
10208 if (!is_error_entity(entity)) {
10209 error_redefined_as_different_kind(&token.source_position,
10210 entity, ENTITY_NAMESPACE);
10216 if (entity == NULL) {
10217 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10218 entity->base.symbol = symbol;
10219 entity->base.source_position = token.source_position;
10220 entity->base.namespc = NAMESPACE_NORMAL;
10221 entity->base.parent_scope = current_scope;
10224 if (token.type == '=') {
10225 /* TODO: parse namespace alias */
10226 panic("namespace alias definition not supported yet");
10229 environment_push(entity);
10230 append_entity(current_scope, entity);
10232 size_t const top = environment_top();
10233 scope_t *old_scope = scope_push(&entity->namespacee.members);
10235 expect('{', end_error);
10237 expect('}', end_error);
10240 assert(current_scope == &entity->namespacee.members);
10241 scope_pop(old_scope);
10242 environment_pop_to(top);
10246 * Parse a statement.
10247 * There's also parse_statement() which additionally checks for
10248 * "statement has no effect" warnings
10250 static statement_t *intern_parse_statement(void)
10252 statement_t *statement = NULL;
10254 /* declaration or statement */
10255 add_anchor_token(';');
10256 switch (token.type) {
10257 case T_IDENTIFIER: {
10258 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10259 if (la1_type == ':') {
10260 statement = parse_label_statement();
10261 } else if (is_typedef_symbol(token.v.symbol)) {
10262 statement = parse_declaration_statement();
10264 /* it's an identifier, the grammar says this must be an
10265 * expression statement. However it is common that users mistype
10266 * declaration types, so we guess a bit here to improve robustness
10267 * for incorrect programs */
10268 switch (la1_type) {
10271 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10272 goto expression_statment;
10277 statement = parse_declaration_statement();
10281 expression_statment:
10282 statement = parse_expression_statement();
10289 case T___extension__:
10290 /* This can be a prefix to a declaration or an expression statement.
10291 * We simply eat it now and parse the rest with tail recursion. */
10294 } while (token.type == T___extension__);
10295 bool old_gcc_extension = in_gcc_extension;
10296 in_gcc_extension = true;
10297 statement = intern_parse_statement();
10298 in_gcc_extension = old_gcc_extension;
10302 statement = parse_declaration_statement();
10306 statement = parse_local_label_declaration();
10309 case ';': statement = parse_empty_statement(); break;
10310 case '{': statement = parse_compound_statement(false); break;
10311 case T___leave: statement = parse_leave_statement(); break;
10312 case T___try: statement = parse_ms_try_statment(); break;
10313 case T_asm: statement = parse_asm_statement(); break;
10314 case T_break: statement = parse_break(); break;
10315 case T_case: statement = parse_case_statement(); break;
10316 case T_continue: statement = parse_continue(); break;
10317 case T_default: statement = parse_default_statement(); break;
10318 case T_do: statement = parse_do(); break;
10319 case T_for: statement = parse_for(); break;
10320 case T_goto: statement = parse_goto(); break;
10321 case T_if: statement = parse_if(); break;
10322 case T_return: statement = parse_return(); break;
10323 case T_switch: statement = parse_switch(); break;
10324 case T_while: statement = parse_while(); break;
10327 statement = parse_expression_statement();
10331 errorf(HERE, "unexpected token %K while parsing statement", &token);
10332 statement = create_invalid_statement();
10337 rem_anchor_token(';');
10339 assert(statement != NULL
10340 && statement->base.source_position.input_name != NULL);
10346 * parse a statement and emits "statement has no effect" warning if needed
10347 * (This is really a wrapper around intern_parse_statement with check for 1
10348 * single warning. It is needed, because for statement expressions we have
10349 * to avoid the warning on the last statement)
10351 static statement_t *parse_statement(void)
10353 statement_t *statement = intern_parse_statement();
10355 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10356 expression_t *expression = statement->expression.expression;
10357 if (!expression_has_effect(expression)) {
10358 warningf(&expression->base.source_position,
10359 "statement has no effect");
10367 * Parse a compound statement.
10369 static statement_t *parse_compound_statement(bool inside_expression_statement)
10371 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10373 PUSH_PARENT(statement);
10376 add_anchor_token('}');
10377 /* tokens, which can start a statement */
10378 /* TODO MS, __builtin_FOO */
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('~');
10387 add_anchor_token(T_CHARACTER_CONSTANT);
10388 add_anchor_token(T_COLONCOLON);
10389 add_anchor_token(T_FLOATINGPOINT);
10390 add_anchor_token(T_IDENTIFIER);
10391 add_anchor_token(T_INTEGER);
10392 add_anchor_token(T_MINUSMINUS);
10393 add_anchor_token(T_PLUSPLUS);
10394 add_anchor_token(T_STRING_LITERAL);
10395 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10396 add_anchor_token(T_WIDE_STRING_LITERAL);
10397 add_anchor_token(T__Bool);
10398 add_anchor_token(T__Complex);
10399 add_anchor_token(T__Imaginary);
10400 add_anchor_token(T___FUNCTION__);
10401 add_anchor_token(T___PRETTY_FUNCTION__);
10402 add_anchor_token(T___alignof__);
10403 add_anchor_token(T___attribute__);
10404 add_anchor_token(T___builtin_va_start);
10405 add_anchor_token(T___extension__);
10406 add_anchor_token(T___func__);
10407 add_anchor_token(T___imag__);
10408 add_anchor_token(T___label__);
10409 add_anchor_token(T___real__);
10410 add_anchor_token(T___thread);
10411 add_anchor_token(T_asm);
10412 add_anchor_token(T_auto);
10413 add_anchor_token(T_bool);
10414 add_anchor_token(T_break);
10415 add_anchor_token(T_case);
10416 add_anchor_token(T_char);
10417 add_anchor_token(T_class);
10418 add_anchor_token(T_const);
10419 add_anchor_token(T_const_cast);
10420 add_anchor_token(T_continue);
10421 add_anchor_token(T_default);
10422 add_anchor_token(T_delete);
10423 add_anchor_token(T_double);
10424 add_anchor_token(T_do);
10425 add_anchor_token(T_dynamic_cast);
10426 add_anchor_token(T_enum);
10427 add_anchor_token(T_extern);
10428 add_anchor_token(T_false);
10429 add_anchor_token(T_float);
10430 add_anchor_token(T_for);
10431 add_anchor_token(T_goto);
10432 add_anchor_token(T_if);
10433 add_anchor_token(T_inline);
10434 add_anchor_token(T_int);
10435 add_anchor_token(T_long);
10436 add_anchor_token(T_new);
10437 add_anchor_token(T_operator);
10438 add_anchor_token(T_register);
10439 add_anchor_token(T_reinterpret_cast);
10440 add_anchor_token(T_restrict);
10441 add_anchor_token(T_return);
10442 add_anchor_token(T_short);
10443 add_anchor_token(T_signed);
10444 add_anchor_token(T_sizeof);
10445 add_anchor_token(T_static);
10446 add_anchor_token(T_static_cast);
10447 add_anchor_token(T_struct);
10448 add_anchor_token(T_switch);
10449 add_anchor_token(T_template);
10450 add_anchor_token(T_this);
10451 add_anchor_token(T_throw);
10452 add_anchor_token(T_true);
10453 add_anchor_token(T_try);
10454 add_anchor_token(T_typedef);
10455 add_anchor_token(T_typeid);
10456 add_anchor_token(T_typename);
10457 add_anchor_token(T_typeof);
10458 add_anchor_token(T_union);
10459 add_anchor_token(T_unsigned);
10460 add_anchor_token(T_using);
10461 add_anchor_token(T_void);
10462 add_anchor_token(T_volatile);
10463 add_anchor_token(T_wchar_t);
10464 add_anchor_token(T_while);
10466 size_t const top = environment_top();
10467 scope_t *old_scope = scope_push(&statement->compound.scope);
10469 statement_t **anchor = &statement->compound.statements;
10470 bool only_decls_so_far = true;
10471 while (token.type != '}') {
10472 if (token.type == T_EOF) {
10473 errorf(&statement->base.source_position,
10474 "EOF while parsing compound statement");
10477 statement_t *sub_statement = intern_parse_statement();
10478 if (is_invalid_statement(sub_statement)) {
10479 /* an error occurred. if we are at an anchor, return */
10485 if (warning.declaration_after_statement) {
10486 if (sub_statement->kind != STATEMENT_DECLARATION) {
10487 only_decls_so_far = false;
10488 } else if (!only_decls_so_far) {
10489 warningf(&sub_statement->base.source_position,
10490 "ISO C90 forbids mixed declarations and code");
10494 *anchor = sub_statement;
10496 while (sub_statement->base.next != NULL)
10497 sub_statement = sub_statement->base.next;
10499 anchor = &sub_statement->base.next;
10503 /* look over all statements again to produce no effect warnings */
10504 if (warning.unused_value) {
10505 statement_t *sub_statement = statement->compound.statements;
10506 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10507 if (sub_statement->kind != STATEMENT_EXPRESSION)
10509 /* don't emit a warning for the last expression in an expression
10510 * statement as it has always an effect */
10511 if (inside_expression_statement && sub_statement->base.next == NULL)
10514 expression_t *expression = sub_statement->expression.expression;
10515 if (!expression_has_effect(expression)) {
10516 warningf(&expression->base.source_position,
10517 "statement has no effect");
10523 rem_anchor_token(T_while);
10524 rem_anchor_token(T_wchar_t);
10525 rem_anchor_token(T_volatile);
10526 rem_anchor_token(T_void);
10527 rem_anchor_token(T_using);
10528 rem_anchor_token(T_unsigned);
10529 rem_anchor_token(T_union);
10530 rem_anchor_token(T_typeof);
10531 rem_anchor_token(T_typename);
10532 rem_anchor_token(T_typeid);
10533 rem_anchor_token(T_typedef);
10534 rem_anchor_token(T_try);
10535 rem_anchor_token(T_true);
10536 rem_anchor_token(T_throw);
10537 rem_anchor_token(T_this);
10538 rem_anchor_token(T_template);
10539 rem_anchor_token(T_switch);
10540 rem_anchor_token(T_struct);
10541 rem_anchor_token(T_static_cast);
10542 rem_anchor_token(T_static);
10543 rem_anchor_token(T_sizeof);
10544 rem_anchor_token(T_signed);
10545 rem_anchor_token(T_short);
10546 rem_anchor_token(T_return);
10547 rem_anchor_token(T_restrict);
10548 rem_anchor_token(T_reinterpret_cast);
10549 rem_anchor_token(T_register);
10550 rem_anchor_token(T_operator);
10551 rem_anchor_token(T_new);
10552 rem_anchor_token(T_long);
10553 rem_anchor_token(T_int);
10554 rem_anchor_token(T_inline);
10555 rem_anchor_token(T_if);
10556 rem_anchor_token(T_goto);
10557 rem_anchor_token(T_for);
10558 rem_anchor_token(T_float);
10559 rem_anchor_token(T_false);
10560 rem_anchor_token(T_extern);
10561 rem_anchor_token(T_enum);
10562 rem_anchor_token(T_dynamic_cast);
10563 rem_anchor_token(T_do);
10564 rem_anchor_token(T_double);
10565 rem_anchor_token(T_delete);
10566 rem_anchor_token(T_default);
10567 rem_anchor_token(T_continue);
10568 rem_anchor_token(T_const_cast);
10569 rem_anchor_token(T_const);
10570 rem_anchor_token(T_class);
10571 rem_anchor_token(T_char);
10572 rem_anchor_token(T_case);
10573 rem_anchor_token(T_break);
10574 rem_anchor_token(T_bool);
10575 rem_anchor_token(T_auto);
10576 rem_anchor_token(T_asm);
10577 rem_anchor_token(T___thread);
10578 rem_anchor_token(T___real__);
10579 rem_anchor_token(T___label__);
10580 rem_anchor_token(T___imag__);
10581 rem_anchor_token(T___func__);
10582 rem_anchor_token(T___extension__);
10583 rem_anchor_token(T___builtin_va_start);
10584 rem_anchor_token(T___attribute__);
10585 rem_anchor_token(T___alignof__);
10586 rem_anchor_token(T___PRETTY_FUNCTION__);
10587 rem_anchor_token(T___FUNCTION__);
10588 rem_anchor_token(T__Imaginary);
10589 rem_anchor_token(T__Complex);
10590 rem_anchor_token(T__Bool);
10591 rem_anchor_token(T_WIDE_STRING_LITERAL);
10592 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10593 rem_anchor_token(T_STRING_LITERAL);
10594 rem_anchor_token(T_PLUSPLUS);
10595 rem_anchor_token(T_MINUSMINUS);
10596 rem_anchor_token(T_INTEGER);
10597 rem_anchor_token(T_IDENTIFIER);
10598 rem_anchor_token(T_FLOATINGPOINT);
10599 rem_anchor_token(T_COLONCOLON);
10600 rem_anchor_token(T_CHARACTER_CONSTANT);
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 rem_anchor_token('}');
10610 assert(current_scope == &statement->compound.scope);
10611 scope_pop(old_scope);
10612 environment_pop_to(top);
10619 * Check for unused global static functions and variables
10621 static void check_unused_globals(void)
10623 if (!warning.unused_function && !warning.unused_variable)
10626 for (const entity_t *entity = file_scope->entities; entity != NULL;
10627 entity = entity->base.next) {
10628 if (!is_declaration(entity))
10631 const declaration_t *declaration = &entity->declaration;
10632 if (declaration->used ||
10633 declaration->modifiers & DM_UNUSED ||
10634 declaration->modifiers & DM_USED ||
10635 declaration->storage_class != STORAGE_CLASS_STATIC)
10638 type_t *const type = declaration->type;
10640 if (entity->kind == ENTITY_FUNCTION) {
10641 /* inhibit warning for static inline functions */
10642 if (entity->function.is_inline)
10645 s = entity->function.statement != NULL ? "defined" : "declared";
10650 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10651 type, declaration->base.symbol, s);
10655 static void parse_global_asm(void)
10657 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10660 expect('(', end_error);
10662 statement->asms.asm_text = parse_string_literals();
10663 statement->base.next = unit->global_asm;
10664 unit->global_asm = statement;
10666 expect(')', end_error);
10667 expect(';', end_error);
10672 static void parse_linkage_specification(void)
10675 assert(token.type == T_STRING_LITERAL);
10677 const char *linkage = parse_string_literals().begin;
10679 linkage_kind_t old_linkage = current_linkage;
10680 linkage_kind_t new_linkage;
10681 if (strcmp(linkage, "C") == 0) {
10682 new_linkage = LINKAGE_C;
10683 } else if (strcmp(linkage, "C++") == 0) {
10684 new_linkage = LINKAGE_CXX;
10686 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10687 new_linkage = LINKAGE_INVALID;
10689 current_linkage = new_linkage;
10691 if (token.type == '{') {
10694 expect('}', end_error);
10700 assert(current_linkage == new_linkage);
10701 current_linkage = old_linkage;
10704 static void parse_external(void)
10706 switch (token.type) {
10707 DECLARATION_START_NO_EXTERN
10709 case T___extension__:
10710 /* tokens below are for implicit int */
10711 case '&': /* & x; -> int& x; (and error later, because C++ has no
10713 case '*': /* * x; -> int* x; */
10714 case '(': /* (x); -> int (x); */
10715 parse_external_declaration();
10719 if (look_ahead(1)->type == T_STRING_LITERAL) {
10720 parse_linkage_specification();
10722 parse_external_declaration();
10727 parse_global_asm();
10731 parse_namespace_definition();
10735 if (!strict_mode) {
10737 warningf(HERE, "stray ';' outside of function");
10744 errorf(HERE, "stray %K outside of function", &token);
10745 if (token.type == '(' || token.type == '{' || token.type == '[')
10746 eat_until_matching_token(token.type);
10752 static void parse_externals(void)
10754 add_anchor_token('}');
10755 add_anchor_token(T_EOF);
10758 unsigned char token_anchor_copy[T_LAST_TOKEN];
10759 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10762 while (token.type != T_EOF && token.type != '}') {
10764 bool anchor_leak = false;
10765 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10766 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10768 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10769 anchor_leak = true;
10772 if (in_gcc_extension) {
10773 errorf(HERE, "Leaked __extension__");
10774 anchor_leak = true;
10784 rem_anchor_token(T_EOF);
10785 rem_anchor_token('}');
10789 * Parse a translation unit.
10791 static void parse_translation_unit(void)
10793 add_anchor_token(T_EOF);
10798 if (token.type == T_EOF)
10801 errorf(HERE, "stray %K outside of function", &token);
10802 if (token.type == '(' || token.type == '{' || token.type == '[')
10803 eat_until_matching_token(token.type);
10811 * @return the translation unit or NULL if errors occurred.
10813 void start_parsing(void)
10815 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10816 label_stack = NEW_ARR_F(stack_entry_t, 0);
10817 diagnostic_count = 0;
10821 type_set_output(stderr);
10822 ast_set_output(stderr);
10824 assert(unit == NULL);
10825 unit = allocate_ast_zero(sizeof(unit[0]));
10827 assert(file_scope == NULL);
10828 file_scope = &unit->scope;
10830 assert(current_scope == NULL);
10831 scope_push(&unit->scope);
10833 create_gnu_builtins();
10835 create_microsoft_intrinsics();
10838 translation_unit_t *finish_parsing(void)
10840 assert(current_scope == &unit->scope);
10843 assert(file_scope == &unit->scope);
10844 check_unused_globals();
10847 DEL_ARR_F(environment_stack);
10848 DEL_ARR_F(label_stack);
10850 translation_unit_t *result = unit;
10855 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10856 * are given length one. */
10857 static void complete_incomplete_arrays(void)
10859 size_t n = ARR_LEN(incomplete_arrays);
10860 for (size_t i = 0; i != n; ++i) {
10861 declaration_t *const decl = incomplete_arrays[i];
10862 type_t *const orig_type = decl->type;
10863 type_t *const type = skip_typeref(orig_type);
10865 if (!is_type_incomplete(type))
10868 if (warning.other) {
10869 warningf(&decl->base.source_position,
10870 "array '%#T' assumed to have one element",
10871 orig_type, decl->base.symbol);
10874 type_t *const new_type = duplicate_type(type);
10875 new_type->array.size_constant = true;
10876 new_type->array.has_implicit_size = true;
10877 new_type->array.size = 1;
10879 type_t *const result = identify_new_type(new_type);
10881 decl->type = result;
10885 void prepare_main_collect2(entity_t *entity)
10887 // create call to __main
10888 symbol_t *symbol = symbol_table_insert("__main");
10889 entity_t *subsubmain_ent
10890 = create_implicit_function(symbol, &builtin_source_position);
10892 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10893 type_t *ftype = subsubmain_ent->declaration.type;
10894 ref->base.source_position = builtin_source_position;
10895 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10896 ref->reference.entity = subsubmain_ent;
10898 expression_t *call = allocate_expression_zero(EXPR_CALL);
10899 call->base.source_position = builtin_source_position;
10900 call->base.type = type_void;
10901 call->call.function = ref;
10903 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10904 expr_statement->base.source_position = builtin_source_position;
10905 expr_statement->expression.expression = call;
10907 statement_t *statement = entity->function.statement;
10908 assert(statement->kind == STATEMENT_COMPOUND);
10909 compound_statement_t *compounds = &statement->compound;
10911 expr_statement->base.next = compounds->statements;
10912 compounds->statements = expr_statement;
10917 lookahead_bufpos = 0;
10918 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10921 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10922 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10923 parse_translation_unit();
10924 complete_incomplete_arrays();
10925 DEL_ARR_F(incomplete_arrays);
10926 incomplete_arrays = NULL;
10930 * create a builtin function.
10932 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10934 symbol_t *symbol = symbol_table_insert(name);
10935 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10936 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10937 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10938 entity->declaration.type = function_type;
10939 entity->declaration.implicit = true;
10940 entity->base.symbol = symbol;
10941 entity->base.source_position = builtin_source_position;
10943 entity->function.btk = kind;
10945 record_entity(entity, /*is_definition=*/false);
10951 * Create predefined gnu builtins.
10953 static void create_gnu_builtins(void)
10955 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10957 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10958 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10959 GNU_BUILTIN(inf, make_function_0_type(type_double));
10960 GNU_BUILTIN(inff, make_function_0_type(type_float));
10961 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
10962 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
10963 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
10964 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
10965 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
10966 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
10967 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10968 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10969 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
10970 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
10971 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
10972 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
10973 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
10974 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
10975 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
10981 * Create predefined MS intrinsics.
10983 static void create_microsoft_intrinsics(void)
10985 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
10987 /* intrinsics for all architectures */
10988 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10989 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10990 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
10991 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
10992 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
10993 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
10994 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
10996 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
10997 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
10998 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
10999 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11002 MS_BUILTIN(_enable, make_function_0_type(type_void));
11003 MS_BUILTIN(_disable, make_function_0_type(type_void));
11004 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11005 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11006 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11007 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11008 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11009 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11010 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11011 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11012 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11013 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11014 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11016 if (machine_size <= 32) {
11017 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11018 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11020 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11021 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11028 * Initialize the parser.
11030 void init_parser(void)
11032 sym_anonymous = symbol_table_insert("<anonymous>");
11034 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11036 init_expression_parsers();
11037 obstack_init(&temp_obst);
11039 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11040 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11044 * Terminate the parser.
11046 void exit_parser(void)
11048 obstack_free(&temp_obst, NULL);