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(expression) == 0;
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(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;
2538 if (token.type == T___attribute__) {
2539 parse_attributes(NULL);
2542 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2543 if (token.type == T_IDENTIFIER) {
2544 /* the compound has a name, check if we have seen it already */
2545 symbol = token.v.symbol;
2548 entity_t *entity = get_tag(symbol, kind);
2549 if (entity != NULL) {
2550 compound = &entity->compound;
2551 if (compound->base.parent_scope != current_scope &&
2552 (token.type == '{' || token.type == ';')) {
2553 /* we're in an inner scope and have a definition. Shadow
2554 * existing definition in outer scope */
2556 } else if (compound->complete && token.type == '{') {
2557 assert(symbol != NULL);
2558 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2559 is_struct ? "struct" : "union", symbol,
2560 &compound->base.source_position);
2561 /* clear members in the hope to avoid further errors */
2562 compound->members.entities = NULL;
2565 } else if (token.type != '{') {
2567 parse_error_expected("while parsing struct type specifier",
2568 T_IDENTIFIER, '{', NULL);
2570 parse_error_expected("while parsing union type specifier",
2571 T_IDENTIFIER, '{', NULL);
2577 if (compound == NULL) {
2578 entity_t *entity = allocate_entity_zero(kind);
2579 compound = &entity->compound;
2581 compound->base.namespc = NAMESPACE_TAG;
2582 compound->base.source_position = token.source_position;
2583 compound->base.symbol = symbol;
2584 compound->base.parent_scope = current_scope;
2585 if (symbol != NULL) {
2586 environment_push(entity);
2588 append_entity(current_scope, entity);
2591 if (token.type == '{') {
2592 parse_compound_type_entries(compound);
2593 parse_attributes(NULL);
2595 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2596 if (symbol == NULL) {
2597 assert(anonymous_entity == NULL);
2598 anonymous_entity = (entity_t*)compound;
2605 static void parse_enum_entries(type_t *const enum_type)
2609 if (token.type == '}') {
2610 errorf(HERE, "empty enum not allowed");
2615 add_anchor_token('}');
2617 if (token.type != T_IDENTIFIER) {
2618 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2620 rem_anchor_token('}');
2624 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2625 entity->enum_value.enum_type = enum_type;
2626 entity->base.symbol = token.v.symbol;
2627 entity->base.source_position = token.source_position;
2630 if (token.type == '=') {
2632 expression_t *value = parse_constant_expression();
2634 value = create_implicit_cast(value, enum_type);
2635 entity->enum_value.value = value;
2640 record_entity(entity, false);
2642 if (token.type != ',')
2645 } while (token.type != '}');
2646 rem_anchor_token('}');
2648 expect('}', end_error);
2654 static type_t *parse_enum_specifier(void)
2660 if (token.type == T_IDENTIFIER) {
2661 symbol = token.v.symbol;
2664 entity = get_tag(symbol, ENTITY_ENUM);
2665 if (entity != NULL) {
2666 if (entity->base.parent_scope != current_scope &&
2667 (token.type == '{' || token.type == ';')) {
2668 /* we're in an inner scope and have a definition. Shadow
2669 * existing definition in outer scope */
2671 } else if (entity->enume.complete && token.type == '{') {
2672 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2673 symbol, &entity->base.source_position);
2676 } else if (token.type != '{') {
2677 parse_error_expected("while parsing enum type specifier",
2678 T_IDENTIFIER, '{', NULL);
2685 if (entity == NULL) {
2686 entity = allocate_entity_zero(ENTITY_ENUM);
2687 entity->base.namespc = NAMESPACE_TAG;
2688 entity->base.source_position = token.source_position;
2689 entity->base.symbol = symbol;
2690 entity->base.parent_scope = current_scope;
2693 type_t *const type = allocate_type_zero(TYPE_ENUM);
2694 type->enumt.enume = &entity->enume;
2695 type->enumt.akind = ATOMIC_TYPE_INT;
2697 if (token.type == '{') {
2698 if (symbol != NULL) {
2699 environment_push(entity);
2701 append_entity(current_scope, entity);
2702 entity->enume.complete = true;
2704 parse_enum_entries(type);
2705 parse_attributes(NULL);
2707 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2708 if (symbol == NULL) {
2709 assert(anonymous_entity == NULL);
2710 anonymous_entity = entity;
2712 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2713 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2721 * if a symbol is a typedef to another type, return true
2723 static bool is_typedef_symbol(symbol_t *symbol)
2725 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2726 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2729 static type_t *parse_typeof(void)
2735 expect('(', end_error);
2736 add_anchor_token(')');
2738 expression_t *expression = NULL;
2740 bool old_type_prop = in_type_prop;
2741 bool old_gcc_extension = in_gcc_extension;
2742 in_type_prop = true;
2744 while (token.type == T___extension__) {
2745 /* This can be a prefix to a typename or an expression. */
2747 in_gcc_extension = true;
2749 switch (token.type) {
2751 if (is_typedef_symbol(token.v.symbol)) {
2752 type = parse_typename();
2754 expression = parse_expression();
2755 type = revert_automatic_type_conversion(expression);
2760 type = parse_typename();
2764 expression = parse_expression();
2765 type = expression->base.type;
2768 in_type_prop = old_type_prop;
2769 in_gcc_extension = old_gcc_extension;
2771 rem_anchor_token(')');
2772 expect(')', end_error);
2774 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2775 typeof_type->typeoft.expression = expression;
2776 typeof_type->typeoft.typeof_type = type;
2783 typedef enum specifiers_t {
2784 SPECIFIER_SIGNED = 1 << 0,
2785 SPECIFIER_UNSIGNED = 1 << 1,
2786 SPECIFIER_LONG = 1 << 2,
2787 SPECIFIER_INT = 1 << 3,
2788 SPECIFIER_DOUBLE = 1 << 4,
2789 SPECIFIER_CHAR = 1 << 5,
2790 SPECIFIER_WCHAR_T = 1 << 6,
2791 SPECIFIER_SHORT = 1 << 7,
2792 SPECIFIER_LONG_LONG = 1 << 8,
2793 SPECIFIER_FLOAT = 1 << 9,
2794 SPECIFIER_BOOL = 1 << 10,
2795 SPECIFIER_VOID = 1 << 11,
2796 SPECIFIER_INT8 = 1 << 12,
2797 SPECIFIER_INT16 = 1 << 13,
2798 SPECIFIER_INT32 = 1 << 14,
2799 SPECIFIER_INT64 = 1 << 15,
2800 SPECIFIER_INT128 = 1 << 16,
2801 SPECIFIER_COMPLEX = 1 << 17,
2802 SPECIFIER_IMAGINARY = 1 << 18,
2805 static type_t *create_builtin_type(symbol_t *const symbol,
2806 type_t *const real_type)
2808 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2809 type->builtin.symbol = symbol;
2810 type->builtin.real_type = real_type;
2811 return identify_new_type(type);
2814 static type_t *get_typedef_type(symbol_t *symbol)
2816 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2817 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2820 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2821 type->typedeft.typedefe = &entity->typedefe;
2826 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2828 expect('(', end_error);
2830 attribute_property_argument_t *property
2831 = allocate_ast_zero(sizeof(*property));
2834 if (token.type != T_IDENTIFIER) {
2835 parse_error_expected("while parsing property declspec",
2836 T_IDENTIFIER, NULL);
2841 symbol_t *symbol = token.v.symbol;
2843 if (strcmp(symbol->string, "put") == 0) {
2845 } else if (strcmp(symbol->string, "get") == 0) {
2848 errorf(HERE, "expected put or get in property declspec");
2851 expect('=', end_error);
2852 if (token.type != T_IDENTIFIER) {
2853 parse_error_expected("while parsing property declspec",
2854 T_IDENTIFIER, NULL);
2858 property->put_symbol = token.v.symbol;
2860 property->get_symbol = token.v.symbol;
2863 if (token.type == ')')
2865 expect(',', end_error);
2868 attribute->a.property = property;
2870 expect(')', end_error);
2876 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2878 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2879 if (token.type == T_restrict) {
2880 kind = ATTRIBUTE_MS_RESTRICT;
2882 } else if (token.type == T_IDENTIFIER) {
2883 const char *name = token.v.symbol->string;
2885 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2887 const char *attribute_name = get_attribute_name(k);
2888 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2894 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2895 warningf(HERE, "unknown __declspec '%s' ignored", name);
2898 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2902 attribute_t *attribute = allocate_attribute_zero(kind);
2904 if (kind == ATTRIBUTE_MS_PROPERTY) {
2905 return parse_attribute_ms_property(attribute);
2908 /* parse arguments */
2909 if (token.type == '(') {
2911 attribute->a.arguments = parse_attribute_arguments();
2917 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2921 expect('(', end_error);
2923 if (token.type == ')') {
2928 add_anchor_token(')');
2930 attribute_t *last = first;
2933 while (last->next != NULL)
2937 attribute_t *attribute
2938 = parse_microsoft_extended_decl_modifier_single();
2939 if (attribute == NULL)
2945 last->next = attribute;
2949 if (token.type == ')') {
2952 expect(',', end_error);
2955 rem_anchor_token(')');
2956 expect(')', end_error);
2960 rem_anchor_token(')');
2964 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2966 entity_t *entity = allocate_entity_zero(kind);
2967 entity->base.source_position = *HERE;
2968 entity->base.symbol = symbol;
2969 if (is_declaration(entity)) {
2970 entity->declaration.type = type_error_type;
2971 entity->declaration.implicit = true;
2972 } else if (kind == ENTITY_TYPEDEF) {
2973 entity->typedefe.type = type_error_type;
2974 entity->typedefe.builtin = true;
2976 if (kind != ENTITY_COMPOUND_MEMBER)
2977 record_entity(entity, false);
2982 * Finish the construction of a struct type by calculating its size, offsets,
2985 static void finish_struct_type(compound_type_t *type)
2987 assert(type->compound != NULL);
2989 compound_t *compound = type->compound;
2990 if (!compound->complete)
2995 il_alignment_t alignment = compound->alignment;
2996 bool need_pad = false;
2998 entity_t *entry = compound->members.entities;
2999 for (; entry != NULL; entry = entry->base.next) {
3000 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3003 type_t *m_type = entry->declaration.type;
3004 if (! is_type_valid(skip_typeref(m_type))) {
3005 /* simply ignore errors here */
3008 il_alignment_t m_alignment = get_type_alignment(m_type);
3009 if (m_alignment > alignment)
3010 alignment = m_alignment;
3012 offset = (size + m_alignment - 1) & -m_alignment;
3016 entry->compound_member.offset = offset;
3017 size = offset + get_type_size(m_type);
3020 offset = (size + alignment - 1) & -alignment;
3025 if (warning.padded) {
3026 warningf(&compound->base.source_position, "'%T' needs padding",
3029 } else if (compound->packed && warning.packed) {
3030 warningf(&compound->base.source_position,
3031 "superfluous packed attribute on '%T'", type);
3034 compound->size = offset;
3035 compound->alignment = alignment;
3039 * Finish the construction of an union type by calculating
3040 * its size and alignment.
3042 static void finish_union_type(compound_type_t *type)
3044 assert(type->compound != NULL);
3046 compound_t *compound = type->compound;
3047 if (! compound->complete)
3051 il_alignment_t alignment = compound->alignment;
3053 entity_t *entry = compound->members.entities;
3054 for (; entry != NULL; entry = entry->base.next) {
3055 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3058 type_t *m_type = entry->declaration.type;
3059 if (! is_type_valid(skip_typeref(m_type)))
3062 entry->compound_member.offset = 0;
3063 il_size_t m_size = get_type_size(m_type);
3066 il_alignment_t m_alignment = get_type_alignment(m_type);
3067 if (m_alignment > alignment)
3068 alignment = m_alignment;
3070 size = (size + alignment - 1) & -alignment;
3072 compound->size = size;
3073 compound->alignment = alignment;
3076 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3078 type_t *type = NULL;
3079 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3080 unsigned type_specifiers = 0;
3081 bool newtype = false;
3082 bool saw_error = false;
3083 bool old_gcc_extension = in_gcc_extension;
3085 specifiers->source_position = token.source_position;
3088 specifiers->attributes = parse_attributes(specifiers->attributes);
3090 switch (token.type) {
3092 #define MATCH_STORAGE_CLASS(token, class) \
3094 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3095 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3097 specifiers->storage_class = class; \
3098 if (specifiers->thread_local) \
3099 goto check_thread_storage_class; \
3103 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3104 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3105 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3106 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3107 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3110 specifiers->attributes
3111 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
3115 if (specifiers->thread_local) {
3116 errorf(HERE, "duplicate '__thread'");
3118 specifiers->thread_local = true;
3119 check_thread_storage_class:
3120 switch (specifiers->storage_class) {
3121 case STORAGE_CLASS_EXTERN:
3122 case STORAGE_CLASS_NONE:
3123 case STORAGE_CLASS_STATIC:
3127 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3128 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3129 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3130 wrong_thread_stoarge_class:
3131 errorf(HERE, "'__thread' used with '%s'", wrong);
3138 /* type qualifiers */
3139 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3141 qualifiers |= qualifier; \
3145 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3146 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3147 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3148 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3149 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3150 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3151 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3152 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3154 case T___extension__:
3156 in_gcc_extension = true;
3159 /* type specifiers */
3160 #define MATCH_SPECIFIER(token, specifier, name) \
3162 if (type_specifiers & specifier) { \
3163 errorf(HERE, "multiple " name " type specifiers given"); \
3165 type_specifiers |= specifier; \
3170 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3171 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3172 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3173 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3174 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3175 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3176 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3177 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3178 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3179 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3180 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3181 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3182 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3183 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3184 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3185 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3186 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3187 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3191 specifiers->is_inline = true;
3195 case T__forceinline:
3197 specifiers->modifiers |= DM_FORCEINLINE;
3202 if (type_specifiers & SPECIFIER_LONG_LONG) {
3203 errorf(HERE, "multiple type specifiers given");
3204 } else if (type_specifiers & SPECIFIER_LONG) {
3205 type_specifiers |= SPECIFIER_LONG_LONG;
3207 type_specifiers |= SPECIFIER_LONG;
3212 #define CHECK_DOUBLE_TYPE() \
3213 if ( type != NULL) \
3214 errorf(HERE, "multiple data types in declaration specifiers");
3217 CHECK_DOUBLE_TYPE();
3218 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3220 type->compound.compound = parse_compound_type_specifier(true);
3221 finish_struct_type(&type->compound);
3224 CHECK_DOUBLE_TYPE();
3225 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3226 type->compound.compound = parse_compound_type_specifier(false);
3227 finish_union_type(&type->compound);
3230 CHECK_DOUBLE_TYPE();
3231 type = parse_enum_specifier();
3234 CHECK_DOUBLE_TYPE();
3235 type = parse_typeof();
3237 case T___builtin_va_list:
3238 CHECK_DOUBLE_TYPE();
3239 type = duplicate_type(type_valist);
3243 case T_IDENTIFIER: {
3244 /* only parse identifier if we haven't found a type yet */
3245 if (type != NULL || type_specifiers != 0) {
3246 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3247 * declaration, so it doesn't generate errors about expecting '(' or
3249 switch (look_ahead(1)->type) {
3256 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3260 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3265 goto finish_specifiers;
3269 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3270 if (typedef_type == NULL) {
3271 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3272 * declaration, so it doesn't generate 'implicit int' followed by more
3273 * errors later on. */
3274 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3280 errorf(HERE, "%K does not name a type", &token);
3283 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3285 type = allocate_type_zero(TYPE_TYPEDEF);
3286 type->typedeft.typedefe = &entity->typedefe;
3290 if (la1_type == '&' || la1_type == '*')
3291 goto finish_specifiers;
3296 goto finish_specifiers;
3301 type = typedef_type;
3305 /* function specifier */
3307 goto finish_specifiers;
3312 specifiers->attributes = parse_attributes(specifiers->attributes);
3314 in_gcc_extension = old_gcc_extension;
3316 if (type == NULL || (saw_error && type_specifiers != 0)) {
3317 atomic_type_kind_t atomic_type;
3319 /* match valid basic types */
3320 switch (type_specifiers) {
3321 case SPECIFIER_VOID:
3322 atomic_type = ATOMIC_TYPE_VOID;
3324 case SPECIFIER_WCHAR_T:
3325 atomic_type = ATOMIC_TYPE_WCHAR_T;
3327 case SPECIFIER_CHAR:
3328 atomic_type = ATOMIC_TYPE_CHAR;
3330 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3331 atomic_type = ATOMIC_TYPE_SCHAR;
3333 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3334 atomic_type = ATOMIC_TYPE_UCHAR;
3336 case SPECIFIER_SHORT:
3337 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3338 case SPECIFIER_SHORT | SPECIFIER_INT:
3339 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3340 atomic_type = ATOMIC_TYPE_SHORT;
3342 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3343 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3344 atomic_type = ATOMIC_TYPE_USHORT;
3347 case SPECIFIER_SIGNED:
3348 case SPECIFIER_SIGNED | SPECIFIER_INT:
3349 atomic_type = ATOMIC_TYPE_INT;
3351 case SPECIFIER_UNSIGNED:
3352 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3353 atomic_type = ATOMIC_TYPE_UINT;
3355 case SPECIFIER_LONG:
3356 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3357 case SPECIFIER_LONG | SPECIFIER_INT:
3358 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3359 atomic_type = ATOMIC_TYPE_LONG;
3361 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3362 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3363 atomic_type = ATOMIC_TYPE_ULONG;
3366 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3367 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3368 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3369 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3371 atomic_type = ATOMIC_TYPE_LONGLONG;
3372 goto warn_about_long_long;
3374 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3375 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3377 atomic_type = ATOMIC_TYPE_ULONGLONG;
3378 warn_about_long_long:
3379 if (warning.long_long) {
3380 warningf(&specifiers->source_position,
3381 "ISO C90 does not support 'long long'");
3385 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3386 atomic_type = unsigned_int8_type_kind;
3389 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3390 atomic_type = unsigned_int16_type_kind;
3393 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3394 atomic_type = unsigned_int32_type_kind;
3397 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3398 atomic_type = unsigned_int64_type_kind;
3401 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3402 atomic_type = unsigned_int128_type_kind;
3405 case SPECIFIER_INT8:
3406 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3407 atomic_type = int8_type_kind;
3410 case SPECIFIER_INT16:
3411 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3412 atomic_type = int16_type_kind;
3415 case SPECIFIER_INT32:
3416 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3417 atomic_type = int32_type_kind;
3420 case SPECIFIER_INT64:
3421 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3422 atomic_type = int64_type_kind;
3425 case SPECIFIER_INT128:
3426 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3427 atomic_type = int128_type_kind;
3430 case SPECIFIER_FLOAT:
3431 atomic_type = ATOMIC_TYPE_FLOAT;
3433 case SPECIFIER_DOUBLE:
3434 atomic_type = ATOMIC_TYPE_DOUBLE;
3436 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3437 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3439 case SPECIFIER_BOOL:
3440 atomic_type = ATOMIC_TYPE_BOOL;
3442 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3443 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3444 atomic_type = ATOMIC_TYPE_FLOAT;
3446 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3447 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3448 atomic_type = ATOMIC_TYPE_DOUBLE;
3450 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3451 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3452 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3455 /* invalid specifier combination, give an error message */
3456 if (type_specifiers == 0) {
3460 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3461 if (!(c_mode & _CXX) && !strict_mode) {
3462 if (warning.implicit_int) {
3463 warningf(HERE, "no type specifiers in declaration, using 'int'");
3465 atomic_type = ATOMIC_TYPE_INT;
3468 errorf(HERE, "no type specifiers given in declaration");
3470 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3471 (type_specifiers & SPECIFIER_UNSIGNED)) {
3472 errorf(HERE, "signed and unsigned specifiers given");
3473 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3474 errorf(HERE, "only integer types can be signed or unsigned");
3476 errorf(HERE, "multiple datatypes in declaration");
3481 if (type_specifiers & SPECIFIER_COMPLEX) {
3482 type = allocate_type_zero(TYPE_COMPLEX);
3483 type->complex.akind = atomic_type;
3484 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3485 type = allocate_type_zero(TYPE_IMAGINARY);
3486 type->imaginary.akind = atomic_type;
3488 type = allocate_type_zero(TYPE_ATOMIC);
3489 type->atomic.akind = atomic_type;
3492 } else if (type_specifiers != 0) {
3493 errorf(HERE, "multiple datatypes in declaration");
3496 /* FIXME: check type qualifiers here */
3497 type->base.qualifiers = qualifiers;
3500 type = identify_new_type(type);
3502 type = typehash_insert(type);
3505 if (specifiers->attributes != NULL)
3506 type = handle_type_attributes(specifiers->attributes, type);
3507 specifiers->type = type;
3511 specifiers->type = type_error_type;
3515 static type_qualifiers_t parse_type_qualifiers(void)
3517 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3520 switch (token.type) {
3521 /* type qualifiers */
3522 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3523 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3524 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3525 /* microsoft extended type modifiers */
3526 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3527 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3528 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3529 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3530 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3539 * Parses an K&R identifier list
3541 static void parse_identifier_list(scope_t *scope)
3544 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3545 entity->base.source_position = token.source_position;
3546 entity->base.namespc = NAMESPACE_NORMAL;
3547 entity->base.symbol = token.v.symbol;
3548 /* a K&R parameter has no type, yet */
3552 append_entity(scope, entity);
3554 if (token.type != ',') {
3558 } while (token.type == T_IDENTIFIER);
3561 static entity_t *parse_parameter(void)
3563 declaration_specifiers_t specifiers;
3564 memset(&specifiers, 0, sizeof(specifiers));
3566 parse_declaration_specifiers(&specifiers);
3568 entity_t *entity = parse_declarator(&specifiers,
3569 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3570 anonymous_entity = NULL;
3574 static void semantic_parameter_incomplete(const entity_t *entity)
3576 assert(entity->kind == ENTITY_PARAMETER);
3578 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3579 * list in a function declarator that is part of a
3580 * definition of that function shall not have
3581 * incomplete type. */
3582 type_t *type = skip_typeref(entity->declaration.type);
3583 if (is_type_incomplete(type)) {
3584 errorf(&entity->base.source_position,
3585 "parameter '%#T' has incomplete type",
3586 entity->declaration.type, entity->base.symbol);
3590 static bool has_parameters(void)
3592 /* func(void) is not a parameter */
3593 if (token.type == T_IDENTIFIER) {
3594 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3597 if (entity->kind != ENTITY_TYPEDEF)
3599 if (skip_typeref(entity->typedefe.type) != type_void)
3601 } else if (token.type != T_void) {
3604 if (look_ahead(1)->type != ')')
3611 * Parses function type parameters (and optionally creates variable_t entities
3612 * for them in a scope)
3614 static void parse_parameters(function_type_t *type, scope_t *scope)
3617 add_anchor_token(')');
3618 int saved_comma_state = save_and_reset_anchor_state(',');
3620 if (token.type == T_IDENTIFIER &&
3621 !is_typedef_symbol(token.v.symbol)) {
3622 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3623 if (la1_type == ',' || la1_type == ')') {
3624 type->kr_style_parameters = true;
3625 type->unspecified_parameters = true;
3626 parse_identifier_list(scope);
3627 goto parameters_finished;
3631 if (token.type == ')') {
3632 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3633 if (!(c_mode & _CXX))
3634 type->unspecified_parameters = true;
3635 goto parameters_finished;
3638 if (has_parameters()) {
3639 function_parameter_t **anchor = &type->parameters;
3641 switch (token.type) {
3644 type->variadic = true;
3645 goto parameters_finished;
3648 case T___extension__:
3651 entity_t *entity = parse_parameter();
3652 if (entity->kind == ENTITY_TYPEDEF) {
3653 errorf(&entity->base.source_position,
3654 "typedef not allowed as function parameter");
3657 assert(is_declaration(entity));
3659 semantic_parameter_incomplete(entity);
3661 function_parameter_t *const parameter =
3662 allocate_parameter(entity->declaration.type);
3664 if (scope != NULL) {
3665 append_entity(scope, entity);
3668 *anchor = parameter;
3669 anchor = ¶meter->next;
3674 goto parameters_finished;
3676 if (token.type != ',') {
3677 goto parameters_finished;
3684 parameters_finished:
3685 rem_anchor_token(')');
3686 expect(')', end_error);
3689 restore_anchor_state(',', saved_comma_state);
3692 typedef enum construct_type_kind_t {
3695 CONSTRUCT_REFERENCE,
3698 } construct_type_kind_t;
3700 typedef union construct_type_t construct_type_t;
3702 typedef struct construct_type_base_t {
3703 construct_type_kind_t kind;
3704 construct_type_t *next;
3705 } construct_type_base_t;
3707 typedef struct parsed_pointer_t {
3708 construct_type_base_t base;
3709 type_qualifiers_t type_qualifiers;
3710 variable_t *base_variable; /**< MS __based extension. */
3713 typedef struct parsed_reference_t {
3714 construct_type_base_t base;
3715 } parsed_reference_t;
3717 typedef struct construct_function_type_t {
3718 construct_type_base_t base;
3719 type_t *function_type;
3720 } construct_function_type_t;
3722 typedef struct parsed_array_t {
3723 construct_type_base_t base;
3724 type_qualifiers_t type_qualifiers;
3730 union construct_type_t {
3731 construct_type_kind_t kind;
3732 construct_type_base_t base;
3733 parsed_pointer_t pointer;
3734 parsed_reference_t reference;
3735 construct_function_type_t function;
3736 parsed_array_t array;
3739 static construct_type_t *parse_pointer_declarator(void)
3743 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3744 memset(pointer, 0, sizeof(pointer[0]));
3745 pointer->base.kind = CONSTRUCT_POINTER;
3746 pointer->type_qualifiers = parse_type_qualifiers();
3747 //pointer->base_variable = base_variable;
3749 return (construct_type_t*) pointer;
3752 static construct_type_t *parse_reference_declarator(void)
3756 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3757 parsed_reference_t *reference = &cons->reference;
3758 memset(reference, 0, sizeof(*reference));
3759 cons->kind = CONSTRUCT_REFERENCE;
3764 static construct_type_t *parse_array_declarator(void)
3767 add_anchor_token(']');
3769 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3770 parsed_array_t *array = &cons->array;
3771 memset(array, 0, sizeof(*array));
3772 cons->kind = CONSTRUCT_ARRAY;
3774 if (token.type == T_static) {
3775 array->is_static = true;
3779 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3780 if (type_qualifiers != 0) {
3781 if (token.type == T_static) {
3782 array->is_static = true;
3786 array->type_qualifiers = type_qualifiers;
3788 if (token.type == '*' && look_ahead(1)->type == ']') {
3789 array->is_variable = true;
3791 } else if (token.type != ']') {
3792 expression_t *const size = parse_assignment_expression();
3794 /* §6.7.5.2:1 Array size must have integer type */
3795 type_t *const orig_type = size->base.type;
3796 type_t *const type = skip_typeref(orig_type);
3797 if (!is_type_integer(type) && is_type_valid(type)) {
3798 errorf(&size->base.source_position,
3799 "array size '%E' must have integer type but has type '%T'",
3804 mark_vars_read(size, NULL);
3807 rem_anchor_token(']');
3808 expect(']', end_error);
3814 static construct_type_t *parse_function_declarator(scope_t *scope)
3816 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3817 function_type_t *ftype = &type->function;
3819 ftype->linkage = current_linkage;
3822 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
3823 case DM_NONE: break;
3824 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
3825 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
3826 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
3827 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
3830 errorf(HERE, "multiple calling conventions in declaration");
3835 parse_parameters(ftype, scope);
3837 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3838 construct_function_type_t *function = &cons->function;
3839 memset(function, 0, sizeof(*function));
3840 cons->kind = CONSTRUCT_FUNCTION;
3841 function->function_type = type;
3846 typedef struct parse_declarator_env_t {
3847 bool may_be_abstract : 1;
3848 bool must_be_abstract : 1;
3849 decl_modifiers_t modifiers;
3851 source_position_t source_position;
3853 attribute_t *attributes;
3854 } parse_declarator_env_t;
3856 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3858 /* construct a single linked list of construct_type_t's which describe
3859 * how to construct the final declarator type */
3860 construct_type_t *first = NULL;
3861 construct_type_t **anchor = &first;
3863 env->attributes = parse_attributes(env->attributes);
3866 construct_type_t *type;
3867 //variable_t *based = NULL; /* MS __based extension */
3868 switch (token.type) {
3870 if (!(c_mode & _CXX))
3871 errorf(HERE, "references are only available for C++");
3872 type = parse_reference_declarator();
3877 source_position_t const pos = *HERE;
3879 expect('(', end_error);
3880 add_anchor_token(')');
3881 based = parse_microsoft_based();
3882 rem_anchor_token(')');
3883 expect(')', end_error);
3884 if (token.type != '*') {
3885 if (token.type == T__based) {
3886 errorf(&pos, "__based type modifier specified more than once");
3887 } else if (warning.other) {
3889 "__based does not precede a pointer declarator, ignored");
3894 panic("based currently disabled");
3900 type = parse_pointer_declarator();
3904 goto ptr_operator_end;
3908 anchor = &type->base.next;
3910 /* TODO: find out if this is correct */
3911 env->attributes = parse_attributes(env->attributes);
3916 modifiers |= env->modifiers;
3917 env->modifiers = modifiers;
3920 construct_type_t *inner_types = NULL;
3922 switch (token.type) {
3924 if (env->must_be_abstract) {
3925 errorf(HERE, "no identifier expected in typename");
3927 env->symbol = token.v.symbol;
3928 env->source_position = token.source_position;
3933 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3934 * interpreted as ``function with no parameter specification'', rather
3935 * than redundant parentheses around the omitted identifier. */
3936 if (look_ahead(1)->type != ')') {
3938 add_anchor_token(')');
3939 inner_types = parse_inner_declarator(env);
3940 if (inner_types != NULL) {
3941 /* All later declarators only modify the return type */
3942 env->must_be_abstract = true;
3944 rem_anchor_token(')');
3945 expect(')', end_error);
3949 if (env->may_be_abstract)
3951 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3956 construct_type_t **const p = anchor;
3959 construct_type_t *type;
3960 switch (token.type) {
3962 scope_t *scope = NULL;
3963 if (!env->must_be_abstract) {
3964 scope = &env->parameters;
3967 type = parse_function_declarator(scope);
3971 type = parse_array_declarator();
3974 goto declarator_finished;
3977 /* insert in the middle of the list (at p) */
3978 type->base.next = *p;
3981 anchor = &type->base.next;
3984 declarator_finished:
3985 /* append inner_types at the end of the list, we don't to set anchor anymore
3986 * as it's not needed anymore */
3987 *anchor = inner_types;
3994 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3996 construct_type_t *iter = construct_list;
3997 for (; iter != NULL; iter = iter->base.next) {
3998 switch (iter->kind) {
3999 case CONSTRUCT_INVALID:
4001 case CONSTRUCT_FUNCTION: {
4002 construct_function_type_t *function = &iter->function;
4003 type_t *function_type = function->function_type;
4005 function_type->function.return_type = type;
4007 type_t *skipped_return_type = skip_typeref(type);
4009 if (is_type_function(skipped_return_type)) {
4010 errorf(HERE, "function returning function is not allowed");
4011 } else if (is_type_array(skipped_return_type)) {
4012 errorf(HERE, "function returning array is not allowed");
4014 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4016 "type qualifiers in return type of function type are meaningless");
4020 /* The function type was constructed earlier. Freeing it here will
4021 * destroy other types. */
4022 type = typehash_insert(function_type);
4026 case CONSTRUCT_POINTER: {
4027 if (is_type_reference(skip_typeref(type)))
4028 errorf(HERE, "cannot declare a pointer to reference");
4030 parsed_pointer_t *pointer = &iter->pointer;
4031 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
4035 case CONSTRUCT_REFERENCE:
4036 if (is_type_reference(skip_typeref(type)))
4037 errorf(HERE, "cannot declare a reference to reference");
4039 type = make_reference_type(type);
4042 case CONSTRUCT_ARRAY: {
4043 if (is_type_reference(skip_typeref(type)))
4044 errorf(HERE, "cannot declare an array of references");
4046 parsed_array_t *array = &iter->array;
4047 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4049 expression_t *size_expression = array->size;
4050 if (size_expression != NULL) {
4052 = create_implicit_cast(size_expression, type_size_t);
4055 array_type->base.qualifiers = array->type_qualifiers;
4056 array_type->array.element_type = type;
4057 array_type->array.is_static = array->is_static;
4058 array_type->array.is_variable = array->is_variable;
4059 array_type->array.size_expression = size_expression;
4061 if (size_expression != NULL) {
4062 if (is_constant_expression(size_expression)) {
4063 long const size = fold_constant(size_expression);
4064 array_type->array.size = size;
4065 array_type->array.size_constant = true;
4066 /* §6.7.5.2:1 If the expression is a constant expression, it shall
4067 * have a value greater than zero. */
4069 if (size < 0 || !GNU_MODE) {
4070 errorf(&size_expression->base.source_position,
4071 "size of array must be greater than zero");
4072 } else if (warning.other) {
4073 warningf(&size_expression->base.source_position,
4074 "zero length arrays are a GCC extension");
4078 array_type->array.is_vla = true;
4082 type_t *skipped_type = skip_typeref(type);
4084 if (is_type_incomplete(skipped_type)) {
4085 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4086 } else if (is_type_function(skipped_type)) {
4087 errorf(HERE, "array of functions is not allowed");
4089 type = identify_new_type(array_type);
4093 internal_errorf(HERE, "invalid type construction found");
4099 static type_t *automatic_type_conversion(type_t *orig_type);
4101 static type_t *semantic_parameter(const source_position_t *pos,
4103 const declaration_specifiers_t *specifiers,
4106 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4107 * shall be adjusted to ``qualified pointer to type'',
4109 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4110 * type'' shall be adjusted to ``pointer to function
4111 * returning type'', as in 6.3.2.1. */
4112 type = automatic_type_conversion(type);
4114 if (specifiers->is_inline && is_type_valid(type)) {
4115 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
4118 /* §6.9.1:6 The declarations in the declaration list shall contain
4119 * no storage-class specifier other than register and no
4120 * initializations. */
4121 if (specifiers->thread_local || (
4122 specifiers->storage_class != STORAGE_CLASS_NONE &&
4123 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4125 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
4128 /* delay test for incomplete type, because we might have (void)
4129 * which is legal but incomplete... */
4134 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4135 declarator_flags_t flags)
4137 parse_declarator_env_t env;
4138 memset(&env, 0, sizeof(env));
4139 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
4141 construct_type_t *construct_type = parse_inner_declarator(&env);
4143 construct_declarator_type(construct_type, specifiers->type);
4144 type_t *type = skip_typeref(orig_type);
4146 if (construct_type != NULL) {
4147 obstack_free(&temp_obst, construct_type);
4150 attribute_t *attributes = parse_attributes(env.attributes);
4151 /* append (shared) specifier attribute behind attributes of this
4153 if (attributes != NULL) {
4154 attribute_t *last = attributes;
4155 while (last->next != NULL)
4157 last->next = specifiers->attributes;
4159 attributes = specifiers->attributes;
4163 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4164 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4165 entity->base.symbol = env.symbol;
4166 entity->base.source_position = env.source_position;
4167 entity->typedefe.type = orig_type;
4169 if (anonymous_entity != NULL) {
4170 if (is_type_compound(type)) {
4171 assert(anonymous_entity->compound.alias == NULL);
4172 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4173 anonymous_entity->kind == ENTITY_UNION);
4174 anonymous_entity->compound.alias = entity;
4175 anonymous_entity = NULL;
4176 } else if (is_type_enum(type)) {
4177 assert(anonymous_entity->enume.alias == NULL);
4178 assert(anonymous_entity->kind == ENTITY_ENUM);
4179 anonymous_entity->enume.alias = entity;
4180 anonymous_entity = NULL;
4184 /* create a declaration type entity */
4185 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4186 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4188 if (env.symbol != NULL) {
4189 if (specifiers->is_inline && is_type_valid(type)) {
4190 errorf(&env.source_position,
4191 "compound member '%Y' declared 'inline'", env.symbol);
4194 if (specifiers->thread_local ||
4195 specifiers->storage_class != STORAGE_CLASS_NONE) {
4196 errorf(&env.source_position,
4197 "compound member '%Y' must have no storage class",
4201 } else if (flags & DECL_IS_PARAMETER) {
4202 orig_type = semantic_parameter(&env.source_position, orig_type,
4203 specifiers, env.symbol);
4205 entity = allocate_entity_zero(ENTITY_PARAMETER);
4206 } else if (is_type_function(type)) {
4207 entity = allocate_entity_zero(ENTITY_FUNCTION);
4209 entity->function.is_inline = specifiers->is_inline;
4210 entity->function.parameters = env.parameters;
4212 if (env.symbol != NULL) {
4213 /* this needs fixes for C++ */
4214 bool in_function_scope = current_function != NULL;
4216 if (specifiers->thread_local || (
4217 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4218 specifiers->storage_class != STORAGE_CLASS_NONE &&
4219 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4221 errorf(&env.source_position,
4222 "invalid storage class for function '%Y'", env.symbol);
4226 entity = allocate_entity_zero(ENTITY_VARIABLE);
4228 entity->variable.thread_local = specifiers->thread_local;
4230 if (env.symbol != NULL) {
4231 if (specifiers->is_inline && is_type_valid(type)) {
4232 errorf(&env.source_position,
4233 "variable '%Y' declared 'inline'", env.symbol);
4236 bool invalid_storage_class = false;
4237 if (current_scope == file_scope) {
4238 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4239 specifiers->storage_class != STORAGE_CLASS_NONE &&
4240 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4241 invalid_storage_class = true;
4244 if (specifiers->thread_local &&
4245 specifiers->storage_class == STORAGE_CLASS_NONE) {
4246 invalid_storage_class = true;
4249 if (invalid_storage_class) {
4250 errorf(&env.source_position,
4251 "invalid storage class for variable '%Y'", env.symbol);
4256 if (env.symbol != NULL) {
4257 entity->base.symbol = env.symbol;
4258 entity->base.source_position = env.source_position;
4260 entity->base.source_position = specifiers->source_position;
4262 entity->base.namespc = NAMESPACE_NORMAL;
4263 entity->declaration.type = orig_type;
4264 entity->declaration.alignment = get_type_alignment(orig_type);
4265 entity->declaration.modifiers = env.modifiers;
4266 entity->declaration.attributes = attributes;
4268 storage_class_t storage_class = specifiers->storage_class;
4269 entity->declaration.declared_storage_class = storage_class;
4271 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4272 storage_class = STORAGE_CLASS_AUTO;
4273 entity->declaration.storage_class = storage_class;
4276 if (attributes != NULL) {
4277 handle_entity_attributes(attributes, entity);
4283 static type_t *parse_abstract_declarator(type_t *base_type)
4285 parse_declarator_env_t env;
4286 memset(&env, 0, sizeof(env));
4287 env.may_be_abstract = true;
4288 env.must_be_abstract = true;
4290 construct_type_t *construct_type = parse_inner_declarator(&env);
4292 type_t *result = construct_declarator_type(construct_type, base_type);
4293 if (construct_type != NULL) {
4294 obstack_free(&temp_obst, construct_type);
4296 result = handle_type_attributes(env.attributes, result);
4302 * Check if the declaration of main is suspicious. main should be a
4303 * function with external linkage, returning int, taking either zero
4304 * arguments, two, or three arguments of appropriate types, ie.
4306 * int main([ int argc, char **argv [, char **env ] ]).
4308 * @param decl the declaration to check
4309 * @param type the function type of the declaration
4311 static void check_type_of_main(const entity_t *entity)
4313 const source_position_t *pos = &entity->base.source_position;
4314 if (entity->kind != ENTITY_FUNCTION) {
4315 warningf(pos, "'main' is not a function");
4319 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4320 warningf(pos, "'main' is normally a non-static function");
4323 type_t *type = skip_typeref(entity->declaration.type);
4324 assert(is_type_function(type));
4326 function_type_t *func_type = &type->function;
4327 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4328 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4329 func_type->return_type);
4331 const function_parameter_t *parm = func_type->parameters;
4333 type_t *const first_type = parm->type;
4334 if (!types_compatible(skip_typeref(first_type), type_int)) {
4336 "first argument of 'main' should be 'int', but is '%T'",
4341 type_t *const second_type = parm->type;
4342 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4343 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4347 type_t *const third_type = parm->type;
4348 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4349 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4353 goto warn_arg_count;
4357 warningf(pos, "'main' takes only zero, two or three arguments");
4363 * Check if a symbol is the equal to "main".
4365 static bool is_sym_main(const symbol_t *const sym)
4367 return strcmp(sym->string, "main") == 0;
4370 static void error_redefined_as_different_kind(const source_position_t *pos,
4371 const entity_t *old, entity_kind_t new_kind)
4373 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4374 get_entity_kind_name(old->kind), old->base.symbol,
4375 get_entity_kind_name(new_kind), &old->base.source_position);
4378 static bool is_error_entity(entity_t *const ent)
4380 if (is_declaration(ent)) {
4381 return is_type_valid(skip_typeref(ent->declaration.type));
4382 } else if (ent->kind == ENTITY_TYPEDEF) {
4383 return is_type_valid(skip_typeref(ent->typedefe.type));
4389 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4390 * for various problems that occur for multiple definitions
4392 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4394 const symbol_t *const symbol = entity->base.symbol;
4395 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4396 const source_position_t *pos = &entity->base.source_position;
4398 /* can happen in error cases */
4402 entity_t *const previous_entity = get_entity(symbol, namespc);
4403 /* pushing the same entity twice will break the stack structure */
4404 assert(previous_entity != entity);
4406 if (entity->kind == ENTITY_FUNCTION) {
4407 type_t *const orig_type = entity->declaration.type;
4408 type_t *const type = skip_typeref(orig_type);
4410 assert(is_type_function(type));
4411 if (type->function.unspecified_parameters &&
4412 warning.strict_prototypes &&
4413 previous_entity == NULL) {
4414 warningf(pos, "function declaration '%#T' is not a prototype",
4418 if (warning.main && current_scope == file_scope
4419 && is_sym_main(symbol)) {
4420 check_type_of_main(entity);
4424 if (is_declaration(entity) &&
4425 warning.nested_externs &&
4426 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4427 current_scope != file_scope) {
4428 warningf(pos, "nested extern declaration of '%#T'",
4429 entity->declaration.type, symbol);
4432 if (previous_entity != NULL) {
4433 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4434 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4435 assert(previous_entity->kind == ENTITY_PARAMETER);
4437 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4438 entity->declaration.type, symbol,
4439 previous_entity->declaration.type, symbol,
4440 &previous_entity->base.source_position);
4444 if (previous_entity->base.parent_scope == current_scope) {
4445 if (previous_entity->kind != entity->kind) {
4446 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4447 error_redefined_as_different_kind(pos, previous_entity,
4452 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4453 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4454 symbol, &previous_entity->base.source_position);
4457 if (previous_entity->kind == ENTITY_TYPEDEF) {
4458 /* TODO: C++ allows this for exactly the same type */
4459 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4460 symbol, &previous_entity->base.source_position);
4464 /* at this point we should have only VARIABLES or FUNCTIONS */
4465 assert(is_declaration(previous_entity) && is_declaration(entity));
4467 declaration_t *const prev_decl = &previous_entity->declaration;
4468 declaration_t *const decl = &entity->declaration;
4470 /* can happen for K&R style declarations */
4471 if (prev_decl->type == NULL &&
4472 previous_entity->kind == ENTITY_PARAMETER &&
4473 entity->kind == ENTITY_PARAMETER) {
4474 prev_decl->type = decl->type;
4475 prev_decl->storage_class = decl->storage_class;
4476 prev_decl->declared_storage_class = decl->declared_storage_class;
4477 prev_decl->modifiers = decl->modifiers;
4478 return previous_entity;
4481 type_t *const orig_type = decl->type;
4482 assert(orig_type != NULL);
4483 type_t *const type = skip_typeref(orig_type);
4484 type_t *const prev_type = skip_typeref(prev_decl->type);
4486 if (!types_compatible(type, prev_type)) {
4488 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4489 orig_type, symbol, prev_decl->type, symbol,
4490 &previous_entity->base.source_position);
4492 unsigned old_storage_class = prev_decl->storage_class;
4493 if (warning.redundant_decls &&
4496 !(prev_decl->modifiers & DM_USED) &&
4497 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4498 warningf(&previous_entity->base.source_position,
4499 "unnecessary static forward declaration for '%#T'",
4500 prev_decl->type, symbol);
4503 storage_class_t new_storage_class = decl->storage_class;
4505 /* pretend no storage class means extern for function
4506 * declarations (except if the previous declaration is neither
4507 * none nor extern) */
4508 if (entity->kind == ENTITY_FUNCTION) {
4509 /* the previous declaration could have unspecified parameters or
4510 * be a typedef, so use the new type */
4511 if (prev_type->function.unspecified_parameters || is_definition)
4512 prev_decl->type = type;
4514 switch (old_storage_class) {
4515 case STORAGE_CLASS_NONE:
4516 old_storage_class = STORAGE_CLASS_EXTERN;
4519 case STORAGE_CLASS_EXTERN:
4520 if (is_definition) {
4521 if (warning.missing_prototypes &&
4522 prev_type->function.unspecified_parameters &&
4523 !is_sym_main(symbol)) {
4524 warningf(pos, "no previous prototype for '%#T'",
4527 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4528 new_storage_class = STORAGE_CLASS_EXTERN;
4535 } else if (is_type_incomplete(prev_type)) {
4536 prev_decl->type = type;
4539 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4540 new_storage_class == STORAGE_CLASS_EXTERN) {
4541 warn_redundant_declaration:
4542 if (!is_definition &&
4543 warning.redundant_decls &&
4544 is_type_valid(prev_type) &&
4545 strcmp(previous_entity->base.source_position.input_name,
4546 "<builtin>") != 0) {
4548 "redundant declaration for '%Y' (declared %P)",
4549 symbol, &previous_entity->base.source_position);
4551 } else if (current_function == NULL) {
4552 if (old_storage_class != STORAGE_CLASS_STATIC &&
4553 new_storage_class == STORAGE_CLASS_STATIC) {
4555 "static declaration of '%Y' follows non-static declaration (declared %P)",
4556 symbol, &previous_entity->base.source_position);
4557 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4558 prev_decl->storage_class = STORAGE_CLASS_NONE;
4559 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4561 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4563 goto error_redeclaration;
4564 goto warn_redundant_declaration;
4566 } else if (is_type_valid(prev_type)) {
4567 if (old_storage_class == new_storage_class) {
4568 error_redeclaration:
4569 errorf(pos, "redeclaration of '%Y' (declared %P)",
4570 symbol, &previous_entity->base.source_position);
4573 "redeclaration of '%Y' with different linkage (declared %P)",
4574 symbol, &previous_entity->base.source_position);
4579 prev_decl->modifiers |= decl->modifiers;
4580 if (entity->kind == ENTITY_FUNCTION) {
4581 previous_entity->function.is_inline |= entity->function.is_inline;
4583 return previous_entity;
4586 if (warning.shadow) {
4587 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4588 get_entity_kind_name(entity->kind), symbol,
4589 get_entity_kind_name(previous_entity->kind),
4590 &previous_entity->base.source_position);
4594 if (entity->kind == ENTITY_FUNCTION) {
4595 if (is_definition &&
4596 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4597 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4598 warningf(pos, "no previous prototype for '%#T'",
4599 entity->declaration.type, symbol);
4600 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4601 warningf(pos, "no previous declaration for '%#T'",
4602 entity->declaration.type, symbol);
4605 } else if (warning.missing_declarations &&
4606 entity->kind == ENTITY_VARIABLE &&
4607 current_scope == file_scope) {
4608 declaration_t *declaration = &entity->declaration;
4609 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4610 warningf(pos, "no previous declaration for '%#T'",
4611 declaration->type, symbol);
4616 assert(entity->base.parent_scope == NULL);
4617 assert(current_scope != NULL);
4619 entity->base.parent_scope = current_scope;
4620 entity->base.namespc = NAMESPACE_NORMAL;
4621 environment_push(entity);
4622 append_entity(current_scope, entity);
4627 static void parser_error_multiple_definition(entity_t *entity,
4628 const source_position_t *source_position)
4630 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4631 entity->base.symbol, &entity->base.source_position);
4634 static bool is_declaration_specifier(const token_t *token,
4635 bool only_specifiers_qualifiers)
4637 switch (token->type) {
4642 return is_typedef_symbol(token->v.symbol);
4644 case T___extension__:
4646 return !only_specifiers_qualifiers;
4653 static void parse_init_declarator_rest(entity_t *entity)
4655 assert(is_declaration(entity));
4656 declaration_t *const declaration = &entity->declaration;
4660 type_t *orig_type = declaration->type;
4661 type_t *type = skip_typeref(orig_type);
4663 if (entity->kind == ENTITY_VARIABLE
4664 && entity->variable.initializer != NULL) {
4665 parser_error_multiple_definition(entity, HERE);
4668 bool must_be_constant = false;
4669 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4670 entity->base.parent_scope == file_scope) {
4671 must_be_constant = true;
4674 if (is_type_function(type)) {
4675 errorf(&entity->base.source_position,
4676 "function '%#T' is initialized like a variable",
4677 orig_type, entity->base.symbol);
4678 orig_type = type_error_type;
4681 parse_initializer_env_t env;
4682 env.type = orig_type;
4683 env.must_be_constant = must_be_constant;
4684 env.entity = entity;
4685 current_init_decl = entity;
4687 initializer_t *initializer = parse_initializer(&env);
4688 current_init_decl = NULL;
4690 if (entity->kind == ENTITY_VARIABLE) {
4691 /* §6.7.5:22 array initializers for arrays with unknown size
4692 * determine the array type size */
4693 declaration->type = env.type;
4694 entity->variable.initializer = initializer;
4698 /* parse rest of a declaration without any declarator */
4699 static void parse_anonymous_declaration_rest(
4700 const declaration_specifiers_t *specifiers)
4703 anonymous_entity = NULL;
4705 if (warning.other) {
4706 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4707 specifiers->thread_local) {
4708 warningf(&specifiers->source_position,
4709 "useless storage class in empty declaration");
4712 type_t *type = specifiers->type;
4713 switch (type->kind) {
4714 case TYPE_COMPOUND_STRUCT:
4715 case TYPE_COMPOUND_UNION: {
4716 if (type->compound.compound->base.symbol == NULL) {
4717 warningf(&specifiers->source_position,
4718 "unnamed struct/union that defines no instances");
4727 warningf(&specifiers->source_position, "empty declaration");
4733 static void check_variable_type_complete(entity_t *ent)
4735 if (ent->kind != ENTITY_VARIABLE)
4738 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4739 * type for the object shall be complete [...] */
4740 declaration_t *decl = &ent->declaration;
4741 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4742 decl->storage_class == STORAGE_CLASS_STATIC)
4745 type_t *const orig_type = decl->type;
4746 type_t *const type = skip_typeref(orig_type);
4747 if (!is_type_incomplete(type))
4750 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4751 * are given length one. */
4752 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4753 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4757 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4758 orig_type, ent->base.symbol);
4762 static void parse_declaration_rest(entity_t *ndeclaration,
4763 const declaration_specifiers_t *specifiers,
4764 parsed_declaration_func finished_declaration,
4765 declarator_flags_t flags)
4767 add_anchor_token(';');
4768 add_anchor_token(',');
4770 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4772 if (token.type == '=') {
4773 parse_init_declarator_rest(entity);
4774 } else if (entity->kind == ENTITY_VARIABLE) {
4775 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4776 * [...] where the extern specifier is explicitly used. */
4777 declaration_t *decl = &entity->declaration;
4778 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4779 type_t *type = decl->type;
4780 if (is_type_reference(skip_typeref(type))) {
4781 errorf(&entity->base.source_position,
4782 "reference '%#T' must be initialized",
4783 type, entity->base.symbol);
4788 check_variable_type_complete(entity);
4790 if (token.type != ',')
4794 add_anchor_token('=');
4795 ndeclaration = parse_declarator(specifiers, flags);
4796 rem_anchor_token('=');
4798 expect(';', end_error);
4801 anonymous_entity = NULL;
4802 rem_anchor_token(';');
4803 rem_anchor_token(',');
4806 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4808 symbol_t *symbol = entity->base.symbol;
4809 if (symbol == NULL) {
4810 errorf(HERE, "anonymous declaration not valid as function parameter");
4814 assert(entity->base.namespc == NAMESPACE_NORMAL);
4815 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4816 if (previous_entity == NULL
4817 || previous_entity->base.parent_scope != current_scope) {
4818 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4823 if (is_definition) {
4824 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4827 return record_entity(entity, false);
4830 static void parse_declaration(parsed_declaration_func finished_declaration,
4831 declarator_flags_t flags)
4833 declaration_specifiers_t specifiers;
4834 memset(&specifiers, 0, sizeof(specifiers));
4836 add_anchor_token(';');
4837 parse_declaration_specifiers(&specifiers);
4838 rem_anchor_token(';');
4840 if (token.type == ';') {
4841 parse_anonymous_declaration_rest(&specifiers);
4843 entity_t *entity = parse_declarator(&specifiers, flags);
4844 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4849 static type_t *get_default_promoted_type(type_t *orig_type)
4851 type_t *result = orig_type;
4853 type_t *type = skip_typeref(orig_type);
4854 if (is_type_integer(type)) {
4855 result = promote_integer(type);
4856 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4857 result = type_double;
4863 static void parse_kr_declaration_list(entity_t *entity)
4865 if (entity->kind != ENTITY_FUNCTION)
4868 type_t *type = skip_typeref(entity->declaration.type);
4869 assert(is_type_function(type));
4870 if (!type->function.kr_style_parameters)
4874 add_anchor_token('{');
4876 /* push function parameters */
4877 size_t const top = environment_top();
4878 scope_t *old_scope = scope_push(&entity->function.parameters);
4880 entity_t *parameter = entity->function.parameters.entities;
4881 for ( ; parameter != NULL; parameter = parameter->base.next) {
4882 assert(parameter->base.parent_scope == NULL);
4883 parameter->base.parent_scope = current_scope;
4884 environment_push(parameter);
4887 /* parse declaration list */
4889 switch (token.type) {
4891 case T___extension__:
4892 /* This covers symbols, which are no type, too, and results in
4893 * better error messages. The typical cases are misspelled type
4894 * names and missing includes. */
4896 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4904 /* pop function parameters */
4905 assert(current_scope == &entity->function.parameters);
4906 scope_pop(old_scope);
4907 environment_pop_to(top);
4909 /* update function type */
4910 type_t *new_type = duplicate_type(type);
4912 function_parameter_t *parameters = NULL;
4913 function_parameter_t **anchor = ¶meters;
4915 parameter = entity->function.parameters.entities;
4916 for (; parameter != NULL; parameter = parameter->base.next) {
4917 if (parameter->kind != ENTITY_PARAMETER)
4920 type_t *parameter_type = parameter->declaration.type;
4921 if (parameter_type == NULL) {
4923 errorf(HERE, "no type specified for function parameter '%Y'",
4924 parameter->base.symbol);
4925 parameter_type = type_error_type;
4927 if (warning.implicit_int) {
4928 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4929 parameter->base.symbol);
4931 parameter_type = type_int;
4933 parameter->declaration.type = parameter_type;
4936 semantic_parameter_incomplete(parameter);
4939 * we need the default promoted types for the function type
4941 parameter_type = get_default_promoted_type(parameter_type);
4943 function_parameter_t *const parameter =
4944 allocate_parameter(parameter_type);
4946 *anchor = parameter;
4947 anchor = ¶meter->next;
4950 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4952 new_type->function.parameters = parameters;
4953 new_type->function.unspecified_parameters = true;
4955 new_type = identify_new_type(new_type);
4957 entity->declaration.type = new_type;
4959 rem_anchor_token('{');
4962 static bool first_err = true;
4965 * When called with first_err set, prints the name of the current function,
4968 static void print_in_function(void)
4972 diagnosticf("%s: In function '%Y':\n",
4973 current_function->base.base.source_position.input_name,
4974 current_function->base.base.symbol);
4979 * Check if all labels are defined in the current function.
4980 * Check if all labels are used in the current function.
4982 static void check_labels(void)
4984 for (const goto_statement_t *goto_statement = goto_first;
4985 goto_statement != NULL;
4986 goto_statement = goto_statement->next) {
4987 /* skip computed gotos */
4988 if (goto_statement->expression != NULL)
4991 label_t *label = goto_statement->label;
4994 if (label->base.source_position.input_name == NULL) {
4995 print_in_function();
4996 errorf(&goto_statement->base.source_position,
4997 "label '%Y' used but not defined", label->base.symbol);
5001 if (warning.unused_label) {
5002 for (const label_statement_t *label_statement = label_first;
5003 label_statement != NULL;
5004 label_statement = label_statement->next) {
5005 label_t *label = label_statement->label;
5007 if (! label->used) {
5008 print_in_function();
5009 warningf(&label_statement->base.source_position,
5010 "label '%Y' defined but not used", label->base.symbol);
5016 static void warn_unused_entity(entity_t *entity, entity_t *last)
5018 entity_t const *const end = last != NULL ? last->base.next : NULL;
5019 for (; entity != end; entity = entity->base.next) {
5020 if (!is_declaration(entity))
5023 declaration_t *declaration = &entity->declaration;
5024 if (declaration->implicit)
5027 if (!declaration->used) {
5028 print_in_function();
5029 const char *what = get_entity_kind_name(entity->kind);
5030 warningf(&entity->base.source_position, "%s '%Y' is unused",
5031 what, entity->base.symbol);
5032 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5033 print_in_function();
5034 const char *what = get_entity_kind_name(entity->kind);
5035 warningf(&entity->base.source_position, "%s '%Y' is never read",
5036 what, entity->base.symbol);
5041 static void check_unused_variables(statement_t *const stmt, void *const env)
5045 switch (stmt->kind) {
5046 case STATEMENT_DECLARATION: {
5047 declaration_statement_t const *const decls = &stmt->declaration;
5048 warn_unused_entity(decls->declarations_begin,
5049 decls->declarations_end);
5054 warn_unused_entity(stmt->fors.scope.entities, NULL);
5063 * Check declarations of current_function for unused entities.
5065 static void check_declarations(void)
5067 if (warning.unused_parameter) {
5068 const scope_t *scope = ¤t_function->parameters;
5070 /* do not issue unused warnings for main */
5071 if (!is_sym_main(current_function->base.base.symbol)) {
5072 warn_unused_entity(scope->entities, NULL);
5075 if (warning.unused_variable) {
5076 walk_statements(current_function->statement, check_unused_variables,
5081 static int determine_truth(expression_t const* const cond)
5084 !is_constant_expression(cond) ? 0 :
5085 fold_constant(cond) != 0 ? 1 :
5089 static void check_reachable(statement_t *);
5090 static bool reaches_end;
5092 static bool expression_returns(expression_t const *const expr)
5094 switch (expr->kind) {
5096 expression_t const *const func = expr->call.function;
5097 if (func->kind == EXPR_REFERENCE) {
5098 entity_t *entity = func->reference.entity;
5099 if (entity->kind == ENTITY_FUNCTION
5100 && entity->declaration.modifiers & DM_NORETURN)
5104 if (!expression_returns(func))
5107 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5108 if (!expression_returns(arg->expression))
5115 case EXPR_REFERENCE:
5116 case EXPR_REFERENCE_ENUM_VALUE:
5118 case EXPR_CHARACTER_CONSTANT:
5119 case EXPR_WIDE_CHARACTER_CONSTANT:
5120 case EXPR_STRING_LITERAL:
5121 case EXPR_WIDE_STRING_LITERAL:
5122 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5123 case EXPR_LABEL_ADDRESS:
5124 case EXPR_CLASSIFY_TYPE:
5125 case EXPR_SIZEOF: // TODO handle obscure VLA case
5128 case EXPR_BUILTIN_CONSTANT_P:
5129 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5134 case EXPR_STATEMENT: {
5135 bool old_reaches_end = reaches_end;
5136 reaches_end = false;
5137 check_reachable(expr->statement.statement);
5138 bool returns = reaches_end;
5139 reaches_end = old_reaches_end;
5143 case EXPR_CONDITIONAL:
5144 // TODO handle constant expression
5146 if (!expression_returns(expr->conditional.condition))
5149 if (expr->conditional.true_expression != NULL
5150 && expression_returns(expr->conditional.true_expression))
5153 return expression_returns(expr->conditional.false_expression);
5156 return expression_returns(expr->select.compound);
5158 case EXPR_ARRAY_ACCESS:
5160 expression_returns(expr->array_access.array_ref) &&
5161 expression_returns(expr->array_access.index);
5164 return expression_returns(expr->va_starte.ap);
5167 return expression_returns(expr->va_arge.ap);
5170 return expression_returns(expr->va_copye.src);
5172 EXPR_UNARY_CASES_MANDATORY
5173 return expression_returns(expr->unary.value);
5175 case EXPR_UNARY_THROW:
5179 // TODO handle constant lhs of && and ||
5181 expression_returns(expr->binary.left) &&
5182 expression_returns(expr->binary.right);
5188 panic("unhandled expression");
5191 static bool initializer_returns(initializer_t const *const init)
5193 switch (init->kind) {
5194 case INITIALIZER_VALUE:
5195 return expression_returns(init->value.value);
5197 case INITIALIZER_LIST: {
5198 initializer_t * const* i = init->list.initializers;
5199 initializer_t * const* const end = i + init->list.len;
5200 bool returns = true;
5201 for (; i != end; ++i) {
5202 if (!initializer_returns(*i))
5208 case INITIALIZER_STRING:
5209 case INITIALIZER_WIDE_STRING:
5210 case INITIALIZER_DESIGNATOR: // designators have no payload
5213 panic("unhandled initializer");
5216 static bool noreturn_candidate;
5218 static void check_reachable(statement_t *const stmt)
5220 if (stmt->base.reachable)
5222 if (stmt->kind != STATEMENT_DO_WHILE)
5223 stmt->base.reachable = true;
5225 statement_t *last = stmt;
5227 switch (stmt->kind) {
5228 case STATEMENT_INVALID:
5229 case STATEMENT_EMPTY:
5231 next = stmt->base.next;
5234 case STATEMENT_DECLARATION: {
5235 declaration_statement_t const *const decl = &stmt->declaration;
5236 entity_t const * ent = decl->declarations_begin;
5237 entity_t const *const last = decl->declarations_end;
5239 for (;; ent = ent->base.next) {
5240 if (ent->kind == ENTITY_VARIABLE &&
5241 ent->variable.initializer != NULL &&
5242 !initializer_returns(ent->variable.initializer)) {
5249 next = stmt->base.next;
5253 case STATEMENT_COMPOUND:
5254 next = stmt->compound.statements;
5256 next = stmt->base.next;
5259 case STATEMENT_RETURN: {
5260 expression_t const *const val = stmt->returns.value;
5261 if (val == NULL || expression_returns(val))
5262 noreturn_candidate = false;
5266 case STATEMENT_IF: {
5267 if_statement_t const *const ifs = &stmt->ifs;
5268 expression_t const *const cond = ifs->condition;
5270 if (!expression_returns(cond))
5273 int const val = determine_truth(cond);
5276 check_reachable(ifs->true_statement);
5281 if (ifs->false_statement != NULL) {
5282 check_reachable(ifs->false_statement);
5286 next = stmt->base.next;
5290 case STATEMENT_SWITCH: {
5291 switch_statement_t const *const switchs = &stmt->switchs;
5292 expression_t const *const expr = switchs->expression;
5294 if (!expression_returns(expr))
5297 if (is_constant_expression(expr)) {
5298 long const val = fold_constant(expr);
5299 case_label_statement_t * defaults = NULL;
5300 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5301 if (i->expression == NULL) {
5306 if (i->first_case <= val && val <= i->last_case) {
5307 check_reachable((statement_t*)i);
5312 if (defaults != NULL) {
5313 check_reachable((statement_t*)defaults);
5317 bool has_default = false;
5318 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5319 if (i->expression == NULL)
5322 check_reachable((statement_t*)i);
5329 next = stmt->base.next;
5333 case STATEMENT_EXPRESSION: {
5334 /* Check for noreturn function call */
5335 expression_t const *const expr = stmt->expression.expression;
5336 if (!expression_returns(expr))
5339 next = stmt->base.next;
5343 case STATEMENT_CONTINUE: {
5344 statement_t *parent = stmt;
5346 parent = parent->base.parent;
5347 if (parent == NULL) /* continue not within loop */
5351 switch (parent->kind) {
5352 case STATEMENT_WHILE: goto continue_while;
5353 case STATEMENT_DO_WHILE: goto continue_do_while;
5354 case STATEMENT_FOR: goto continue_for;
5361 case STATEMENT_BREAK: {
5362 statement_t *parent = stmt;
5364 parent = parent->base.parent;
5365 if (parent == NULL) /* break not within loop/switch */
5368 switch (parent->kind) {
5369 case STATEMENT_SWITCH:
5370 case STATEMENT_WHILE:
5371 case STATEMENT_DO_WHILE:
5374 next = parent->base.next;
5375 goto found_break_parent;
5384 case STATEMENT_GOTO:
5385 if (stmt->gotos.expression) {
5386 if (!expression_returns(stmt->gotos.expression))
5389 statement_t *parent = stmt->base.parent;
5390 if (parent == NULL) /* top level goto */
5394 next = stmt->gotos.label->statement;
5395 if (next == NULL) /* missing label */
5400 case STATEMENT_LABEL:
5401 next = stmt->label.statement;
5404 case STATEMENT_CASE_LABEL:
5405 next = stmt->case_label.statement;
5408 case STATEMENT_WHILE: {
5409 while_statement_t const *const whiles = &stmt->whiles;
5410 expression_t const *const cond = whiles->condition;
5412 if (!expression_returns(cond))
5415 int const val = determine_truth(cond);
5418 check_reachable(whiles->body);
5423 next = stmt->base.next;
5427 case STATEMENT_DO_WHILE:
5428 next = stmt->do_while.body;
5431 case STATEMENT_FOR: {
5432 for_statement_t *const fors = &stmt->fors;
5434 if (fors->condition_reachable)
5436 fors->condition_reachable = true;
5438 expression_t const *const cond = fors->condition;
5443 } else if (expression_returns(cond)) {
5444 val = determine_truth(cond);
5450 check_reachable(fors->body);
5455 next = stmt->base.next;
5459 case STATEMENT_MS_TRY: {
5460 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5461 check_reachable(ms_try->try_statement);
5462 next = ms_try->final_statement;
5466 case STATEMENT_LEAVE: {
5467 statement_t *parent = stmt;
5469 parent = parent->base.parent;
5470 if (parent == NULL) /* __leave not within __try */
5473 if (parent->kind == STATEMENT_MS_TRY) {
5475 next = parent->ms_try.final_statement;
5483 panic("invalid statement kind");
5486 while (next == NULL) {
5487 next = last->base.parent;
5489 noreturn_candidate = false;
5491 type_t *const type = skip_typeref(current_function->base.type);
5492 assert(is_type_function(type));
5493 type_t *const ret = skip_typeref(type->function.return_type);
5494 if (warning.return_type &&
5495 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5496 is_type_valid(ret) &&
5497 !is_sym_main(current_function->base.base.symbol)) {
5498 warningf(&stmt->base.source_position,
5499 "control reaches end of non-void function");
5504 switch (next->kind) {
5505 case STATEMENT_INVALID:
5506 case STATEMENT_EMPTY:
5507 case STATEMENT_DECLARATION:
5508 case STATEMENT_EXPRESSION:
5510 case STATEMENT_RETURN:
5511 case STATEMENT_CONTINUE:
5512 case STATEMENT_BREAK:
5513 case STATEMENT_GOTO:
5514 case STATEMENT_LEAVE:
5515 panic("invalid control flow in function");
5517 case STATEMENT_COMPOUND:
5518 if (next->compound.stmt_expr) {
5524 case STATEMENT_SWITCH:
5525 case STATEMENT_LABEL:
5526 case STATEMENT_CASE_LABEL:
5528 next = next->base.next;
5531 case STATEMENT_WHILE: {
5533 if (next->base.reachable)
5535 next->base.reachable = true;
5537 while_statement_t const *const whiles = &next->whiles;
5538 expression_t const *const cond = whiles->condition;
5540 if (!expression_returns(cond))
5543 int const val = determine_truth(cond);
5546 check_reachable(whiles->body);
5552 next = next->base.next;
5556 case STATEMENT_DO_WHILE: {
5558 if (next->base.reachable)
5560 next->base.reachable = true;
5562 do_while_statement_t const *const dw = &next->do_while;
5563 expression_t const *const cond = dw->condition;
5565 if (!expression_returns(cond))
5568 int const val = determine_truth(cond);
5571 check_reachable(dw->body);
5577 next = next->base.next;
5581 case STATEMENT_FOR: {
5583 for_statement_t *const fors = &next->fors;
5585 fors->step_reachable = true;
5587 if (fors->condition_reachable)
5589 fors->condition_reachable = true;
5591 expression_t const *const cond = fors->condition;
5596 } else if (expression_returns(cond)) {
5597 val = determine_truth(cond);
5603 check_reachable(fors->body);
5609 next = next->base.next;
5613 case STATEMENT_MS_TRY:
5615 next = next->ms_try.final_statement;
5620 check_reachable(next);
5623 static void check_unreachable(statement_t* const stmt, void *const env)
5627 switch (stmt->kind) {
5628 case STATEMENT_DO_WHILE:
5629 if (!stmt->base.reachable) {
5630 expression_t const *const cond = stmt->do_while.condition;
5631 if (determine_truth(cond) >= 0) {
5632 warningf(&cond->base.source_position,
5633 "condition of do-while-loop is unreachable");
5638 case STATEMENT_FOR: {
5639 for_statement_t const* const fors = &stmt->fors;
5641 // if init and step are unreachable, cond is unreachable, too
5642 if (!stmt->base.reachable && !fors->step_reachable) {
5643 warningf(&stmt->base.source_position, "statement is unreachable");
5645 if (!stmt->base.reachable && fors->initialisation != NULL) {
5646 warningf(&fors->initialisation->base.source_position,
5647 "initialisation of for-statement is unreachable");
5650 if (!fors->condition_reachable && fors->condition != NULL) {
5651 warningf(&fors->condition->base.source_position,
5652 "condition of for-statement is unreachable");
5655 if (!fors->step_reachable && fors->step != NULL) {
5656 warningf(&fors->step->base.source_position,
5657 "step of for-statement is unreachable");
5663 case STATEMENT_COMPOUND:
5664 if (stmt->compound.statements != NULL)
5666 goto warn_unreachable;
5668 case STATEMENT_DECLARATION: {
5669 /* Only warn if there is at least one declarator with an initializer.
5670 * This typically occurs in switch statements. */
5671 declaration_statement_t const *const decl = &stmt->declaration;
5672 entity_t const * ent = decl->declarations_begin;
5673 entity_t const *const last = decl->declarations_end;
5675 for (;; ent = ent->base.next) {
5676 if (ent->kind == ENTITY_VARIABLE &&
5677 ent->variable.initializer != NULL) {
5678 goto warn_unreachable;
5688 if (!stmt->base.reachable)
5689 warningf(&stmt->base.source_position, "statement is unreachable");
5694 static void parse_external_declaration(void)
5696 /* function-definitions and declarations both start with declaration
5698 declaration_specifiers_t specifiers;
5699 memset(&specifiers, 0, sizeof(specifiers));
5701 add_anchor_token(';');
5702 parse_declaration_specifiers(&specifiers);
5703 rem_anchor_token(';');
5705 /* must be a declaration */
5706 if (token.type == ';') {
5707 parse_anonymous_declaration_rest(&specifiers);
5711 add_anchor_token(',');
5712 add_anchor_token('=');
5713 add_anchor_token(';');
5714 add_anchor_token('{');
5716 /* declarator is common to both function-definitions and declarations */
5717 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5719 rem_anchor_token('{');
5720 rem_anchor_token(';');
5721 rem_anchor_token('=');
5722 rem_anchor_token(',');
5724 /* must be a declaration */
5725 switch (token.type) {
5729 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5734 /* must be a function definition */
5735 parse_kr_declaration_list(ndeclaration);
5737 if (token.type != '{') {
5738 parse_error_expected("while parsing function definition", '{', NULL);
5739 eat_until_matching_token(';');
5743 assert(is_declaration(ndeclaration));
5744 type_t *const orig_type = ndeclaration->declaration.type;
5745 type_t * type = skip_typeref(orig_type);
5747 if (!is_type_function(type)) {
5748 if (is_type_valid(type)) {
5749 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5750 type, ndeclaration->base.symbol);
5754 } else if (is_typeref(orig_type)) {
5756 errorf(&ndeclaration->base.source_position,
5757 "type of function definition '%#T' is a typedef",
5758 orig_type, ndeclaration->base.symbol);
5761 if (warning.aggregate_return &&
5762 is_type_compound(skip_typeref(type->function.return_type))) {
5763 warningf(HERE, "function '%Y' returns an aggregate",
5764 ndeclaration->base.symbol);
5766 if (warning.traditional && !type->function.unspecified_parameters) {
5767 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5768 ndeclaration->base.symbol);
5770 if (warning.old_style_definition && type->function.unspecified_parameters) {
5771 warningf(HERE, "old-style function definition '%Y'",
5772 ndeclaration->base.symbol);
5775 /* §6.7.5.3:14 a function definition with () means no
5776 * parameters (and not unspecified parameters) */
5777 if (type->function.unspecified_parameters &&
5778 type->function.parameters == NULL &&
5779 !type->function.kr_style_parameters) {
5780 type_t *copy = duplicate_type(type);
5781 copy->function.unspecified_parameters = false;
5782 type = identify_new_type(copy);
5784 ndeclaration->declaration.type = type;
5787 entity_t *const entity = record_entity(ndeclaration, true);
5788 assert(entity->kind == ENTITY_FUNCTION);
5789 assert(ndeclaration->kind == ENTITY_FUNCTION);
5791 function_t *function = &entity->function;
5792 if (ndeclaration != entity) {
5793 function->parameters = ndeclaration->function.parameters;
5795 assert(is_declaration(entity));
5796 type = skip_typeref(entity->declaration.type);
5798 /* push function parameters and switch scope */
5799 size_t const top = environment_top();
5800 scope_t *old_scope = scope_push(&function->parameters);
5802 entity_t *parameter = function->parameters.entities;
5803 for (; parameter != NULL; parameter = parameter->base.next) {
5804 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5805 parameter->base.parent_scope = current_scope;
5807 assert(parameter->base.parent_scope == NULL
5808 || parameter->base.parent_scope == current_scope);
5809 parameter->base.parent_scope = current_scope;
5810 if (parameter->base.symbol == NULL) {
5811 errorf(¶meter->base.source_position, "parameter name omitted");
5814 environment_push(parameter);
5817 if (function->statement != NULL) {
5818 parser_error_multiple_definition(entity, HERE);
5821 /* parse function body */
5822 int label_stack_top = label_top();
5823 function_t *old_current_function = current_function;
5824 current_function = function;
5825 current_parent = NULL;
5828 goto_anchor = &goto_first;
5830 label_anchor = &label_first;
5832 statement_t *const body = parse_compound_statement(false);
5833 function->statement = body;
5836 check_declarations();
5837 if (warning.return_type ||
5838 warning.unreachable_code ||
5839 (warning.missing_noreturn
5840 && !(function->base.modifiers & DM_NORETURN))) {
5841 noreturn_candidate = true;
5842 check_reachable(body);
5843 if (warning.unreachable_code)
5844 walk_statements(body, check_unreachable, NULL);
5845 if (warning.missing_noreturn &&
5846 noreturn_candidate &&
5847 !(function->base.modifiers & DM_NORETURN)) {
5848 warningf(&body->base.source_position,
5849 "function '%#T' is candidate for attribute 'noreturn'",
5850 type, entity->base.symbol);
5854 assert(current_parent == NULL);
5855 assert(current_function == function);
5856 current_function = old_current_function;
5857 label_pop_to(label_stack_top);
5860 assert(current_scope == &function->parameters);
5861 scope_pop(old_scope);
5862 environment_pop_to(top);
5865 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5866 source_position_t *source_position,
5867 const symbol_t *symbol)
5869 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5871 type->bitfield.base_type = base_type;
5872 type->bitfield.size_expression = size;
5875 type_t *skipped_type = skip_typeref(base_type);
5876 if (!is_type_integer(skipped_type)) {
5877 errorf(HERE, "bitfield base type '%T' is not an integer type",
5881 bit_size = get_type_size(base_type) * 8;
5884 if (is_constant_expression(size)) {
5885 long v = fold_constant(size);
5888 errorf(source_position, "negative width in bit-field '%Y'", symbol);
5889 } else if (v == 0) {
5890 errorf(source_position, "zero width for bit-field '%Y'", symbol);
5891 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5892 errorf(source_position, "width of '%Y' exceeds its type", symbol);
5894 type->bitfield.bit_size = v;
5901 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5903 entity_t *iter = compound->members.entities;
5904 for (; iter != NULL; iter = iter->base.next) {
5905 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5908 if (iter->base.symbol == symbol) {
5910 } else if (iter->base.symbol == NULL) {
5911 type_t *type = skip_typeref(iter->declaration.type);
5912 if (is_type_compound(type)) {
5914 = find_compound_entry(type->compound.compound, symbol);
5925 static void parse_compound_declarators(compound_t *compound,
5926 const declaration_specifiers_t *specifiers)
5931 if (token.type == ':') {
5932 source_position_t source_position = *HERE;
5935 type_t *base_type = specifiers->type;
5936 expression_t *size = parse_constant_expression();
5938 type_t *type = make_bitfield_type(base_type, size,
5939 &source_position, sym_anonymous);
5941 attribute_t *attributes = parse_attributes(NULL);
5942 if (attributes != NULL) {
5943 attribute_t *last = attributes;
5944 while (last->next != NULL)
5946 last->next = specifiers->attributes;
5948 attributes = specifiers->attributes;
5951 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5952 entity->base.namespc = NAMESPACE_NORMAL;
5953 entity->base.source_position = source_position;
5954 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5955 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5956 entity->declaration.type = type;
5957 entity->declaration.attributes = attributes;
5959 if (attributes != NULL) {
5960 handle_entity_attributes(attributes, entity);
5962 append_entity(&compound->members, entity);
5964 entity = parse_declarator(specifiers,
5965 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5966 if (entity->kind == ENTITY_TYPEDEF) {
5967 errorf(&entity->base.source_position,
5968 "typedef not allowed as compound member");
5970 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5972 /* make sure we don't define a symbol multiple times */
5973 symbol_t *symbol = entity->base.symbol;
5974 if (symbol != NULL) {
5975 entity_t *prev = find_compound_entry(compound, symbol);
5977 errorf(&entity->base.source_position,
5978 "multiple declarations of symbol '%Y' (declared %P)",
5979 symbol, &prev->base.source_position);
5983 if (token.type == ':') {
5984 source_position_t source_position = *HERE;
5986 expression_t *size = parse_constant_expression();
5988 type_t *type = entity->declaration.type;
5989 type_t *bitfield_type = make_bitfield_type(type, size,
5990 &source_position, entity->base.symbol);
5992 attribute_t *attributes = parse_attributes(NULL);
5993 entity->declaration.type = bitfield_type;
5994 handle_entity_attributes(attributes, entity);
5996 type_t *orig_type = entity->declaration.type;
5997 type_t *type = skip_typeref(orig_type);
5998 if (is_type_function(type)) {
5999 errorf(&entity->base.source_position,
6000 "compound member '%Y' must not have function type '%T'",
6001 entity->base.symbol, orig_type);
6002 } else if (is_type_incomplete(type)) {
6003 /* §6.7.2.1:16 flexible array member */
6004 if (!is_type_array(type) ||
6005 token.type != ';' ||
6006 look_ahead(1)->type != '}') {
6007 errorf(&entity->base.source_position,
6008 "compound member '%Y' has incomplete type '%T'",
6009 entity->base.symbol, orig_type);
6014 append_entity(&compound->members, entity);
6018 if (token.type != ',')
6022 expect(';', end_error);
6025 anonymous_entity = NULL;
6028 static void parse_compound_type_entries(compound_t *compound)
6031 add_anchor_token('}');
6033 while (token.type != '}') {
6034 if (token.type == T_EOF) {
6035 errorf(HERE, "EOF while parsing struct");
6038 declaration_specifiers_t specifiers;
6039 memset(&specifiers, 0, sizeof(specifiers));
6040 parse_declaration_specifiers(&specifiers);
6042 parse_compound_declarators(compound, &specifiers);
6044 rem_anchor_token('}');
6048 compound->complete = true;
6051 static type_t *parse_typename(void)
6053 declaration_specifiers_t specifiers;
6054 memset(&specifiers, 0, sizeof(specifiers));
6055 parse_declaration_specifiers(&specifiers);
6056 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6057 specifiers.thread_local) {
6058 /* TODO: improve error message, user does probably not know what a
6059 * storage class is...
6061 errorf(HERE, "typename may not have a storage class");
6064 type_t *result = parse_abstract_declarator(specifiers.type);
6072 typedef expression_t* (*parse_expression_function)(void);
6073 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6075 typedef struct expression_parser_function_t expression_parser_function_t;
6076 struct expression_parser_function_t {
6077 parse_expression_function parser;
6078 precedence_t infix_precedence;
6079 parse_expression_infix_function infix_parser;
6082 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6085 * Prints an error message if an expression was expected but not read
6087 static expression_t *expected_expression_error(void)
6089 /* skip the error message if the error token was read */
6090 if (token.type != T_ERROR) {
6091 errorf(HERE, "expected expression, got token %K", &token);
6095 return create_invalid_expression();
6099 * Parse a string constant.
6101 static expression_t *parse_string_const(void)
6104 if (token.type == T_STRING_LITERAL) {
6105 string_t res = token.v.string;
6107 while (token.type == T_STRING_LITERAL) {
6108 res = concat_strings(&res, &token.v.string);
6111 if (token.type != T_WIDE_STRING_LITERAL) {
6112 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6113 /* note: that we use type_char_ptr here, which is already the
6114 * automatic converted type. revert_automatic_type_conversion
6115 * will construct the array type */
6116 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6117 cnst->string.value = res;
6121 wres = concat_string_wide_string(&res, &token.v.wide_string);
6123 wres = token.v.wide_string;
6128 switch (token.type) {
6129 case T_WIDE_STRING_LITERAL:
6130 wres = concat_wide_strings(&wres, &token.v.wide_string);
6133 case T_STRING_LITERAL:
6134 wres = concat_wide_string_string(&wres, &token.v.string);
6138 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6139 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6140 cnst->wide_string.value = wres;
6149 * Parse a boolean constant.
6151 static expression_t *parse_bool_const(bool value)
6153 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6154 cnst->base.type = type_bool;
6155 cnst->conste.v.int_value = value;
6163 * Parse an integer constant.
6165 static expression_t *parse_int_const(void)
6167 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6168 cnst->base.type = token.datatype;
6169 cnst->conste.v.int_value = token.v.intvalue;
6177 * Parse a character constant.
6179 static expression_t *parse_character_constant(void)
6181 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6182 cnst->base.type = token.datatype;
6183 cnst->conste.v.character = token.v.string;
6185 if (cnst->conste.v.character.size != 1) {
6187 errorf(HERE, "more than 1 character in character constant");
6188 } else if (warning.multichar) {
6189 warningf(HERE, "multi-character character constant");
6198 * Parse a wide character constant.
6200 static expression_t *parse_wide_character_constant(void)
6202 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6203 cnst->base.type = token.datatype;
6204 cnst->conste.v.wide_character = token.v.wide_string;
6206 if (cnst->conste.v.wide_character.size != 1) {
6208 errorf(HERE, "more than 1 character in character constant");
6209 } else if (warning.multichar) {
6210 warningf(HERE, "multi-character character constant");
6219 * Parse a float constant.
6221 static expression_t *parse_float_const(void)
6223 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6224 cnst->base.type = token.datatype;
6225 cnst->conste.v.float_value = token.v.floatvalue;
6232 static entity_t *create_implicit_function(symbol_t *symbol,
6233 const source_position_t *source_position)
6235 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6236 ntype->function.return_type = type_int;
6237 ntype->function.unspecified_parameters = true;
6238 ntype->function.linkage = LINKAGE_C;
6239 type_t *type = identify_new_type(ntype);
6241 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6242 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6243 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6244 entity->declaration.type = type;
6245 entity->declaration.implicit = true;
6246 entity->base.symbol = symbol;
6247 entity->base.source_position = *source_position;
6249 bool strict_prototypes_old = warning.strict_prototypes;
6250 warning.strict_prototypes = false;
6251 record_entity(entity, false);
6252 warning.strict_prototypes = strict_prototypes_old;
6258 * Creates a return_type (func)(argument_type) function type if not
6261 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6262 type_t *argument_type2)
6264 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6265 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6266 parameter1->next = parameter2;
6268 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6269 type->function.return_type = return_type;
6270 type->function.parameters = parameter1;
6272 return identify_new_type(type);
6276 * Creates a return_type (func)(argument_type) function type if not
6279 * @param return_type the return type
6280 * @param argument_type the argument type
6282 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6284 function_parameter_t *const parameter = allocate_parameter(argument_type);
6286 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6287 type->function.return_type = return_type;
6288 type->function.parameters = parameter;
6290 return identify_new_type(type);
6293 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6295 type_t *res = make_function_1_type(return_type, argument_type);
6296 res->function.variadic = 1;
6301 * Creates a return_type (func)(void) function type if not
6304 * @param return_type the return type
6306 static type_t *make_function_0_type(type_t *return_type)
6308 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6309 type->function.return_type = return_type;
6310 type->function.parameters = NULL;
6312 return identify_new_type(type);
6316 * Creates a NO_RETURN return_type (func)(void) function type if not
6319 * @param return_type the return type
6321 static type_t *make_function_0_type_noreturn(type_t *return_type)
6323 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6324 type->function.return_type = return_type;
6325 type->function.parameters = NULL;
6326 type->function.modifiers |= DM_NORETURN;
6327 return identify_new_type(type);
6331 * Performs automatic type cast as described in §6.3.2.1.
6333 * @param orig_type the original type
6335 static type_t *automatic_type_conversion(type_t *orig_type)
6337 type_t *type = skip_typeref(orig_type);
6338 if (is_type_array(type)) {
6339 array_type_t *array_type = &type->array;
6340 type_t *element_type = array_type->element_type;
6341 unsigned qualifiers = array_type->base.qualifiers;
6343 return make_pointer_type(element_type, qualifiers);
6346 if (is_type_function(type)) {
6347 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6354 * reverts the automatic casts of array to pointer types and function
6355 * to function-pointer types as defined §6.3.2.1
6357 type_t *revert_automatic_type_conversion(const expression_t *expression)
6359 switch (expression->kind) {
6360 case EXPR_REFERENCE: {
6361 entity_t *entity = expression->reference.entity;
6362 if (is_declaration(entity)) {
6363 return entity->declaration.type;
6364 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6365 return entity->enum_value.enum_type;
6367 panic("no declaration or enum in reference");
6372 entity_t *entity = expression->select.compound_entry;
6373 assert(is_declaration(entity));
6374 type_t *type = entity->declaration.type;
6375 return get_qualified_type(type,
6376 expression->base.type->base.qualifiers);
6379 case EXPR_UNARY_DEREFERENCE: {
6380 const expression_t *const value = expression->unary.value;
6381 type_t *const type = skip_typeref(value->base.type);
6382 if (!is_type_pointer(type))
6383 return type_error_type;
6384 return type->pointer.points_to;
6387 case EXPR_ARRAY_ACCESS: {
6388 const expression_t *array_ref = expression->array_access.array_ref;
6389 type_t *type_left = skip_typeref(array_ref->base.type);
6390 if (!is_type_pointer(type_left))
6391 return type_error_type;
6392 return type_left->pointer.points_to;
6395 case EXPR_STRING_LITERAL: {
6396 size_t size = expression->string.value.size;
6397 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6400 case EXPR_WIDE_STRING_LITERAL: {
6401 size_t size = expression->wide_string.value.size;
6402 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6405 case EXPR_COMPOUND_LITERAL:
6406 return expression->compound_literal.type;
6409 return expression->base.type;
6413 static void check_deprecated(const source_position_t *source_position,
6414 const entity_t *entity)
6416 if (!warning.deprecated_declarations)
6418 if (!is_declaration(entity))
6420 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
6423 char const *const prefix = get_entity_kind_name(entity->kind);
6424 const char *deprecated_string
6425 = get_deprecated_string(entity->declaration.attributes);
6426 if (deprecated_string != NULL) {
6427 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
6428 prefix, entity->base.symbol, &entity->base.source_position,
6431 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
6432 entity->base.symbol, &entity->base.source_position);
6436 static expression_t *parse_reference(void)
6438 symbol_t *const symbol = token.v.symbol;
6440 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6442 if (entity == NULL) {
6443 if (!strict_mode && look_ahead(1)->type == '(') {
6444 /* an implicitly declared function */
6445 if (warning.error_implicit_function_declaration) {
6446 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6447 } else if (warning.implicit_function_declaration) {
6448 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6451 entity = create_implicit_function(symbol, HERE);
6453 errorf(HERE, "unknown identifier '%Y' found.", symbol);
6454 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6460 if (is_declaration(entity)) {
6461 orig_type = entity->declaration.type;
6462 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6463 orig_type = entity->enum_value.enum_type;
6465 panic("expected declaration or enum value in reference");
6468 /* we always do the auto-type conversions; the & and sizeof parser contains
6469 * code to revert this! */
6470 type_t *type = automatic_type_conversion(orig_type);
6472 expression_kind_t kind = EXPR_REFERENCE;
6473 if (entity->kind == ENTITY_ENUM_VALUE)
6474 kind = EXPR_REFERENCE_ENUM_VALUE;
6476 expression_t *expression = allocate_expression_zero(kind);
6477 expression->reference.entity = entity;
6478 expression->base.type = type;
6480 /* this declaration is used */
6481 if (is_declaration(entity)) {
6482 entity->declaration.used = true;
6485 if (entity->base.parent_scope != file_scope
6486 && (current_function != NULL && entity->base.parent_scope->depth < current_function->parameters.depth)
6487 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6488 if (entity->kind == ENTITY_VARIABLE) {
6489 /* access of a variable from an outer function */
6490 entity->variable.address_taken = true;
6491 } else if (entity->kind == ENTITY_PARAMETER) {
6492 entity->parameter.address_taken = true;
6494 current_function->need_closure = true;
6497 check_deprecated(HERE, entity);
6499 if (warning.init_self && entity == current_init_decl && !in_type_prop
6500 && entity->kind == ENTITY_VARIABLE) {
6501 current_init_decl = NULL;
6502 warningf(HERE, "variable '%#T' is initialized by itself",
6503 entity->declaration.type, entity->base.symbol);
6510 static bool semantic_cast(expression_t *cast)
6512 expression_t *expression = cast->unary.value;
6513 type_t *orig_dest_type = cast->base.type;
6514 type_t *orig_type_right = expression->base.type;
6515 type_t const *dst_type = skip_typeref(orig_dest_type);
6516 type_t const *src_type = skip_typeref(orig_type_right);
6517 source_position_t const *pos = &cast->base.source_position;
6519 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6520 if (dst_type == type_void)
6523 /* only integer and pointer can be casted to pointer */
6524 if (is_type_pointer(dst_type) &&
6525 !is_type_pointer(src_type) &&
6526 !is_type_integer(src_type) &&
6527 is_type_valid(src_type)) {
6528 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6532 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6533 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6537 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6538 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6542 if (warning.cast_qual &&
6543 is_type_pointer(src_type) &&
6544 is_type_pointer(dst_type)) {
6545 type_t *src = skip_typeref(src_type->pointer.points_to);
6546 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6547 unsigned missing_qualifiers =
6548 src->base.qualifiers & ~dst->base.qualifiers;
6549 if (missing_qualifiers != 0) {
6551 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6552 missing_qualifiers, orig_type_right);
6558 static expression_t *parse_compound_literal(type_t *type)
6560 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6562 parse_initializer_env_t env;
6565 env.must_be_constant = false;
6566 initializer_t *initializer = parse_initializer(&env);
6569 expression->compound_literal.initializer = initializer;
6570 expression->compound_literal.type = type;
6571 expression->base.type = automatic_type_conversion(type);
6577 * Parse a cast expression.
6579 static expression_t *parse_cast(void)
6581 add_anchor_token(')');
6583 source_position_t source_position = token.source_position;
6585 type_t *type = parse_typename();
6587 rem_anchor_token(')');
6588 expect(')', end_error);
6590 if (token.type == '{') {
6591 return parse_compound_literal(type);
6594 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6595 cast->base.source_position = source_position;
6597 expression_t *value = parse_sub_expression(PREC_CAST);
6598 cast->base.type = type;
6599 cast->unary.value = value;
6601 if (! semantic_cast(cast)) {
6602 /* TODO: record the error in the AST. else it is impossible to detect it */
6607 return create_invalid_expression();
6611 * Parse a statement expression.
6613 static expression_t *parse_statement_expression(void)
6615 add_anchor_token(')');
6617 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6619 statement_t *statement = parse_compound_statement(true);
6620 statement->compound.stmt_expr = true;
6621 expression->statement.statement = statement;
6623 /* find last statement and use its type */
6624 type_t *type = type_void;
6625 const statement_t *stmt = statement->compound.statements;
6627 while (stmt->base.next != NULL)
6628 stmt = stmt->base.next;
6630 if (stmt->kind == STATEMENT_EXPRESSION) {
6631 type = stmt->expression.expression->base.type;
6633 } else if (warning.other) {
6634 warningf(&expression->base.source_position, "empty statement expression ({})");
6636 expression->base.type = type;
6638 rem_anchor_token(')');
6639 expect(')', end_error);
6646 * Parse a parenthesized expression.
6648 static expression_t *parse_parenthesized_expression(void)
6652 switch (token.type) {
6654 /* gcc extension: a statement expression */
6655 return parse_statement_expression();
6659 return parse_cast();
6661 if (is_typedef_symbol(token.v.symbol)) {
6662 return parse_cast();
6666 add_anchor_token(')');
6667 expression_t *result = parse_expression();
6668 result->base.parenthesized = true;
6669 rem_anchor_token(')');
6670 expect(')', end_error);
6676 static expression_t *parse_function_keyword(void)
6680 if (current_function == NULL) {
6681 errorf(HERE, "'__func__' used outside of a function");
6684 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6685 expression->base.type = type_char_ptr;
6686 expression->funcname.kind = FUNCNAME_FUNCTION;
6693 static expression_t *parse_pretty_function_keyword(void)
6695 if (current_function == NULL) {
6696 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6699 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6700 expression->base.type = type_char_ptr;
6701 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6703 eat(T___PRETTY_FUNCTION__);
6708 static expression_t *parse_funcsig_keyword(void)
6710 if (current_function == NULL) {
6711 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6714 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6715 expression->base.type = type_char_ptr;
6716 expression->funcname.kind = FUNCNAME_FUNCSIG;
6723 static expression_t *parse_funcdname_keyword(void)
6725 if (current_function == NULL) {
6726 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6729 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6730 expression->base.type = type_char_ptr;
6731 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6733 eat(T___FUNCDNAME__);
6738 static designator_t *parse_designator(void)
6740 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6741 result->source_position = *HERE;
6743 if (token.type != T_IDENTIFIER) {
6744 parse_error_expected("while parsing member designator",
6745 T_IDENTIFIER, NULL);
6748 result->symbol = token.v.symbol;
6751 designator_t *last_designator = result;
6753 if (token.type == '.') {
6755 if (token.type != T_IDENTIFIER) {
6756 parse_error_expected("while parsing member designator",
6757 T_IDENTIFIER, NULL);
6760 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6761 designator->source_position = *HERE;
6762 designator->symbol = token.v.symbol;
6765 last_designator->next = designator;
6766 last_designator = designator;
6769 if (token.type == '[') {
6771 add_anchor_token(']');
6772 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6773 designator->source_position = *HERE;
6774 designator->array_index = parse_expression();
6775 rem_anchor_token(']');
6776 expect(']', end_error);
6777 if (designator->array_index == NULL) {
6781 last_designator->next = designator;
6782 last_designator = designator;
6794 * Parse the __builtin_offsetof() expression.
6796 static expression_t *parse_offsetof(void)
6798 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6799 expression->base.type = type_size_t;
6801 eat(T___builtin_offsetof);
6803 expect('(', end_error);
6804 add_anchor_token(',');
6805 type_t *type = parse_typename();
6806 rem_anchor_token(',');
6807 expect(',', end_error);
6808 add_anchor_token(')');
6809 designator_t *designator = parse_designator();
6810 rem_anchor_token(')');
6811 expect(')', end_error);
6813 expression->offsetofe.type = type;
6814 expression->offsetofe.designator = designator;
6817 memset(&path, 0, sizeof(path));
6818 path.top_type = type;
6819 path.path = NEW_ARR_F(type_path_entry_t, 0);
6821 descend_into_subtype(&path);
6823 if (!walk_designator(&path, designator, true)) {
6824 return create_invalid_expression();
6827 DEL_ARR_F(path.path);
6831 return create_invalid_expression();
6835 * Parses a _builtin_va_start() expression.
6837 static expression_t *parse_va_start(void)
6839 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6841 eat(T___builtin_va_start);
6843 expect('(', end_error);
6844 add_anchor_token(',');
6845 expression->va_starte.ap = parse_assignment_expression();
6846 rem_anchor_token(',');
6847 expect(',', end_error);
6848 expression_t *const expr = parse_assignment_expression();
6849 if (expr->kind == EXPR_REFERENCE) {
6850 entity_t *const entity = expr->reference.entity;
6851 if (entity->base.parent_scope != ¤t_function->parameters
6852 || entity->base.next != NULL
6853 || entity->kind != ENTITY_PARAMETER) {
6854 errorf(&expr->base.source_position,
6855 "second argument of 'va_start' must be last parameter of the current function");
6857 expression->va_starte.parameter = &entity->variable;
6859 expect(')', end_error);
6862 expect(')', end_error);
6864 return create_invalid_expression();
6868 * Parses a __builtin_va_arg() expression.
6870 static expression_t *parse_va_arg(void)
6872 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6874 eat(T___builtin_va_arg);
6876 expect('(', end_error);
6878 ap.expression = parse_assignment_expression();
6879 expression->va_arge.ap = ap.expression;
6880 check_call_argument(type_valist, &ap, 1);
6882 expect(',', end_error);
6883 expression->base.type = parse_typename();
6884 expect(')', end_error);
6888 return create_invalid_expression();
6892 * Parses a __builtin_va_copy() expression.
6894 static expression_t *parse_va_copy(void)
6896 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6898 eat(T___builtin_va_copy);
6900 expect('(', end_error);
6901 expression_t *dst = parse_assignment_expression();
6902 assign_error_t error = semantic_assign(type_valist, dst);
6903 report_assign_error(error, type_valist, dst, "call argument 1",
6904 &dst->base.source_position);
6905 expression->va_copye.dst = dst;
6907 expect(',', end_error);
6909 call_argument_t src;
6910 src.expression = parse_assignment_expression();
6911 check_call_argument(type_valist, &src, 2);
6912 expression->va_copye.src = src.expression;
6913 expect(')', end_error);
6917 return create_invalid_expression();
6921 * Parses a __builtin_constant_p() expression.
6923 static expression_t *parse_builtin_constant(void)
6925 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6927 eat(T___builtin_constant_p);
6929 expect('(', end_error);
6930 add_anchor_token(')');
6931 expression->builtin_constant.value = parse_assignment_expression();
6932 rem_anchor_token(')');
6933 expect(')', end_error);
6934 expression->base.type = type_int;
6938 return create_invalid_expression();
6942 * Parses a __builtin_types_compatible_p() expression.
6944 static expression_t *parse_builtin_types_compatible(void)
6946 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6948 eat(T___builtin_types_compatible_p);
6950 expect('(', end_error);
6951 add_anchor_token(')');
6952 add_anchor_token(',');
6953 expression->builtin_types_compatible.left = parse_typename();
6954 rem_anchor_token(',');
6955 expect(',', end_error);
6956 expression->builtin_types_compatible.right = parse_typename();
6957 rem_anchor_token(')');
6958 expect(')', end_error);
6959 expression->base.type = type_int;
6963 return create_invalid_expression();
6967 * Parses a __builtin_is_*() compare expression.
6969 static expression_t *parse_compare_builtin(void)
6971 expression_t *expression;
6973 switch (token.type) {
6974 case T___builtin_isgreater:
6975 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6977 case T___builtin_isgreaterequal:
6978 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6980 case T___builtin_isless:
6981 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6983 case T___builtin_islessequal:
6984 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6986 case T___builtin_islessgreater:
6987 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6989 case T___builtin_isunordered:
6990 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6993 internal_errorf(HERE, "invalid compare builtin found");
6995 expression->base.source_position = *HERE;
6998 expect('(', end_error);
6999 expression->binary.left = parse_assignment_expression();
7000 expect(',', end_error);
7001 expression->binary.right = parse_assignment_expression();
7002 expect(')', end_error);
7004 type_t *const orig_type_left = expression->binary.left->base.type;
7005 type_t *const orig_type_right = expression->binary.right->base.type;
7007 type_t *const type_left = skip_typeref(orig_type_left);
7008 type_t *const type_right = skip_typeref(orig_type_right);
7009 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7010 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7011 type_error_incompatible("invalid operands in comparison",
7012 &expression->base.source_position, orig_type_left, orig_type_right);
7015 semantic_comparison(&expression->binary);
7020 return create_invalid_expression();
7025 * Parses a __builtin_expect(, end_error) expression.
7027 static expression_t *parse_builtin_expect(void, end_error)
7029 expression_t *expression
7030 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7032 eat(T___builtin_expect);
7034 expect('(', end_error);
7035 expression->binary.left = parse_assignment_expression();
7036 expect(',', end_error);
7037 expression->binary.right = parse_constant_expression();
7038 expect(')', end_error);
7040 expression->base.type = expression->binary.left->base.type;
7044 return create_invalid_expression();
7049 * Parses a MS assume() expression.
7051 static expression_t *parse_assume(void)
7053 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7057 expect('(', end_error);
7058 add_anchor_token(')');
7059 expression->unary.value = parse_assignment_expression();
7060 rem_anchor_token(')');
7061 expect(')', end_error);
7063 expression->base.type = type_void;
7066 return create_invalid_expression();
7070 * Return the declaration for a given label symbol or create a new one.
7072 * @param symbol the symbol of the label
7074 static label_t *get_label(symbol_t *symbol)
7077 assert(current_function != NULL);
7079 label = get_entity(symbol, NAMESPACE_LABEL);
7080 /* if we found a local label, we already created the declaration */
7081 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7082 if (label->base.parent_scope != current_scope) {
7083 assert(label->base.parent_scope->depth < current_scope->depth);
7084 current_function->goto_to_outer = true;
7086 return &label->label;
7089 label = get_entity(symbol, NAMESPACE_LABEL);
7090 /* if we found a label in the same function, then we already created the
7093 && label->base.parent_scope == ¤t_function->parameters) {
7094 return &label->label;
7097 /* otherwise we need to create a new one */
7098 label = allocate_entity_zero(ENTITY_LABEL);
7099 label->base.namespc = NAMESPACE_LABEL;
7100 label->base.symbol = symbol;
7104 return &label->label;
7108 * Parses a GNU && label address expression.
7110 static expression_t *parse_label_address(void)
7112 source_position_t source_position = token.source_position;
7114 if (token.type != T_IDENTIFIER) {
7115 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7118 symbol_t *symbol = token.v.symbol;
7121 label_t *label = get_label(symbol);
7123 label->address_taken = true;
7125 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7126 expression->base.source_position = source_position;
7128 /* label address is threaten as a void pointer */
7129 expression->base.type = type_void_ptr;
7130 expression->label_address.label = label;
7133 return create_invalid_expression();
7137 * Parse a microsoft __noop expression.
7139 static expression_t *parse_noop_expression(void)
7141 /* the result is a (int)0 */
7142 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7143 cnst->base.type = type_int;
7144 cnst->conste.v.int_value = 0;
7145 cnst->conste.is_ms_noop = true;
7149 if (token.type == '(') {
7150 /* parse arguments */
7152 add_anchor_token(')');
7153 add_anchor_token(',');
7155 if (token.type != ')') {
7157 (void)parse_assignment_expression();
7158 if (token.type != ',')
7164 rem_anchor_token(',');
7165 rem_anchor_token(')');
7166 expect(')', end_error);
7173 * Parses a primary expression.
7175 static expression_t *parse_primary_expression(void)
7177 switch (token.type) {
7178 case T_false: return parse_bool_const(false);
7179 case T_true: return parse_bool_const(true);
7180 case T_INTEGER: return parse_int_const();
7181 case T_CHARACTER_CONSTANT: return parse_character_constant();
7182 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7183 case T_FLOATINGPOINT: return parse_float_const();
7184 case T_STRING_LITERAL:
7185 case T_WIDE_STRING_LITERAL: return parse_string_const();
7186 case T___FUNCTION__:
7187 case T___func__: return parse_function_keyword();
7188 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7189 case T___FUNCSIG__: return parse_funcsig_keyword();
7190 case T___FUNCDNAME__: return parse_funcdname_keyword();
7191 case T___builtin_offsetof: return parse_offsetof();
7192 case T___builtin_va_start: return parse_va_start();
7193 case T___builtin_va_arg: return parse_va_arg();
7194 case T___builtin_va_copy: return parse_va_copy();
7195 case T___builtin_isgreater:
7196 case T___builtin_isgreaterequal:
7197 case T___builtin_isless:
7198 case T___builtin_islessequal:
7199 case T___builtin_islessgreater:
7200 case T___builtin_isunordered: return parse_compare_builtin();
7201 case T___builtin_constant_p: return parse_builtin_constant();
7202 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7203 case T__assume: return parse_assume();
7206 return parse_label_address();
7209 case '(': return parse_parenthesized_expression();
7210 case T___noop: return parse_noop_expression();
7212 /* Gracefully handle type names while parsing expressions. */
7214 if (!is_typedef_symbol(token.v.symbol)) {
7215 return parse_reference();
7219 source_position_t const pos = *HERE;
7220 type_t const *const type = parse_typename();
7221 errorf(&pos, "encountered type '%T' while parsing expression", type);
7222 return create_invalid_expression();
7226 errorf(HERE, "unexpected token %K, expected an expression", &token);
7227 return create_invalid_expression();
7231 * Check if the expression has the character type and issue a warning then.
7233 static void check_for_char_index_type(const expression_t *expression)
7235 type_t *const type = expression->base.type;
7236 const type_t *const base_type = skip_typeref(type);
7238 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7239 warning.char_subscripts) {
7240 warningf(&expression->base.source_position,
7241 "array subscript has type '%T'", type);
7245 static expression_t *parse_array_expression(expression_t *left)
7247 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7250 add_anchor_token(']');
7252 expression_t *inside = parse_expression();
7254 type_t *const orig_type_left = left->base.type;
7255 type_t *const orig_type_inside = inside->base.type;
7257 type_t *const type_left = skip_typeref(orig_type_left);
7258 type_t *const type_inside = skip_typeref(orig_type_inside);
7260 type_t *return_type;
7261 array_access_expression_t *array_access = &expression->array_access;
7262 if (is_type_pointer(type_left)) {
7263 return_type = type_left->pointer.points_to;
7264 array_access->array_ref = left;
7265 array_access->index = inside;
7266 check_for_char_index_type(inside);
7267 } else if (is_type_pointer(type_inside)) {
7268 return_type = type_inside->pointer.points_to;
7269 array_access->array_ref = inside;
7270 array_access->index = left;
7271 array_access->flipped = true;
7272 check_for_char_index_type(left);
7274 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7276 "array access on object with non-pointer types '%T', '%T'",
7277 orig_type_left, orig_type_inside);
7279 return_type = type_error_type;
7280 array_access->array_ref = left;
7281 array_access->index = inside;
7284 expression->base.type = automatic_type_conversion(return_type);
7286 rem_anchor_token(']');
7287 expect(']', end_error);
7292 static expression_t *parse_typeprop(expression_kind_t const kind)
7294 expression_t *tp_expression = allocate_expression_zero(kind);
7295 tp_expression->base.type = type_size_t;
7297 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7299 /* we only refer to a type property, mark this case */
7300 bool old = in_type_prop;
7301 in_type_prop = true;
7304 expression_t *expression;
7305 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7307 add_anchor_token(')');
7308 orig_type = parse_typename();
7309 rem_anchor_token(')');
7310 expect(')', end_error);
7312 if (token.type == '{') {
7313 /* It was not sizeof(type) after all. It is sizeof of an expression
7314 * starting with a compound literal */
7315 expression = parse_compound_literal(orig_type);
7316 goto typeprop_expression;
7319 expression = parse_sub_expression(PREC_UNARY);
7321 typeprop_expression:
7322 tp_expression->typeprop.tp_expression = expression;
7324 orig_type = revert_automatic_type_conversion(expression);
7325 expression->base.type = orig_type;
7328 tp_expression->typeprop.type = orig_type;
7329 type_t const* const type = skip_typeref(orig_type);
7330 char const* const wrong_type =
7331 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7332 is_type_incomplete(type) ? "incomplete" :
7333 type->kind == TYPE_FUNCTION ? "function designator" :
7334 type->kind == TYPE_BITFIELD ? "bitfield" :
7336 if (wrong_type != NULL) {
7337 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7338 errorf(&tp_expression->base.source_position,
7339 "operand of %s expression must not be of %s type '%T'",
7340 what, wrong_type, orig_type);
7345 return tp_expression;
7348 static expression_t *parse_sizeof(void)
7350 return parse_typeprop(EXPR_SIZEOF);
7353 static expression_t *parse_alignof(void)
7355 return parse_typeprop(EXPR_ALIGNOF);
7358 static expression_t *parse_select_expression(expression_t *compound)
7360 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7361 select->select.compound = compound;
7363 assert(token.type == '.' || token.type == T_MINUSGREATER);
7364 bool is_pointer = (token.type == T_MINUSGREATER);
7367 if (token.type != T_IDENTIFIER) {
7368 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7371 symbol_t *symbol = token.v.symbol;
7374 type_t *const orig_type = compound->base.type;
7375 type_t *const type = skip_typeref(orig_type);
7378 bool saw_error = false;
7379 if (is_type_pointer(type)) {
7382 "request for member '%Y' in something not a struct or union, but '%T'",
7386 type_left = skip_typeref(type->pointer.points_to);
7388 if (is_pointer && is_type_valid(type)) {
7389 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7396 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7397 type_left->kind == TYPE_COMPOUND_UNION) {
7398 compound_t *compound = type_left->compound.compound;
7400 if (!compound->complete) {
7401 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7403 goto create_error_entry;
7406 entry = find_compound_entry(compound, symbol);
7407 if (entry == NULL) {
7408 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7409 goto create_error_entry;
7412 if (is_type_valid(type_left) && !saw_error) {
7414 "request for member '%Y' in something not a struct or union, but '%T'",
7418 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7421 assert(is_declaration(entry));
7422 select->select.compound_entry = entry;
7424 check_deprecated(HERE, entry);
7426 type_t *entry_type = entry->declaration.type;
7428 = get_qualified_type(entry_type, type_left->base.qualifiers);
7430 /* we always do the auto-type conversions; the & and sizeof parser contains
7431 * code to revert this! */
7432 select->base.type = automatic_type_conversion(res_type);
7434 type_t *skipped = skip_typeref(res_type);
7435 if (skipped->kind == TYPE_BITFIELD) {
7436 select->base.type = skipped->bitfield.base_type;
7442 static void check_call_argument(type_t *expected_type,
7443 call_argument_t *argument, unsigned pos)
7445 type_t *expected_type_skip = skip_typeref(expected_type);
7446 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7447 expression_t *arg_expr = argument->expression;
7448 type_t *arg_type = skip_typeref(arg_expr->base.type);
7450 /* handle transparent union gnu extension */
7451 if (is_type_union(expected_type_skip)
7452 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7453 compound_t *union_decl = expected_type_skip->compound.compound;
7454 type_t *best_type = NULL;
7455 entity_t *entry = union_decl->members.entities;
7456 for ( ; entry != NULL; entry = entry->base.next) {
7457 assert(is_declaration(entry));
7458 type_t *decl_type = entry->declaration.type;
7459 error = semantic_assign(decl_type, arg_expr);
7460 if (error == ASSIGN_ERROR_INCOMPATIBLE
7461 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7464 if (error == ASSIGN_SUCCESS) {
7465 best_type = decl_type;
7466 } else if (best_type == NULL) {
7467 best_type = decl_type;
7471 if (best_type != NULL) {
7472 expected_type = best_type;
7476 error = semantic_assign(expected_type, arg_expr);
7477 argument->expression = create_implicit_cast(arg_expr, expected_type);
7479 if (error != ASSIGN_SUCCESS) {
7480 /* report exact scope in error messages (like "in argument 3") */
7482 snprintf(buf, sizeof(buf), "call argument %u", pos);
7483 report_assign_error(error, expected_type, arg_expr, buf,
7484 &arg_expr->base.source_position);
7485 } else if (warning.traditional || warning.conversion) {
7486 type_t *const promoted_type = get_default_promoted_type(arg_type);
7487 if (!types_compatible(expected_type_skip, promoted_type) &&
7488 !types_compatible(expected_type_skip, type_void_ptr) &&
7489 !types_compatible(type_void_ptr, promoted_type)) {
7490 /* Deliberately show the skipped types in this warning */
7491 warningf(&arg_expr->base.source_position,
7492 "passing call argument %u as '%T' rather than '%T' due to prototype",
7493 pos, expected_type_skip, promoted_type);
7499 * Handle the semantic restrictions of builtin calls
7501 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7502 switch (call->function->reference.entity->function.btk) {
7503 case bk_gnu_builtin_return_address:
7504 case bk_gnu_builtin_frame_address: {
7505 /* argument must be constant */
7506 call_argument_t *argument = call->arguments;
7508 if (! is_constant_expression(argument->expression)) {
7509 errorf(&call->base.source_position,
7510 "argument of '%Y' must be a constant expression",
7511 call->function->reference.entity->base.symbol);
7515 case bk_gnu_builtin_prefetch: {
7516 /* second and third argument must be constant if existent */
7517 call_argument_t *rw = call->arguments->next;
7518 call_argument_t *locality = NULL;
7521 if (! is_constant_expression(rw->expression)) {
7522 errorf(&call->base.source_position,
7523 "second argument of '%Y' must be a constant expression",
7524 call->function->reference.entity->base.symbol);
7526 locality = rw->next;
7528 if (locality != NULL) {
7529 if (! is_constant_expression(locality->expression)) {
7530 errorf(&call->base.source_position,
7531 "third argument of '%Y' must be a constant expression",
7532 call->function->reference.entity->base.symbol);
7534 locality = rw->next;
7544 * Parse a call expression, ie. expression '( ... )'.
7546 * @param expression the function address
7548 static expression_t *parse_call_expression(expression_t *expression)
7550 expression_t *result = allocate_expression_zero(EXPR_CALL);
7551 call_expression_t *call = &result->call;
7552 call->function = expression;
7554 type_t *const orig_type = expression->base.type;
7555 type_t *const type = skip_typeref(orig_type);
7557 function_type_t *function_type = NULL;
7558 if (is_type_pointer(type)) {
7559 type_t *const to_type = skip_typeref(type->pointer.points_to);
7561 if (is_type_function(to_type)) {
7562 function_type = &to_type->function;
7563 call->base.type = function_type->return_type;
7567 if (function_type == NULL && is_type_valid(type)) {
7569 "called object '%E' (type '%T') is not a pointer to a function",
7570 expression, orig_type);
7573 /* parse arguments */
7575 add_anchor_token(')');
7576 add_anchor_token(',');
7578 if (token.type != ')') {
7579 call_argument_t **anchor = &call->arguments;
7581 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7582 argument->expression = parse_assignment_expression();
7585 anchor = &argument->next;
7587 if (token.type != ',')
7592 rem_anchor_token(',');
7593 rem_anchor_token(')');
7594 expect(')', end_error);
7596 if (function_type == NULL)
7599 /* check type and count of call arguments */
7600 function_parameter_t *parameter = function_type->parameters;
7601 call_argument_t *argument = call->arguments;
7602 if (!function_type->unspecified_parameters) {
7603 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7604 parameter = parameter->next, argument = argument->next) {
7605 check_call_argument(parameter->type, argument, ++pos);
7608 if (parameter != NULL) {
7609 errorf(HERE, "too few arguments to function '%E'", expression);
7610 } else if (argument != NULL && !function_type->variadic) {
7611 errorf(HERE, "too many arguments to function '%E'", expression);
7615 /* do default promotion for other arguments */
7616 for (; argument != NULL; argument = argument->next) {
7617 type_t *type = argument->expression->base.type;
7619 type = get_default_promoted_type(type);
7621 argument->expression
7622 = create_implicit_cast(argument->expression, type);
7625 check_format(&result->call);
7627 if (warning.aggregate_return &&
7628 is_type_compound(skip_typeref(function_type->return_type))) {
7629 warningf(&result->base.source_position,
7630 "function call has aggregate value");
7633 if (call->function->kind == EXPR_REFERENCE) {
7634 reference_expression_t *reference = &call->function->reference;
7635 if (reference->entity->kind == ENTITY_FUNCTION &&
7636 reference->entity->function.btk != bk_none)
7637 handle_builtin_argument_restrictions(call);
7644 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7646 static bool same_compound_type(const type_t *type1, const type_t *type2)
7649 is_type_compound(type1) &&
7650 type1->kind == type2->kind &&
7651 type1->compound.compound == type2->compound.compound;
7654 static expression_t const *get_reference_address(expression_t const *expr)
7656 bool regular_take_address = true;
7658 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7659 expr = expr->unary.value;
7661 regular_take_address = false;
7664 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7667 expr = expr->unary.value;
7670 if (expr->kind != EXPR_REFERENCE)
7673 /* special case for functions which are automatically converted to a
7674 * pointer to function without an extra TAKE_ADDRESS operation */
7675 if (!regular_take_address &&
7676 expr->reference.entity->kind != ENTITY_FUNCTION) {
7683 static void warn_reference_address_as_bool(expression_t const* expr)
7685 if (!warning.address)
7688 expr = get_reference_address(expr);
7690 warningf(&expr->base.source_position,
7691 "the address of '%Y' will always evaluate as 'true'",
7692 expr->reference.entity->base.symbol);
7696 static void warn_assignment_in_condition(const expression_t *const expr)
7698 if (!warning.parentheses)
7700 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7702 if (expr->base.parenthesized)
7704 warningf(&expr->base.source_position,
7705 "suggest parentheses around assignment used as truth value");
7708 static void semantic_condition(expression_t const *const expr,
7709 char const *const context)
7711 type_t *const type = skip_typeref(expr->base.type);
7712 if (is_type_scalar(type)) {
7713 warn_reference_address_as_bool(expr);
7714 warn_assignment_in_condition(expr);
7715 } else if (is_type_valid(type)) {
7716 errorf(&expr->base.source_position,
7717 "%s must have scalar type", context);
7722 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7724 * @param expression the conditional expression
7726 static expression_t *parse_conditional_expression(expression_t *expression)
7728 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7730 conditional_expression_t *conditional = &result->conditional;
7731 conditional->condition = expression;
7734 add_anchor_token(':');
7736 /* §6.5.15:2 The first operand shall have scalar type. */
7737 semantic_condition(expression, "condition of conditional operator");
7739 expression_t *true_expression = expression;
7740 bool gnu_cond = false;
7741 if (GNU_MODE && token.type == ':') {
7744 true_expression = parse_expression();
7746 rem_anchor_token(':');
7747 expect(':', end_error);
7749 expression_t *false_expression =
7750 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7752 type_t *const orig_true_type = true_expression->base.type;
7753 type_t *const orig_false_type = false_expression->base.type;
7754 type_t *const true_type = skip_typeref(orig_true_type);
7755 type_t *const false_type = skip_typeref(orig_false_type);
7758 type_t *result_type;
7759 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7760 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7761 /* ISO/IEC 14882:1998(E) §5.16:2 */
7762 if (true_expression->kind == EXPR_UNARY_THROW) {
7763 result_type = false_type;
7764 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7765 result_type = true_type;
7767 if (warning.other && (
7768 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7769 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7771 warningf(&conditional->base.source_position,
7772 "ISO C forbids conditional expression with only one void side");
7774 result_type = type_void;
7776 } else if (is_type_arithmetic(true_type)
7777 && is_type_arithmetic(false_type)) {
7778 result_type = semantic_arithmetic(true_type, false_type);
7780 true_expression = create_implicit_cast(true_expression, result_type);
7781 false_expression = create_implicit_cast(false_expression, result_type);
7783 conditional->true_expression = true_expression;
7784 conditional->false_expression = false_expression;
7785 conditional->base.type = result_type;
7786 } else if (same_compound_type(true_type, false_type)) {
7787 /* just take 1 of the 2 types */
7788 result_type = true_type;
7789 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7790 type_t *pointer_type;
7792 expression_t *other_expression;
7793 if (is_type_pointer(true_type) &&
7794 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7795 pointer_type = true_type;
7796 other_type = false_type;
7797 other_expression = false_expression;
7799 pointer_type = false_type;
7800 other_type = true_type;
7801 other_expression = true_expression;
7804 if (is_null_pointer_constant(other_expression)) {
7805 result_type = pointer_type;
7806 } else if (is_type_pointer(other_type)) {
7807 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7808 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7811 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7812 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7814 } else if (types_compatible(get_unqualified_type(to1),
7815 get_unqualified_type(to2))) {
7818 if (warning.other) {
7819 warningf(&conditional->base.source_position,
7820 "pointer types '%T' and '%T' in conditional expression are incompatible",
7821 true_type, false_type);
7826 type_t *const type =
7827 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7828 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7829 } else if (is_type_integer(other_type)) {
7830 if (warning.other) {
7831 warningf(&conditional->base.source_position,
7832 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7834 result_type = pointer_type;
7836 if (is_type_valid(other_type)) {
7837 type_error_incompatible("while parsing conditional",
7838 &expression->base.source_position, true_type, false_type);
7840 result_type = type_error_type;
7843 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7844 type_error_incompatible("while parsing conditional",
7845 &conditional->base.source_position, true_type,
7848 result_type = type_error_type;
7851 conditional->true_expression
7852 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7853 conditional->false_expression
7854 = create_implicit_cast(false_expression, result_type);
7855 conditional->base.type = result_type;
7860 * Parse an extension expression.
7862 static expression_t *parse_extension(void)
7864 eat(T___extension__);
7866 bool old_gcc_extension = in_gcc_extension;
7867 in_gcc_extension = true;
7868 expression_t *expression = parse_sub_expression(PREC_UNARY);
7869 in_gcc_extension = old_gcc_extension;
7874 * Parse a __builtin_classify_type() expression.
7876 static expression_t *parse_builtin_classify_type(void)
7878 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7879 result->base.type = type_int;
7881 eat(T___builtin_classify_type);
7883 expect('(', end_error);
7884 add_anchor_token(')');
7885 expression_t *expression = parse_expression();
7886 rem_anchor_token(')');
7887 expect(')', end_error);
7888 result->classify_type.type_expression = expression;
7892 return create_invalid_expression();
7896 * Parse a delete expression
7897 * ISO/IEC 14882:1998(E) §5.3.5
7899 static expression_t *parse_delete(void)
7901 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7902 result->base.type = type_void;
7906 if (token.type == '[') {
7908 result->kind = EXPR_UNARY_DELETE_ARRAY;
7909 expect(']', end_error);
7913 expression_t *const value = parse_sub_expression(PREC_CAST);
7914 result->unary.value = value;
7916 type_t *const type = skip_typeref(value->base.type);
7917 if (!is_type_pointer(type)) {
7918 if (is_type_valid(type)) {
7919 errorf(&value->base.source_position,
7920 "operand of delete must have pointer type");
7922 } else if (warning.other &&
7923 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7924 warningf(&value->base.source_position,
7925 "deleting 'void*' is undefined");
7932 * Parse a throw expression
7933 * ISO/IEC 14882:1998(E) §15:1
7935 static expression_t *parse_throw(void)
7937 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7938 result->base.type = type_void;
7942 expression_t *value = NULL;
7943 switch (token.type) {
7945 value = parse_assignment_expression();
7946 /* ISO/IEC 14882:1998(E) §15.1:3 */
7947 type_t *const orig_type = value->base.type;
7948 type_t *const type = skip_typeref(orig_type);
7949 if (is_type_incomplete(type)) {
7950 errorf(&value->base.source_position,
7951 "cannot throw object of incomplete type '%T'", orig_type);
7952 } else if (is_type_pointer(type)) {
7953 type_t *const points_to = skip_typeref(type->pointer.points_to);
7954 if (is_type_incomplete(points_to) &&
7955 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7956 errorf(&value->base.source_position,
7957 "cannot throw pointer to incomplete type '%T'", orig_type);
7965 result->unary.value = value;
7970 static bool check_pointer_arithmetic(const source_position_t *source_position,
7971 type_t *pointer_type,
7972 type_t *orig_pointer_type)
7974 type_t *points_to = pointer_type->pointer.points_to;
7975 points_to = skip_typeref(points_to);
7977 if (is_type_incomplete(points_to)) {
7978 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7979 errorf(source_position,
7980 "arithmetic with pointer to incomplete type '%T' not allowed",
7983 } else if (warning.pointer_arith) {
7984 warningf(source_position,
7985 "pointer of type '%T' used in arithmetic",
7988 } else if (is_type_function(points_to)) {
7990 errorf(source_position,
7991 "arithmetic with pointer to function type '%T' not allowed",
7994 } else if (warning.pointer_arith) {
7995 warningf(source_position,
7996 "pointer to a function '%T' used in arithmetic",
8003 static bool is_lvalue(const expression_t *expression)
8005 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8006 switch (expression->kind) {
8007 case EXPR_ARRAY_ACCESS:
8008 case EXPR_COMPOUND_LITERAL:
8009 case EXPR_REFERENCE:
8011 case EXPR_UNARY_DEREFERENCE:
8015 type_t *type = skip_typeref(expression->base.type);
8017 /* ISO/IEC 14882:1998(E) §3.10:3 */
8018 is_type_reference(type) ||
8019 /* Claim it is an lvalue, if the type is invalid. There was a parse
8020 * error before, which maybe prevented properly recognizing it as
8022 !is_type_valid(type);
8027 static void semantic_incdec(unary_expression_t *expression)
8029 type_t *const orig_type = expression->value->base.type;
8030 type_t *const type = skip_typeref(orig_type);
8031 if (is_type_pointer(type)) {
8032 if (!check_pointer_arithmetic(&expression->base.source_position,
8036 } else if (!is_type_real(type) && is_type_valid(type)) {
8037 /* TODO: improve error message */
8038 errorf(&expression->base.source_position,
8039 "operation needs an arithmetic or pointer type");
8042 if (!is_lvalue(expression->value)) {
8043 /* TODO: improve error message */
8044 errorf(&expression->base.source_position, "lvalue required as operand");
8046 expression->base.type = orig_type;
8049 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8051 type_t *const orig_type = expression->value->base.type;
8052 type_t *const type = skip_typeref(orig_type);
8053 if (!is_type_arithmetic(type)) {
8054 if (is_type_valid(type)) {
8055 /* TODO: improve error message */
8056 errorf(&expression->base.source_position,
8057 "operation needs an arithmetic type");
8062 expression->base.type = orig_type;
8065 static void semantic_unexpr_plus(unary_expression_t *expression)
8067 semantic_unexpr_arithmetic(expression);
8068 if (warning.traditional)
8069 warningf(&expression->base.source_position,
8070 "traditional C rejects the unary plus operator");
8073 static void semantic_not(unary_expression_t *expression)
8075 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8076 semantic_condition(expression->value, "operand of !");
8077 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8080 static void semantic_unexpr_integer(unary_expression_t *expression)
8082 type_t *const orig_type = expression->value->base.type;
8083 type_t *const type = skip_typeref(orig_type);
8084 if (!is_type_integer(type)) {
8085 if (is_type_valid(type)) {
8086 errorf(&expression->base.source_position,
8087 "operand of ~ must be of integer type");
8092 expression->base.type = orig_type;
8095 static void semantic_dereference(unary_expression_t *expression)
8097 type_t *const orig_type = expression->value->base.type;
8098 type_t *const type = skip_typeref(orig_type);
8099 if (!is_type_pointer(type)) {
8100 if (is_type_valid(type)) {
8101 errorf(&expression->base.source_position,
8102 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8107 type_t *result_type = type->pointer.points_to;
8108 result_type = automatic_type_conversion(result_type);
8109 expression->base.type = result_type;
8113 * Record that an address is taken (expression represents an lvalue).
8115 * @param expression the expression
8116 * @param may_be_register if true, the expression might be an register
8118 static void set_address_taken(expression_t *expression, bool may_be_register)
8120 if (expression->kind != EXPR_REFERENCE)
8123 entity_t *const entity = expression->reference.entity;
8125 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8128 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8129 && !may_be_register) {
8130 errorf(&expression->base.source_position,
8131 "address of register %s '%Y' requested",
8132 get_entity_kind_name(entity->kind), entity->base.symbol);
8135 if (entity->kind == ENTITY_VARIABLE) {
8136 entity->variable.address_taken = true;
8138 assert(entity->kind == ENTITY_PARAMETER);
8139 entity->parameter.address_taken = true;
8144 * Check the semantic of the address taken expression.
8146 static void semantic_take_addr(unary_expression_t *expression)
8148 expression_t *value = expression->value;
8149 value->base.type = revert_automatic_type_conversion(value);
8151 type_t *orig_type = value->base.type;
8152 type_t *type = skip_typeref(orig_type);
8153 if (!is_type_valid(type))
8157 if (!is_lvalue(value)) {
8158 errorf(&expression->base.source_position, "'&' requires an lvalue");
8160 if (type->kind == TYPE_BITFIELD) {
8161 errorf(&expression->base.source_position,
8162 "'&' not allowed on object with bitfield type '%T'",
8166 set_address_taken(value, false);
8168 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8171 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8172 static expression_t *parse_##unexpression_type(void) \
8174 expression_t *unary_expression \
8175 = allocate_expression_zero(unexpression_type); \
8177 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8179 sfunc(&unary_expression->unary); \
8181 return unary_expression; \
8184 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8185 semantic_unexpr_arithmetic)
8186 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8187 semantic_unexpr_plus)
8188 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8190 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8191 semantic_dereference)
8192 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8194 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8195 semantic_unexpr_integer)
8196 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8198 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8201 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8203 static expression_t *parse_##unexpression_type(expression_t *left) \
8205 expression_t *unary_expression \
8206 = allocate_expression_zero(unexpression_type); \
8208 unary_expression->unary.value = left; \
8210 sfunc(&unary_expression->unary); \
8212 return unary_expression; \
8215 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8216 EXPR_UNARY_POSTFIX_INCREMENT,
8218 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8219 EXPR_UNARY_POSTFIX_DECREMENT,
8222 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8224 /* TODO: handle complex + imaginary types */
8226 type_left = get_unqualified_type(type_left);
8227 type_right = get_unqualified_type(type_right);
8229 /* §6.3.1.8 Usual arithmetic conversions */
8230 if (type_left == type_long_double || type_right == type_long_double) {
8231 return type_long_double;
8232 } else if (type_left == type_double || type_right == type_double) {
8234 } else if (type_left == type_float || type_right == type_float) {
8238 type_left = promote_integer(type_left);
8239 type_right = promote_integer(type_right);
8241 if (type_left == type_right)
8244 bool const signed_left = is_type_signed(type_left);
8245 bool const signed_right = is_type_signed(type_right);
8246 int const rank_left = get_rank(type_left);
8247 int const rank_right = get_rank(type_right);
8249 if (signed_left == signed_right)
8250 return rank_left >= rank_right ? type_left : type_right;
8259 u_rank = rank_right;
8260 u_type = type_right;
8262 s_rank = rank_right;
8263 s_type = type_right;
8268 if (u_rank >= s_rank)
8271 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8273 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8274 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8278 case ATOMIC_TYPE_INT: return type_unsigned_int;
8279 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8280 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8282 default: panic("invalid atomic type");
8287 * Check the semantic restrictions for a binary expression.
8289 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8291 expression_t *const left = expression->left;
8292 expression_t *const right = expression->right;
8293 type_t *const orig_type_left = left->base.type;
8294 type_t *const orig_type_right = right->base.type;
8295 type_t *const type_left = skip_typeref(orig_type_left);
8296 type_t *const type_right = skip_typeref(orig_type_right);
8298 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8299 /* TODO: improve error message */
8300 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8301 errorf(&expression->base.source_position,
8302 "operation needs arithmetic types");
8307 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8308 expression->left = create_implicit_cast(left, arithmetic_type);
8309 expression->right = create_implicit_cast(right, arithmetic_type);
8310 expression->base.type = arithmetic_type;
8313 static void warn_div_by_zero(binary_expression_t const *const expression)
8315 if (!warning.div_by_zero ||
8316 !is_type_integer(expression->base.type))
8319 expression_t const *const right = expression->right;
8320 /* The type of the right operand can be different for /= */
8321 if (is_type_integer(right->base.type) &&
8322 is_constant_expression(right) &&
8323 fold_constant(right) == 0) {
8324 warningf(&expression->base.source_position, "division by zero");
8329 * Check the semantic restrictions for a div/mod expression.
8331 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8333 semantic_binexpr_arithmetic(expression);
8334 warn_div_by_zero(expression);
8337 static void warn_addsub_in_shift(const expression_t *const expr)
8339 if (expr->base.parenthesized)
8343 switch (expr->kind) {
8344 case EXPR_BINARY_ADD: op = '+'; break;
8345 case EXPR_BINARY_SUB: op = '-'; break;
8349 warningf(&expr->base.source_position,
8350 "suggest parentheses around '%c' inside shift", op);
8353 static bool semantic_shift(binary_expression_t *expression)
8355 expression_t *const left = expression->left;
8356 expression_t *const right = expression->right;
8357 type_t *const orig_type_left = left->base.type;
8358 type_t *const orig_type_right = right->base.type;
8359 type_t * type_left = skip_typeref(orig_type_left);
8360 type_t * type_right = skip_typeref(orig_type_right);
8362 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8363 /* TODO: improve error message */
8364 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8365 errorf(&expression->base.source_position,
8366 "operands of shift operation must have integer types");
8371 type_left = promote_integer(type_left);
8373 if (is_constant_expression(right)) {
8374 long count = fold_constant(right);
8376 warningf(&right->base.source_position,
8377 "shift count must be non-negative");
8378 } else if ((unsigned long)count >=
8379 get_atomic_type_size(type_left->atomic.akind) * 8) {
8380 warningf(&right->base.source_position,
8381 "shift count must be less than type width");
8385 type_right = promote_integer(type_right);
8386 expression->right = create_implicit_cast(right, type_right);
8391 static void semantic_shift_op(binary_expression_t *expression)
8393 expression_t *const left = expression->left;
8394 expression_t *const right = expression->right;
8396 if (!semantic_shift(expression))
8399 if (warning.parentheses) {
8400 warn_addsub_in_shift(left);
8401 warn_addsub_in_shift(right);
8404 type_t *const orig_type_left = left->base.type;
8405 type_t * type_left = skip_typeref(orig_type_left);
8407 type_left = promote_integer(type_left);
8408 expression->left = create_implicit_cast(left, type_left);
8409 expression->base.type = type_left;
8412 static void semantic_add(binary_expression_t *expression)
8414 expression_t *const left = expression->left;
8415 expression_t *const right = expression->right;
8416 type_t *const orig_type_left = left->base.type;
8417 type_t *const orig_type_right = right->base.type;
8418 type_t *const type_left = skip_typeref(orig_type_left);
8419 type_t *const type_right = skip_typeref(orig_type_right);
8422 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8423 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8424 expression->left = create_implicit_cast(left, arithmetic_type);
8425 expression->right = create_implicit_cast(right, arithmetic_type);
8426 expression->base.type = arithmetic_type;
8427 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8428 check_pointer_arithmetic(&expression->base.source_position,
8429 type_left, orig_type_left);
8430 expression->base.type = type_left;
8431 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8432 check_pointer_arithmetic(&expression->base.source_position,
8433 type_right, orig_type_right);
8434 expression->base.type = type_right;
8435 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8436 errorf(&expression->base.source_position,
8437 "invalid operands to binary + ('%T', '%T')",
8438 orig_type_left, orig_type_right);
8442 static void semantic_sub(binary_expression_t *expression)
8444 expression_t *const left = expression->left;
8445 expression_t *const right = expression->right;
8446 type_t *const orig_type_left = left->base.type;
8447 type_t *const orig_type_right = right->base.type;
8448 type_t *const type_left = skip_typeref(orig_type_left);
8449 type_t *const type_right = skip_typeref(orig_type_right);
8450 source_position_t const *const pos = &expression->base.source_position;
8453 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8454 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8455 expression->left = create_implicit_cast(left, arithmetic_type);
8456 expression->right = create_implicit_cast(right, arithmetic_type);
8457 expression->base.type = arithmetic_type;
8458 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8459 check_pointer_arithmetic(&expression->base.source_position,
8460 type_left, orig_type_left);
8461 expression->base.type = type_left;
8462 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8463 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8464 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8465 if (!types_compatible(unqual_left, unqual_right)) {
8467 "subtracting pointers to incompatible types '%T' and '%T'",
8468 orig_type_left, orig_type_right);
8469 } else if (!is_type_object(unqual_left)) {
8470 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8471 errorf(pos, "subtracting pointers to non-object types '%T'",
8473 } else if (warning.other) {
8474 warningf(pos, "subtracting pointers to void");
8477 expression->base.type = type_ptrdiff_t;
8478 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8479 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8480 orig_type_left, orig_type_right);
8484 static void warn_string_literal_address(expression_t const* expr)
8486 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8487 expr = expr->unary.value;
8488 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8490 expr = expr->unary.value;
8493 if (expr->kind == EXPR_STRING_LITERAL ||
8494 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8495 warningf(&expr->base.source_position,
8496 "comparison with string literal results in unspecified behaviour");
8500 static void warn_comparison_in_comparison(const expression_t *const expr)
8502 if (expr->base.parenthesized)
8504 switch (expr->base.kind) {
8505 case EXPR_BINARY_LESS:
8506 case EXPR_BINARY_GREATER:
8507 case EXPR_BINARY_LESSEQUAL:
8508 case EXPR_BINARY_GREATEREQUAL:
8509 case EXPR_BINARY_NOTEQUAL:
8510 case EXPR_BINARY_EQUAL:
8511 warningf(&expr->base.source_position,
8512 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8519 static bool maybe_negative(expression_t const *const expr)
8522 !is_constant_expression(expr) ||
8523 fold_constant(expr) < 0;
8527 * Check the semantics of comparison expressions.
8529 * @param expression The expression to check.
8531 static void semantic_comparison(binary_expression_t *expression)
8533 expression_t *left = expression->left;
8534 expression_t *right = expression->right;
8536 if (warning.address) {
8537 warn_string_literal_address(left);
8538 warn_string_literal_address(right);
8540 expression_t const* const func_left = get_reference_address(left);
8541 if (func_left != NULL && is_null_pointer_constant(right)) {
8542 warningf(&expression->base.source_position,
8543 "the address of '%Y' will never be NULL",
8544 func_left->reference.entity->base.symbol);
8547 expression_t const* const func_right = get_reference_address(right);
8548 if (func_right != NULL && is_null_pointer_constant(right)) {
8549 warningf(&expression->base.source_position,
8550 "the address of '%Y' will never be NULL",
8551 func_right->reference.entity->base.symbol);
8555 if (warning.parentheses) {
8556 warn_comparison_in_comparison(left);
8557 warn_comparison_in_comparison(right);
8560 type_t *orig_type_left = left->base.type;
8561 type_t *orig_type_right = right->base.type;
8562 type_t *type_left = skip_typeref(orig_type_left);
8563 type_t *type_right = skip_typeref(orig_type_right);
8565 /* TODO non-arithmetic types */
8566 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8567 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8569 /* test for signed vs unsigned compares */
8570 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8571 bool const signed_left = is_type_signed(type_left);
8572 bool const signed_right = is_type_signed(type_right);
8573 if (signed_left != signed_right) {
8574 /* FIXME long long needs better const folding magic */
8575 /* TODO check whether constant value can be represented by other type */
8576 if ((signed_left && maybe_negative(left)) ||
8577 (signed_right && maybe_negative(right))) {
8578 warningf(&expression->base.source_position,
8579 "comparison between signed and unsigned");
8584 expression->left = create_implicit_cast(left, arithmetic_type);
8585 expression->right = create_implicit_cast(right, arithmetic_type);
8586 expression->base.type = arithmetic_type;
8587 if (warning.float_equal &&
8588 (expression->base.kind == EXPR_BINARY_EQUAL ||
8589 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8590 is_type_float(arithmetic_type)) {
8591 warningf(&expression->base.source_position,
8592 "comparing floating point with == or != is unsafe");
8594 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8595 /* TODO check compatibility */
8596 } else if (is_type_pointer(type_left)) {
8597 expression->right = create_implicit_cast(right, type_left);
8598 } else if (is_type_pointer(type_right)) {
8599 expression->left = create_implicit_cast(left, type_right);
8600 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8601 type_error_incompatible("invalid operands in comparison",
8602 &expression->base.source_position,
8603 type_left, type_right);
8605 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8609 * Checks if a compound type has constant fields.
8611 static bool has_const_fields(const compound_type_t *type)
8613 compound_t *compound = type->compound;
8614 entity_t *entry = compound->members.entities;
8616 for (; entry != NULL; entry = entry->base.next) {
8617 if (!is_declaration(entry))
8620 const type_t *decl_type = skip_typeref(entry->declaration.type);
8621 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8628 static bool is_valid_assignment_lhs(expression_t const* const left)
8630 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8631 type_t *const type_left = skip_typeref(orig_type_left);
8633 if (!is_lvalue(left)) {
8634 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8639 if (left->kind == EXPR_REFERENCE
8640 && left->reference.entity->kind == ENTITY_FUNCTION) {
8641 errorf(HERE, "cannot assign to function '%E'", left);
8645 if (is_type_array(type_left)) {
8646 errorf(HERE, "cannot assign to array '%E'", left);
8649 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8650 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8654 if (is_type_incomplete(type_left)) {
8655 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8656 left, orig_type_left);
8659 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8660 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8661 left, orig_type_left);
8668 static void semantic_arithmetic_assign(binary_expression_t *expression)
8670 expression_t *left = expression->left;
8671 expression_t *right = expression->right;
8672 type_t *orig_type_left = left->base.type;
8673 type_t *orig_type_right = right->base.type;
8675 if (!is_valid_assignment_lhs(left))
8678 type_t *type_left = skip_typeref(orig_type_left);
8679 type_t *type_right = skip_typeref(orig_type_right);
8681 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8682 /* TODO: improve error message */
8683 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8684 errorf(&expression->base.source_position,
8685 "operation needs arithmetic types");
8690 /* combined instructions are tricky. We can't create an implicit cast on
8691 * the left side, because we need the uncasted form for the store.
8692 * The ast2firm pass has to know that left_type must be right_type
8693 * for the arithmetic operation and create a cast by itself */
8694 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8695 expression->right = create_implicit_cast(right, arithmetic_type);
8696 expression->base.type = type_left;
8699 static void semantic_divmod_assign(binary_expression_t *expression)
8701 semantic_arithmetic_assign(expression);
8702 warn_div_by_zero(expression);
8705 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8707 expression_t *const left = expression->left;
8708 expression_t *const right = expression->right;
8709 type_t *const orig_type_left = left->base.type;
8710 type_t *const orig_type_right = right->base.type;
8711 type_t *const type_left = skip_typeref(orig_type_left);
8712 type_t *const type_right = skip_typeref(orig_type_right);
8714 if (!is_valid_assignment_lhs(left))
8717 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8718 /* combined instructions are tricky. We can't create an implicit cast on
8719 * the left side, because we need the uncasted form for the store.
8720 * The ast2firm pass has to know that left_type must be right_type
8721 * for the arithmetic operation and create a cast by itself */
8722 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8723 expression->right = create_implicit_cast(right, arithmetic_type);
8724 expression->base.type = type_left;
8725 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8726 check_pointer_arithmetic(&expression->base.source_position,
8727 type_left, orig_type_left);
8728 expression->base.type = type_left;
8729 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8730 errorf(&expression->base.source_position,
8731 "incompatible types '%T' and '%T' in assignment",
8732 orig_type_left, orig_type_right);
8736 static void semantic_integer_assign(binary_expression_t *expression)
8738 expression_t *left = expression->left;
8739 expression_t *right = expression->right;
8740 type_t *orig_type_left = left->base.type;
8741 type_t *orig_type_right = right->base.type;
8743 if (!is_valid_assignment_lhs(left))
8746 type_t *type_left = skip_typeref(orig_type_left);
8747 type_t *type_right = skip_typeref(orig_type_right);
8749 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8750 /* TODO: improve error message */
8751 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8752 errorf(&expression->base.source_position,
8753 "operation needs integer types");
8758 /* combined instructions are tricky. We can't create an implicit cast on
8759 * the left side, because we need the uncasted form for the store.
8760 * The ast2firm pass has to know that left_type must be right_type
8761 * for the arithmetic operation and create a cast by itself */
8762 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8763 expression->right = create_implicit_cast(right, arithmetic_type);
8764 expression->base.type = type_left;
8767 static void semantic_shift_assign(binary_expression_t *expression)
8769 expression_t *left = expression->left;
8771 if (!is_valid_assignment_lhs(left))
8774 if (!semantic_shift(expression))
8777 expression->base.type = skip_typeref(left->base.type);
8780 static void warn_logical_and_within_or(const expression_t *const expr)
8782 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8784 if (expr->base.parenthesized)
8786 warningf(&expr->base.source_position,
8787 "suggest parentheses around && within ||");
8791 * Check the semantic restrictions of a logical expression.
8793 static void semantic_logical_op(binary_expression_t *expression)
8795 /* §6.5.13:2 Each of the operands shall have scalar type.
8796 * §6.5.14:2 Each of the operands shall have scalar type. */
8797 semantic_condition(expression->left, "left operand of logical operator");
8798 semantic_condition(expression->right, "right operand of logical operator");
8799 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8800 warning.parentheses) {
8801 warn_logical_and_within_or(expression->left);
8802 warn_logical_and_within_or(expression->right);
8804 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8808 * Check the semantic restrictions of a binary assign expression.
8810 static void semantic_binexpr_assign(binary_expression_t *expression)
8812 expression_t *left = expression->left;
8813 type_t *orig_type_left = left->base.type;
8815 if (!is_valid_assignment_lhs(left))
8818 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8819 report_assign_error(error, orig_type_left, expression->right,
8820 "assignment", &left->base.source_position);
8821 expression->right = create_implicit_cast(expression->right, orig_type_left);
8822 expression->base.type = orig_type_left;
8826 * Determine if the outermost operation (or parts thereof) of the given
8827 * expression has no effect in order to generate a warning about this fact.
8828 * Therefore in some cases this only examines some of the operands of the
8829 * expression (see comments in the function and examples below).
8831 * f() + 23; // warning, because + has no effect
8832 * x || f(); // no warning, because x controls execution of f()
8833 * x ? y : f(); // warning, because y has no effect
8834 * (void)x; // no warning to be able to suppress the warning
8835 * This function can NOT be used for an "expression has definitely no effect"-
8837 static bool expression_has_effect(const expression_t *const expr)
8839 switch (expr->kind) {
8840 case EXPR_UNKNOWN: break;
8841 case EXPR_INVALID: return true; /* do NOT warn */
8842 case EXPR_REFERENCE: return false;
8843 case EXPR_REFERENCE_ENUM_VALUE: return false;
8844 /* suppress the warning for microsoft __noop operations */
8845 case EXPR_CONST: return expr->conste.is_ms_noop;
8846 case EXPR_CHARACTER_CONSTANT: return false;
8847 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8848 case EXPR_STRING_LITERAL: return false;
8849 case EXPR_WIDE_STRING_LITERAL: return false;
8850 case EXPR_LABEL_ADDRESS: return false;
8853 const call_expression_t *const call = &expr->call;
8854 if (call->function->kind != EXPR_REFERENCE)
8857 switch (call->function->reference.entity->function.btk) {
8858 /* FIXME: which builtins have no effect? */
8859 default: return true;
8863 /* Generate the warning if either the left or right hand side of a
8864 * conditional expression has no effect */
8865 case EXPR_CONDITIONAL: {
8866 conditional_expression_t const *const cond = &expr->conditional;
8867 expression_t const *const t = cond->true_expression;
8869 (t == NULL || expression_has_effect(t)) &&
8870 expression_has_effect(cond->false_expression);
8873 case EXPR_SELECT: return false;
8874 case EXPR_ARRAY_ACCESS: return false;
8875 case EXPR_SIZEOF: return false;
8876 case EXPR_CLASSIFY_TYPE: return false;
8877 case EXPR_ALIGNOF: return false;
8879 case EXPR_FUNCNAME: return false;
8880 case EXPR_BUILTIN_CONSTANT_P: return false;
8881 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8882 case EXPR_OFFSETOF: return false;
8883 case EXPR_VA_START: return true;
8884 case EXPR_VA_ARG: return true;
8885 case EXPR_VA_COPY: return true;
8886 case EXPR_STATEMENT: return true; // TODO
8887 case EXPR_COMPOUND_LITERAL: return false;
8889 case EXPR_UNARY_NEGATE: return false;
8890 case EXPR_UNARY_PLUS: return false;
8891 case EXPR_UNARY_BITWISE_NEGATE: return false;
8892 case EXPR_UNARY_NOT: return false;
8893 case EXPR_UNARY_DEREFERENCE: return false;
8894 case EXPR_UNARY_TAKE_ADDRESS: return false;
8895 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8896 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8897 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8898 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8900 /* Treat void casts as if they have an effect in order to being able to
8901 * suppress the warning */
8902 case EXPR_UNARY_CAST: {
8903 type_t *const type = skip_typeref(expr->base.type);
8904 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8907 case EXPR_UNARY_CAST_IMPLICIT: return true;
8908 case EXPR_UNARY_ASSUME: return true;
8909 case EXPR_UNARY_DELETE: return true;
8910 case EXPR_UNARY_DELETE_ARRAY: return true;
8911 case EXPR_UNARY_THROW: return true;
8913 case EXPR_BINARY_ADD: return false;
8914 case EXPR_BINARY_SUB: return false;
8915 case EXPR_BINARY_MUL: return false;
8916 case EXPR_BINARY_DIV: return false;
8917 case EXPR_BINARY_MOD: return false;
8918 case EXPR_BINARY_EQUAL: return false;
8919 case EXPR_BINARY_NOTEQUAL: return false;
8920 case EXPR_BINARY_LESS: return false;
8921 case EXPR_BINARY_LESSEQUAL: return false;
8922 case EXPR_BINARY_GREATER: return false;
8923 case EXPR_BINARY_GREATEREQUAL: return false;
8924 case EXPR_BINARY_BITWISE_AND: return false;
8925 case EXPR_BINARY_BITWISE_OR: return false;
8926 case EXPR_BINARY_BITWISE_XOR: return false;
8927 case EXPR_BINARY_SHIFTLEFT: return false;
8928 case EXPR_BINARY_SHIFTRIGHT: return false;
8929 case EXPR_BINARY_ASSIGN: return true;
8930 case EXPR_BINARY_MUL_ASSIGN: return true;
8931 case EXPR_BINARY_DIV_ASSIGN: return true;
8932 case EXPR_BINARY_MOD_ASSIGN: return true;
8933 case EXPR_BINARY_ADD_ASSIGN: return true;
8934 case EXPR_BINARY_SUB_ASSIGN: return true;
8935 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8936 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8937 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8938 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8939 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8941 /* Only examine the right hand side of && and ||, because the left hand
8942 * side already has the effect of controlling the execution of the right
8944 case EXPR_BINARY_LOGICAL_AND:
8945 case EXPR_BINARY_LOGICAL_OR:
8946 /* Only examine the right hand side of a comma expression, because the left
8947 * hand side has a separate warning */
8948 case EXPR_BINARY_COMMA:
8949 return expression_has_effect(expr->binary.right);
8951 case EXPR_BINARY_ISGREATER: return false;
8952 case EXPR_BINARY_ISGREATEREQUAL: return false;
8953 case EXPR_BINARY_ISLESS: return false;
8954 case EXPR_BINARY_ISLESSEQUAL: return false;
8955 case EXPR_BINARY_ISLESSGREATER: return false;
8956 case EXPR_BINARY_ISUNORDERED: return false;
8959 internal_errorf(HERE, "unexpected expression");
8962 static void semantic_comma(binary_expression_t *expression)
8964 if (warning.unused_value) {
8965 const expression_t *const left = expression->left;
8966 if (!expression_has_effect(left)) {
8967 warningf(&left->base.source_position,
8968 "left-hand operand of comma expression has no effect");
8971 expression->base.type = expression->right->base.type;
8975 * @param prec_r precedence of the right operand
8977 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8978 static expression_t *parse_##binexpression_type(expression_t *left) \
8980 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8981 binexpr->binary.left = left; \
8984 expression_t *right = parse_sub_expression(prec_r); \
8986 binexpr->binary.right = right; \
8987 sfunc(&binexpr->binary); \
8992 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8993 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8994 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8995 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8996 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8997 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8998 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8999 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9000 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9001 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9002 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9003 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9004 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9005 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9006 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9007 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9008 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9009 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9010 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9011 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9012 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9013 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9014 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9015 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9016 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9017 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9018 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9019 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9020 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9021 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9024 static expression_t *parse_sub_expression(precedence_t precedence)
9026 if (token.type < 0) {
9027 return expected_expression_error();
9030 expression_parser_function_t *parser
9031 = &expression_parsers[token.type];
9032 source_position_t source_position = token.source_position;
9035 if (parser->parser != NULL) {
9036 left = parser->parser();
9038 left = parse_primary_expression();
9040 assert(left != NULL);
9041 left->base.source_position = source_position;
9044 if (token.type < 0) {
9045 return expected_expression_error();
9048 parser = &expression_parsers[token.type];
9049 if (parser->infix_parser == NULL)
9051 if (parser->infix_precedence < precedence)
9054 left = parser->infix_parser(left);
9056 assert(left != NULL);
9057 assert(left->kind != EXPR_UNKNOWN);
9058 left->base.source_position = source_position;
9065 * Parse an expression.
9067 static expression_t *parse_expression(void)
9069 return parse_sub_expression(PREC_EXPRESSION);
9073 * Register a parser for a prefix-like operator.
9075 * @param parser the parser function
9076 * @param token_type the token type of the prefix token
9078 static void register_expression_parser(parse_expression_function parser,
9081 expression_parser_function_t *entry = &expression_parsers[token_type];
9083 if (entry->parser != NULL) {
9084 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9085 panic("trying to register multiple expression parsers for a token");
9087 entry->parser = parser;
9091 * Register a parser for an infix operator with given precedence.
9093 * @param parser the parser function
9094 * @param token_type the token type of the infix operator
9095 * @param precedence the precedence of the operator
9097 static void register_infix_parser(parse_expression_infix_function parser,
9098 int token_type, precedence_t precedence)
9100 expression_parser_function_t *entry = &expression_parsers[token_type];
9102 if (entry->infix_parser != NULL) {
9103 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9104 panic("trying to register multiple infix expression parsers for a "
9107 entry->infix_parser = parser;
9108 entry->infix_precedence = precedence;
9112 * Initialize the expression parsers.
9114 static void init_expression_parsers(void)
9116 memset(&expression_parsers, 0, sizeof(expression_parsers));
9118 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9119 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9120 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9121 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9122 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9123 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9124 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9125 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9126 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9127 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9128 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9129 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9130 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9131 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9132 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9133 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9134 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9135 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9136 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9137 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9138 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9139 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9140 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9141 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9142 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9143 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9144 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9145 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9146 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9147 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9148 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9149 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9150 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9151 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9152 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9153 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9154 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9156 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9157 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9158 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9159 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9160 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9161 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9162 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9163 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9164 register_expression_parser(parse_sizeof, T_sizeof);
9165 register_expression_parser(parse_alignof, T___alignof__);
9166 register_expression_parser(parse_extension, T___extension__);
9167 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9168 register_expression_parser(parse_delete, T_delete);
9169 register_expression_parser(parse_throw, T_throw);
9173 * Parse a asm statement arguments specification.
9175 static asm_argument_t *parse_asm_arguments(bool is_out)
9177 asm_argument_t *result = NULL;
9178 asm_argument_t **anchor = &result;
9180 while (token.type == T_STRING_LITERAL || token.type == '[') {
9181 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9182 memset(argument, 0, sizeof(argument[0]));
9184 if (token.type == '[') {
9186 if (token.type != T_IDENTIFIER) {
9187 parse_error_expected("while parsing asm argument",
9188 T_IDENTIFIER, NULL);
9191 argument->symbol = token.v.symbol;
9193 expect(']', end_error);
9196 argument->constraints = parse_string_literals();
9197 expect('(', end_error);
9198 add_anchor_token(')');
9199 expression_t *expression = parse_expression();
9200 rem_anchor_token(')');
9202 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9203 * change size or type representation (e.g. int -> long is ok, but
9204 * int -> float is not) */
9205 if (expression->kind == EXPR_UNARY_CAST) {
9206 type_t *const type = expression->base.type;
9207 type_kind_t const kind = type->kind;
9208 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9211 if (kind == TYPE_ATOMIC) {
9212 atomic_type_kind_t const akind = type->atomic.akind;
9213 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9214 size = get_atomic_type_size(akind);
9216 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9217 size = get_atomic_type_size(get_intptr_kind());
9221 expression_t *const value = expression->unary.value;
9222 type_t *const value_type = value->base.type;
9223 type_kind_t const value_kind = value_type->kind;
9225 unsigned value_flags;
9226 unsigned value_size;
9227 if (value_kind == TYPE_ATOMIC) {
9228 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9229 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9230 value_size = get_atomic_type_size(value_akind);
9231 } else if (value_kind == TYPE_POINTER) {
9232 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9233 value_size = get_atomic_type_size(get_intptr_kind());
9238 if (value_flags != flags || value_size != size)
9242 } while (expression->kind == EXPR_UNARY_CAST);
9246 if (!is_lvalue(expression)) {
9247 errorf(&expression->base.source_position,
9248 "asm output argument is not an lvalue");
9251 if (argument->constraints.begin[0] == '+')
9252 mark_vars_read(expression, NULL);
9254 mark_vars_read(expression, NULL);
9256 argument->expression = expression;
9257 expect(')', end_error);
9259 set_address_taken(expression, true);
9262 anchor = &argument->next;
9264 if (token.type != ',')
9275 * Parse a asm statement clobber specification.
9277 static asm_clobber_t *parse_asm_clobbers(void)
9279 asm_clobber_t *result = NULL;
9280 asm_clobber_t *last = NULL;
9282 while (token.type == T_STRING_LITERAL) {
9283 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9284 clobber->clobber = parse_string_literals();
9287 last->next = clobber;
9293 if (token.type != ',')
9302 * Parse an asm statement.
9304 static statement_t *parse_asm_statement(void)
9306 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9307 asm_statement_t *asm_statement = &statement->asms;
9311 if (token.type == T_volatile) {
9313 asm_statement->is_volatile = true;
9316 expect('(', end_error);
9317 add_anchor_token(')');
9318 add_anchor_token(':');
9319 asm_statement->asm_text = parse_string_literals();
9321 if (token.type != ':') {
9322 rem_anchor_token(':');
9327 asm_statement->outputs = parse_asm_arguments(true);
9328 if (token.type != ':') {
9329 rem_anchor_token(':');
9334 asm_statement->inputs = parse_asm_arguments(false);
9335 if (token.type != ':') {
9336 rem_anchor_token(':');
9339 rem_anchor_token(':');
9342 asm_statement->clobbers = parse_asm_clobbers();
9345 rem_anchor_token(')');
9346 expect(')', end_error);
9347 expect(';', end_error);
9349 if (asm_statement->outputs == NULL) {
9350 /* GCC: An 'asm' instruction without any output operands will be treated
9351 * identically to a volatile 'asm' instruction. */
9352 asm_statement->is_volatile = true;
9357 return create_invalid_statement();
9361 * Parse a case statement.
9363 static statement_t *parse_case_statement(void)
9365 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9366 source_position_t *const pos = &statement->base.source_position;
9370 expression_t *const expression = parse_expression();
9371 statement->case_label.expression = expression;
9372 if (!is_constant_expression(expression)) {
9373 /* This check does not prevent the error message in all cases of an
9374 * prior error while parsing the expression. At least it catches the
9375 * common case of a mistyped enum entry. */
9376 if (is_type_valid(skip_typeref(expression->base.type))) {
9377 errorf(pos, "case label does not reduce to an integer constant");
9379 statement->case_label.is_bad = true;
9381 long const val = fold_constant(expression);
9382 statement->case_label.first_case = val;
9383 statement->case_label.last_case = val;
9387 if (token.type == T_DOTDOTDOT) {
9389 expression_t *const end_range = parse_expression();
9390 statement->case_label.end_range = end_range;
9391 if (!is_constant_expression(end_range)) {
9392 /* This check does not prevent the error message in all cases of an
9393 * prior error while parsing the expression. At least it catches the
9394 * common case of a mistyped enum entry. */
9395 if (is_type_valid(skip_typeref(end_range->base.type))) {
9396 errorf(pos, "case range does not reduce to an integer constant");
9398 statement->case_label.is_bad = true;
9400 long const val = fold_constant(end_range);
9401 statement->case_label.last_case = val;
9403 if (warning.other && val < statement->case_label.first_case) {
9404 statement->case_label.is_empty_range = true;
9405 warningf(pos, "empty range specified");
9411 PUSH_PARENT(statement);
9413 expect(':', end_error);
9416 if (current_switch != NULL) {
9417 if (! statement->case_label.is_bad) {
9418 /* Check for duplicate case values */
9419 case_label_statement_t *c = &statement->case_label;
9420 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9421 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9424 if (c->last_case < l->first_case || c->first_case > l->last_case)
9427 errorf(pos, "duplicate case value (previously used %P)",
9428 &l->base.source_position);
9432 /* link all cases into the switch statement */
9433 if (current_switch->last_case == NULL) {
9434 current_switch->first_case = &statement->case_label;
9436 current_switch->last_case->next = &statement->case_label;
9438 current_switch->last_case = &statement->case_label;
9440 errorf(pos, "case label not within a switch statement");
9443 statement_t *const inner_stmt = parse_statement();
9444 statement->case_label.statement = inner_stmt;
9445 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9446 errorf(&inner_stmt->base.source_position, "declaration after case label");
9454 * Parse a default statement.
9456 static statement_t *parse_default_statement(void)
9458 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9462 PUSH_PARENT(statement);
9464 expect(':', end_error);
9465 if (current_switch != NULL) {
9466 const case_label_statement_t *def_label = current_switch->default_label;
9467 if (def_label != NULL) {
9468 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9469 &def_label->base.source_position);
9471 current_switch->default_label = &statement->case_label;
9473 /* link all cases into the switch statement */
9474 if (current_switch->last_case == NULL) {
9475 current_switch->first_case = &statement->case_label;
9477 current_switch->last_case->next = &statement->case_label;
9479 current_switch->last_case = &statement->case_label;
9482 errorf(&statement->base.source_position,
9483 "'default' label not within a switch statement");
9486 statement_t *const inner_stmt = parse_statement();
9487 statement->case_label.statement = inner_stmt;
9488 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9489 errorf(&inner_stmt->base.source_position, "declaration after default label");
9496 return create_invalid_statement();
9500 * Parse a label statement.
9502 static statement_t *parse_label_statement(void)
9504 assert(token.type == T_IDENTIFIER);
9505 symbol_t *symbol = token.v.symbol;
9506 label_t *label = get_label(symbol);
9508 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9509 statement->label.label = label;
9513 PUSH_PARENT(statement);
9515 /* if statement is already set then the label is defined twice,
9516 * otherwise it was just mentioned in a goto/local label declaration so far
9518 if (label->statement != NULL) {
9519 errorf(HERE, "duplicate label '%Y' (declared %P)",
9520 symbol, &label->base.source_position);
9522 label->base.source_position = token.source_position;
9523 label->statement = statement;
9528 if (token.type == '}') {
9529 /* TODO only warn? */
9530 if (warning.other && false) {
9531 warningf(HERE, "label at end of compound statement");
9532 statement->label.statement = create_empty_statement();
9534 errorf(HERE, "label at end of compound statement");
9535 statement->label.statement = create_invalid_statement();
9537 } else if (token.type == ';') {
9538 /* Eat an empty statement here, to avoid the warning about an empty
9539 * statement after a label. label:; is commonly used to have a label
9540 * before a closing brace. */
9541 statement->label.statement = create_empty_statement();
9544 statement_t *const inner_stmt = parse_statement();
9545 statement->label.statement = inner_stmt;
9546 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9547 errorf(&inner_stmt->base.source_position, "declaration after label");
9551 /* remember the labels in a list for later checking */
9552 *label_anchor = &statement->label;
9553 label_anchor = &statement->label.next;
9560 * Parse an if statement.
9562 static statement_t *parse_if(void)
9564 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9568 PUSH_PARENT(statement);
9570 add_anchor_token('{');
9572 expect('(', end_error);
9573 add_anchor_token(')');
9574 expression_t *const expr = parse_expression();
9575 statement->ifs.condition = expr;
9576 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9578 semantic_condition(expr, "condition of 'if'-statment");
9579 mark_vars_read(expr, NULL);
9580 rem_anchor_token(')');
9581 expect(')', end_error);
9584 rem_anchor_token('{');
9586 add_anchor_token(T_else);
9587 statement_t *const true_stmt = parse_statement();
9588 statement->ifs.true_statement = true_stmt;
9589 rem_anchor_token(T_else);
9591 if (token.type == T_else) {
9593 statement->ifs.false_statement = parse_statement();
9594 } else if (warning.parentheses &&
9595 true_stmt->kind == STATEMENT_IF &&
9596 true_stmt->ifs.false_statement != NULL) {
9597 warningf(&true_stmt->base.source_position,
9598 "suggest explicit braces to avoid ambiguous 'else'");
9606 * Check that all enums are handled in a switch.
9608 * @param statement the switch statement to check
9610 static void check_enum_cases(const switch_statement_t *statement)
9612 const type_t *type = skip_typeref(statement->expression->base.type);
9613 if (! is_type_enum(type))
9615 const enum_type_t *enumt = &type->enumt;
9617 /* if we have a default, no warnings */
9618 if (statement->default_label != NULL)
9621 /* FIXME: calculation of value should be done while parsing */
9622 /* TODO: quadratic algorithm here. Change to an n log n one */
9623 long last_value = -1;
9624 const entity_t *entry = enumt->enume->base.next;
9625 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9626 entry = entry->base.next) {
9627 const expression_t *expression = entry->enum_value.value;
9628 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9630 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9631 if (l->expression == NULL)
9633 if (l->first_case <= value && value <= l->last_case) {
9639 warningf(&statement->base.source_position,
9640 "enumeration value '%Y' not handled in switch",
9641 entry->base.symbol);
9648 * Parse a switch statement.
9650 static statement_t *parse_switch(void)
9652 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9656 PUSH_PARENT(statement);
9658 expect('(', end_error);
9659 add_anchor_token(')');
9660 expression_t *const expr = parse_expression();
9661 mark_vars_read(expr, NULL);
9662 type_t * type = skip_typeref(expr->base.type);
9663 if (is_type_integer(type)) {
9664 type = promote_integer(type);
9665 if (warning.traditional) {
9666 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9667 warningf(&expr->base.source_position,
9668 "'%T' switch expression not converted to '%T' in ISO C",
9672 } else if (is_type_valid(type)) {
9673 errorf(&expr->base.source_position,
9674 "switch quantity is not an integer, but '%T'", type);
9675 type = type_error_type;
9677 statement->switchs.expression = create_implicit_cast(expr, type);
9678 expect(')', end_error);
9679 rem_anchor_token(')');
9681 switch_statement_t *rem = current_switch;
9682 current_switch = &statement->switchs;
9683 statement->switchs.body = parse_statement();
9684 current_switch = rem;
9686 if (warning.switch_default &&
9687 statement->switchs.default_label == NULL) {
9688 warningf(&statement->base.source_position, "switch has no default case");
9690 if (warning.switch_enum)
9691 check_enum_cases(&statement->switchs);
9697 return create_invalid_statement();
9700 static statement_t *parse_loop_body(statement_t *const loop)
9702 statement_t *const rem = current_loop;
9703 current_loop = loop;
9705 statement_t *const body = parse_statement();
9712 * Parse a while statement.
9714 static statement_t *parse_while(void)
9716 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9720 PUSH_PARENT(statement);
9722 expect('(', end_error);
9723 add_anchor_token(')');
9724 expression_t *const cond = parse_expression();
9725 statement->whiles.condition = cond;
9726 /* §6.8.5:2 The controlling expression of an iteration statement shall
9727 * have scalar type. */
9728 semantic_condition(cond, "condition of 'while'-statement");
9729 mark_vars_read(cond, NULL);
9730 rem_anchor_token(')');
9731 expect(')', end_error);
9733 statement->whiles.body = parse_loop_body(statement);
9739 return create_invalid_statement();
9743 * Parse a do statement.
9745 static statement_t *parse_do(void)
9747 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9751 PUSH_PARENT(statement);
9753 add_anchor_token(T_while);
9754 statement->do_while.body = parse_loop_body(statement);
9755 rem_anchor_token(T_while);
9757 expect(T_while, end_error);
9758 expect('(', end_error);
9759 add_anchor_token(')');
9760 expression_t *const cond = parse_expression();
9761 statement->do_while.condition = cond;
9762 /* §6.8.5:2 The controlling expression of an iteration statement shall
9763 * have scalar type. */
9764 semantic_condition(cond, "condition of 'do-while'-statement");
9765 mark_vars_read(cond, NULL);
9766 rem_anchor_token(')');
9767 expect(')', end_error);
9768 expect(';', end_error);
9774 return create_invalid_statement();
9778 * Parse a for statement.
9780 static statement_t *parse_for(void)
9782 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9786 expect('(', end_error1);
9787 add_anchor_token(')');
9789 PUSH_PARENT(statement);
9791 size_t const top = environment_top();
9792 scope_t *old_scope = scope_push(&statement->fors.scope);
9794 bool old_gcc_extension;
9795 while (token.type == T___extension__) {
9797 in_gcc_extension = true;
9800 if (token.type == ';') {
9802 } else if (is_declaration_specifier(&token, false)) {
9803 parse_declaration(record_entity, DECL_FLAGS_NONE);
9805 add_anchor_token(';');
9806 expression_t *const init = parse_expression();
9807 statement->fors.initialisation = init;
9808 mark_vars_read(init, ENT_ANY);
9809 if (warning.unused_value && !expression_has_effect(init)) {
9810 warningf(&init->base.source_position,
9811 "initialisation of 'for'-statement has no effect");
9813 rem_anchor_token(';');
9814 expect(';', end_error2);
9816 in_gcc_extension = old_gcc_extension;
9818 if (token.type != ';') {
9819 add_anchor_token(';');
9820 expression_t *const cond = parse_expression();
9821 statement->fors.condition = cond;
9822 /* §6.8.5:2 The controlling expression of an iteration statement
9823 * shall have scalar type. */
9824 semantic_condition(cond, "condition of 'for'-statement");
9825 mark_vars_read(cond, NULL);
9826 rem_anchor_token(';');
9828 expect(';', end_error2);
9829 if (token.type != ')') {
9830 expression_t *const step = parse_expression();
9831 statement->fors.step = step;
9832 mark_vars_read(step, ENT_ANY);
9833 if (warning.unused_value && !expression_has_effect(step)) {
9834 warningf(&step->base.source_position,
9835 "step of 'for'-statement has no effect");
9838 expect(')', end_error2);
9839 rem_anchor_token(')');
9840 statement->fors.body = parse_loop_body(statement);
9842 assert(current_scope == &statement->fors.scope);
9843 scope_pop(old_scope);
9844 environment_pop_to(top);
9851 rem_anchor_token(')');
9852 assert(current_scope == &statement->fors.scope);
9853 scope_pop(old_scope);
9854 environment_pop_to(top);
9858 return create_invalid_statement();
9862 * Parse a goto statement.
9864 static statement_t *parse_goto(void)
9866 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9869 if (GNU_MODE && token.type == '*') {
9871 expression_t *expression = parse_expression();
9872 mark_vars_read(expression, NULL);
9874 /* Argh: although documentation says the expression must be of type void*,
9875 * gcc accepts anything that can be casted into void* without error */
9876 type_t *type = expression->base.type;
9878 if (type != type_error_type) {
9879 if (!is_type_pointer(type) && !is_type_integer(type)) {
9880 errorf(&expression->base.source_position,
9881 "cannot convert to a pointer type");
9882 } else if (warning.other && type != type_void_ptr) {
9883 warningf(&expression->base.source_position,
9884 "type of computed goto expression should be 'void*' not '%T'", type);
9886 expression = create_implicit_cast(expression, type_void_ptr);
9889 statement->gotos.expression = expression;
9890 } else if (token.type == T_IDENTIFIER) {
9891 symbol_t *symbol = token.v.symbol;
9893 statement->gotos.label = get_label(symbol);
9896 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9898 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9903 /* remember the goto's in a list for later checking */
9904 *goto_anchor = &statement->gotos;
9905 goto_anchor = &statement->gotos.next;
9907 expect(';', end_error);
9911 return create_invalid_statement();
9915 * Parse a continue statement.
9917 static statement_t *parse_continue(void)
9919 if (current_loop == NULL) {
9920 errorf(HERE, "continue statement not within loop");
9923 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9926 expect(';', end_error);
9933 * Parse a break statement.
9935 static statement_t *parse_break(void)
9937 if (current_switch == NULL && current_loop == NULL) {
9938 errorf(HERE, "break statement not within loop or switch");
9941 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9944 expect(';', end_error);
9951 * Parse a __leave statement.
9953 static statement_t *parse_leave_statement(void)
9955 if (current_try == NULL) {
9956 errorf(HERE, "__leave statement not within __try");
9959 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9962 expect(';', end_error);
9969 * Check if a given entity represents a local variable.
9971 static bool is_local_variable(const entity_t *entity)
9973 if (entity->kind != ENTITY_VARIABLE)
9976 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9977 case STORAGE_CLASS_AUTO:
9978 case STORAGE_CLASS_REGISTER: {
9979 const type_t *type = skip_typeref(entity->declaration.type);
9980 if (is_type_function(type)) {
9992 * Check if a given expression represents a local variable.
9994 static bool expression_is_local_variable(const expression_t *expression)
9996 if (expression->base.kind != EXPR_REFERENCE) {
9999 const entity_t *entity = expression->reference.entity;
10000 return is_local_variable(entity);
10004 * Check if a given expression represents a local variable and
10005 * return its declaration then, else return NULL.
10007 entity_t *expression_is_variable(const expression_t *expression)
10009 if (expression->base.kind != EXPR_REFERENCE) {
10012 entity_t *entity = expression->reference.entity;
10013 if (entity->kind != ENTITY_VARIABLE)
10020 * Parse a return statement.
10022 static statement_t *parse_return(void)
10026 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10028 expression_t *return_value = NULL;
10029 if (token.type != ';') {
10030 return_value = parse_expression();
10031 mark_vars_read(return_value, NULL);
10034 const type_t *const func_type = skip_typeref(current_function->base.type);
10035 assert(is_type_function(func_type));
10036 type_t *const return_type = skip_typeref(func_type->function.return_type);
10038 source_position_t const *const pos = &statement->base.source_position;
10039 if (return_value != NULL) {
10040 type_t *return_value_type = skip_typeref(return_value->base.type);
10042 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10043 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10044 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10045 /* Only warn in C mode, because GCC does the same */
10046 if (c_mode & _CXX || strict_mode) {
10048 "'return' with a value, in function returning 'void'");
10049 } else if (warning.other) {
10051 "'return' with a value, in function returning 'void'");
10053 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10054 /* Only warn in C mode, because GCC does the same */
10057 "'return' with expression in function returning 'void'");
10058 } else if (warning.other) {
10060 "'return' with expression in function returning 'void'");
10064 assign_error_t error = semantic_assign(return_type, return_value);
10065 report_assign_error(error, return_type, return_value, "'return'",
10068 return_value = create_implicit_cast(return_value, return_type);
10069 /* check for returning address of a local var */
10070 if (warning.other && return_value != NULL
10071 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10072 const expression_t *expression = return_value->unary.value;
10073 if (expression_is_local_variable(expression)) {
10074 warningf(pos, "function returns address of local variable");
10077 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10078 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10079 if (c_mode & _CXX || strict_mode) {
10081 "'return' without value, in function returning non-void");
10084 "'return' without value, in function returning non-void");
10087 statement->returns.value = return_value;
10089 expect(';', end_error);
10096 * Parse a declaration statement.
10098 static statement_t *parse_declaration_statement(void)
10100 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10102 entity_t *before = current_scope->last_entity;
10104 parse_external_declaration();
10106 parse_declaration(record_entity, DECL_FLAGS_NONE);
10109 declaration_statement_t *const decl = &statement->declaration;
10110 entity_t *const begin =
10111 before != NULL ? before->base.next : current_scope->entities;
10112 decl->declarations_begin = begin;
10113 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10119 * Parse an expression statement, ie. expr ';'.
10121 static statement_t *parse_expression_statement(void)
10123 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10125 expression_t *const expr = parse_expression();
10126 statement->expression.expression = expr;
10127 mark_vars_read(expr, ENT_ANY);
10129 expect(';', end_error);
10136 * Parse a microsoft __try { } __finally { } or
10137 * __try{ } __except() { }
10139 static statement_t *parse_ms_try_statment(void)
10141 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10144 PUSH_PARENT(statement);
10146 ms_try_statement_t *rem = current_try;
10147 current_try = &statement->ms_try;
10148 statement->ms_try.try_statement = parse_compound_statement(false);
10153 if (token.type == T___except) {
10155 expect('(', end_error);
10156 add_anchor_token(')');
10157 expression_t *const expr = parse_expression();
10158 mark_vars_read(expr, NULL);
10159 type_t * type = skip_typeref(expr->base.type);
10160 if (is_type_integer(type)) {
10161 type = promote_integer(type);
10162 } else if (is_type_valid(type)) {
10163 errorf(&expr->base.source_position,
10164 "__expect expression is not an integer, but '%T'", type);
10165 type = type_error_type;
10167 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10168 rem_anchor_token(')');
10169 expect(')', end_error);
10170 statement->ms_try.final_statement = parse_compound_statement(false);
10171 } else if (token.type == T__finally) {
10173 statement->ms_try.final_statement = parse_compound_statement(false);
10175 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10176 return create_invalid_statement();
10180 return create_invalid_statement();
10183 static statement_t *parse_empty_statement(void)
10185 if (warning.empty_statement) {
10186 warningf(HERE, "statement is empty");
10188 statement_t *const statement = create_empty_statement();
10193 static statement_t *parse_local_label_declaration(void)
10195 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10199 entity_t *begin = NULL, *end = NULL;
10202 if (token.type != T_IDENTIFIER) {
10203 parse_error_expected("while parsing local label declaration",
10204 T_IDENTIFIER, NULL);
10207 symbol_t *symbol = token.v.symbol;
10208 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10209 if (entity != NULL && entity->base.parent_scope == current_scope) {
10210 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10211 symbol, &entity->base.source_position);
10213 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10215 entity->base.parent_scope = current_scope;
10216 entity->base.namespc = NAMESPACE_LABEL;
10217 entity->base.source_position = token.source_position;
10218 entity->base.symbol = symbol;
10221 end->base.next = entity;
10226 environment_push(entity);
10230 if (token.type != ',')
10236 statement->declaration.declarations_begin = begin;
10237 statement->declaration.declarations_end = end;
10241 static void parse_namespace_definition(void)
10245 entity_t *entity = NULL;
10246 symbol_t *symbol = NULL;
10248 if (token.type == T_IDENTIFIER) {
10249 symbol = token.v.symbol;
10252 entity = get_entity(symbol, NAMESPACE_NORMAL);
10253 if (entity != NULL &&
10254 entity->kind != ENTITY_NAMESPACE &&
10255 entity->base.parent_scope == current_scope) {
10256 if (!is_error_entity(entity)) {
10257 error_redefined_as_different_kind(&token.source_position,
10258 entity, ENTITY_NAMESPACE);
10264 if (entity == NULL) {
10265 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10266 entity->base.symbol = symbol;
10267 entity->base.source_position = token.source_position;
10268 entity->base.namespc = NAMESPACE_NORMAL;
10269 entity->base.parent_scope = current_scope;
10272 if (token.type == '=') {
10273 /* TODO: parse namespace alias */
10274 panic("namespace alias definition not supported yet");
10277 environment_push(entity);
10278 append_entity(current_scope, entity);
10280 size_t const top = environment_top();
10281 scope_t *old_scope = scope_push(&entity->namespacee.members);
10283 expect('{', end_error);
10285 expect('}', end_error);
10288 assert(current_scope == &entity->namespacee.members);
10289 scope_pop(old_scope);
10290 environment_pop_to(top);
10294 * Parse a statement.
10295 * There's also parse_statement() which additionally checks for
10296 * "statement has no effect" warnings
10298 static statement_t *intern_parse_statement(void)
10300 statement_t *statement = NULL;
10302 /* declaration or statement */
10303 add_anchor_token(';');
10304 switch (token.type) {
10305 case T_IDENTIFIER: {
10306 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10307 if (la1_type == ':') {
10308 statement = parse_label_statement();
10309 } else if (is_typedef_symbol(token.v.symbol)) {
10310 statement = parse_declaration_statement();
10312 /* it's an identifier, the grammar says this must be an
10313 * expression statement. However it is common that users mistype
10314 * declaration types, so we guess a bit here to improve robustness
10315 * for incorrect programs */
10316 switch (la1_type) {
10319 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10320 goto expression_statment;
10325 statement = parse_declaration_statement();
10329 expression_statment:
10330 statement = parse_expression_statement();
10337 case T___extension__:
10338 /* This can be a prefix to a declaration or an expression statement.
10339 * We simply eat it now and parse the rest with tail recursion. */
10342 } while (token.type == T___extension__);
10343 bool old_gcc_extension = in_gcc_extension;
10344 in_gcc_extension = true;
10345 statement = intern_parse_statement();
10346 in_gcc_extension = old_gcc_extension;
10350 statement = parse_declaration_statement();
10354 statement = parse_local_label_declaration();
10357 case ';': statement = parse_empty_statement(); break;
10358 case '{': statement = parse_compound_statement(false); break;
10359 case T___leave: statement = parse_leave_statement(); break;
10360 case T___try: statement = parse_ms_try_statment(); break;
10361 case T_asm: statement = parse_asm_statement(); break;
10362 case T_break: statement = parse_break(); break;
10363 case T_case: statement = parse_case_statement(); break;
10364 case T_continue: statement = parse_continue(); break;
10365 case T_default: statement = parse_default_statement(); break;
10366 case T_do: statement = parse_do(); break;
10367 case T_for: statement = parse_for(); break;
10368 case T_goto: statement = parse_goto(); break;
10369 case T_if: statement = parse_if(); break;
10370 case T_return: statement = parse_return(); break;
10371 case T_switch: statement = parse_switch(); break;
10372 case T_while: statement = parse_while(); break;
10375 statement = parse_expression_statement();
10379 errorf(HERE, "unexpected token %K while parsing statement", &token);
10380 statement = create_invalid_statement();
10385 rem_anchor_token(';');
10387 assert(statement != NULL
10388 && statement->base.source_position.input_name != NULL);
10394 * parse a statement and emits "statement has no effect" warning if needed
10395 * (This is really a wrapper around intern_parse_statement with check for 1
10396 * single warning. It is needed, because for statement expressions we have
10397 * to avoid the warning on the last statement)
10399 static statement_t *parse_statement(void)
10401 statement_t *statement = intern_parse_statement();
10403 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10404 expression_t *expression = statement->expression.expression;
10405 if (!expression_has_effect(expression)) {
10406 warningf(&expression->base.source_position,
10407 "statement has no effect");
10415 * Parse a compound statement.
10417 static statement_t *parse_compound_statement(bool inside_expression_statement)
10419 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10421 PUSH_PARENT(statement);
10424 add_anchor_token('}');
10425 /* tokens, which can start a statement */
10426 /* TODO MS, __builtin_FOO */
10427 add_anchor_token('!');
10428 add_anchor_token('&');
10429 add_anchor_token('(');
10430 add_anchor_token('*');
10431 add_anchor_token('+');
10432 add_anchor_token('-');
10433 add_anchor_token('{');
10434 add_anchor_token('~');
10435 add_anchor_token(T_CHARACTER_CONSTANT);
10436 add_anchor_token(T_COLONCOLON);
10437 add_anchor_token(T_FLOATINGPOINT);
10438 add_anchor_token(T_IDENTIFIER);
10439 add_anchor_token(T_INTEGER);
10440 add_anchor_token(T_MINUSMINUS);
10441 add_anchor_token(T_PLUSPLUS);
10442 add_anchor_token(T_STRING_LITERAL);
10443 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10444 add_anchor_token(T_WIDE_STRING_LITERAL);
10445 add_anchor_token(T__Bool);
10446 add_anchor_token(T__Complex);
10447 add_anchor_token(T__Imaginary);
10448 add_anchor_token(T___FUNCTION__);
10449 add_anchor_token(T___PRETTY_FUNCTION__);
10450 add_anchor_token(T___alignof__);
10451 add_anchor_token(T___attribute__);
10452 add_anchor_token(T___builtin_va_start);
10453 add_anchor_token(T___extension__);
10454 add_anchor_token(T___func__);
10455 add_anchor_token(T___imag__);
10456 add_anchor_token(T___label__);
10457 add_anchor_token(T___real__);
10458 add_anchor_token(T___thread);
10459 add_anchor_token(T_asm);
10460 add_anchor_token(T_auto);
10461 add_anchor_token(T_bool);
10462 add_anchor_token(T_break);
10463 add_anchor_token(T_case);
10464 add_anchor_token(T_char);
10465 add_anchor_token(T_class);
10466 add_anchor_token(T_const);
10467 add_anchor_token(T_const_cast);
10468 add_anchor_token(T_continue);
10469 add_anchor_token(T_default);
10470 add_anchor_token(T_delete);
10471 add_anchor_token(T_double);
10472 add_anchor_token(T_do);
10473 add_anchor_token(T_dynamic_cast);
10474 add_anchor_token(T_enum);
10475 add_anchor_token(T_extern);
10476 add_anchor_token(T_false);
10477 add_anchor_token(T_float);
10478 add_anchor_token(T_for);
10479 add_anchor_token(T_goto);
10480 add_anchor_token(T_if);
10481 add_anchor_token(T_inline);
10482 add_anchor_token(T_int);
10483 add_anchor_token(T_long);
10484 add_anchor_token(T_new);
10485 add_anchor_token(T_operator);
10486 add_anchor_token(T_register);
10487 add_anchor_token(T_reinterpret_cast);
10488 add_anchor_token(T_restrict);
10489 add_anchor_token(T_return);
10490 add_anchor_token(T_short);
10491 add_anchor_token(T_signed);
10492 add_anchor_token(T_sizeof);
10493 add_anchor_token(T_static);
10494 add_anchor_token(T_static_cast);
10495 add_anchor_token(T_struct);
10496 add_anchor_token(T_switch);
10497 add_anchor_token(T_template);
10498 add_anchor_token(T_this);
10499 add_anchor_token(T_throw);
10500 add_anchor_token(T_true);
10501 add_anchor_token(T_try);
10502 add_anchor_token(T_typedef);
10503 add_anchor_token(T_typeid);
10504 add_anchor_token(T_typename);
10505 add_anchor_token(T_typeof);
10506 add_anchor_token(T_union);
10507 add_anchor_token(T_unsigned);
10508 add_anchor_token(T_using);
10509 add_anchor_token(T_void);
10510 add_anchor_token(T_volatile);
10511 add_anchor_token(T_wchar_t);
10512 add_anchor_token(T_while);
10514 size_t const top = environment_top();
10515 scope_t *old_scope = scope_push(&statement->compound.scope);
10517 statement_t **anchor = &statement->compound.statements;
10518 bool only_decls_so_far = true;
10519 while (token.type != '}') {
10520 if (token.type == T_EOF) {
10521 errorf(&statement->base.source_position,
10522 "EOF while parsing compound statement");
10525 statement_t *sub_statement = intern_parse_statement();
10526 if (is_invalid_statement(sub_statement)) {
10527 /* an error occurred. if we are at an anchor, return */
10533 if (warning.declaration_after_statement) {
10534 if (sub_statement->kind != STATEMENT_DECLARATION) {
10535 only_decls_so_far = false;
10536 } else if (!only_decls_so_far) {
10537 warningf(&sub_statement->base.source_position,
10538 "ISO C90 forbids mixed declarations and code");
10542 *anchor = sub_statement;
10544 while (sub_statement->base.next != NULL)
10545 sub_statement = sub_statement->base.next;
10547 anchor = &sub_statement->base.next;
10551 /* look over all statements again to produce no effect warnings */
10552 if (warning.unused_value) {
10553 statement_t *sub_statement = statement->compound.statements;
10554 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10555 if (sub_statement->kind != STATEMENT_EXPRESSION)
10557 /* don't emit a warning for the last expression in an expression
10558 * statement as it has always an effect */
10559 if (inside_expression_statement && sub_statement->base.next == NULL)
10562 expression_t *expression = sub_statement->expression.expression;
10563 if (!expression_has_effect(expression)) {
10564 warningf(&expression->base.source_position,
10565 "statement has no effect");
10571 rem_anchor_token(T_while);
10572 rem_anchor_token(T_wchar_t);
10573 rem_anchor_token(T_volatile);
10574 rem_anchor_token(T_void);
10575 rem_anchor_token(T_using);
10576 rem_anchor_token(T_unsigned);
10577 rem_anchor_token(T_union);
10578 rem_anchor_token(T_typeof);
10579 rem_anchor_token(T_typename);
10580 rem_anchor_token(T_typeid);
10581 rem_anchor_token(T_typedef);
10582 rem_anchor_token(T_try);
10583 rem_anchor_token(T_true);
10584 rem_anchor_token(T_throw);
10585 rem_anchor_token(T_this);
10586 rem_anchor_token(T_template);
10587 rem_anchor_token(T_switch);
10588 rem_anchor_token(T_struct);
10589 rem_anchor_token(T_static_cast);
10590 rem_anchor_token(T_static);
10591 rem_anchor_token(T_sizeof);
10592 rem_anchor_token(T_signed);
10593 rem_anchor_token(T_short);
10594 rem_anchor_token(T_return);
10595 rem_anchor_token(T_restrict);
10596 rem_anchor_token(T_reinterpret_cast);
10597 rem_anchor_token(T_register);
10598 rem_anchor_token(T_operator);
10599 rem_anchor_token(T_new);
10600 rem_anchor_token(T_long);
10601 rem_anchor_token(T_int);
10602 rem_anchor_token(T_inline);
10603 rem_anchor_token(T_if);
10604 rem_anchor_token(T_goto);
10605 rem_anchor_token(T_for);
10606 rem_anchor_token(T_float);
10607 rem_anchor_token(T_false);
10608 rem_anchor_token(T_extern);
10609 rem_anchor_token(T_enum);
10610 rem_anchor_token(T_dynamic_cast);
10611 rem_anchor_token(T_do);
10612 rem_anchor_token(T_double);
10613 rem_anchor_token(T_delete);
10614 rem_anchor_token(T_default);
10615 rem_anchor_token(T_continue);
10616 rem_anchor_token(T_const_cast);
10617 rem_anchor_token(T_const);
10618 rem_anchor_token(T_class);
10619 rem_anchor_token(T_char);
10620 rem_anchor_token(T_case);
10621 rem_anchor_token(T_break);
10622 rem_anchor_token(T_bool);
10623 rem_anchor_token(T_auto);
10624 rem_anchor_token(T_asm);
10625 rem_anchor_token(T___thread);
10626 rem_anchor_token(T___real__);
10627 rem_anchor_token(T___label__);
10628 rem_anchor_token(T___imag__);
10629 rem_anchor_token(T___func__);
10630 rem_anchor_token(T___extension__);
10631 rem_anchor_token(T___builtin_va_start);
10632 rem_anchor_token(T___attribute__);
10633 rem_anchor_token(T___alignof__);
10634 rem_anchor_token(T___PRETTY_FUNCTION__);
10635 rem_anchor_token(T___FUNCTION__);
10636 rem_anchor_token(T__Imaginary);
10637 rem_anchor_token(T__Complex);
10638 rem_anchor_token(T__Bool);
10639 rem_anchor_token(T_WIDE_STRING_LITERAL);
10640 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10641 rem_anchor_token(T_STRING_LITERAL);
10642 rem_anchor_token(T_PLUSPLUS);
10643 rem_anchor_token(T_MINUSMINUS);
10644 rem_anchor_token(T_INTEGER);
10645 rem_anchor_token(T_IDENTIFIER);
10646 rem_anchor_token(T_FLOATINGPOINT);
10647 rem_anchor_token(T_COLONCOLON);
10648 rem_anchor_token(T_CHARACTER_CONSTANT);
10649 rem_anchor_token('~');
10650 rem_anchor_token('{');
10651 rem_anchor_token('-');
10652 rem_anchor_token('+');
10653 rem_anchor_token('*');
10654 rem_anchor_token('(');
10655 rem_anchor_token('&');
10656 rem_anchor_token('!');
10657 rem_anchor_token('}');
10658 assert(current_scope == &statement->compound.scope);
10659 scope_pop(old_scope);
10660 environment_pop_to(top);
10667 * Check for unused global static functions and variables
10669 static void check_unused_globals(void)
10671 if (!warning.unused_function && !warning.unused_variable)
10674 for (const entity_t *entity = file_scope->entities; entity != NULL;
10675 entity = entity->base.next) {
10676 if (!is_declaration(entity))
10679 const declaration_t *declaration = &entity->declaration;
10680 if (declaration->used ||
10681 declaration->modifiers & DM_UNUSED ||
10682 declaration->modifiers & DM_USED ||
10683 declaration->storage_class != STORAGE_CLASS_STATIC)
10686 type_t *const type = declaration->type;
10688 if (entity->kind == ENTITY_FUNCTION) {
10689 /* inhibit warning for static inline functions */
10690 if (entity->function.is_inline)
10693 s = entity->function.statement != NULL ? "defined" : "declared";
10698 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10699 type, declaration->base.symbol, s);
10703 static void parse_global_asm(void)
10705 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10708 expect('(', end_error);
10710 statement->asms.asm_text = parse_string_literals();
10711 statement->base.next = unit->global_asm;
10712 unit->global_asm = statement;
10714 expect(')', end_error);
10715 expect(';', end_error);
10720 static void parse_linkage_specification(void)
10723 assert(token.type == T_STRING_LITERAL);
10725 const char *linkage = parse_string_literals().begin;
10727 linkage_kind_t old_linkage = current_linkage;
10728 linkage_kind_t new_linkage;
10729 if (strcmp(linkage, "C") == 0) {
10730 new_linkage = LINKAGE_C;
10731 } else if (strcmp(linkage, "C++") == 0) {
10732 new_linkage = LINKAGE_CXX;
10734 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10735 new_linkage = LINKAGE_INVALID;
10737 current_linkage = new_linkage;
10739 if (token.type == '{') {
10742 expect('}', end_error);
10748 assert(current_linkage == new_linkage);
10749 current_linkage = old_linkage;
10752 static void parse_external(void)
10754 switch (token.type) {
10755 DECLARATION_START_NO_EXTERN
10757 case T___extension__:
10758 /* tokens below are for implicit int */
10759 case '&': /* & x; -> int& x; (and error later, because C++ has no
10761 case '*': /* * x; -> int* x; */
10762 case '(': /* (x); -> int (x); */
10763 parse_external_declaration();
10767 if (look_ahead(1)->type == T_STRING_LITERAL) {
10768 parse_linkage_specification();
10770 parse_external_declaration();
10775 parse_global_asm();
10779 parse_namespace_definition();
10783 if (!strict_mode) {
10785 warningf(HERE, "stray ';' outside of function");
10792 errorf(HERE, "stray %K outside of function", &token);
10793 if (token.type == '(' || token.type == '{' || token.type == '[')
10794 eat_until_matching_token(token.type);
10800 static void parse_externals(void)
10802 add_anchor_token('}');
10803 add_anchor_token(T_EOF);
10806 unsigned char token_anchor_copy[T_LAST_TOKEN];
10807 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10810 while (token.type != T_EOF && token.type != '}') {
10812 bool anchor_leak = false;
10813 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10814 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10816 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10817 anchor_leak = true;
10820 if (in_gcc_extension) {
10821 errorf(HERE, "Leaked __extension__");
10822 anchor_leak = true;
10832 rem_anchor_token(T_EOF);
10833 rem_anchor_token('}');
10837 * Parse a translation unit.
10839 static void parse_translation_unit(void)
10841 add_anchor_token(T_EOF);
10846 if (token.type == T_EOF)
10849 errorf(HERE, "stray %K outside of function", &token);
10850 if (token.type == '(' || token.type == '{' || token.type == '[')
10851 eat_until_matching_token(token.type);
10859 * @return the translation unit or NULL if errors occurred.
10861 void start_parsing(void)
10863 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10864 label_stack = NEW_ARR_F(stack_entry_t, 0);
10865 diagnostic_count = 0;
10869 type_set_output(stderr);
10870 ast_set_output(stderr);
10872 assert(unit == NULL);
10873 unit = allocate_ast_zero(sizeof(unit[0]));
10875 assert(file_scope == NULL);
10876 file_scope = &unit->scope;
10878 assert(current_scope == NULL);
10879 scope_push(&unit->scope);
10881 create_gnu_builtins();
10883 create_microsoft_intrinsics();
10886 translation_unit_t *finish_parsing(void)
10888 assert(current_scope == &unit->scope);
10891 assert(file_scope == &unit->scope);
10892 check_unused_globals();
10895 DEL_ARR_F(environment_stack);
10896 DEL_ARR_F(label_stack);
10898 translation_unit_t *result = unit;
10903 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10904 * are given length one. */
10905 static void complete_incomplete_arrays(void)
10907 size_t n = ARR_LEN(incomplete_arrays);
10908 for (size_t i = 0; i != n; ++i) {
10909 declaration_t *const decl = incomplete_arrays[i];
10910 type_t *const orig_type = decl->type;
10911 type_t *const type = skip_typeref(orig_type);
10913 if (!is_type_incomplete(type))
10916 if (warning.other) {
10917 warningf(&decl->base.source_position,
10918 "array '%#T' assumed to have one element",
10919 orig_type, decl->base.symbol);
10922 type_t *const new_type = duplicate_type(type);
10923 new_type->array.size_constant = true;
10924 new_type->array.has_implicit_size = true;
10925 new_type->array.size = 1;
10927 type_t *const result = identify_new_type(new_type);
10929 decl->type = result;
10935 lookahead_bufpos = 0;
10936 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10939 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10940 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10941 parse_translation_unit();
10942 complete_incomplete_arrays();
10943 DEL_ARR_F(incomplete_arrays);
10944 incomplete_arrays = NULL;
10948 * create a builtin function.
10950 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10952 symbol_t *symbol = symbol_table_insert(name);
10953 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10954 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10955 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10956 entity->declaration.type = function_type;
10957 entity->declaration.implicit = true;
10958 entity->base.symbol = symbol;
10959 entity->base.source_position = builtin_source_position;
10961 entity->function.btk = kind;
10963 record_entity(entity, /*is_definition=*/false);
10969 * Create predefined gnu builtins.
10971 static void create_gnu_builtins(void)
10973 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10975 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10976 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10977 GNU_BUILTIN(inf, make_function_0_type(type_double));
10978 GNU_BUILTIN(inff, make_function_0_type(type_float));
10979 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
10980 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
10981 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
10982 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
10983 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
10984 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
10985 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10986 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10987 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
10988 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
10989 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
10990 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
10991 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
10992 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
10993 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
10999 * Create predefined MS intrinsics.
11001 static void create_microsoft_intrinsics(void)
11003 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11005 /* intrinsics for all architectures */
11006 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11007 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11008 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11009 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11010 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11011 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11012 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11014 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11015 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11016 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11017 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11020 MS_BUILTIN(_enable, make_function_0_type(type_void));
11021 MS_BUILTIN(_disable, make_function_0_type(type_void));
11022 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11023 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11024 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11025 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11026 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11027 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11028 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11029 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11030 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11031 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11032 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11034 if (machine_size <= 32) {
11035 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11036 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11038 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11039 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11046 * Initialize the parser.
11048 void init_parser(void)
11050 sym_anonymous = symbol_table_insert("<anonymous>");
11052 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11054 init_expression_parsers();
11055 obstack_init(&temp_obst);
11057 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11058 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11062 * Terminate the parser.
11064 void exit_parser(void)
11066 obstack_free(&temp_obst, NULL);