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) {
1337 /* maybe we need more tokens ... add them on demand */
1338 return token.v.symbol;
1344 static attribute_t *parse_attribute_gnu_single(void)
1346 /* parse "any-word" */
1347 symbol_t *symbol = get_symbol_from_token();
1348 if (symbol == NULL) {
1349 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1353 const char *name = symbol->string;
1356 attribute_kind_t kind;
1357 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1358 const char *attribute_name = get_attribute_name(kind);
1359 if (attribute_name != NULL
1360 && strcmp_underscore(attribute_name, name) == 0)
1364 if (kind >= ATTRIBUTE_GNU_LAST) {
1365 if (warning.attribute) {
1366 warningf(HERE, "unknown attribute '%s' ignored", name);
1368 /* TODO: we should still save the attribute in the list... */
1369 kind = ATTRIBUTE_UNKNOWN;
1372 attribute_t *attribute = allocate_attribute_zero(kind);
1374 /* parse arguments */
1375 if (token.type == '(') {
1377 attribute->a.arguments = parse_attribute_arguments();
1386 static attribute_t *parse_attribute_gnu(void)
1388 attribute_t *first = NULL;
1389 attribute_t *last = NULL;
1391 eat(T___attribute__);
1392 expect('(', end_error);
1393 expect('(', end_error);
1395 if (token.type == ')') {
1397 expect(')', end_error);
1402 attribute_t *attribute = parse_attribute_gnu_single();
1403 if (attribute == NULL)
1409 last->next = attribute;
1413 if (token.type == ')') {
1417 expect(',', end_error);
1419 expect(')', end_error);
1425 /** Parse attributes. */
1426 static attribute_t *parse_attributes(attribute_t *first)
1428 attribute_t *last = first;
1431 while (last->next != NULL)
1435 attribute_t *attribute;
1436 switch (token.type) {
1437 case T___attribute__:
1438 attribute = parse_attribute_gnu();
1442 attribute = parse_attribute_asm();
1447 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1452 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1455 case T__forceinline:
1457 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1462 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1467 /* TODO record modifier */
1469 warningf(HERE, "Ignoring declaration modifier %K", &token);
1470 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1480 last->next = attribute;
1486 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1488 static entity_t *determine_lhs_ent(expression_t *const expr,
1491 switch (expr->kind) {
1492 case EXPR_REFERENCE: {
1493 entity_t *const entity = expr->reference.entity;
1494 /* we should only find variables as lvalues... */
1495 if (entity->base.kind != ENTITY_VARIABLE
1496 && entity->base.kind != ENTITY_PARAMETER)
1502 case EXPR_ARRAY_ACCESS: {
1503 expression_t *const ref = expr->array_access.array_ref;
1504 entity_t * ent = NULL;
1505 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1506 ent = determine_lhs_ent(ref, lhs_ent);
1509 mark_vars_read(expr->select.compound, lhs_ent);
1511 mark_vars_read(expr->array_access.index, lhs_ent);
1516 if (is_type_compound(skip_typeref(expr->base.type))) {
1517 return determine_lhs_ent(expr->select.compound, lhs_ent);
1519 mark_vars_read(expr->select.compound, lhs_ent);
1524 case EXPR_UNARY_DEREFERENCE: {
1525 expression_t *const val = expr->unary.value;
1526 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1528 return determine_lhs_ent(val->unary.value, lhs_ent);
1530 mark_vars_read(val, NULL);
1536 mark_vars_read(expr, NULL);
1541 #define ENT_ANY ((entity_t*)-1)
1544 * Mark declarations, which are read. This is used to detect variables, which
1548 * x is not marked as "read", because it is only read to calculate its own new
1552 * x and y are not detected as "not read", because multiple variables are
1555 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1557 switch (expr->kind) {
1558 case EXPR_REFERENCE: {
1559 entity_t *const entity = expr->reference.entity;
1560 if (entity->kind != ENTITY_VARIABLE
1561 && entity->kind != ENTITY_PARAMETER)
1564 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1565 if (entity->kind == ENTITY_VARIABLE) {
1566 entity->variable.read = true;
1568 entity->parameter.read = true;
1575 // TODO respect pure/const
1576 mark_vars_read(expr->call.function, NULL);
1577 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1578 mark_vars_read(arg->expression, NULL);
1582 case EXPR_CONDITIONAL:
1583 // TODO lhs_decl should depend on whether true/false have an effect
1584 mark_vars_read(expr->conditional.condition, NULL);
1585 if (expr->conditional.true_expression != NULL)
1586 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1587 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1591 if (lhs_ent == ENT_ANY
1592 && !is_type_compound(skip_typeref(expr->base.type)))
1594 mark_vars_read(expr->select.compound, lhs_ent);
1597 case EXPR_ARRAY_ACCESS: {
1598 expression_t *const ref = expr->array_access.array_ref;
1599 mark_vars_read(ref, lhs_ent);
1600 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1601 mark_vars_read(expr->array_access.index, lhs_ent);
1606 mark_vars_read(expr->va_arge.ap, lhs_ent);
1610 mark_vars_read(expr->va_copye.src, lhs_ent);
1613 case EXPR_UNARY_CAST:
1614 /* Special case: Use void cast to mark a variable as "read" */
1615 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1620 case EXPR_UNARY_THROW:
1621 if (expr->unary.value == NULL)
1624 case EXPR_UNARY_DEREFERENCE:
1625 case EXPR_UNARY_DELETE:
1626 case EXPR_UNARY_DELETE_ARRAY:
1627 if (lhs_ent == ENT_ANY)
1631 case EXPR_UNARY_NEGATE:
1632 case EXPR_UNARY_PLUS:
1633 case EXPR_UNARY_BITWISE_NEGATE:
1634 case EXPR_UNARY_NOT:
1635 case EXPR_UNARY_TAKE_ADDRESS:
1636 case EXPR_UNARY_POSTFIX_INCREMENT:
1637 case EXPR_UNARY_POSTFIX_DECREMENT:
1638 case EXPR_UNARY_PREFIX_INCREMENT:
1639 case EXPR_UNARY_PREFIX_DECREMENT:
1640 case EXPR_UNARY_CAST_IMPLICIT:
1641 case EXPR_UNARY_ASSUME:
1643 mark_vars_read(expr->unary.value, lhs_ent);
1646 case EXPR_BINARY_ADD:
1647 case EXPR_BINARY_SUB:
1648 case EXPR_BINARY_MUL:
1649 case EXPR_BINARY_DIV:
1650 case EXPR_BINARY_MOD:
1651 case EXPR_BINARY_EQUAL:
1652 case EXPR_BINARY_NOTEQUAL:
1653 case EXPR_BINARY_LESS:
1654 case EXPR_BINARY_LESSEQUAL:
1655 case EXPR_BINARY_GREATER:
1656 case EXPR_BINARY_GREATEREQUAL:
1657 case EXPR_BINARY_BITWISE_AND:
1658 case EXPR_BINARY_BITWISE_OR:
1659 case EXPR_BINARY_BITWISE_XOR:
1660 case EXPR_BINARY_LOGICAL_AND:
1661 case EXPR_BINARY_LOGICAL_OR:
1662 case EXPR_BINARY_SHIFTLEFT:
1663 case EXPR_BINARY_SHIFTRIGHT:
1664 case EXPR_BINARY_COMMA:
1665 case EXPR_BINARY_ISGREATER:
1666 case EXPR_BINARY_ISGREATEREQUAL:
1667 case EXPR_BINARY_ISLESS:
1668 case EXPR_BINARY_ISLESSEQUAL:
1669 case EXPR_BINARY_ISLESSGREATER:
1670 case EXPR_BINARY_ISUNORDERED:
1671 mark_vars_read(expr->binary.left, lhs_ent);
1672 mark_vars_read(expr->binary.right, lhs_ent);
1675 case EXPR_BINARY_ASSIGN:
1676 case EXPR_BINARY_MUL_ASSIGN:
1677 case EXPR_BINARY_DIV_ASSIGN:
1678 case EXPR_BINARY_MOD_ASSIGN:
1679 case EXPR_BINARY_ADD_ASSIGN:
1680 case EXPR_BINARY_SUB_ASSIGN:
1681 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1682 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1683 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1684 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1685 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1686 if (lhs_ent == ENT_ANY)
1688 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1689 mark_vars_read(expr->binary.right, lhs_ent);
1694 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1700 case EXPR_CHARACTER_CONSTANT:
1701 case EXPR_WIDE_CHARACTER_CONSTANT:
1702 case EXPR_STRING_LITERAL:
1703 case EXPR_WIDE_STRING_LITERAL:
1704 case EXPR_COMPOUND_LITERAL: // TODO init?
1706 case EXPR_CLASSIFY_TYPE:
1709 case EXPR_BUILTIN_CONSTANT_P:
1710 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1712 case EXPR_STATEMENT: // TODO
1713 case EXPR_LABEL_ADDRESS:
1714 case EXPR_REFERENCE_ENUM_VALUE:
1718 panic("unhandled expression");
1721 static designator_t *parse_designation(void)
1723 designator_t *result = NULL;
1724 designator_t *last = NULL;
1727 designator_t *designator;
1728 switch (token.type) {
1730 designator = allocate_ast_zero(sizeof(designator[0]));
1731 designator->source_position = token.source_position;
1733 add_anchor_token(']');
1734 designator->array_index = parse_constant_expression();
1735 rem_anchor_token(']');
1736 expect(']', end_error);
1739 designator = allocate_ast_zero(sizeof(designator[0]));
1740 designator->source_position = token.source_position;
1742 if (token.type != T_IDENTIFIER) {
1743 parse_error_expected("while parsing designator",
1744 T_IDENTIFIER, NULL);
1747 designator->symbol = token.v.symbol;
1751 expect('=', end_error);
1755 assert(designator != NULL);
1757 last->next = designator;
1759 result = designator;
1767 static initializer_t *initializer_from_string(array_type_t *type,
1768 const string_t *const string)
1770 /* TODO: check len vs. size of array type */
1773 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1774 initializer->string.string = *string;
1779 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1780 wide_string_t *const string)
1782 /* TODO: check len vs. size of array type */
1785 initializer_t *const initializer =
1786 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1787 initializer->wide_string.string = *string;
1793 * Build an initializer from a given expression.
1795 static initializer_t *initializer_from_expression(type_t *orig_type,
1796 expression_t *expression)
1798 /* TODO check that expression is a constant expression */
1800 /* §6.7.8.14/15 char array may be initialized by string literals */
1801 type_t *type = skip_typeref(orig_type);
1802 type_t *expr_type_orig = expression->base.type;
1803 type_t *expr_type = skip_typeref(expr_type_orig);
1804 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1805 array_type_t *const array_type = &type->array;
1806 type_t *const element_type = skip_typeref(array_type->element_type);
1808 if (element_type->kind == TYPE_ATOMIC) {
1809 atomic_type_kind_t akind = element_type->atomic.akind;
1810 switch (expression->kind) {
1811 case EXPR_STRING_LITERAL:
1812 if (akind == ATOMIC_TYPE_CHAR
1813 || akind == ATOMIC_TYPE_SCHAR
1814 || akind == ATOMIC_TYPE_UCHAR) {
1815 return initializer_from_string(array_type,
1816 &expression->string.value);
1820 case EXPR_WIDE_STRING_LITERAL: {
1821 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1822 if (get_unqualified_type(element_type) == bare_wchar_type) {
1823 return initializer_from_wide_string(array_type,
1824 &expression->wide_string.value);
1835 assign_error_t error = semantic_assign(type, expression);
1836 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1838 report_assign_error(error, type, expression, "initializer",
1839 &expression->base.source_position);
1841 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1843 if (type->kind == TYPE_BITFIELD) {
1844 type = type->bitfield.base_type;
1847 result->value.value = create_implicit_cast(expression, type);
1853 * Checks if a given expression can be used as an constant initializer.
1855 static bool is_initializer_constant(const expression_t *expression)
1857 return is_constant_expression(expression)
1858 || is_address_constant(expression);
1862 * Parses an scalar initializer.
1864 * §6.7.8.11; eat {} without warning
1866 static initializer_t *parse_scalar_initializer(type_t *type,
1867 bool must_be_constant)
1869 /* there might be extra {} hierarchies */
1871 if (token.type == '{') {
1873 warningf(HERE, "extra curly braces around scalar initializer");
1877 } while (token.type == '{');
1880 expression_t *expression = parse_assignment_expression();
1881 mark_vars_read(expression, NULL);
1882 if (must_be_constant && !is_initializer_constant(expression)) {
1883 errorf(&expression->base.source_position,
1884 "Initialisation expression '%E' is not constant",
1888 initializer_t *initializer = initializer_from_expression(type, expression);
1890 if (initializer == NULL) {
1891 errorf(&expression->base.source_position,
1892 "expression '%E' (type '%T') doesn't match expected type '%T'",
1893 expression, expression->base.type, type);
1898 bool additional_warning_displayed = false;
1899 while (braces > 0) {
1900 if (token.type == ',') {
1903 if (token.type != '}') {
1904 if (!additional_warning_displayed && warning.other) {
1905 warningf(HERE, "additional elements in scalar initializer");
1906 additional_warning_displayed = true;
1917 * An entry in the type path.
1919 typedef struct type_path_entry_t type_path_entry_t;
1920 struct type_path_entry_t {
1921 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1923 size_t index; /**< For array types: the current index. */
1924 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1929 * A type path expression a position inside compound or array types.
1931 typedef struct type_path_t type_path_t;
1932 struct type_path_t {
1933 type_path_entry_t *path; /**< An flexible array containing the current path. */
1934 type_t *top_type; /**< type of the element the path points */
1935 size_t max_index; /**< largest index in outermost array */
1939 * Prints a type path for debugging.
1941 static __attribute__((unused)) void debug_print_type_path(
1942 const type_path_t *path)
1944 size_t len = ARR_LEN(path->path);
1946 for (size_t i = 0; i < len; ++i) {
1947 const type_path_entry_t *entry = & path->path[i];
1949 type_t *type = skip_typeref(entry->type);
1950 if (is_type_compound(type)) {
1951 /* in gcc mode structs can have no members */
1952 if (entry->v.compound_entry == NULL) {
1956 fprintf(stderr, ".%s",
1957 entry->v.compound_entry->base.symbol->string);
1958 } else if (is_type_array(type)) {
1959 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1961 fprintf(stderr, "-INVALID-");
1964 if (path->top_type != NULL) {
1965 fprintf(stderr, " (");
1966 print_type(path->top_type);
1967 fprintf(stderr, ")");
1972 * Return the top type path entry, ie. in a path
1973 * (type).a.b returns the b.
1975 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1977 size_t len = ARR_LEN(path->path);
1979 return &path->path[len-1];
1983 * Enlarge the type path by an (empty) element.
1985 static type_path_entry_t *append_to_type_path(type_path_t *path)
1987 size_t len = ARR_LEN(path->path);
1988 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1990 type_path_entry_t *result = & path->path[len];
1991 memset(result, 0, sizeof(result[0]));
1996 * Descending into a sub-type. Enter the scope of the current top_type.
1998 static void descend_into_subtype(type_path_t *path)
2000 type_t *orig_top_type = path->top_type;
2001 type_t *top_type = skip_typeref(orig_top_type);
2003 type_path_entry_t *top = append_to_type_path(path);
2004 top->type = top_type;
2006 if (is_type_compound(top_type)) {
2007 compound_t *compound = top_type->compound.compound;
2008 entity_t *entry = compound->members.entities;
2010 if (entry != NULL) {
2011 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
2012 top->v.compound_entry = &entry->declaration;
2013 path->top_type = entry->declaration.type;
2015 path->top_type = NULL;
2017 } else if (is_type_array(top_type)) {
2019 path->top_type = top_type->array.element_type;
2021 assert(!is_type_valid(top_type));
2026 * Pop an entry from the given type path, ie. returning from
2027 * (type).a.b to (type).a
2029 static void ascend_from_subtype(type_path_t *path)
2031 type_path_entry_t *top = get_type_path_top(path);
2033 path->top_type = top->type;
2035 size_t len = ARR_LEN(path->path);
2036 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2040 * Pop entries from the given type path until the given
2041 * path level is reached.
2043 static void ascend_to(type_path_t *path, size_t top_path_level)
2045 size_t len = ARR_LEN(path->path);
2047 while (len > top_path_level) {
2048 ascend_from_subtype(path);
2049 len = ARR_LEN(path->path);
2053 static bool walk_designator(type_path_t *path, const designator_t *designator,
2054 bool used_in_offsetof)
2056 for (; designator != NULL; designator = designator->next) {
2057 type_path_entry_t *top = get_type_path_top(path);
2058 type_t *orig_type = top->type;
2060 type_t *type = skip_typeref(orig_type);
2062 if (designator->symbol != NULL) {
2063 symbol_t *symbol = designator->symbol;
2064 if (!is_type_compound(type)) {
2065 if (is_type_valid(type)) {
2066 errorf(&designator->source_position,
2067 "'.%Y' designator used for non-compound type '%T'",
2071 top->type = type_error_type;
2072 top->v.compound_entry = NULL;
2073 orig_type = type_error_type;
2075 compound_t *compound = type->compound.compound;
2076 entity_t *iter = compound->members.entities;
2077 for (; iter != NULL; iter = iter->base.next) {
2078 if (iter->base.symbol == symbol) {
2083 errorf(&designator->source_position,
2084 "'%T' has no member named '%Y'", orig_type, symbol);
2087 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2088 if (used_in_offsetof) {
2089 type_t *real_type = skip_typeref(iter->declaration.type);
2090 if (real_type->kind == TYPE_BITFIELD) {
2091 errorf(&designator->source_position,
2092 "offsetof designator '%Y' may not specify bitfield",
2098 top->type = orig_type;
2099 top->v.compound_entry = &iter->declaration;
2100 orig_type = iter->declaration.type;
2103 expression_t *array_index = designator->array_index;
2104 assert(designator->array_index != NULL);
2106 if (!is_type_array(type)) {
2107 if (is_type_valid(type)) {
2108 errorf(&designator->source_position,
2109 "[%E] designator used for non-array type '%T'",
2110 array_index, orig_type);
2115 long index = fold_constant(array_index);
2116 if (!used_in_offsetof) {
2118 errorf(&designator->source_position,
2119 "array index [%E] must be positive", array_index);
2120 } else if (type->array.size_constant) {
2121 long array_size = type->array.size;
2122 if (index >= array_size) {
2123 errorf(&designator->source_position,
2124 "designator [%E] (%d) exceeds array size %d",
2125 array_index, index, array_size);
2130 top->type = orig_type;
2131 top->v.index = (size_t) index;
2132 orig_type = type->array.element_type;
2134 path->top_type = orig_type;
2136 if (designator->next != NULL) {
2137 descend_into_subtype(path);
2146 static void advance_current_object(type_path_t *path, size_t top_path_level)
2148 type_path_entry_t *top = get_type_path_top(path);
2150 type_t *type = skip_typeref(top->type);
2151 if (is_type_union(type)) {
2152 /* in unions only the first element is initialized */
2153 top->v.compound_entry = NULL;
2154 } else if (is_type_struct(type)) {
2155 declaration_t *entry = top->v.compound_entry;
2157 entity_t *next_entity = entry->base.next;
2158 if (next_entity != NULL) {
2159 assert(is_declaration(next_entity));
2160 entry = &next_entity->declaration;
2165 top->v.compound_entry = entry;
2166 if (entry != NULL) {
2167 path->top_type = entry->type;
2170 } else if (is_type_array(type)) {
2171 assert(is_type_array(type));
2175 if (!type->array.size_constant || top->v.index < type->array.size) {
2179 assert(!is_type_valid(type));
2183 /* we're past the last member of the current sub-aggregate, try if we
2184 * can ascend in the type hierarchy and continue with another subobject */
2185 size_t len = ARR_LEN(path->path);
2187 if (len > top_path_level) {
2188 ascend_from_subtype(path);
2189 advance_current_object(path, top_path_level);
2191 path->top_type = NULL;
2196 * skip any {...} blocks until a closing bracket is reached.
2198 static void skip_initializers(void)
2200 if (token.type == '{')
2203 while (token.type != '}') {
2204 if (token.type == T_EOF)
2206 if (token.type == '{') {
2214 static initializer_t *create_empty_initializer(void)
2216 static initializer_t empty_initializer
2217 = { .list = { { INITIALIZER_LIST }, 0 } };
2218 return &empty_initializer;
2222 * Parse a part of an initialiser for a struct or union,
2224 static initializer_t *parse_sub_initializer(type_path_t *path,
2225 type_t *outer_type, size_t top_path_level,
2226 parse_initializer_env_t *env)
2228 if (token.type == '}') {
2229 /* empty initializer */
2230 return create_empty_initializer();
2233 type_t *orig_type = path->top_type;
2234 type_t *type = NULL;
2236 if (orig_type == NULL) {
2237 /* We are initializing an empty compound. */
2239 type = skip_typeref(orig_type);
2242 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2245 designator_t *designator = NULL;
2246 if (token.type == '.' || token.type == '[') {
2247 designator = parse_designation();
2248 goto finish_designator;
2249 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2250 /* GNU-style designator ("identifier: value") */
2251 designator = allocate_ast_zero(sizeof(designator[0]));
2252 designator->source_position = token.source_position;
2253 designator->symbol = token.v.symbol;
2258 /* reset path to toplevel, evaluate designator from there */
2259 ascend_to(path, top_path_level);
2260 if (!walk_designator(path, designator, false)) {
2261 /* can't continue after designation error */
2265 initializer_t *designator_initializer
2266 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2267 designator_initializer->designator.designator = designator;
2268 ARR_APP1(initializer_t*, initializers, designator_initializer);
2270 orig_type = path->top_type;
2271 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2276 if (token.type == '{') {
2277 if (type != NULL && is_type_scalar(type)) {
2278 sub = parse_scalar_initializer(type, env->must_be_constant);
2282 if (env->entity != NULL) {
2284 "extra brace group at end of initializer for '%Y'",
2285 env->entity->base.symbol);
2287 errorf(HERE, "extra brace group at end of initializer");
2290 descend_into_subtype(path);
2292 add_anchor_token('}');
2293 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2295 rem_anchor_token('}');
2298 ascend_from_subtype(path);
2299 expect('}', end_error);
2301 expect('}', end_error);
2302 goto error_parse_next;
2306 /* must be an expression */
2307 expression_t *expression = parse_assignment_expression();
2308 mark_vars_read(expression, NULL);
2310 if (env->must_be_constant && !is_initializer_constant(expression)) {
2311 errorf(&expression->base.source_position,
2312 "Initialisation expression '%E' is not constant",
2317 /* we are already outside, ... */
2318 type_t *const outer_type_skip = skip_typeref(outer_type);
2319 if (is_type_compound(outer_type_skip) &&
2320 !outer_type_skip->compound.compound->complete) {
2321 goto error_parse_next;
2326 /* handle { "string" } special case */
2327 if ((expression->kind == EXPR_STRING_LITERAL
2328 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2329 && outer_type != NULL) {
2330 sub = initializer_from_expression(outer_type, expression);
2332 if (token.type == ',') {
2335 if (token.type != '}' && warning.other) {
2336 warningf(HERE, "excessive elements in initializer for type '%T'",
2339 /* TODO: eat , ... */
2344 /* descend into subtypes until expression matches type */
2346 orig_type = path->top_type;
2347 type = skip_typeref(orig_type);
2349 sub = initializer_from_expression(orig_type, expression);
2353 if (!is_type_valid(type)) {
2356 if (is_type_scalar(type)) {
2357 errorf(&expression->base.source_position,
2358 "expression '%E' doesn't match expected type '%T'",
2359 expression, orig_type);
2363 descend_into_subtype(path);
2367 /* update largest index of top array */
2368 const type_path_entry_t *first = &path->path[0];
2369 type_t *first_type = first->type;
2370 first_type = skip_typeref(first_type);
2371 if (is_type_array(first_type)) {
2372 size_t index = first->v.index;
2373 if (index > path->max_index)
2374 path->max_index = index;
2378 /* append to initializers list */
2379 ARR_APP1(initializer_t*, initializers, sub);
2382 if (warning.other) {
2383 if (env->entity != NULL) {
2384 warningf(HERE, "excess elements in struct initializer for '%Y'",
2385 env->entity->base.symbol);
2387 warningf(HERE, "excess elements in struct initializer");
2393 if (token.type == '}') {
2396 expect(',', end_error);
2397 if (token.type == '}') {
2402 /* advance to the next declaration if we are not at the end */
2403 advance_current_object(path, top_path_level);
2404 orig_type = path->top_type;
2405 if (orig_type != NULL)
2406 type = skip_typeref(orig_type);
2412 size_t len = ARR_LEN(initializers);
2413 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2414 initializer_t *result = allocate_ast_zero(size);
2415 result->kind = INITIALIZER_LIST;
2416 result->list.len = len;
2417 memcpy(&result->list.initializers, initializers,
2418 len * sizeof(initializers[0]));
2420 DEL_ARR_F(initializers);
2421 ascend_to(path, top_path_level+1);
2426 skip_initializers();
2427 DEL_ARR_F(initializers);
2428 ascend_to(path, top_path_level+1);
2433 * Parses an initializer. Parsers either a compound literal
2434 * (env->declaration == NULL) or an initializer of a declaration.
2436 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2438 type_t *type = skip_typeref(env->type);
2439 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2440 initializer_t *result;
2442 if (is_type_scalar(type)) {
2443 result = parse_scalar_initializer(type, env->must_be_constant);
2444 } else if (token.type == '{') {
2448 memset(&path, 0, sizeof(path));
2449 path.top_type = env->type;
2450 path.path = NEW_ARR_F(type_path_entry_t, 0);
2452 descend_into_subtype(&path);
2454 add_anchor_token('}');
2455 result = parse_sub_initializer(&path, env->type, 1, env);
2456 rem_anchor_token('}');
2458 max_index = path.max_index;
2459 DEL_ARR_F(path.path);
2461 expect('}', end_error);
2463 /* parse_scalar_initializer() also works in this case: we simply
2464 * have an expression without {} around it */
2465 result = parse_scalar_initializer(type, env->must_be_constant);
2468 /* §6.7.8:22 array initializers for arrays with unknown size determine
2469 * the array type size */
2470 if (is_type_array(type) && type->array.size_expression == NULL
2471 && result != NULL) {
2473 switch (result->kind) {
2474 case INITIALIZER_LIST:
2475 assert(max_index != 0xdeadbeaf);
2476 size = max_index + 1;
2479 case INITIALIZER_STRING:
2480 size = result->string.string.size;
2483 case INITIALIZER_WIDE_STRING:
2484 size = result->wide_string.string.size;
2487 case INITIALIZER_DESIGNATOR:
2488 case INITIALIZER_VALUE:
2489 /* can happen for parse errors */
2494 internal_errorf(HERE, "invalid initializer type");
2497 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2498 cnst->base.type = type_size_t;
2499 cnst->conste.v.int_value = size;
2501 type_t *new_type = duplicate_type(type);
2503 new_type->array.size_expression = cnst;
2504 new_type->array.size_constant = true;
2505 new_type->array.has_implicit_size = true;
2506 new_type->array.size = size;
2507 env->type = new_type;
2515 static void append_entity(scope_t *scope, entity_t *entity)
2517 if (scope->last_entity != NULL) {
2518 scope->last_entity->base.next = entity;
2520 scope->entities = entity;
2522 scope->last_entity = entity;
2526 static compound_t *parse_compound_type_specifier(bool is_struct)
2534 symbol_t *symbol = NULL;
2535 compound_t *compound = NULL;
2537 if (token.type == T___attribute__) {
2538 parse_attributes(NULL);
2541 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2542 if (token.type == T_IDENTIFIER) {
2543 /* the compound has a name, check if we have seen it already */
2544 symbol = token.v.symbol;
2547 entity_t *entity = get_tag(symbol, kind);
2548 if (entity != NULL) {
2549 compound = &entity->compound;
2550 if (compound->base.parent_scope != current_scope &&
2551 (token.type == '{' || token.type == ';')) {
2552 /* we're in an inner scope and have a definition. Shadow
2553 * existing definition in outer scope */
2555 } else if (compound->complete && token.type == '{') {
2556 assert(symbol != NULL);
2557 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2558 is_struct ? "struct" : "union", symbol,
2559 &compound->base.source_position);
2560 /* clear members in the hope to avoid further errors */
2561 compound->members.entities = NULL;
2564 } else if (token.type != '{') {
2566 parse_error_expected("while parsing struct type specifier",
2567 T_IDENTIFIER, '{', NULL);
2569 parse_error_expected("while parsing union type specifier",
2570 T_IDENTIFIER, '{', NULL);
2576 if (compound == NULL) {
2577 entity_t *entity = allocate_entity_zero(kind);
2578 compound = &entity->compound;
2580 compound->base.namespc = NAMESPACE_TAG;
2581 compound->base.source_position = token.source_position;
2582 compound->base.symbol = symbol;
2583 compound->base.parent_scope = current_scope;
2584 if (symbol != NULL) {
2585 environment_push(entity);
2587 append_entity(current_scope, entity);
2590 if (token.type == '{') {
2591 parse_compound_type_entries(compound);
2592 parse_attributes(NULL);
2594 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2595 if (symbol == NULL) {
2596 assert(anonymous_entity == NULL);
2597 anonymous_entity = (entity_t*)compound;
2604 static void parse_enum_entries(type_t *const enum_type)
2608 if (token.type == '}') {
2609 errorf(HERE, "empty enum not allowed");
2614 add_anchor_token('}');
2616 if (token.type != T_IDENTIFIER) {
2617 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2619 rem_anchor_token('}');
2623 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2624 entity->enum_value.enum_type = enum_type;
2625 entity->base.symbol = token.v.symbol;
2626 entity->base.source_position = token.source_position;
2629 if (token.type == '=') {
2631 expression_t *value = parse_constant_expression();
2633 value = create_implicit_cast(value, enum_type);
2634 entity->enum_value.value = value;
2639 record_entity(entity, false);
2641 if (token.type != ',')
2644 } while (token.type != '}');
2645 rem_anchor_token('}');
2647 expect('}', end_error);
2653 static type_t *parse_enum_specifier(void)
2659 if (token.type == T_IDENTIFIER) {
2660 symbol = token.v.symbol;
2663 entity = get_tag(symbol, ENTITY_ENUM);
2664 if (entity != NULL) {
2665 if (entity->base.parent_scope != current_scope &&
2666 (token.type == '{' || token.type == ';')) {
2667 /* we're in an inner scope and have a definition. Shadow
2668 * existing definition in outer scope */
2670 } else if (entity->enume.complete && token.type == '{') {
2671 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2672 symbol, &entity->base.source_position);
2675 } else if (token.type != '{') {
2676 parse_error_expected("while parsing enum type specifier",
2677 T_IDENTIFIER, '{', NULL);
2684 if (entity == NULL) {
2685 entity = allocate_entity_zero(ENTITY_ENUM);
2686 entity->base.namespc = NAMESPACE_TAG;
2687 entity->base.source_position = token.source_position;
2688 entity->base.symbol = symbol;
2689 entity->base.parent_scope = current_scope;
2692 type_t *const type = allocate_type_zero(TYPE_ENUM);
2693 type->enumt.enume = &entity->enume;
2694 type->enumt.akind = ATOMIC_TYPE_INT;
2696 if (token.type == '{') {
2697 if (symbol != NULL) {
2698 environment_push(entity);
2700 append_entity(current_scope, entity);
2701 entity->enume.complete = true;
2703 parse_enum_entries(type);
2704 parse_attributes(NULL);
2706 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2707 if (symbol == NULL) {
2708 assert(anonymous_entity == NULL);
2709 anonymous_entity = entity;
2711 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2712 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2720 * if a symbol is a typedef to another type, return true
2722 static bool is_typedef_symbol(symbol_t *symbol)
2724 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2725 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2728 static type_t *parse_typeof(void)
2734 expect('(', end_error);
2735 add_anchor_token(')');
2737 expression_t *expression = NULL;
2739 bool old_type_prop = in_type_prop;
2740 bool old_gcc_extension = in_gcc_extension;
2741 in_type_prop = true;
2743 while (token.type == T___extension__) {
2744 /* This can be a prefix to a typename or an expression. */
2746 in_gcc_extension = true;
2748 switch (token.type) {
2750 if (is_typedef_symbol(token.v.symbol)) {
2751 type = parse_typename();
2753 expression = parse_expression();
2754 type = revert_automatic_type_conversion(expression);
2759 type = parse_typename();
2763 expression = parse_expression();
2764 type = expression->base.type;
2767 in_type_prop = old_type_prop;
2768 in_gcc_extension = old_gcc_extension;
2770 rem_anchor_token(')');
2771 expect(')', end_error);
2773 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2774 typeof_type->typeoft.expression = expression;
2775 typeof_type->typeoft.typeof_type = type;
2782 typedef enum specifiers_t {
2783 SPECIFIER_SIGNED = 1 << 0,
2784 SPECIFIER_UNSIGNED = 1 << 1,
2785 SPECIFIER_LONG = 1 << 2,
2786 SPECIFIER_INT = 1 << 3,
2787 SPECIFIER_DOUBLE = 1 << 4,
2788 SPECIFIER_CHAR = 1 << 5,
2789 SPECIFIER_WCHAR_T = 1 << 6,
2790 SPECIFIER_SHORT = 1 << 7,
2791 SPECIFIER_LONG_LONG = 1 << 8,
2792 SPECIFIER_FLOAT = 1 << 9,
2793 SPECIFIER_BOOL = 1 << 10,
2794 SPECIFIER_VOID = 1 << 11,
2795 SPECIFIER_INT8 = 1 << 12,
2796 SPECIFIER_INT16 = 1 << 13,
2797 SPECIFIER_INT32 = 1 << 14,
2798 SPECIFIER_INT64 = 1 << 15,
2799 SPECIFIER_INT128 = 1 << 16,
2800 SPECIFIER_COMPLEX = 1 << 17,
2801 SPECIFIER_IMAGINARY = 1 << 18,
2804 static type_t *create_builtin_type(symbol_t *const symbol,
2805 type_t *const real_type)
2807 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2808 type->builtin.symbol = symbol;
2809 type->builtin.real_type = real_type;
2810 return identify_new_type(type);
2813 static type_t *get_typedef_type(symbol_t *symbol)
2815 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2816 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2819 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2820 type->typedeft.typedefe = &entity->typedefe;
2825 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2827 expect('(', end_error);
2829 attribute_property_argument_t *property
2830 = allocate_ast_zero(sizeof(*property));
2833 if (token.type != T_IDENTIFIER) {
2834 parse_error_expected("while parsing property declspec",
2835 T_IDENTIFIER, NULL);
2840 symbol_t *symbol = token.v.symbol;
2842 if (strcmp(symbol->string, "put") == 0) {
2844 } else if (strcmp(symbol->string, "get") == 0) {
2847 errorf(HERE, "expected put or get in property declspec");
2850 expect('=', end_error);
2851 if (token.type != T_IDENTIFIER) {
2852 parse_error_expected("while parsing property declspec",
2853 T_IDENTIFIER, NULL);
2857 property->put_symbol = token.v.symbol;
2859 property->get_symbol = token.v.symbol;
2862 if (token.type == ')')
2864 expect(',', end_error);
2867 attribute->a.property = property;
2869 expect(')', end_error);
2875 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2877 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2878 if (token.type == T_restrict) {
2879 kind = ATTRIBUTE_MS_RESTRICT;
2881 } else if (token.type == T_IDENTIFIER) {
2882 const char *name = token.v.symbol->string;
2884 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2886 const char *attribute_name = get_attribute_name(k);
2887 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2893 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2894 warningf(HERE, "unknown __declspec '%s' ignored", name);
2897 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2901 attribute_t *attribute = allocate_attribute_zero(kind);
2903 if (kind == ATTRIBUTE_MS_PROPERTY) {
2904 return parse_attribute_ms_property(attribute);
2907 /* parse arguments */
2908 if (token.type == '(') {
2910 attribute->a.arguments = parse_attribute_arguments();
2916 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2920 expect('(', end_error);
2922 if (token.type == ')') {
2927 add_anchor_token(')');
2929 attribute_t *last = first;
2932 while (last->next != NULL)
2936 attribute_t *attribute
2937 = parse_microsoft_extended_decl_modifier_single();
2938 if (attribute == NULL)
2944 last->next = attribute;
2948 if (token.type == ')') {
2951 expect(',', end_error);
2954 rem_anchor_token(')');
2955 expect(')', end_error);
2959 rem_anchor_token(')');
2963 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2965 entity_t *entity = allocate_entity_zero(kind);
2966 entity->base.source_position = *HERE;
2967 entity->base.symbol = symbol;
2968 if (is_declaration(entity)) {
2969 entity->declaration.type = type_error_type;
2970 entity->declaration.implicit = true;
2971 } else if (kind == ENTITY_TYPEDEF) {
2972 entity->typedefe.type = type_error_type;
2973 entity->typedefe.builtin = true;
2975 if (kind != ENTITY_COMPOUND_MEMBER)
2976 record_entity(entity, false);
2981 * Finish the construction of a struct type by calculating its size, offsets,
2984 static void finish_struct_type(compound_type_t *type)
2986 assert(type->compound != NULL);
2988 compound_t *compound = type->compound;
2989 if (!compound->complete)
2994 il_alignment_t alignment = compound->alignment;
2995 bool need_pad = false;
2997 entity_t *entry = compound->members.entities;
2998 for (; entry != NULL; entry = entry->base.next) {
2999 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3002 type_t *m_type = entry->declaration.type;
3003 if (! is_type_valid(skip_typeref(m_type))) {
3004 /* simply ignore errors here */
3007 il_alignment_t m_alignment = get_type_alignment(m_type);
3008 if (m_alignment > alignment)
3009 alignment = m_alignment;
3011 offset = (size + m_alignment - 1) & -m_alignment;
3015 entry->compound_member.offset = offset;
3016 size = offset + get_type_size(m_type);
3019 offset = (size + alignment - 1) & -alignment;
3024 if (warning.padded) {
3025 warningf(&compound->base.source_position, "'%T' needs padding",
3028 } else if (compound->packed && warning.packed) {
3029 warningf(&compound->base.source_position,
3030 "superfluous packed attribute on '%T'", type);
3033 compound->size = offset;
3034 compound->alignment = alignment;
3038 * Finish the construction of an union type by calculating
3039 * its size and alignment.
3041 static void finish_union_type(compound_type_t *type)
3043 assert(type->compound != NULL);
3045 compound_t *compound = type->compound;
3046 if (! compound->complete)
3050 il_alignment_t alignment = compound->alignment;
3052 entity_t *entry = compound->members.entities;
3053 for (; entry != NULL; entry = entry->base.next) {
3054 if (entry->kind != ENTITY_COMPOUND_MEMBER)
3057 type_t *m_type = entry->declaration.type;
3058 if (! is_type_valid(skip_typeref(m_type)))
3061 entry->compound_member.offset = 0;
3062 il_size_t m_size = get_type_size(m_type);
3065 il_alignment_t m_alignment = get_type_alignment(m_type);
3066 if (m_alignment > alignment)
3067 alignment = m_alignment;
3069 size = (size + alignment - 1) & -alignment;
3071 compound->size = size;
3072 compound->alignment = alignment;
3075 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
3077 type_t *type = NULL;
3078 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3079 unsigned type_specifiers = 0;
3080 bool newtype = false;
3081 bool saw_error = false;
3082 bool old_gcc_extension = in_gcc_extension;
3084 specifiers->source_position = token.source_position;
3087 specifiers->attributes = parse_attributes(specifiers->attributes);
3089 switch (token.type) {
3091 #define MATCH_STORAGE_CLASS(token, class) \
3093 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
3094 errorf(HERE, "multiple storage classes in declaration specifiers"); \
3096 specifiers->storage_class = class; \
3097 if (specifiers->thread_local) \
3098 goto check_thread_storage_class; \
3102 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
3103 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
3104 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
3105 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
3106 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
3109 specifiers->attributes
3110 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
3114 if (specifiers->thread_local) {
3115 errorf(HERE, "duplicate '__thread'");
3117 specifiers->thread_local = true;
3118 check_thread_storage_class:
3119 switch (specifiers->storage_class) {
3120 case STORAGE_CLASS_EXTERN:
3121 case STORAGE_CLASS_NONE:
3122 case STORAGE_CLASS_STATIC:
3126 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
3127 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
3128 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
3129 wrong_thread_stoarge_class:
3130 errorf(HERE, "'__thread' used with '%s'", wrong);
3137 /* type qualifiers */
3138 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3140 qualifiers |= qualifier; \
3144 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3145 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3146 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3147 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3148 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3149 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3150 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3151 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3153 case T___extension__:
3155 in_gcc_extension = true;
3158 /* type specifiers */
3159 #define MATCH_SPECIFIER(token, specifier, name) \
3161 if (type_specifiers & specifier) { \
3162 errorf(HERE, "multiple " name " type specifiers given"); \
3164 type_specifiers |= specifier; \
3169 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3170 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3171 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3172 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3173 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3174 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3175 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3176 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3177 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3178 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3179 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3180 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3181 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3182 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3183 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3184 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3185 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3186 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3190 specifiers->is_inline = true;
3194 case T__forceinline:
3196 specifiers->modifiers |= DM_FORCEINLINE;
3201 if (type_specifiers & SPECIFIER_LONG_LONG) {
3202 errorf(HERE, "multiple type specifiers given");
3203 } else if (type_specifiers & SPECIFIER_LONG) {
3204 type_specifiers |= SPECIFIER_LONG_LONG;
3206 type_specifiers |= SPECIFIER_LONG;
3211 #define CHECK_DOUBLE_TYPE() \
3212 if ( type != NULL) \
3213 errorf(HERE, "multiple data types in declaration specifiers");
3216 CHECK_DOUBLE_TYPE();
3217 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3219 type->compound.compound = parse_compound_type_specifier(true);
3220 finish_struct_type(&type->compound);
3223 CHECK_DOUBLE_TYPE();
3224 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3225 type->compound.compound = parse_compound_type_specifier(false);
3226 finish_union_type(&type->compound);
3229 CHECK_DOUBLE_TYPE();
3230 type = parse_enum_specifier();
3233 CHECK_DOUBLE_TYPE();
3234 type = parse_typeof();
3236 case T___builtin_va_list:
3237 CHECK_DOUBLE_TYPE();
3238 type = duplicate_type(type_valist);
3242 case T_IDENTIFIER: {
3243 /* only parse identifier if we haven't found a type yet */
3244 if (type != NULL || type_specifiers != 0) {
3245 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3246 * declaration, so it doesn't generate errors about expecting '(' or
3248 switch (look_ahead(1)->type) {
3255 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3259 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3264 goto finish_specifiers;
3268 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3269 if (typedef_type == NULL) {
3270 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3271 * declaration, so it doesn't generate 'implicit int' followed by more
3272 * errors later on. */
3273 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3279 errorf(HERE, "%K does not name a type", &token);
3282 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3284 type = allocate_type_zero(TYPE_TYPEDEF);
3285 type->typedeft.typedefe = &entity->typedefe;
3289 if (la1_type == '&' || la1_type == '*')
3290 goto finish_specifiers;
3295 goto finish_specifiers;
3300 type = typedef_type;
3304 /* function specifier */
3306 goto finish_specifiers;
3311 specifiers->attributes = parse_attributes(specifiers->attributes);
3313 in_gcc_extension = old_gcc_extension;
3315 if (type == NULL || (saw_error && type_specifiers != 0)) {
3316 atomic_type_kind_t atomic_type;
3318 /* match valid basic types */
3319 switch (type_specifiers) {
3320 case SPECIFIER_VOID:
3321 atomic_type = ATOMIC_TYPE_VOID;
3323 case SPECIFIER_WCHAR_T:
3324 atomic_type = ATOMIC_TYPE_WCHAR_T;
3326 case SPECIFIER_CHAR:
3327 atomic_type = ATOMIC_TYPE_CHAR;
3329 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3330 atomic_type = ATOMIC_TYPE_SCHAR;
3332 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3333 atomic_type = ATOMIC_TYPE_UCHAR;
3335 case SPECIFIER_SHORT:
3336 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3337 case SPECIFIER_SHORT | SPECIFIER_INT:
3338 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3339 atomic_type = ATOMIC_TYPE_SHORT;
3341 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3342 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3343 atomic_type = ATOMIC_TYPE_USHORT;
3346 case SPECIFIER_SIGNED:
3347 case SPECIFIER_SIGNED | SPECIFIER_INT:
3348 atomic_type = ATOMIC_TYPE_INT;
3350 case SPECIFIER_UNSIGNED:
3351 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3352 atomic_type = ATOMIC_TYPE_UINT;
3354 case SPECIFIER_LONG:
3355 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3356 case SPECIFIER_LONG | SPECIFIER_INT:
3357 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3358 atomic_type = ATOMIC_TYPE_LONG;
3360 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3361 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3362 atomic_type = ATOMIC_TYPE_ULONG;
3365 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3366 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3367 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3368 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3370 atomic_type = ATOMIC_TYPE_LONGLONG;
3371 goto warn_about_long_long;
3373 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3374 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3376 atomic_type = ATOMIC_TYPE_ULONGLONG;
3377 warn_about_long_long:
3378 if (warning.long_long) {
3379 warningf(&specifiers->source_position,
3380 "ISO C90 does not support 'long long'");
3384 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3385 atomic_type = unsigned_int8_type_kind;
3388 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3389 atomic_type = unsigned_int16_type_kind;
3392 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3393 atomic_type = unsigned_int32_type_kind;
3396 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3397 atomic_type = unsigned_int64_type_kind;
3400 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3401 atomic_type = unsigned_int128_type_kind;
3404 case SPECIFIER_INT8:
3405 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3406 atomic_type = int8_type_kind;
3409 case SPECIFIER_INT16:
3410 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3411 atomic_type = int16_type_kind;
3414 case SPECIFIER_INT32:
3415 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3416 atomic_type = int32_type_kind;
3419 case SPECIFIER_INT64:
3420 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3421 atomic_type = int64_type_kind;
3424 case SPECIFIER_INT128:
3425 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3426 atomic_type = int128_type_kind;
3429 case SPECIFIER_FLOAT:
3430 atomic_type = ATOMIC_TYPE_FLOAT;
3432 case SPECIFIER_DOUBLE:
3433 atomic_type = ATOMIC_TYPE_DOUBLE;
3435 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3436 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3438 case SPECIFIER_BOOL:
3439 atomic_type = ATOMIC_TYPE_BOOL;
3441 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3442 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3443 atomic_type = ATOMIC_TYPE_FLOAT;
3445 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3446 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3447 atomic_type = ATOMIC_TYPE_DOUBLE;
3449 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3450 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3451 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3454 /* invalid specifier combination, give an error message */
3455 if (type_specifiers == 0) {
3459 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3460 if (!(c_mode & _CXX) && !strict_mode) {
3461 if (warning.implicit_int) {
3462 warningf(HERE, "no type specifiers in declaration, using 'int'");
3464 atomic_type = ATOMIC_TYPE_INT;
3467 errorf(HERE, "no type specifiers given in declaration");
3469 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3470 (type_specifiers & SPECIFIER_UNSIGNED)) {
3471 errorf(HERE, "signed and unsigned specifiers given");
3472 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3473 errorf(HERE, "only integer types can be signed or unsigned");
3475 errorf(HERE, "multiple datatypes in declaration");
3480 if (type_specifiers & SPECIFIER_COMPLEX) {
3481 type = allocate_type_zero(TYPE_COMPLEX);
3482 type->complex.akind = atomic_type;
3483 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3484 type = allocate_type_zero(TYPE_IMAGINARY);
3485 type->imaginary.akind = atomic_type;
3487 type = allocate_type_zero(TYPE_ATOMIC);
3488 type->atomic.akind = atomic_type;
3491 } else if (type_specifiers != 0) {
3492 errorf(HERE, "multiple datatypes in declaration");
3495 /* FIXME: check type qualifiers here */
3496 type->base.qualifiers = qualifiers;
3499 type = identify_new_type(type);
3501 type = typehash_insert(type);
3504 if (specifiers->attributes != NULL)
3505 type = handle_type_attributes(specifiers->attributes, type);
3506 specifiers->type = type;
3510 specifiers->type = type_error_type;
3514 static type_qualifiers_t parse_type_qualifiers(void)
3516 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3519 switch (token.type) {
3520 /* type qualifiers */
3521 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3522 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3523 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3524 /* microsoft extended type modifiers */
3525 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3526 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3527 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3528 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3529 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3538 * Parses an K&R identifier list
3540 static void parse_identifier_list(scope_t *scope)
3543 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3544 entity->base.source_position = token.source_position;
3545 entity->base.namespc = NAMESPACE_NORMAL;
3546 entity->base.symbol = token.v.symbol;
3547 /* a K&R parameter has no type, yet */
3551 append_entity(scope, entity);
3553 if (token.type != ',') {
3557 } while (token.type == T_IDENTIFIER);
3560 static entity_t *parse_parameter(void)
3562 declaration_specifiers_t specifiers;
3563 memset(&specifiers, 0, sizeof(specifiers));
3565 parse_declaration_specifiers(&specifiers);
3567 entity_t *entity = parse_declarator(&specifiers,
3568 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3569 anonymous_entity = NULL;
3573 static void semantic_parameter_incomplete(const entity_t *entity)
3575 assert(entity->kind == ENTITY_PARAMETER);
3577 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3578 * list in a function declarator that is part of a
3579 * definition of that function shall not have
3580 * incomplete type. */
3581 type_t *type = skip_typeref(entity->declaration.type);
3582 if (is_type_incomplete(type)) {
3583 errorf(&entity->base.source_position,
3584 "parameter '%#T' has incomplete type",
3585 entity->declaration.type, entity->base.symbol);
3589 static bool has_parameters(void)
3591 /* func(void) is not a parameter */
3592 if (token.type == T_IDENTIFIER) {
3593 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3596 if (entity->kind != ENTITY_TYPEDEF)
3598 if (skip_typeref(entity->typedefe.type) != type_void)
3600 } else if (token.type != T_void) {
3603 if (look_ahead(1)->type != ')')
3610 * Parses function type parameters (and optionally creates variable_t entities
3611 * for them in a scope)
3613 static void parse_parameters(function_type_t *type, scope_t *scope)
3616 add_anchor_token(')');
3617 int saved_comma_state = save_and_reset_anchor_state(',');
3619 if (token.type == T_IDENTIFIER &&
3620 !is_typedef_symbol(token.v.symbol)) {
3621 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3622 if (la1_type == ',' || la1_type == ')') {
3623 type->kr_style_parameters = true;
3624 type->unspecified_parameters = true;
3625 parse_identifier_list(scope);
3626 goto parameters_finished;
3630 if (token.type == ')') {
3631 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3632 if (!(c_mode & _CXX))
3633 type->unspecified_parameters = true;
3634 goto parameters_finished;
3637 if (has_parameters()) {
3638 function_parameter_t **anchor = &type->parameters;
3640 switch (token.type) {
3643 type->variadic = true;
3644 goto parameters_finished;
3647 case T___extension__:
3650 entity_t *entity = parse_parameter();
3651 if (entity->kind == ENTITY_TYPEDEF) {
3652 errorf(&entity->base.source_position,
3653 "typedef not allowed as function parameter");
3656 assert(is_declaration(entity));
3658 semantic_parameter_incomplete(entity);
3660 function_parameter_t *const parameter =
3661 allocate_parameter(entity->declaration.type);
3663 if (scope != NULL) {
3664 append_entity(scope, entity);
3667 *anchor = parameter;
3668 anchor = ¶meter->next;
3673 goto parameters_finished;
3675 if (token.type != ',') {
3676 goto parameters_finished;
3683 parameters_finished:
3684 rem_anchor_token(')');
3685 expect(')', end_error);
3688 restore_anchor_state(',', saved_comma_state);
3691 typedef enum construct_type_kind_t {
3694 CONSTRUCT_REFERENCE,
3697 } construct_type_kind_t;
3699 typedef union construct_type_t construct_type_t;
3701 typedef struct construct_type_base_t {
3702 construct_type_kind_t kind;
3703 construct_type_t *next;
3704 } construct_type_base_t;
3706 typedef struct parsed_pointer_t {
3707 construct_type_base_t base;
3708 type_qualifiers_t type_qualifiers;
3709 variable_t *base_variable; /**< MS __based extension. */
3712 typedef struct parsed_reference_t {
3713 construct_type_base_t base;
3714 } parsed_reference_t;
3716 typedef struct construct_function_type_t {
3717 construct_type_base_t base;
3718 type_t *function_type;
3719 } construct_function_type_t;
3721 typedef struct parsed_array_t {
3722 construct_type_base_t base;
3723 type_qualifiers_t type_qualifiers;
3729 union construct_type_t {
3730 construct_type_kind_t kind;
3731 construct_type_base_t base;
3732 parsed_pointer_t pointer;
3733 parsed_reference_t reference;
3734 construct_function_type_t function;
3735 parsed_array_t array;
3738 static construct_type_t *parse_pointer_declarator(void)
3742 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3743 memset(pointer, 0, sizeof(pointer[0]));
3744 pointer->base.kind = CONSTRUCT_POINTER;
3745 pointer->type_qualifiers = parse_type_qualifiers();
3746 //pointer->base_variable = base_variable;
3748 return (construct_type_t*) pointer;
3751 static construct_type_t *parse_reference_declarator(void)
3755 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3756 parsed_reference_t *reference = &cons->reference;
3757 memset(reference, 0, sizeof(*reference));
3758 cons->kind = CONSTRUCT_REFERENCE;
3763 static construct_type_t *parse_array_declarator(void)
3766 add_anchor_token(']');
3768 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3769 parsed_array_t *array = &cons->array;
3770 memset(array, 0, sizeof(*array));
3771 cons->kind = CONSTRUCT_ARRAY;
3773 if (token.type == T_static) {
3774 array->is_static = true;
3778 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3779 if (type_qualifiers != 0) {
3780 if (token.type == T_static) {
3781 array->is_static = true;
3785 array->type_qualifiers = type_qualifiers;
3787 if (token.type == '*' && look_ahead(1)->type == ']') {
3788 array->is_variable = true;
3790 } else if (token.type != ']') {
3791 expression_t *const size = parse_assignment_expression();
3793 /* §6.7.5.2:1 Array size must have integer type */
3794 type_t *const orig_type = size->base.type;
3795 type_t *const type = skip_typeref(orig_type);
3796 if (!is_type_integer(type) && is_type_valid(type)) {
3797 errorf(&size->base.source_position,
3798 "array size '%E' must have integer type but has type '%T'",
3803 mark_vars_read(size, NULL);
3806 rem_anchor_token(']');
3807 expect(']', end_error);
3813 static construct_type_t *parse_function_declarator(scope_t *scope)
3815 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3816 function_type_t *ftype = &type->function;
3818 ftype->linkage = current_linkage;
3821 switch (modifiers & (DM_CDECL | DM_STDCALL | DM_FASTCALL | DM_THISCALL)) {
3822 case DM_NONE: break;
3823 case DM_CDECL: ftype->calling_convention = CC_CDECL; break;
3824 case DM_STDCALL: ftype->calling_convention = CC_STDCALL; break;
3825 case DM_FASTCALL: ftype->calling_convention = CC_FASTCALL; break;
3826 case DM_THISCALL: ftype->calling_convention = CC_THISCALL; break;
3829 errorf(HERE, "multiple calling conventions in declaration");
3834 parse_parameters(ftype, scope);
3836 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3837 construct_function_type_t *function = &cons->function;
3838 memset(function, 0, sizeof(*function));
3839 cons->kind = CONSTRUCT_FUNCTION;
3840 function->function_type = type;
3845 typedef struct parse_declarator_env_t {
3846 bool may_be_abstract : 1;
3847 bool must_be_abstract : 1;
3848 decl_modifiers_t modifiers;
3850 source_position_t source_position;
3852 attribute_t *attributes;
3853 } parse_declarator_env_t;
3855 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3857 /* construct a single linked list of construct_type_t's which describe
3858 * how to construct the final declarator type */
3859 construct_type_t *first = NULL;
3860 construct_type_t **anchor = &first;
3862 env->attributes = parse_attributes(env->attributes);
3865 construct_type_t *type;
3866 //variable_t *based = NULL; /* MS __based extension */
3867 switch (token.type) {
3869 if (!(c_mode & _CXX))
3870 errorf(HERE, "references are only available for C++");
3871 type = parse_reference_declarator();
3876 source_position_t const pos = *HERE;
3878 expect('(', end_error);
3879 add_anchor_token(')');
3880 based = parse_microsoft_based();
3881 rem_anchor_token(')');
3882 expect(')', end_error);
3883 if (token.type != '*') {
3884 if (token.type == T__based) {
3885 errorf(&pos, "__based type modifier specified more than once");
3886 } else if (warning.other) {
3888 "__based does not precede a pointer declarator, ignored");
3893 panic("based currently disabled");
3899 type = parse_pointer_declarator();
3903 goto ptr_operator_end;
3907 anchor = &type->base.next;
3909 /* TODO: find out if this is correct */
3910 env->attributes = parse_attributes(env->attributes);
3915 modifiers |= env->modifiers;
3916 env->modifiers = modifiers;
3919 construct_type_t *inner_types = NULL;
3921 switch (token.type) {
3923 if (env->must_be_abstract) {
3924 errorf(HERE, "no identifier expected in typename");
3926 env->symbol = token.v.symbol;
3927 env->source_position = token.source_position;
3932 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3933 * interpreted as ``function with no parameter specification'', rather
3934 * than redundant parentheses around the omitted identifier. */
3935 if (look_ahead(1)->type != ')') {
3937 add_anchor_token(')');
3938 inner_types = parse_inner_declarator(env);
3939 if (inner_types != NULL) {
3940 /* All later declarators only modify the return type */
3941 env->must_be_abstract = true;
3943 rem_anchor_token(')');
3944 expect(')', end_error);
3948 if (env->may_be_abstract)
3950 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3955 construct_type_t **const p = anchor;
3958 construct_type_t *type;
3959 switch (token.type) {
3961 scope_t *scope = NULL;
3962 if (!env->must_be_abstract) {
3963 scope = &env->parameters;
3966 type = parse_function_declarator(scope);
3970 type = parse_array_declarator();
3973 goto declarator_finished;
3976 /* insert in the middle of the list (at p) */
3977 type->base.next = *p;
3980 anchor = &type->base.next;
3983 declarator_finished:
3984 /* append inner_types at the end of the list, we don't to set anchor anymore
3985 * as it's not needed anymore */
3986 *anchor = inner_types;
3993 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3995 construct_type_t *iter = construct_list;
3996 for (; iter != NULL; iter = iter->base.next) {
3997 switch (iter->kind) {
3998 case CONSTRUCT_INVALID:
4000 case CONSTRUCT_FUNCTION: {
4001 construct_function_type_t *function = &iter->function;
4002 type_t *function_type = function->function_type;
4004 function_type->function.return_type = type;
4006 type_t *skipped_return_type = skip_typeref(type);
4008 if (is_type_function(skipped_return_type)) {
4009 errorf(HERE, "function returning function is not allowed");
4010 } else if (is_type_array(skipped_return_type)) {
4011 errorf(HERE, "function returning array is not allowed");
4013 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
4015 "type qualifiers in return type of function type are meaningless");
4019 /* The function type was constructed earlier. Freeing it here will
4020 * destroy other types. */
4021 type = typehash_insert(function_type);
4025 case CONSTRUCT_POINTER: {
4026 if (is_type_reference(skip_typeref(type)))
4027 errorf(HERE, "cannot declare a pointer to reference");
4029 parsed_pointer_t *pointer = &iter->pointer;
4030 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
4034 case CONSTRUCT_REFERENCE:
4035 if (is_type_reference(skip_typeref(type)))
4036 errorf(HERE, "cannot declare a reference to reference");
4038 type = make_reference_type(type);
4041 case CONSTRUCT_ARRAY: {
4042 if (is_type_reference(skip_typeref(type)))
4043 errorf(HERE, "cannot declare an array of references");
4045 parsed_array_t *array = &iter->array;
4046 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
4048 expression_t *size_expression = array->size;
4049 if (size_expression != NULL) {
4051 = create_implicit_cast(size_expression, type_size_t);
4054 array_type->base.qualifiers = array->type_qualifiers;
4055 array_type->array.element_type = type;
4056 array_type->array.is_static = array->is_static;
4057 array_type->array.is_variable = array->is_variable;
4058 array_type->array.size_expression = size_expression;
4060 if (size_expression != NULL) {
4061 if (is_constant_expression(size_expression)) {
4062 long const size = fold_constant(size_expression);
4063 array_type->array.size = size;
4064 array_type->array.size_constant = true;
4065 /* §6.7.5.2:1 If the expression is a constant expression, it shall
4066 * have a value greater than zero. */
4068 if (size < 0 || !GNU_MODE) {
4069 errorf(&size_expression->base.source_position,
4070 "size of array must be greater than zero");
4071 } else if (warning.other) {
4072 warningf(&size_expression->base.source_position,
4073 "zero length arrays are a GCC extension");
4077 array_type->array.is_vla = true;
4081 type_t *skipped_type = skip_typeref(type);
4083 if (is_type_incomplete(skipped_type)) {
4084 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
4085 } else if (is_type_function(skipped_type)) {
4086 errorf(HERE, "array of functions is not allowed");
4088 type = identify_new_type(array_type);
4092 internal_errorf(HERE, "invalid type construction found");
4098 static type_t *automatic_type_conversion(type_t *orig_type);
4100 static type_t *semantic_parameter(const source_position_t *pos,
4102 const declaration_specifiers_t *specifiers,
4105 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
4106 * shall be adjusted to ``qualified pointer to type'',
4108 * §6.7.5.3:8 A declaration of a parameter as ``function returning
4109 * type'' shall be adjusted to ``pointer to function
4110 * returning type'', as in 6.3.2.1. */
4111 type = automatic_type_conversion(type);
4113 if (specifiers->is_inline && is_type_valid(type)) {
4114 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
4117 /* §6.9.1:6 The declarations in the declaration list shall contain
4118 * no storage-class specifier other than register and no
4119 * initializations. */
4120 if (specifiers->thread_local || (
4121 specifiers->storage_class != STORAGE_CLASS_NONE &&
4122 specifiers->storage_class != STORAGE_CLASS_REGISTER)
4124 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
4127 /* delay test for incomplete type, because we might have (void)
4128 * which is legal but incomplete... */
4133 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
4134 declarator_flags_t flags)
4136 parse_declarator_env_t env;
4137 memset(&env, 0, sizeof(env));
4138 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
4140 construct_type_t *construct_type = parse_inner_declarator(&env);
4142 construct_declarator_type(construct_type, specifiers->type);
4143 type_t *type = skip_typeref(orig_type);
4145 if (construct_type != NULL) {
4146 obstack_free(&temp_obst, construct_type);
4149 attribute_t *attributes = parse_attributes(env.attributes);
4150 /* append (shared) specifier attribute behind attributes of this
4152 if (attributes != NULL) {
4153 attribute_t *last = attributes;
4154 while (last->next != NULL)
4156 last->next = specifiers->attributes;
4158 attributes = specifiers->attributes;
4162 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
4163 entity = allocate_entity_zero(ENTITY_TYPEDEF);
4164 entity->base.symbol = env.symbol;
4165 entity->base.source_position = env.source_position;
4166 entity->typedefe.type = orig_type;
4168 if (anonymous_entity != NULL) {
4169 if (is_type_compound(type)) {
4170 assert(anonymous_entity->compound.alias == NULL);
4171 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4172 anonymous_entity->kind == ENTITY_UNION);
4173 anonymous_entity->compound.alias = entity;
4174 anonymous_entity = NULL;
4175 } else if (is_type_enum(type)) {
4176 assert(anonymous_entity->enume.alias == NULL);
4177 assert(anonymous_entity->kind == ENTITY_ENUM);
4178 anonymous_entity->enume.alias = entity;
4179 anonymous_entity = NULL;
4183 /* create a declaration type entity */
4184 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4185 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4187 if (env.symbol != NULL) {
4188 if (specifiers->is_inline && is_type_valid(type)) {
4189 errorf(&env.source_position,
4190 "compound member '%Y' declared 'inline'", env.symbol);
4193 if (specifiers->thread_local ||
4194 specifiers->storage_class != STORAGE_CLASS_NONE) {
4195 errorf(&env.source_position,
4196 "compound member '%Y' must have no storage class",
4200 } else if (flags & DECL_IS_PARAMETER) {
4201 orig_type = semantic_parameter(&env.source_position, orig_type,
4202 specifiers, env.symbol);
4204 entity = allocate_entity_zero(ENTITY_PARAMETER);
4205 } else if (is_type_function(type)) {
4206 entity = allocate_entity_zero(ENTITY_FUNCTION);
4208 entity->function.is_inline = specifiers->is_inline;
4209 entity->function.parameters = env.parameters;
4211 if (env.symbol != NULL) {
4212 /* this needs fixes for C++ */
4213 bool in_function_scope = current_function != NULL;
4215 if (specifiers->thread_local || (
4216 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4217 specifiers->storage_class != STORAGE_CLASS_NONE &&
4218 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4220 errorf(&env.source_position,
4221 "invalid storage class for function '%Y'", env.symbol);
4225 entity = allocate_entity_zero(ENTITY_VARIABLE);
4227 entity->variable.thread_local = specifiers->thread_local;
4229 if (env.symbol != NULL) {
4230 if (specifiers->is_inline && is_type_valid(type)) {
4231 errorf(&env.source_position,
4232 "variable '%Y' declared 'inline'", env.symbol);
4235 bool invalid_storage_class = false;
4236 if (current_scope == file_scope) {
4237 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4238 specifiers->storage_class != STORAGE_CLASS_NONE &&
4239 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4240 invalid_storage_class = true;
4243 if (specifiers->thread_local &&
4244 specifiers->storage_class == STORAGE_CLASS_NONE) {
4245 invalid_storage_class = true;
4248 if (invalid_storage_class) {
4249 errorf(&env.source_position,
4250 "invalid storage class for variable '%Y'", env.symbol);
4255 if (env.symbol != NULL) {
4256 entity->base.symbol = env.symbol;
4257 entity->base.source_position = env.source_position;
4259 entity->base.source_position = specifiers->source_position;
4261 entity->base.namespc = NAMESPACE_NORMAL;
4262 entity->declaration.type = orig_type;
4263 entity->declaration.alignment = get_type_alignment(orig_type);
4264 entity->declaration.modifiers = env.modifiers;
4265 entity->declaration.attributes = attributes;
4267 storage_class_t storage_class = specifiers->storage_class;
4268 entity->declaration.declared_storage_class = storage_class;
4270 if (storage_class == STORAGE_CLASS_NONE && current_scope != file_scope)
4271 storage_class = STORAGE_CLASS_AUTO;
4272 entity->declaration.storage_class = storage_class;
4275 if (attributes != NULL) {
4276 handle_entity_attributes(attributes, entity);
4282 static type_t *parse_abstract_declarator(type_t *base_type)
4284 parse_declarator_env_t env;
4285 memset(&env, 0, sizeof(env));
4286 env.may_be_abstract = true;
4287 env.must_be_abstract = true;
4289 construct_type_t *construct_type = parse_inner_declarator(&env);
4291 type_t *result = construct_declarator_type(construct_type, base_type);
4292 if (construct_type != NULL) {
4293 obstack_free(&temp_obst, construct_type);
4295 result = handle_type_attributes(env.attributes, result);
4301 * Check if the declaration of main is suspicious. main should be a
4302 * function with external linkage, returning int, taking either zero
4303 * arguments, two, or three arguments of appropriate types, ie.
4305 * int main([ int argc, char **argv [, char **env ] ]).
4307 * @param decl the declaration to check
4308 * @param type the function type of the declaration
4310 static void check_type_of_main(const entity_t *entity)
4312 const source_position_t *pos = &entity->base.source_position;
4313 if (entity->kind != ENTITY_FUNCTION) {
4314 warningf(pos, "'main' is not a function");
4318 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4319 warningf(pos, "'main' is normally a non-static function");
4322 type_t *type = skip_typeref(entity->declaration.type);
4323 assert(is_type_function(type));
4325 function_type_t *func_type = &type->function;
4326 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4327 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4328 func_type->return_type);
4330 const function_parameter_t *parm = func_type->parameters;
4332 type_t *const first_type = parm->type;
4333 if (!types_compatible(skip_typeref(first_type), type_int)) {
4335 "first argument of 'main' should be 'int', but is '%T'",
4340 type_t *const second_type = parm->type;
4341 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4342 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4346 type_t *const third_type = parm->type;
4347 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4348 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4352 goto warn_arg_count;
4356 warningf(pos, "'main' takes only zero, two or three arguments");
4362 * Check if a symbol is the equal to "main".
4364 static bool is_sym_main(const symbol_t *const sym)
4366 return strcmp(sym->string, "main") == 0;
4369 static void error_redefined_as_different_kind(const source_position_t *pos,
4370 const entity_t *old, entity_kind_t new_kind)
4372 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4373 get_entity_kind_name(old->kind), old->base.symbol,
4374 get_entity_kind_name(new_kind), &old->base.source_position);
4377 static bool is_error_entity(entity_t *const ent)
4379 if (is_declaration(ent)) {
4380 return is_type_valid(skip_typeref(ent->declaration.type));
4381 } else if (ent->kind == ENTITY_TYPEDEF) {
4382 return is_type_valid(skip_typeref(ent->typedefe.type));
4388 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4389 * for various problems that occur for multiple definitions
4391 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4393 const symbol_t *const symbol = entity->base.symbol;
4394 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4395 const source_position_t *pos = &entity->base.source_position;
4397 /* can happen in error cases */
4401 entity_t *const previous_entity = get_entity(symbol, namespc);
4402 /* pushing the same entity twice will break the stack structure */
4403 assert(previous_entity != entity);
4405 if (entity->kind == ENTITY_FUNCTION) {
4406 type_t *const orig_type = entity->declaration.type;
4407 type_t *const type = skip_typeref(orig_type);
4409 assert(is_type_function(type));
4410 if (type->function.unspecified_parameters &&
4411 warning.strict_prototypes &&
4412 previous_entity == NULL) {
4413 warningf(pos, "function declaration '%#T' is not a prototype",
4417 if (warning.main && current_scope == file_scope
4418 && is_sym_main(symbol)) {
4419 check_type_of_main(entity);
4423 if (is_declaration(entity) &&
4424 warning.nested_externs &&
4425 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4426 current_scope != file_scope) {
4427 warningf(pos, "nested extern declaration of '%#T'",
4428 entity->declaration.type, symbol);
4431 if (previous_entity != NULL) {
4432 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4433 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4434 assert(previous_entity->kind == ENTITY_PARAMETER);
4436 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4437 entity->declaration.type, symbol,
4438 previous_entity->declaration.type, symbol,
4439 &previous_entity->base.source_position);
4443 if (previous_entity->base.parent_scope == current_scope) {
4444 if (previous_entity->kind != entity->kind) {
4445 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4446 error_redefined_as_different_kind(pos, previous_entity,
4451 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4452 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4453 symbol, &previous_entity->base.source_position);
4456 if (previous_entity->kind == ENTITY_TYPEDEF) {
4457 /* TODO: C++ allows this for exactly the same type */
4458 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4459 symbol, &previous_entity->base.source_position);
4463 /* at this point we should have only VARIABLES or FUNCTIONS */
4464 assert(is_declaration(previous_entity) && is_declaration(entity));
4466 declaration_t *const prev_decl = &previous_entity->declaration;
4467 declaration_t *const decl = &entity->declaration;
4469 /* can happen for K&R style declarations */
4470 if (prev_decl->type == NULL &&
4471 previous_entity->kind == ENTITY_PARAMETER &&
4472 entity->kind == ENTITY_PARAMETER) {
4473 prev_decl->type = decl->type;
4474 prev_decl->storage_class = decl->storage_class;
4475 prev_decl->declared_storage_class = decl->declared_storage_class;
4476 prev_decl->modifiers = decl->modifiers;
4477 return previous_entity;
4480 type_t *const orig_type = decl->type;
4481 assert(orig_type != NULL);
4482 type_t *const type = skip_typeref(orig_type);
4483 type_t *const prev_type = skip_typeref(prev_decl->type);
4485 if (!types_compatible(type, prev_type)) {
4487 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4488 orig_type, symbol, prev_decl->type, symbol,
4489 &previous_entity->base.source_position);
4491 unsigned old_storage_class = prev_decl->storage_class;
4492 if (warning.redundant_decls &&
4495 !(prev_decl->modifiers & DM_USED) &&
4496 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4497 warningf(&previous_entity->base.source_position,
4498 "unnecessary static forward declaration for '%#T'",
4499 prev_decl->type, symbol);
4502 storage_class_t new_storage_class = decl->storage_class;
4504 /* pretend no storage class means extern for function
4505 * declarations (except if the previous declaration is neither
4506 * none nor extern) */
4507 if (entity->kind == ENTITY_FUNCTION) {
4508 /* the previous declaration could have unspecified parameters or
4509 * be a typedef, so use the new type */
4510 if (prev_type->function.unspecified_parameters || is_definition)
4511 prev_decl->type = type;
4513 switch (old_storage_class) {
4514 case STORAGE_CLASS_NONE:
4515 old_storage_class = STORAGE_CLASS_EXTERN;
4518 case STORAGE_CLASS_EXTERN:
4519 if (is_definition) {
4520 if (warning.missing_prototypes &&
4521 prev_type->function.unspecified_parameters &&
4522 !is_sym_main(symbol)) {
4523 warningf(pos, "no previous prototype for '%#T'",
4526 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4527 new_storage_class = STORAGE_CLASS_EXTERN;
4534 } else if (is_type_incomplete(prev_type)) {
4535 prev_decl->type = type;
4538 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4539 new_storage_class == STORAGE_CLASS_EXTERN) {
4540 warn_redundant_declaration:
4541 if (!is_definition &&
4542 warning.redundant_decls &&
4543 is_type_valid(prev_type) &&
4544 strcmp(previous_entity->base.source_position.input_name,
4545 "<builtin>") != 0) {
4547 "redundant declaration for '%Y' (declared %P)",
4548 symbol, &previous_entity->base.source_position);
4550 } else if (current_function == NULL) {
4551 if (old_storage_class != STORAGE_CLASS_STATIC &&
4552 new_storage_class == STORAGE_CLASS_STATIC) {
4554 "static declaration of '%Y' follows non-static declaration (declared %P)",
4555 symbol, &previous_entity->base.source_position);
4556 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4557 prev_decl->storage_class = STORAGE_CLASS_NONE;
4558 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4560 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4562 goto error_redeclaration;
4563 goto warn_redundant_declaration;
4565 } else if (is_type_valid(prev_type)) {
4566 if (old_storage_class == new_storage_class) {
4567 error_redeclaration:
4568 errorf(pos, "redeclaration of '%Y' (declared %P)",
4569 symbol, &previous_entity->base.source_position);
4572 "redeclaration of '%Y' with different linkage (declared %P)",
4573 symbol, &previous_entity->base.source_position);
4578 prev_decl->modifiers |= decl->modifiers;
4579 if (entity->kind == ENTITY_FUNCTION) {
4580 previous_entity->function.is_inline |= entity->function.is_inline;
4582 return previous_entity;
4585 if (warning.shadow) {
4586 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4587 get_entity_kind_name(entity->kind), symbol,
4588 get_entity_kind_name(previous_entity->kind),
4589 &previous_entity->base.source_position);
4593 if (entity->kind == ENTITY_FUNCTION) {
4594 if (is_definition &&
4595 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4596 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4597 warningf(pos, "no previous prototype for '%#T'",
4598 entity->declaration.type, symbol);
4599 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4600 warningf(pos, "no previous declaration for '%#T'",
4601 entity->declaration.type, symbol);
4604 } else if (warning.missing_declarations &&
4605 entity->kind == ENTITY_VARIABLE &&
4606 current_scope == file_scope) {
4607 declaration_t *declaration = &entity->declaration;
4608 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4609 warningf(pos, "no previous declaration for '%#T'",
4610 declaration->type, symbol);
4615 assert(entity->base.parent_scope == NULL);
4616 assert(current_scope != NULL);
4618 entity->base.parent_scope = current_scope;
4619 entity->base.namespc = NAMESPACE_NORMAL;
4620 environment_push(entity);
4621 append_entity(current_scope, entity);
4626 static void parser_error_multiple_definition(entity_t *entity,
4627 const source_position_t *source_position)
4629 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4630 entity->base.symbol, &entity->base.source_position);
4633 static bool is_declaration_specifier(const token_t *token,
4634 bool only_specifiers_qualifiers)
4636 switch (token->type) {
4641 return is_typedef_symbol(token->v.symbol);
4643 case T___extension__:
4645 return !only_specifiers_qualifiers;
4652 static void parse_init_declarator_rest(entity_t *entity)
4654 assert(is_declaration(entity));
4655 declaration_t *const declaration = &entity->declaration;
4659 type_t *orig_type = declaration->type;
4660 type_t *type = skip_typeref(orig_type);
4662 if (entity->kind == ENTITY_VARIABLE
4663 && entity->variable.initializer != NULL) {
4664 parser_error_multiple_definition(entity, HERE);
4667 bool must_be_constant = false;
4668 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4669 entity->base.parent_scope == file_scope) {
4670 must_be_constant = true;
4673 if (is_type_function(type)) {
4674 errorf(&entity->base.source_position,
4675 "function '%#T' is initialized like a variable",
4676 orig_type, entity->base.symbol);
4677 orig_type = type_error_type;
4680 parse_initializer_env_t env;
4681 env.type = orig_type;
4682 env.must_be_constant = must_be_constant;
4683 env.entity = entity;
4684 current_init_decl = entity;
4686 initializer_t *initializer = parse_initializer(&env);
4687 current_init_decl = NULL;
4689 if (entity->kind == ENTITY_VARIABLE) {
4690 /* §6.7.5:22 array initializers for arrays with unknown size
4691 * determine the array type size */
4692 declaration->type = env.type;
4693 entity->variable.initializer = initializer;
4697 /* parse rest of a declaration without any declarator */
4698 static void parse_anonymous_declaration_rest(
4699 const declaration_specifiers_t *specifiers)
4702 anonymous_entity = NULL;
4704 if (warning.other) {
4705 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4706 specifiers->thread_local) {
4707 warningf(&specifiers->source_position,
4708 "useless storage class in empty declaration");
4711 type_t *type = specifiers->type;
4712 switch (type->kind) {
4713 case TYPE_COMPOUND_STRUCT:
4714 case TYPE_COMPOUND_UNION: {
4715 if (type->compound.compound->base.symbol == NULL) {
4716 warningf(&specifiers->source_position,
4717 "unnamed struct/union that defines no instances");
4726 warningf(&specifiers->source_position, "empty declaration");
4732 static void check_variable_type_complete(entity_t *ent)
4734 if (ent->kind != ENTITY_VARIABLE)
4737 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4738 * type for the object shall be complete [...] */
4739 declaration_t *decl = &ent->declaration;
4740 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4741 decl->storage_class == STORAGE_CLASS_STATIC)
4744 type_t *const orig_type = decl->type;
4745 type_t *const type = skip_typeref(orig_type);
4746 if (!is_type_incomplete(type))
4749 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4750 * are given length one. */
4751 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4752 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4756 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4757 orig_type, ent->base.symbol);
4761 static void parse_declaration_rest(entity_t *ndeclaration,
4762 const declaration_specifiers_t *specifiers,
4763 parsed_declaration_func finished_declaration,
4764 declarator_flags_t flags)
4766 add_anchor_token(';');
4767 add_anchor_token(',');
4769 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4771 if (token.type == '=') {
4772 parse_init_declarator_rest(entity);
4773 } else if (entity->kind == ENTITY_VARIABLE) {
4774 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4775 * [...] where the extern specifier is explicitly used. */
4776 declaration_t *decl = &entity->declaration;
4777 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4778 type_t *type = decl->type;
4779 if (is_type_reference(skip_typeref(type))) {
4780 errorf(&entity->base.source_position,
4781 "reference '%#T' must be initialized",
4782 type, entity->base.symbol);
4787 check_variable_type_complete(entity);
4789 if (token.type != ',')
4793 add_anchor_token('=');
4794 ndeclaration = parse_declarator(specifiers, flags);
4795 rem_anchor_token('=');
4797 expect(';', end_error);
4800 anonymous_entity = NULL;
4801 rem_anchor_token(';');
4802 rem_anchor_token(',');
4805 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4807 symbol_t *symbol = entity->base.symbol;
4808 if (symbol == NULL) {
4809 errorf(HERE, "anonymous declaration not valid as function parameter");
4813 assert(entity->base.namespc == NAMESPACE_NORMAL);
4814 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4815 if (previous_entity == NULL
4816 || previous_entity->base.parent_scope != current_scope) {
4817 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4822 if (is_definition) {
4823 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4826 return record_entity(entity, false);
4829 static void parse_declaration(parsed_declaration_func finished_declaration,
4830 declarator_flags_t flags)
4832 declaration_specifiers_t specifiers;
4833 memset(&specifiers, 0, sizeof(specifiers));
4835 add_anchor_token(';');
4836 parse_declaration_specifiers(&specifiers);
4837 rem_anchor_token(';');
4839 if (token.type == ';') {
4840 parse_anonymous_declaration_rest(&specifiers);
4842 entity_t *entity = parse_declarator(&specifiers, flags);
4843 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4848 static type_t *get_default_promoted_type(type_t *orig_type)
4850 type_t *result = orig_type;
4852 type_t *type = skip_typeref(orig_type);
4853 if (is_type_integer(type)) {
4854 result = promote_integer(type);
4855 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4856 result = type_double;
4862 static void parse_kr_declaration_list(entity_t *entity)
4864 if (entity->kind != ENTITY_FUNCTION)
4867 type_t *type = skip_typeref(entity->declaration.type);
4868 assert(is_type_function(type));
4869 if (!type->function.kr_style_parameters)
4873 add_anchor_token('{');
4875 /* push function parameters */
4876 size_t const top = environment_top();
4877 scope_t *old_scope = scope_push(&entity->function.parameters);
4879 entity_t *parameter = entity->function.parameters.entities;
4880 for ( ; parameter != NULL; parameter = parameter->base.next) {
4881 assert(parameter->base.parent_scope == NULL);
4882 parameter->base.parent_scope = current_scope;
4883 environment_push(parameter);
4886 /* parse declaration list */
4888 switch (token.type) {
4890 case T___extension__:
4891 /* This covers symbols, which are no type, too, and results in
4892 * better error messages. The typical cases are misspelled type
4893 * names and missing includes. */
4895 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4903 /* pop function parameters */
4904 assert(current_scope == &entity->function.parameters);
4905 scope_pop(old_scope);
4906 environment_pop_to(top);
4908 /* update function type */
4909 type_t *new_type = duplicate_type(type);
4911 function_parameter_t *parameters = NULL;
4912 function_parameter_t **anchor = ¶meters;
4914 parameter = entity->function.parameters.entities;
4915 for (; parameter != NULL; parameter = parameter->base.next) {
4916 if (parameter->kind != ENTITY_PARAMETER)
4919 type_t *parameter_type = parameter->declaration.type;
4920 if (parameter_type == NULL) {
4922 errorf(HERE, "no type specified for function parameter '%Y'",
4923 parameter->base.symbol);
4924 parameter_type = type_error_type;
4926 if (warning.implicit_int) {
4927 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4928 parameter->base.symbol);
4930 parameter_type = type_int;
4932 parameter->declaration.type = parameter_type;
4935 semantic_parameter_incomplete(parameter);
4938 * we need the default promoted types for the function type
4940 parameter_type = get_default_promoted_type(parameter_type);
4942 function_parameter_t *const parameter =
4943 allocate_parameter(parameter_type);
4945 *anchor = parameter;
4946 anchor = ¶meter->next;
4949 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4951 new_type->function.parameters = parameters;
4952 new_type->function.unspecified_parameters = true;
4954 new_type = identify_new_type(new_type);
4956 entity->declaration.type = new_type;
4958 rem_anchor_token('{');
4961 static bool first_err = true;
4964 * When called with first_err set, prints the name of the current function,
4967 static void print_in_function(void)
4971 diagnosticf("%s: In function '%Y':\n",
4972 current_function->base.base.source_position.input_name,
4973 current_function->base.base.symbol);
4978 * Check if all labels are defined in the current function.
4979 * Check if all labels are used in the current function.
4981 static void check_labels(void)
4983 for (const goto_statement_t *goto_statement = goto_first;
4984 goto_statement != NULL;
4985 goto_statement = goto_statement->next) {
4986 /* skip computed gotos */
4987 if (goto_statement->expression != NULL)
4990 label_t *label = goto_statement->label;
4993 if (label->base.source_position.input_name == NULL) {
4994 print_in_function();
4995 errorf(&goto_statement->base.source_position,
4996 "label '%Y' used but not defined", label->base.symbol);
5000 if (warning.unused_label) {
5001 for (const label_statement_t *label_statement = label_first;
5002 label_statement != NULL;
5003 label_statement = label_statement->next) {
5004 label_t *label = label_statement->label;
5006 if (! label->used) {
5007 print_in_function();
5008 warningf(&label_statement->base.source_position,
5009 "label '%Y' defined but not used", label->base.symbol);
5015 static void warn_unused_entity(entity_t *entity, entity_t *last)
5017 entity_t const *const end = last != NULL ? last->base.next : NULL;
5018 for (; entity != end; entity = entity->base.next) {
5019 if (!is_declaration(entity))
5022 declaration_t *declaration = &entity->declaration;
5023 if (declaration->implicit)
5026 if (!declaration->used) {
5027 print_in_function();
5028 const char *what = get_entity_kind_name(entity->kind);
5029 warningf(&entity->base.source_position, "%s '%Y' is unused",
5030 what, entity->base.symbol);
5031 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
5032 print_in_function();
5033 const char *what = get_entity_kind_name(entity->kind);
5034 warningf(&entity->base.source_position, "%s '%Y' is never read",
5035 what, entity->base.symbol);
5040 static void check_unused_variables(statement_t *const stmt, void *const env)
5044 switch (stmt->kind) {
5045 case STATEMENT_DECLARATION: {
5046 declaration_statement_t const *const decls = &stmt->declaration;
5047 warn_unused_entity(decls->declarations_begin,
5048 decls->declarations_end);
5053 warn_unused_entity(stmt->fors.scope.entities, NULL);
5062 * Check declarations of current_function for unused entities.
5064 static void check_declarations(void)
5066 if (warning.unused_parameter) {
5067 const scope_t *scope = ¤t_function->parameters;
5069 /* do not issue unused warnings for main */
5070 if (!is_sym_main(current_function->base.base.symbol)) {
5071 warn_unused_entity(scope->entities, NULL);
5074 if (warning.unused_variable) {
5075 walk_statements(current_function->statement, check_unused_variables,
5080 static int determine_truth(expression_t const* const cond)
5083 !is_constant_expression(cond) ? 0 :
5084 fold_constant(cond) != 0 ? 1 :
5088 static void check_reachable(statement_t *);
5089 static bool reaches_end;
5091 static bool expression_returns(expression_t const *const expr)
5093 switch (expr->kind) {
5095 expression_t const *const func = expr->call.function;
5096 if (func->kind == EXPR_REFERENCE) {
5097 entity_t *entity = func->reference.entity;
5098 if (entity->kind == ENTITY_FUNCTION
5099 && entity->declaration.modifiers & DM_NORETURN)
5103 if (!expression_returns(func))
5106 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5107 if (!expression_returns(arg->expression))
5114 case EXPR_REFERENCE:
5115 case EXPR_REFERENCE_ENUM_VALUE:
5117 case EXPR_CHARACTER_CONSTANT:
5118 case EXPR_WIDE_CHARACTER_CONSTANT:
5119 case EXPR_STRING_LITERAL:
5120 case EXPR_WIDE_STRING_LITERAL:
5121 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5122 case EXPR_LABEL_ADDRESS:
5123 case EXPR_CLASSIFY_TYPE:
5124 case EXPR_SIZEOF: // TODO handle obscure VLA case
5127 case EXPR_BUILTIN_CONSTANT_P:
5128 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5133 case EXPR_STATEMENT: {
5134 bool old_reaches_end = reaches_end;
5135 reaches_end = false;
5136 check_reachable(expr->statement.statement);
5137 bool returns = reaches_end;
5138 reaches_end = old_reaches_end;
5142 case EXPR_CONDITIONAL:
5143 // TODO handle constant expression
5145 if (!expression_returns(expr->conditional.condition))
5148 if (expr->conditional.true_expression != NULL
5149 && expression_returns(expr->conditional.true_expression))
5152 return expression_returns(expr->conditional.false_expression);
5155 return expression_returns(expr->select.compound);
5157 case EXPR_ARRAY_ACCESS:
5159 expression_returns(expr->array_access.array_ref) &&
5160 expression_returns(expr->array_access.index);
5163 return expression_returns(expr->va_starte.ap);
5166 return expression_returns(expr->va_arge.ap);
5169 return expression_returns(expr->va_copye.src);
5171 EXPR_UNARY_CASES_MANDATORY
5172 return expression_returns(expr->unary.value);
5174 case EXPR_UNARY_THROW:
5178 // TODO handle constant lhs of && and ||
5180 expression_returns(expr->binary.left) &&
5181 expression_returns(expr->binary.right);
5187 panic("unhandled expression");
5190 static bool initializer_returns(initializer_t const *const init)
5192 switch (init->kind) {
5193 case INITIALIZER_VALUE:
5194 return expression_returns(init->value.value);
5196 case INITIALIZER_LIST: {
5197 initializer_t * const* i = init->list.initializers;
5198 initializer_t * const* const end = i + init->list.len;
5199 bool returns = true;
5200 for (; i != end; ++i) {
5201 if (!initializer_returns(*i))
5207 case INITIALIZER_STRING:
5208 case INITIALIZER_WIDE_STRING:
5209 case INITIALIZER_DESIGNATOR: // designators have no payload
5212 panic("unhandled initializer");
5215 static bool noreturn_candidate;
5217 static void check_reachable(statement_t *const stmt)
5219 if (stmt->base.reachable)
5221 if (stmt->kind != STATEMENT_DO_WHILE)
5222 stmt->base.reachable = true;
5224 statement_t *last = stmt;
5226 switch (stmt->kind) {
5227 case STATEMENT_INVALID:
5228 case STATEMENT_EMPTY:
5230 next = stmt->base.next;
5233 case STATEMENT_DECLARATION: {
5234 declaration_statement_t const *const decl = &stmt->declaration;
5235 entity_t const * ent = decl->declarations_begin;
5236 entity_t const *const last = decl->declarations_end;
5238 for (;; ent = ent->base.next) {
5239 if (ent->kind == ENTITY_VARIABLE &&
5240 ent->variable.initializer != NULL &&
5241 !initializer_returns(ent->variable.initializer)) {
5248 next = stmt->base.next;
5252 case STATEMENT_COMPOUND:
5253 next = stmt->compound.statements;
5255 next = stmt->base.next;
5258 case STATEMENT_RETURN: {
5259 expression_t const *const val = stmt->returns.value;
5260 if (val == NULL || expression_returns(val))
5261 noreturn_candidate = false;
5265 case STATEMENT_IF: {
5266 if_statement_t const *const ifs = &stmt->ifs;
5267 expression_t const *const cond = ifs->condition;
5269 if (!expression_returns(cond))
5272 int const val = determine_truth(cond);
5275 check_reachable(ifs->true_statement);
5280 if (ifs->false_statement != NULL) {
5281 check_reachable(ifs->false_statement);
5285 next = stmt->base.next;
5289 case STATEMENT_SWITCH: {
5290 switch_statement_t const *const switchs = &stmt->switchs;
5291 expression_t const *const expr = switchs->expression;
5293 if (!expression_returns(expr))
5296 if (is_constant_expression(expr)) {
5297 long const val = fold_constant(expr);
5298 case_label_statement_t * defaults = NULL;
5299 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5300 if (i->expression == NULL) {
5305 if (i->first_case <= val && val <= i->last_case) {
5306 check_reachable((statement_t*)i);
5311 if (defaults != NULL) {
5312 check_reachable((statement_t*)defaults);
5316 bool has_default = false;
5317 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5318 if (i->expression == NULL)
5321 check_reachable((statement_t*)i);
5328 next = stmt->base.next;
5332 case STATEMENT_EXPRESSION: {
5333 /* Check for noreturn function call */
5334 expression_t const *const expr = stmt->expression.expression;
5335 if (!expression_returns(expr))
5338 next = stmt->base.next;
5342 case STATEMENT_CONTINUE: {
5343 statement_t *parent = stmt;
5345 parent = parent->base.parent;
5346 if (parent == NULL) /* continue not within loop */
5350 switch (parent->kind) {
5351 case STATEMENT_WHILE: goto continue_while;
5352 case STATEMENT_DO_WHILE: goto continue_do_while;
5353 case STATEMENT_FOR: goto continue_for;
5360 case STATEMENT_BREAK: {
5361 statement_t *parent = stmt;
5363 parent = parent->base.parent;
5364 if (parent == NULL) /* break not within loop/switch */
5367 switch (parent->kind) {
5368 case STATEMENT_SWITCH:
5369 case STATEMENT_WHILE:
5370 case STATEMENT_DO_WHILE:
5373 next = parent->base.next;
5374 goto found_break_parent;
5383 case STATEMENT_GOTO:
5384 if (stmt->gotos.expression) {
5385 if (!expression_returns(stmt->gotos.expression))
5388 statement_t *parent = stmt->base.parent;
5389 if (parent == NULL) /* top level goto */
5393 next = stmt->gotos.label->statement;
5394 if (next == NULL) /* missing label */
5399 case STATEMENT_LABEL:
5400 next = stmt->label.statement;
5403 case STATEMENT_CASE_LABEL:
5404 next = stmt->case_label.statement;
5407 case STATEMENT_WHILE: {
5408 while_statement_t const *const whiles = &stmt->whiles;
5409 expression_t const *const cond = whiles->condition;
5411 if (!expression_returns(cond))
5414 int const val = determine_truth(cond);
5417 check_reachable(whiles->body);
5422 next = stmt->base.next;
5426 case STATEMENT_DO_WHILE:
5427 next = stmt->do_while.body;
5430 case STATEMENT_FOR: {
5431 for_statement_t *const fors = &stmt->fors;
5433 if (fors->condition_reachable)
5435 fors->condition_reachable = true;
5437 expression_t const *const cond = fors->condition;
5442 } else if (expression_returns(cond)) {
5443 val = determine_truth(cond);
5449 check_reachable(fors->body);
5454 next = stmt->base.next;
5458 case STATEMENT_MS_TRY: {
5459 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5460 check_reachable(ms_try->try_statement);
5461 next = ms_try->final_statement;
5465 case STATEMENT_LEAVE: {
5466 statement_t *parent = stmt;
5468 parent = parent->base.parent;
5469 if (parent == NULL) /* __leave not within __try */
5472 if (parent->kind == STATEMENT_MS_TRY) {
5474 next = parent->ms_try.final_statement;
5482 panic("invalid statement kind");
5485 while (next == NULL) {
5486 next = last->base.parent;
5488 noreturn_candidate = false;
5490 type_t *const type = skip_typeref(current_function->base.type);
5491 assert(is_type_function(type));
5492 type_t *const ret = skip_typeref(type->function.return_type);
5493 if (warning.return_type &&
5494 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5495 is_type_valid(ret) &&
5496 !is_sym_main(current_function->base.base.symbol)) {
5497 warningf(&stmt->base.source_position,
5498 "control reaches end of non-void function");
5503 switch (next->kind) {
5504 case STATEMENT_INVALID:
5505 case STATEMENT_EMPTY:
5506 case STATEMENT_DECLARATION:
5507 case STATEMENT_EXPRESSION:
5509 case STATEMENT_RETURN:
5510 case STATEMENT_CONTINUE:
5511 case STATEMENT_BREAK:
5512 case STATEMENT_GOTO:
5513 case STATEMENT_LEAVE:
5514 panic("invalid control flow in function");
5516 case STATEMENT_COMPOUND:
5517 if (next->compound.stmt_expr) {
5523 case STATEMENT_SWITCH:
5524 case STATEMENT_LABEL:
5525 case STATEMENT_CASE_LABEL:
5527 next = next->base.next;
5530 case STATEMENT_WHILE: {
5532 if (next->base.reachable)
5534 next->base.reachable = true;
5536 while_statement_t const *const whiles = &next->whiles;
5537 expression_t const *const cond = whiles->condition;
5539 if (!expression_returns(cond))
5542 int const val = determine_truth(cond);
5545 check_reachable(whiles->body);
5551 next = next->base.next;
5555 case STATEMENT_DO_WHILE: {
5557 if (next->base.reachable)
5559 next->base.reachable = true;
5561 do_while_statement_t const *const dw = &next->do_while;
5562 expression_t const *const cond = dw->condition;
5564 if (!expression_returns(cond))
5567 int const val = determine_truth(cond);
5570 check_reachable(dw->body);
5576 next = next->base.next;
5580 case STATEMENT_FOR: {
5582 for_statement_t *const fors = &next->fors;
5584 fors->step_reachable = true;
5586 if (fors->condition_reachable)
5588 fors->condition_reachable = true;
5590 expression_t const *const cond = fors->condition;
5595 } else if (expression_returns(cond)) {
5596 val = determine_truth(cond);
5602 check_reachable(fors->body);
5608 next = next->base.next;
5612 case STATEMENT_MS_TRY:
5614 next = next->ms_try.final_statement;
5619 check_reachable(next);
5622 static void check_unreachable(statement_t* const stmt, void *const env)
5626 switch (stmt->kind) {
5627 case STATEMENT_DO_WHILE:
5628 if (!stmt->base.reachable) {
5629 expression_t const *const cond = stmt->do_while.condition;
5630 if (determine_truth(cond) >= 0) {
5631 warningf(&cond->base.source_position,
5632 "condition of do-while-loop is unreachable");
5637 case STATEMENT_FOR: {
5638 for_statement_t const* const fors = &stmt->fors;
5640 // if init and step are unreachable, cond is unreachable, too
5641 if (!stmt->base.reachable && !fors->step_reachable) {
5642 warningf(&stmt->base.source_position, "statement is unreachable");
5644 if (!stmt->base.reachable && fors->initialisation != NULL) {
5645 warningf(&fors->initialisation->base.source_position,
5646 "initialisation of for-statement is unreachable");
5649 if (!fors->condition_reachable && fors->condition != NULL) {
5650 warningf(&fors->condition->base.source_position,
5651 "condition of for-statement is unreachable");
5654 if (!fors->step_reachable && fors->step != NULL) {
5655 warningf(&fors->step->base.source_position,
5656 "step of for-statement is unreachable");
5662 case STATEMENT_COMPOUND:
5663 if (stmt->compound.statements != NULL)
5665 goto warn_unreachable;
5667 case STATEMENT_DECLARATION: {
5668 /* Only warn if there is at least one declarator with an initializer.
5669 * This typically occurs in switch statements. */
5670 declaration_statement_t const *const decl = &stmt->declaration;
5671 entity_t const * ent = decl->declarations_begin;
5672 entity_t const *const last = decl->declarations_end;
5674 for (;; ent = ent->base.next) {
5675 if (ent->kind == ENTITY_VARIABLE &&
5676 ent->variable.initializer != NULL) {
5677 goto warn_unreachable;
5687 if (!stmt->base.reachable)
5688 warningf(&stmt->base.source_position, "statement is unreachable");
5693 static void parse_external_declaration(void)
5695 /* function-definitions and declarations both start with declaration
5697 declaration_specifiers_t specifiers;
5698 memset(&specifiers, 0, sizeof(specifiers));
5700 add_anchor_token(';');
5701 parse_declaration_specifiers(&specifiers);
5702 rem_anchor_token(';');
5704 /* must be a declaration */
5705 if (token.type == ';') {
5706 parse_anonymous_declaration_rest(&specifiers);
5710 add_anchor_token(',');
5711 add_anchor_token('=');
5712 add_anchor_token(';');
5713 add_anchor_token('{');
5715 /* declarator is common to both function-definitions and declarations */
5716 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5718 rem_anchor_token('{');
5719 rem_anchor_token(';');
5720 rem_anchor_token('=');
5721 rem_anchor_token(',');
5723 /* must be a declaration */
5724 switch (token.type) {
5728 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5733 /* must be a function definition */
5734 parse_kr_declaration_list(ndeclaration);
5736 if (token.type != '{') {
5737 parse_error_expected("while parsing function definition", '{', NULL);
5738 eat_until_matching_token(';');
5742 assert(is_declaration(ndeclaration));
5743 type_t *const orig_type = ndeclaration->declaration.type;
5744 type_t * type = skip_typeref(orig_type);
5746 if (!is_type_function(type)) {
5747 if (is_type_valid(type)) {
5748 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5749 type, ndeclaration->base.symbol);
5753 } else if (is_typeref(orig_type)) {
5755 errorf(&ndeclaration->base.source_position,
5756 "type of function definition '%#T' is a typedef",
5757 orig_type, ndeclaration->base.symbol);
5760 if (warning.aggregate_return &&
5761 is_type_compound(skip_typeref(type->function.return_type))) {
5762 warningf(HERE, "function '%Y' returns an aggregate",
5763 ndeclaration->base.symbol);
5765 if (warning.traditional && !type->function.unspecified_parameters) {
5766 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5767 ndeclaration->base.symbol);
5769 if (warning.old_style_definition && type->function.unspecified_parameters) {
5770 warningf(HERE, "old-style function definition '%Y'",
5771 ndeclaration->base.symbol);
5774 /* §6.7.5.3:14 a function definition with () means no
5775 * parameters (and not unspecified parameters) */
5776 if (type->function.unspecified_parameters &&
5777 type->function.parameters == NULL &&
5778 !type->function.kr_style_parameters) {
5779 type_t *copy = duplicate_type(type);
5780 copy->function.unspecified_parameters = false;
5781 type = identify_new_type(copy);
5783 ndeclaration->declaration.type = type;
5786 entity_t *const entity = record_entity(ndeclaration, true);
5787 assert(entity->kind == ENTITY_FUNCTION);
5788 assert(ndeclaration->kind == ENTITY_FUNCTION);
5790 function_t *function = &entity->function;
5791 if (ndeclaration != entity) {
5792 function->parameters = ndeclaration->function.parameters;
5794 assert(is_declaration(entity));
5795 type = skip_typeref(entity->declaration.type);
5797 /* push function parameters and switch scope */
5798 size_t const top = environment_top();
5799 scope_t *old_scope = scope_push(&function->parameters);
5801 entity_t *parameter = function->parameters.entities;
5802 for (; parameter != NULL; parameter = parameter->base.next) {
5803 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5804 parameter->base.parent_scope = current_scope;
5806 assert(parameter->base.parent_scope == NULL
5807 || parameter->base.parent_scope == current_scope);
5808 parameter->base.parent_scope = current_scope;
5809 if (parameter->base.symbol == NULL) {
5810 errorf(¶meter->base.source_position, "parameter name omitted");
5813 environment_push(parameter);
5816 if (function->statement != NULL) {
5817 parser_error_multiple_definition(entity, HERE);
5820 /* parse function body */
5821 int label_stack_top = label_top();
5822 function_t *old_current_function = current_function;
5823 current_function = function;
5824 current_parent = NULL;
5827 goto_anchor = &goto_first;
5829 label_anchor = &label_first;
5831 statement_t *const body = parse_compound_statement(false);
5832 function->statement = body;
5835 check_declarations();
5836 if (warning.return_type ||
5837 warning.unreachable_code ||
5838 (warning.missing_noreturn
5839 && !(function->base.modifiers & DM_NORETURN))) {
5840 noreturn_candidate = true;
5841 check_reachable(body);
5842 if (warning.unreachable_code)
5843 walk_statements(body, check_unreachable, NULL);
5844 if (warning.missing_noreturn &&
5845 noreturn_candidate &&
5846 !(function->base.modifiers & DM_NORETURN)) {
5847 warningf(&body->base.source_position,
5848 "function '%#T' is candidate for attribute 'noreturn'",
5849 type, entity->base.symbol);
5853 assert(current_parent == NULL);
5854 assert(current_function == function);
5855 current_function = old_current_function;
5856 label_pop_to(label_stack_top);
5859 assert(current_scope == &function->parameters);
5860 scope_pop(old_scope);
5861 environment_pop_to(top);
5864 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5865 source_position_t *source_position,
5866 const symbol_t *symbol)
5868 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5870 type->bitfield.base_type = base_type;
5871 type->bitfield.size_expression = size;
5874 type_t *skipped_type = skip_typeref(base_type);
5875 if (!is_type_integer(skipped_type)) {
5876 errorf(HERE, "bitfield base type '%T' is not an integer type",
5880 bit_size = get_type_size(base_type) * 8;
5883 if (is_constant_expression(size)) {
5884 long v = fold_constant(size);
5887 errorf(source_position, "negative width in bit-field '%Y'", symbol);
5888 } else if (v == 0) {
5889 errorf(source_position, "zero width for bit-field '%Y'", symbol);
5890 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5891 errorf(source_position, "width of '%Y' exceeds its type", symbol);
5893 type->bitfield.bit_size = v;
5900 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5902 entity_t *iter = compound->members.entities;
5903 for (; iter != NULL; iter = iter->base.next) {
5904 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5907 if (iter->base.symbol == symbol) {
5909 } else if (iter->base.symbol == NULL) {
5910 type_t *type = skip_typeref(iter->declaration.type);
5911 if (is_type_compound(type)) {
5913 = find_compound_entry(type->compound.compound, symbol);
5924 static void parse_compound_declarators(compound_t *compound,
5925 const declaration_specifiers_t *specifiers)
5930 if (token.type == ':') {
5931 source_position_t source_position = *HERE;
5934 type_t *base_type = specifiers->type;
5935 expression_t *size = parse_constant_expression();
5937 type_t *type = make_bitfield_type(base_type, size,
5938 &source_position, sym_anonymous);
5940 attribute_t *attributes = parse_attributes(NULL);
5941 if (attributes != NULL) {
5942 attribute_t *last = attributes;
5943 while (last->next != NULL)
5945 last->next = specifiers->attributes;
5947 attributes = specifiers->attributes;
5950 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5951 entity->base.namespc = NAMESPACE_NORMAL;
5952 entity->base.source_position = source_position;
5953 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5954 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5955 entity->declaration.type = type;
5956 entity->declaration.attributes = attributes;
5958 if (attributes != NULL) {
5959 handle_entity_attributes(attributes, entity);
5961 append_entity(&compound->members, entity);
5963 entity = parse_declarator(specifiers,
5964 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5965 if (entity->kind == ENTITY_TYPEDEF) {
5966 errorf(&entity->base.source_position,
5967 "typedef not allowed as compound member");
5969 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5971 /* make sure we don't define a symbol multiple times */
5972 symbol_t *symbol = entity->base.symbol;
5973 if (symbol != NULL) {
5974 entity_t *prev = find_compound_entry(compound, symbol);
5976 errorf(&entity->base.source_position,
5977 "multiple declarations of symbol '%Y' (declared %P)",
5978 symbol, &prev->base.source_position);
5982 if (token.type == ':') {
5983 source_position_t source_position = *HERE;
5985 expression_t *size = parse_constant_expression();
5987 type_t *type = entity->declaration.type;
5988 type_t *bitfield_type = make_bitfield_type(type, size,
5989 &source_position, entity->base.symbol);
5991 attribute_t *attributes = parse_attributes(NULL);
5992 entity->declaration.type = bitfield_type;
5993 handle_entity_attributes(attributes, entity);
5995 type_t *orig_type = entity->declaration.type;
5996 type_t *type = skip_typeref(orig_type);
5997 if (is_type_function(type)) {
5998 errorf(&entity->base.source_position,
5999 "compound member '%Y' must not have function type '%T'",
6000 entity->base.symbol, orig_type);
6001 } else if (is_type_incomplete(type)) {
6002 /* §6.7.2.1:16 flexible array member */
6003 if (!is_type_array(type) ||
6004 token.type != ';' ||
6005 look_ahead(1)->type != '}') {
6006 errorf(&entity->base.source_position,
6007 "compound member '%Y' has incomplete type '%T'",
6008 entity->base.symbol, orig_type);
6013 append_entity(&compound->members, entity);
6017 if (token.type != ',')
6021 expect(';', end_error);
6024 anonymous_entity = NULL;
6027 static void parse_compound_type_entries(compound_t *compound)
6030 add_anchor_token('}');
6032 while (token.type != '}') {
6033 if (token.type == T_EOF) {
6034 errorf(HERE, "EOF while parsing struct");
6037 declaration_specifiers_t specifiers;
6038 memset(&specifiers, 0, sizeof(specifiers));
6039 parse_declaration_specifiers(&specifiers);
6041 parse_compound_declarators(compound, &specifiers);
6043 rem_anchor_token('}');
6047 compound->complete = true;
6050 static type_t *parse_typename(void)
6052 declaration_specifiers_t specifiers;
6053 memset(&specifiers, 0, sizeof(specifiers));
6054 parse_declaration_specifiers(&specifiers);
6055 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6056 specifiers.thread_local) {
6057 /* TODO: improve error message, user does probably not know what a
6058 * storage class is...
6060 errorf(HERE, "typename may not have a storage class");
6063 type_t *result = parse_abstract_declarator(specifiers.type);
6071 typedef expression_t* (*parse_expression_function)(void);
6072 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6074 typedef struct expression_parser_function_t expression_parser_function_t;
6075 struct expression_parser_function_t {
6076 parse_expression_function parser;
6077 precedence_t infix_precedence;
6078 parse_expression_infix_function infix_parser;
6081 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6084 * Prints an error message if an expression was expected but not read
6086 static expression_t *expected_expression_error(void)
6088 /* skip the error message if the error token was read */
6089 if (token.type != T_ERROR) {
6090 errorf(HERE, "expected expression, got token %K", &token);
6094 return create_invalid_expression();
6098 * Parse a string constant.
6100 static expression_t *parse_string_const(void)
6103 if (token.type == T_STRING_LITERAL) {
6104 string_t res = token.v.string;
6106 while (token.type == T_STRING_LITERAL) {
6107 res = concat_strings(&res, &token.v.string);
6110 if (token.type != T_WIDE_STRING_LITERAL) {
6111 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6112 /* note: that we use type_char_ptr here, which is already the
6113 * automatic converted type. revert_automatic_type_conversion
6114 * will construct the array type */
6115 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6116 cnst->string.value = res;
6120 wres = concat_string_wide_string(&res, &token.v.wide_string);
6122 wres = token.v.wide_string;
6127 switch (token.type) {
6128 case T_WIDE_STRING_LITERAL:
6129 wres = concat_wide_strings(&wres, &token.v.wide_string);
6132 case T_STRING_LITERAL:
6133 wres = concat_wide_string_string(&wres, &token.v.string);
6137 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6138 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6139 cnst->wide_string.value = wres;
6148 * Parse a boolean constant.
6150 static expression_t *parse_bool_const(bool value)
6152 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6153 cnst->base.type = type_bool;
6154 cnst->conste.v.int_value = value;
6162 * Parse an integer constant.
6164 static expression_t *parse_int_const(void)
6166 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6167 cnst->base.type = token.datatype;
6168 cnst->conste.v.int_value = token.v.intvalue;
6176 * Parse a character constant.
6178 static expression_t *parse_character_constant(void)
6180 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6181 cnst->base.type = token.datatype;
6182 cnst->conste.v.character = token.v.string;
6184 if (cnst->conste.v.character.size != 1) {
6186 errorf(HERE, "more than 1 character in character constant");
6187 } else if (warning.multichar) {
6188 warningf(HERE, "multi-character character constant");
6197 * Parse a wide character constant.
6199 static expression_t *parse_wide_character_constant(void)
6201 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6202 cnst->base.type = token.datatype;
6203 cnst->conste.v.wide_character = token.v.wide_string;
6205 if (cnst->conste.v.wide_character.size != 1) {
6207 errorf(HERE, "more than 1 character in character constant");
6208 } else if (warning.multichar) {
6209 warningf(HERE, "multi-character character constant");
6218 * Parse a float constant.
6220 static expression_t *parse_float_const(void)
6222 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6223 cnst->base.type = token.datatype;
6224 cnst->conste.v.float_value = token.v.floatvalue;
6231 static entity_t *create_implicit_function(symbol_t *symbol,
6232 const source_position_t *source_position)
6234 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6235 ntype->function.return_type = type_int;
6236 ntype->function.unspecified_parameters = true;
6237 ntype->function.linkage = LINKAGE_C;
6238 type_t *type = identify_new_type(ntype);
6240 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6241 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6242 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6243 entity->declaration.type = type;
6244 entity->declaration.implicit = true;
6245 entity->base.symbol = symbol;
6246 entity->base.source_position = *source_position;
6248 bool strict_prototypes_old = warning.strict_prototypes;
6249 warning.strict_prototypes = false;
6250 record_entity(entity, false);
6251 warning.strict_prototypes = strict_prototypes_old;
6257 * Creates a return_type (func)(argument_type) function type if not
6260 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6261 type_t *argument_type2)
6263 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6264 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6265 parameter1->next = parameter2;
6267 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6268 type->function.return_type = return_type;
6269 type->function.parameters = parameter1;
6271 return identify_new_type(type);
6275 * Creates a return_type (func)(argument_type) function type if not
6278 * @param return_type the return type
6279 * @param argument_type the argument type
6281 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6283 function_parameter_t *const parameter = allocate_parameter(argument_type);
6285 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6286 type->function.return_type = return_type;
6287 type->function.parameters = parameter;
6289 return identify_new_type(type);
6292 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6294 type_t *res = make_function_1_type(return_type, argument_type);
6295 res->function.variadic = 1;
6300 * Creates a return_type (func)(void) function type if not
6303 * @param return_type the return type
6305 static type_t *make_function_0_type(type_t *return_type)
6307 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6308 type->function.return_type = return_type;
6309 type->function.parameters = NULL;
6311 return identify_new_type(type);
6315 * Creates a NO_RETURN return_type (func)(void) function type if not
6318 * @param return_type the return type
6320 static type_t *make_function_0_type_noreturn(type_t *return_type)
6322 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6323 type->function.return_type = return_type;
6324 type->function.parameters = NULL;
6325 type->function.modifiers |= DM_NORETURN;
6326 return identify_new_type(type);
6330 * Performs automatic type cast as described in §6.3.2.1.
6332 * @param orig_type the original type
6334 static type_t *automatic_type_conversion(type_t *orig_type)
6336 type_t *type = skip_typeref(orig_type);
6337 if (is_type_array(type)) {
6338 array_type_t *array_type = &type->array;
6339 type_t *element_type = array_type->element_type;
6340 unsigned qualifiers = array_type->base.qualifiers;
6342 return make_pointer_type(element_type, qualifiers);
6345 if (is_type_function(type)) {
6346 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6353 * reverts the automatic casts of array to pointer types and function
6354 * to function-pointer types as defined §6.3.2.1
6356 type_t *revert_automatic_type_conversion(const expression_t *expression)
6358 switch (expression->kind) {
6359 case EXPR_REFERENCE: {
6360 entity_t *entity = expression->reference.entity;
6361 if (is_declaration(entity)) {
6362 return entity->declaration.type;
6363 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6364 return entity->enum_value.enum_type;
6366 panic("no declaration or enum in reference");
6371 entity_t *entity = expression->select.compound_entry;
6372 assert(is_declaration(entity));
6373 type_t *type = entity->declaration.type;
6374 return get_qualified_type(type,
6375 expression->base.type->base.qualifiers);
6378 case EXPR_UNARY_DEREFERENCE: {
6379 const expression_t *const value = expression->unary.value;
6380 type_t *const type = skip_typeref(value->base.type);
6381 if (!is_type_pointer(type))
6382 return type_error_type;
6383 return type->pointer.points_to;
6386 case EXPR_ARRAY_ACCESS: {
6387 const expression_t *array_ref = expression->array_access.array_ref;
6388 type_t *type_left = skip_typeref(array_ref->base.type);
6389 if (!is_type_pointer(type_left))
6390 return type_error_type;
6391 return type_left->pointer.points_to;
6394 case EXPR_STRING_LITERAL: {
6395 size_t size = expression->string.value.size;
6396 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6399 case EXPR_WIDE_STRING_LITERAL: {
6400 size_t size = expression->wide_string.value.size;
6401 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6404 case EXPR_COMPOUND_LITERAL:
6405 return expression->compound_literal.type;
6408 return expression->base.type;
6412 static void check_deprecated(const source_position_t *source_position,
6413 const entity_t *entity)
6415 if (!warning.deprecated_declarations)
6417 if (!is_declaration(entity))
6419 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
6422 char const *const prefix = get_entity_kind_name(entity->kind);
6423 const char *deprecated_string
6424 = get_deprecated_string(entity->declaration.attributes);
6425 if (deprecated_string != NULL) {
6426 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
6427 prefix, entity->base.symbol, &entity->base.source_position,
6430 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
6431 entity->base.symbol, &entity->base.source_position);
6435 static expression_t *parse_reference(void)
6437 symbol_t *const symbol = token.v.symbol;
6439 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
6441 if (entity == NULL) {
6442 if (!strict_mode && look_ahead(1)->type == '(') {
6443 /* an implicitly declared function */
6444 if (warning.error_implicit_function_declaration) {
6445 errorf(HERE, "implicit declaration of function '%Y'", symbol);
6446 } else if (warning.implicit_function_declaration) {
6447 warningf(HERE, "implicit declaration of function '%Y'", symbol);
6450 entity = create_implicit_function(symbol, HERE);
6452 errorf(HERE, "unknown identifier '%Y' found.", symbol);
6453 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6459 if (is_declaration(entity)) {
6460 orig_type = entity->declaration.type;
6461 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6462 orig_type = entity->enum_value.enum_type;
6464 panic("expected declaration or enum value in reference");
6467 /* we always do the auto-type conversions; the & and sizeof parser contains
6468 * code to revert this! */
6469 type_t *type = automatic_type_conversion(orig_type);
6471 expression_kind_t kind = EXPR_REFERENCE;
6472 if (entity->kind == ENTITY_ENUM_VALUE)
6473 kind = EXPR_REFERENCE_ENUM_VALUE;
6475 expression_t *expression = allocate_expression_zero(kind);
6476 expression->reference.entity = entity;
6477 expression->base.type = type;
6479 /* this declaration is used */
6480 if (is_declaration(entity)) {
6481 entity->declaration.used = true;
6484 if (entity->base.parent_scope != file_scope
6485 && (current_function != NULL && entity->base.parent_scope->depth < current_function->parameters.depth)
6486 && is_type_valid(orig_type) && !is_type_function(orig_type)) {
6487 if (entity->kind == ENTITY_VARIABLE) {
6488 /* access of a variable from an outer function */
6489 entity->variable.address_taken = true;
6490 } else if (entity->kind == ENTITY_PARAMETER) {
6491 entity->parameter.address_taken = true;
6493 current_function->need_closure = true;
6496 check_deprecated(HERE, entity);
6498 if (warning.init_self && entity == current_init_decl && !in_type_prop
6499 && entity->kind == ENTITY_VARIABLE) {
6500 current_init_decl = NULL;
6501 warningf(HERE, "variable '%#T' is initialized by itself",
6502 entity->declaration.type, entity->base.symbol);
6509 static bool semantic_cast(expression_t *cast)
6511 expression_t *expression = cast->unary.value;
6512 type_t *orig_dest_type = cast->base.type;
6513 type_t *orig_type_right = expression->base.type;
6514 type_t const *dst_type = skip_typeref(orig_dest_type);
6515 type_t const *src_type = skip_typeref(orig_type_right);
6516 source_position_t const *pos = &cast->base.source_position;
6518 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6519 if (dst_type == type_void)
6522 /* only integer and pointer can be casted to pointer */
6523 if (is_type_pointer(dst_type) &&
6524 !is_type_pointer(src_type) &&
6525 !is_type_integer(src_type) &&
6526 is_type_valid(src_type)) {
6527 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6531 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6532 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6536 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6537 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6541 if (warning.cast_qual &&
6542 is_type_pointer(src_type) &&
6543 is_type_pointer(dst_type)) {
6544 type_t *src = skip_typeref(src_type->pointer.points_to);
6545 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6546 unsigned missing_qualifiers =
6547 src->base.qualifiers & ~dst->base.qualifiers;
6548 if (missing_qualifiers != 0) {
6550 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6551 missing_qualifiers, orig_type_right);
6557 static expression_t *parse_compound_literal(type_t *type)
6559 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6561 parse_initializer_env_t env;
6564 env.must_be_constant = false;
6565 initializer_t *initializer = parse_initializer(&env);
6568 expression->compound_literal.initializer = initializer;
6569 expression->compound_literal.type = type;
6570 expression->base.type = automatic_type_conversion(type);
6576 * Parse a cast expression.
6578 static expression_t *parse_cast(void)
6580 add_anchor_token(')');
6582 source_position_t source_position = token.source_position;
6584 type_t *type = parse_typename();
6586 rem_anchor_token(')');
6587 expect(')', end_error);
6589 if (token.type == '{') {
6590 return parse_compound_literal(type);
6593 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6594 cast->base.source_position = source_position;
6596 expression_t *value = parse_sub_expression(PREC_CAST);
6597 cast->base.type = type;
6598 cast->unary.value = value;
6600 if (! semantic_cast(cast)) {
6601 /* TODO: record the error in the AST. else it is impossible to detect it */
6606 return create_invalid_expression();
6610 * Parse a statement expression.
6612 static expression_t *parse_statement_expression(void)
6614 add_anchor_token(')');
6616 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6618 statement_t *statement = parse_compound_statement(true);
6619 statement->compound.stmt_expr = true;
6620 expression->statement.statement = statement;
6622 /* find last statement and use its type */
6623 type_t *type = type_void;
6624 const statement_t *stmt = statement->compound.statements;
6626 while (stmt->base.next != NULL)
6627 stmt = stmt->base.next;
6629 if (stmt->kind == STATEMENT_EXPRESSION) {
6630 type = stmt->expression.expression->base.type;
6632 } else if (warning.other) {
6633 warningf(&expression->base.source_position, "empty statement expression ({})");
6635 expression->base.type = type;
6637 rem_anchor_token(')');
6638 expect(')', end_error);
6645 * Parse a parenthesized expression.
6647 static expression_t *parse_parenthesized_expression(void)
6651 switch (token.type) {
6653 /* gcc extension: a statement expression */
6654 return parse_statement_expression();
6658 return parse_cast();
6660 if (is_typedef_symbol(token.v.symbol)) {
6661 return parse_cast();
6665 add_anchor_token(')');
6666 expression_t *result = parse_expression();
6667 result->base.parenthesized = true;
6668 rem_anchor_token(')');
6669 expect(')', end_error);
6675 static expression_t *parse_function_keyword(void)
6679 if (current_function == NULL) {
6680 errorf(HERE, "'__func__' used outside of a function");
6683 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6684 expression->base.type = type_char_ptr;
6685 expression->funcname.kind = FUNCNAME_FUNCTION;
6692 static expression_t *parse_pretty_function_keyword(void)
6694 if (current_function == NULL) {
6695 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6698 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6699 expression->base.type = type_char_ptr;
6700 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6702 eat(T___PRETTY_FUNCTION__);
6707 static expression_t *parse_funcsig_keyword(void)
6709 if (current_function == NULL) {
6710 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6713 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6714 expression->base.type = type_char_ptr;
6715 expression->funcname.kind = FUNCNAME_FUNCSIG;
6722 static expression_t *parse_funcdname_keyword(void)
6724 if (current_function == NULL) {
6725 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6728 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6729 expression->base.type = type_char_ptr;
6730 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6732 eat(T___FUNCDNAME__);
6737 static designator_t *parse_designator(void)
6739 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6740 result->source_position = *HERE;
6742 if (token.type != T_IDENTIFIER) {
6743 parse_error_expected("while parsing member designator",
6744 T_IDENTIFIER, NULL);
6747 result->symbol = token.v.symbol;
6750 designator_t *last_designator = result;
6752 if (token.type == '.') {
6754 if (token.type != T_IDENTIFIER) {
6755 parse_error_expected("while parsing member designator",
6756 T_IDENTIFIER, NULL);
6759 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6760 designator->source_position = *HERE;
6761 designator->symbol = token.v.symbol;
6764 last_designator->next = designator;
6765 last_designator = designator;
6768 if (token.type == '[') {
6770 add_anchor_token(']');
6771 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6772 designator->source_position = *HERE;
6773 designator->array_index = parse_expression();
6774 rem_anchor_token(']');
6775 expect(']', end_error);
6776 if (designator->array_index == NULL) {
6780 last_designator->next = designator;
6781 last_designator = designator;
6793 * Parse the __builtin_offsetof() expression.
6795 static expression_t *parse_offsetof(void)
6797 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6798 expression->base.type = type_size_t;
6800 eat(T___builtin_offsetof);
6802 expect('(', end_error);
6803 add_anchor_token(',');
6804 type_t *type = parse_typename();
6805 rem_anchor_token(',');
6806 expect(',', end_error);
6807 add_anchor_token(')');
6808 designator_t *designator = parse_designator();
6809 rem_anchor_token(')');
6810 expect(')', end_error);
6812 expression->offsetofe.type = type;
6813 expression->offsetofe.designator = designator;
6816 memset(&path, 0, sizeof(path));
6817 path.top_type = type;
6818 path.path = NEW_ARR_F(type_path_entry_t, 0);
6820 descend_into_subtype(&path);
6822 if (!walk_designator(&path, designator, true)) {
6823 return create_invalid_expression();
6826 DEL_ARR_F(path.path);
6830 return create_invalid_expression();
6834 * Parses a _builtin_va_start() expression.
6836 static expression_t *parse_va_start(void)
6838 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6840 eat(T___builtin_va_start);
6842 expect('(', end_error);
6843 add_anchor_token(',');
6844 expression->va_starte.ap = parse_assignment_expression();
6845 rem_anchor_token(',');
6846 expect(',', end_error);
6847 expression_t *const expr = parse_assignment_expression();
6848 if (expr->kind == EXPR_REFERENCE) {
6849 entity_t *const entity = expr->reference.entity;
6850 if (entity->base.parent_scope != ¤t_function->parameters
6851 || entity->base.next != NULL
6852 || entity->kind != ENTITY_PARAMETER) {
6853 errorf(&expr->base.source_position,
6854 "second argument of 'va_start' must be last parameter of the current function");
6856 expression->va_starte.parameter = &entity->variable;
6858 expect(')', end_error);
6861 expect(')', end_error);
6863 return create_invalid_expression();
6867 * Parses a __builtin_va_arg() expression.
6869 static expression_t *parse_va_arg(void)
6871 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6873 eat(T___builtin_va_arg);
6875 expect('(', end_error);
6877 ap.expression = parse_assignment_expression();
6878 expression->va_arge.ap = ap.expression;
6879 check_call_argument(type_valist, &ap, 1);
6881 expect(',', end_error);
6882 expression->base.type = parse_typename();
6883 expect(')', end_error);
6887 return create_invalid_expression();
6891 * Parses a __builtin_va_copy() expression.
6893 static expression_t *parse_va_copy(void)
6895 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6897 eat(T___builtin_va_copy);
6899 expect('(', end_error);
6900 expression_t *dst = parse_assignment_expression();
6901 assign_error_t error = semantic_assign(type_valist, dst);
6902 report_assign_error(error, type_valist, dst, "call argument 1",
6903 &dst->base.source_position);
6904 expression->va_copye.dst = dst;
6906 expect(',', end_error);
6908 call_argument_t src;
6909 src.expression = parse_assignment_expression();
6910 check_call_argument(type_valist, &src, 2);
6911 expression->va_copye.src = src.expression;
6912 expect(')', end_error);
6916 return create_invalid_expression();
6920 * Parses a __builtin_constant_p() expression.
6922 static expression_t *parse_builtin_constant(void)
6924 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6926 eat(T___builtin_constant_p);
6928 expect('(', end_error);
6929 add_anchor_token(')');
6930 expression->builtin_constant.value = parse_assignment_expression();
6931 rem_anchor_token(')');
6932 expect(')', end_error);
6933 expression->base.type = type_int;
6937 return create_invalid_expression();
6941 * Parses a __builtin_types_compatible_p() expression.
6943 static expression_t *parse_builtin_types_compatible(void)
6945 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6947 eat(T___builtin_types_compatible_p);
6949 expect('(', end_error);
6950 add_anchor_token(')');
6951 add_anchor_token(',');
6952 expression->builtin_types_compatible.left = parse_typename();
6953 rem_anchor_token(',');
6954 expect(',', end_error);
6955 expression->builtin_types_compatible.right = parse_typename();
6956 rem_anchor_token(')');
6957 expect(')', end_error);
6958 expression->base.type = type_int;
6962 return create_invalid_expression();
6966 * Parses a __builtin_is_*() compare expression.
6968 static expression_t *parse_compare_builtin(void)
6970 expression_t *expression;
6972 switch (token.type) {
6973 case T___builtin_isgreater:
6974 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6976 case T___builtin_isgreaterequal:
6977 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6979 case T___builtin_isless:
6980 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6982 case T___builtin_islessequal:
6983 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6985 case T___builtin_islessgreater:
6986 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6988 case T___builtin_isunordered:
6989 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6992 internal_errorf(HERE, "invalid compare builtin found");
6994 expression->base.source_position = *HERE;
6997 expect('(', end_error);
6998 expression->binary.left = parse_assignment_expression();
6999 expect(',', end_error);
7000 expression->binary.right = parse_assignment_expression();
7001 expect(')', end_error);
7003 type_t *const orig_type_left = expression->binary.left->base.type;
7004 type_t *const orig_type_right = expression->binary.right->base.type;
7006 type_t *const type_left = skip_typeref(orig_type_left);
7007 type_t *const type_right = skip_typeref(orig_type_right);
7008 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7009 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7010 type_error_incompatible("invalid operands in comparison",
7011 &expression->base.source_position, orig_type_left, orig_type_right);
7014 semantic_comparison(&expression->binary);
7019 return create_invalid_expression();
7024 * Parses a __builtin_expect(, end_error) expression.
7026 static expression_t *parse_builtin_expect(void, end_error)
7028 expression_t *expression
7029 = allocate_expression_zero(EXPR_BINARY_BUILTIN_EXPECT);
7031 eat(T___builtin_expect);
7033 expect('(', end_error);
7034 expression->binary.left = parse_assignment_expression();
7035 expect(',', end_error);
7036 expression->binary.right = parse_constant_expression();
7037 expect(')', end_error);
7039 expression->base.type = expression->binary.left->base.type;
7043 return create_invalid_expression();
7048 * Parses a MS assume() expression.
7050 static expression_t *parse_assume(void)
7052 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7056 expect('(', end_error);
7057 add_anchor_token(')');
7058 expression->unary.value = parse_assignment_expression();
7059 rem_anchor_token(')');
7060 expect(')', end_error);
7062 expression->base.type = type_void;
7065 return create_invalid_expression();
7069 * Return the declaration for a given label symbol or create a new one.
7071 * @param symbol the symbol of the label
7073 static label_t *get_label(symbol_t *symbol)
7076 assert(current_function != NULL);
7078 label = get_entity(symbol, NAMESPACE_LABEL);
7079 /* if we found a local label, we already created the declaration */
7080 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7081 if (label->base.parent_scope != current_scope) {
7082 assert(label->base.parent_scope->depth < current_scope->depth);
7083 current_function->goto_to_outer = true;
7085 return &label->label;
7088 label = get_entity(symbol, NAMESPACE_LABEL);
7089 /* if we found a label in the same function, then we already created the
7092 && label->base.parent_scope == ¤t_function->parameters) {
7093 return &label->label;
7096 /* otherwise we need to create a new one */
7097 label = allocate_entity_zero(ENTITY_LABEL);
7098 label->base.namespc = NAMESPACE_LABEL;
7099 label->base.symbol = symbol;
7103 return &label->label;
7107 * Parses a GNU && label address expression.
7109 static expression_t *parse_label_address(void)
7111 source_position_t source_position = token.source_position;
7113 if (token.type != T_IDENTIFIER) {
7114 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7117 symbol_t *symbol = token.v.symbol;
7120 label_t *label = get_label(symbol);
7122 label->address_taken = true;
7124 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7125 expression->base.source_position = source_position;
7127 /* label address is threaten as a void pointer */
7128 expression->base.type = type_void_ptr;
7129 expression->label_address.label = label;
7132 return create_invalid_expression();
7136 * Parse a microsoft __noop expression.
7138 static expression_t *parse_noop_expression(void)
7140 /* the result is a (int)0 */
7141 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7142 cnst->base.type = type_int;
7143 cnst->conste.v.int_value = 0;
7144 cnst->conste.is_ms_noop = true;
7148 if (token.type == '(') {
7149 /* parse arguments */
7151 add_anchor_token(')');
7152 add_anchor_token(',');
7154 if (token.type != ')') {
7156 (void)parse_assignment_expression();
7157 if (token.type != ',')
7163 rem_anchor_token(',');
7164 rem_anchor_token(')');
7165 expect(')', end_error);
7172 * Parses a primary expression.
7174 static expression_t *parse_primary_expression(void)
7176 switch (token.type) {
7177 case T_false: return parse_bool_const(false);
7178 case T_true: return parse_bool_const(true);
7179 case T_INTEGER: return parse_int_const();
7180 case T_CHARACTER_CONSTANT: return parse_character_constant();
7181 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7182 case T_FLOATINGPOINT: return parse_float_const();
7183 case T_STRING_LITERAL:
7184 case T_WIDE_STRING_LITERAL: return parse_string_const();
7185 case T___FUNCTION__:
7186 case T___func__: return parse_function_keyword();
7187 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7188 case T___FUNCSIG__: return parse_funcsig_keyword();
7189 case T___FUNCDNAME__: return parse_funcdname_keyword();
7190 case T___builtin_offsetof: return parse_offsetof();
7191 case T___builtin_va_start: return parse_va_start();
7192 case T___builtin_va_arg: return parse_va_arg();
7193 case T___builtin_va_copy: return parse_va_copy();
7194 case T___builtin_isgreater:
7195 case T___builtin_isgreaterequal:
7196 case T___builtin_isless:
7197 case T___builtin_islessequal:
7198 case T___builtin_islessgreater:
7199 case T___builtin_isunordered: return parse_compare_builtin();
7200 case T___builtin_constant_p: return parse_builtin_constant();
7201 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7202 case T__assume: return parse_assume();
7205 return parse_label_address();
7208 case '(': return parse_parenthesized_expression();
7209 case T___noop: return parse_noop_expression();
7211 /* Gracefully handle type names while parsing expressions. */
7213 if (!is_typedef_symbol(token.v.symbol)) {
7214 return parse_reference();
7218 source_position_t const pos = *HERE;
7219 type_t const *const type = parse_typename();
7220 errorf(&pos, "encountered type '%T' while parsing expression", type);
7221 return create_invalid_expression();
7225 errorf(HERE, "unexpected token %K, expected an expression", &token);
7226 return create_invalid_expression();
7230 * Check if the expression has the character type and issue a warning then.
7232 static void check_for_char_index_type(const expression_t *expression)
7234 type_t *const type = expression->base.type;
7235 const type_t *const base_type = skip_typeref(type);
7237 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7238 warning.char_subscripts) {
7239 warningf(&expression->base.source_position,
7240 "array subscript has type '%T'", type);
7244 static expression_t *parse_array_expression(expression_t *left)
7246 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7249 add_anchor_token(']');
7251 expression_t *inside = parse_expression();
7253 type_t *const orig_type_left = left->base.type;
7254 type_t *const orig_type_inside = inside->base.type;
7256 type_t *const type_left = skip_typeref(orig_type_left);
7257 type_t *const type_inside = skip_typeref(orig_type_inside);
7259 type_t *return_type;
7260 array_access_expression_t *array_access = &expression->array_access;
7261 if (is_type_pointer(type_left)) {
7262 return_type = type_left->pointer.points_to;
7263 array_access->array_ref = left;
7264 array_access->index = inside;
7265 check_for_char_index_type(inside);
7266 } else if (is_type_pointer(type_inside)) {
7267 return_type = type_inside->pointer.points_to;
7268 array_access->array_ref = inside;
7269 array_access->index = left;
7270 array_access->flipped = true;
7271 check_for_char_index_type(left);
7273 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7275 "array access on object with non-pointer types '%T', '%T'",
7276 orig_type_left, orig_type_inside);
7278 return_type = type_error_type;
7279 array_access->array_ref = left;
7280 array_access->index = inside;
7283 expression->base.type = automatic_type_conversion(return_type);
7285 rem_anchor_token(']');
7286 expect(']', end_error);
7291 static expression_t *parse_typeprop(expression_kind_t const kind)
7293 expression_t *tp_expression = allocate_expression_zero(kind);
7294 tp_expression->base.type = type_size_t;
7296 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7298 /* we only refer to a type property, mark this case */
7299 bool old = in_type_prop;
7300 in_type_prop = true;
7303 expression_t *expression;
7304 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7306 add_anchor_token(')');
7307 orig_type = parse_typename();
7308 rem_anchor_token(')');
7309 expect(')', end_error);
7311 if (token.type == '{') {
7312 /* It was not sizeof(type) after all. It is sizeof of an expression
7313 * starting with a compound literal */
7314 expression = parse_compound_literal(orig_type);
7315 goto typeprop_expression;
7318 expression = parse_sub_expression(PREC_UNARY);
7320 typeprop_expression:
7321 tp_expression->typeprop.tp_expression = expression;
7323 orig_type = revert_automatic_type_conversion(expression);
7324 expression->base.type = orig_type;
7327 tp_expression->typeprop.type = orig_type;
7328 type_t const* const type = skip_typeref(orig_type);
7329 char const* const wrong_type =
7330 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7331 is_type_incomplete(type) ? "incomplete" :
7332 type->kind == TYPE_FUNCTION ? "function designator" :
7333 type->kind == TYPE_BITFIELD ? "bitfield" :
7335 if (wrong_type != NULL) {
7336 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7337 errorf(&tp_expression->base.source_position,
7338 "operand of %s expression must not be of %s type '%T'",
7339 what, wrong_type, orig_type);
7344 return tp_expression;
7347 static expression_t *parse_sizeof(void)
7349 return parse_typeprop(EXPR_SIZEOF);
7352 static expression_t *parse_alignof(void)
7354 return parse_typeprop(EXPR_ALIGNOF);
7357 static expression_t *parse_select_expression(expression_t *compound)
7359 expression_t *select = allocate_expression_zero(EXPR_SELECT);
7360 select->select.compound = compound;
7362 assert(token.type == '.' || token.type == T_MINUSGREATER);
7363 bool is_pointer = (token.type == T_MINUSGREATER);
7366 if (token.type != T_IDENTIFIER) {
7367 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7370 symbol_t *symbol = token.v.symbol;
7373 type_t *const orig_type = compound->base.type;
7374 type_t *const type = skip_typeref(orig_type);
7377 bool saw_error = false;
7378 if (is_type_pointer(type)) {
7381 "request for member '%Y' in something not a struct or union, but '%T'",
7385 type_left = skip_typeref(type->pointer.points_to);
7387 if (is_pointer && is_type_valid(type)) {
7388 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7395 if (type_left->kind == TYPE_COMPOUND_STRUCT ||
7396 type_left->kind == TYPE_COMPOUND_UNION) {
7397 compound_t *compound = type_left->compound.compound;
7399 if (!compound->complete) {
7400 errorf(HERE, "request for member '%Y' of incomplete type '%T'",
7402 goto create_error_entry;
7405 entry = find_compound_entry(compound, symbol);
7406 if (entry == NULL) {
7407 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7408 goto create_error_entry;
7411 if (is_type_valid(type_left) && !saw_error) {
7413 "request for member '%Y' in something not a struct or union, but '%T'",
7417 entry = create_error_entity(symbol, ENTITY_COMPOUND_MEMBER);
7420 assert(is_declaration(entry));
7421 select->select.compound_entry = entry;
7423 check_deprecated(HERE, entry);
7425 type_t *entry_type = entry->declaration.type;
7427 = get_qualified_type(entry_type, type_left->base.qualifiers);
7429 /* we always do the auto-type conversions; the & and sizeof parser contains
7430 * code to revert this! */
7431 select->base.type = automatic_type_conversion(res_type);
7433 type_t *skipped = skip_typeref(res_type);
7434 if (skipped->kind == TYPE_BITFIELD) {
7435 select->base.type = skipped->bitfield.base_type;
7441 static void check_call_argument(type_t *expected_type,
7442 call_argument_t *argument, unsigned pos)
7444 type_t *expected_type_skip = skip_typeref(expected_type);
7445 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7446 expression_t *arg_expr = argument->expression;
7447 type_t *arg_type = skip_typeref(arg_expr->base.type);
7449 /* handle transparent union gnu extension */
7450 if (is_type_union(expected_type_skip)
7451 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7452 compound_t *union_decl = expected_type_skip->compound.compound;
7453 type_t *best_type = NULL;
7454 entity_t *entry = union_decl->members.entities;
7455 for ( ; entry != NULL; entry = entry->base.next) {
7456 assert(is_declaration(entry));
7457 type_t *decl_type = entry->declaration.type;
7458 error = semantic_assign(decl_type, arg_expr);
7459 if (error == ASSIGN_ERROR_INCOMPATIBLE
7460 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7463 if (error == ASSIGN_SUCCESS) {
7464 best_type = decl_type;
7465 } else if (best_type == NULL) {
7466 best_type = decl_type;
7470 if (best_type != NULL) {
7471 expected_type = best_type;
7475 error = semantic_assign(expected_type, arg_expr);
7476 argument->expression = create_implicit_cast(arg_expr, expected_type);
7478 if (error != ASSIGN_SUCCESS) {
7479 /* report exact scope in error messages (like "in argument 3") */
7481 snprintf(buf, sizeof(buf), "call argument %u", pos);
7482 report_assign_error(error, expected_type, arg_expr, buf,
7483 &arg_expr->base.source_position);
7484 } else if (warning.traditional || warning.conversion) {
7485 type_t *const promoted_type = get_default_promoted_type(arg_type);
7486 if (!types_compatible(expected_type_skip, promoted_type) &&
7487 !types_compatible(expected_type_skip, type_void_ptr) &&
7488 !types_compatible(type_void_ptr, promoted_type)) {
7489 /* Deliberately show the skipped types in this warning */
7490 warningf(&arg_expr->base.source_position,
7491 "passing call argument %u as '%T' rather than '%T' due to prototype",
7492 pos, expected_type_skip, promoted_type);
7498 * Handle the semantic restrictions of builtin calls
7500 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7501 switch (call->function->reference.entity->function.btk) {
7502 case bk_gnu_builtin_return_address:
7503 case bk_gnu_builtin_frame_address: {
7504 /* argument must be constant */
7505 call_argument_t *argument = call->arguments;
7507 if (! is_constant_expression(argument->expression)) {
7508 errorf(&call->base.source_position,
7509 "argument of '%Y' must be a constant expression",
7510 call->function->reference.entity->base.symbol);
7514 case bk_gnu_builtin_prefetch: {
7515 /* second and third argument must be constant if existent */
7516 call_argument_t *rw = call->arguments->next;
7517 call_argument_t *locality = NULL;
7520 if (! is_constant_expression(rw->expression)) {
7521 errorf(&call->base.source_position,
7522 "second argument of '%Y' must be a constant expression",
7523 call->function->reference.entity->base.symbol);
7525 locality = rw->next;
7527 if (locality != NULL) {
7528 if (! is_constant_expression(locality->expression)) {
7529 errorf(&call->base.source_position,
7530 "third argument of '%Y' must be a constant expression",
7531 call->function->reference.entity->base.symbol);
7533 locality = rw->next;
7543 * Parse a call expression, ie. expression '( ... )'.
7545 * @param expression the function address
7547 static expression_t *parse_call_expression(expression_t *expression)
7549 expression_t *result = allocate_expression_zero(EXPR_CALL);
7550 call_expression_t *call = &result->call;
7551 call->function = expression;
7553 type_t *const orig_type = expression->base.type;
7554 type_t *const type = skip_typeref(orig_type);
7556 function_type_t *function_type = NULL;
7557 if (is_type_pointer(type)) {
7558 type_t *const to_type = skip_typeref(type->pointer.points_to);
7560 if (is_type_function(to_type)) {
7561 function_type = &to_type->function;
7562 call->base.type = function_type->return_type;
7566 if (function_type == NULL && is_type_valid(type)) {
7568 "called object '%E' (type '%T') is not a pointer to a function",
7569 expression, orig_type);
7572 /* parse arguments */
7574 add_anchor_token(')');
7575 add_anchor_token(',');
7577 if (token.type != ')') {
7578 call_argument_t **anchor = &call->arguments;
7580 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7581 argument->expression = parse_assignment_expression();
7584 anchor = &argument->next;
7586 if (token.type != ',')
7591 rem_anchor_token(',');
7592 rem_anchor_token(')');
7593 expect(')', end_error);
7595 if (function_type == NULL)
7598 /* check type and count of call arguments */
7599 function_parameter_t *parameter = function_type->parameters;
7600 call_argument_t *argument = call->arguments;
7601 if (!function_type->unspecified_parameters) {
7602 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7603 parameter = parameter->next, argument = argument->next) {
7604 check_call_argument(parameter->type, argument, ++pos);
7607 if (parameter != NULL) {
7608 errorf(HERE, "too few arguments to function '%E'", expression);
7609 } else if (argument != NULL && !function_type->variadic) {
7610 errorf(HERE, "too many arguments to function '%E'", expression);
7614 /* do default promotion for other arguments */
7615 for (; argument != NULL; argument = argument->next) {
7616 type_t *type = argument->expression->base.type;
7618 type = get_default_promoted_type(type);
7620 argument->expression
7621 = create_implicit_cast(argument->expression, type);
7624 check_format(&result->call);
7626 if (warning.aggregate_return &&
7627 is_type_compound(skip_typeref(function_type->return_type))) {
7628 warningf(&result->base.source_position,
7629 "function call has aggregate value");
7632 if (call->function->kind == EXPR_REFERENCE) {
7633 reference_expression_t *reference = &call->function->reference;
7634 if (reference->entity->kind == ENTITY_FUNCTION &&
7635 reference->entity->function.btk != bk_none)
7636 handle_builtin_argument_restrictions(call);
7643 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7645 static bool same_compound_type(const type_t *type1, const type_t *type2)
7648 is_type_compound(type1) &&
7649 type1->kind == type2->kind &&
7650 type1->compound.compound == type2->compound.compound;
7653 static expression_t const *get_reference_address(expression_t const *expr)
7655 bool regular_take_address = true;
7657 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7658 expr = expr->unary.value;
7660 regular_take_address = false;
7663 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7666 expr = expr->unary.value;
7669 if (expr->kind != EXPR_REFERENCE)
7672 /* special case for functions which are automatically converted to a
7673 * pointer to function without an extra TAKE_ADDRESS operation */
7674 if (!regular_take_address &&
7675 expr->reference.entity->kind != ENTITY_FUNCTION) {
7682 static void warn_reference_address_as_bool(expression_t const* expr)
7684 if (!warning.address)
7687 expr = get_reference_address(expr);
7689 warningf(&expr->base.source_position,
7690 "the address of '%Y' will always evaluate as 'true'",
7691 expr->reference.entity->base.symbol);
7695 static void warn_assignment_in_condition(const expression_t *const expr)
7697 if (!warning.parentheses)
7699 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7701 if (expr->base.parenthesized)
7703 warningf(&expr->base.source_position,
7704 "suggest parentheses around assignment used as truth value");
7707 static void semantic_condition(expression_t const *const expr,
7708 char const *const context)
7710 type_t *const type = skip_typeref(expr->base.type);
7711 if (is_type_scalar(type)) {
7712 warn_reference_address_as_bool(expr);
7713 warn_assignment_in_condition(expr);
7714 } else if (is_type_valid(type)) {
7715 errorf(&expr->base.source_position,
7716 "%s must have scalar type", context);
7721 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7723 * @param expression the conditional expression
7725 static expression_t *parse_conditional_expression(expression_t *expression)
7727 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7729 conditional_expression_t *conditional = &result->conditional;
7730 conditional->condition = expression;
7733 add_anchor_token(':');
7735 /* §6.5.15:2 The first operand shall have scalar type. */
7736 semantic_condition(expression, "condition of conditional operator");
7738 expression_t *true_expression = expression;
7739 bool gnu_cond = false;
7740 if (GNU_MODE && token.type == ':') {
7743 true_expression = parse_expression();
7745 rem_anchor_token(':');
7746 expect(':', end_error);
7748 expression_t *false_expression =
7749 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7751 type_t *const orig_true_type = true_expression->base.type;
7752 type_t *const orig_false_type = false_expression->base.type;
7753 type_t *const true_type = skip_typeref(orig_true_type);
7754 type_t *const false_type = skip_typeref(orig_false_type);
7757 type_t *result_type;
7758 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7759 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7760 /* ISO/IEC 14882:1998(E) §5.16:2 */
7761 if (true_expression->kind == EXPR_UNARY_THROW) {
7762 result_type = false_type;
7763 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7764 result_type = true_type;
7766 if (warning.other && (
7767 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7768 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7770 warningf(&conditional->base.source_position,
7771 "ISO C forbids conditional expression with only one void side");
7773 result_type = type_void;
7775 } else if (is_type_arithmetic(true_type)
7776 && is_type_arithmetic(false_type)) {
7777 result_type = semantic_arithmetic(true_type, false_type);
7779 true_expression = create_implicit_cast(true_expression, result_type);
7780 false_expression = create_implicit_cast(false_expression, result_type);
7782 conditional->true_expression = true_expression;
7783 conditional->false_expression = false_expression;
7784 conditional->base.type = result_type;
7785 } else if (same_compound_type(true_type, false_type)) {
7786 /* just take 1 of the 2 types */
7787 result_type = true_type;
7788 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7789 type_t *pointer_type;
7791 expression_t *other_expression;
7792 if (is_type_pointer(true_type) &&
7793 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7794 pointer_type = true_type;
7795 other_type = false_type;
7796 other_expression = false_expression;
7798 pointer_type = false_type;
7799 other_type = true_type;
7800 other_expression = true_expression;
7803 if (is_null_pointer_constant(other_expression)) {
7804 result_type = pointer_type;
7805 } else if (is_type_pointer(other_type)) {
7806 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7807 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7810 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7811 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7813 } else if (types_compatible(get_unqualified_type(to1),
7814 get_unqualified_type(to2))) {
7817 if (warning.other) {
7818 warningf(&conditional->base.source_position,
7819 "pointer types '%T' and '%T' in conditional expression are incompatible",
7820 true_type, false_type);
7825 type_t *const type =
7826 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7827 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7828 } else if (is_type_integer(other_type)) {
7829 if (warning.other) {
7830 warningf(&conditional->base.source_position,
7831 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7833 result_type = pointer_type;
7835 if (is_type_valid(other_type)) {
7836 type_error_incompatible("while parsing conditional",
7837 &expression->base.source_position, true_type, false_type);
7839 result_type = type_error_type;
7842 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7843 type_error_incompatible("while parsing conditional",
7844 &conditional->base.source_position, true_type,
7847 result_type = type_error_type;
7850 conditional->true_expression
7851 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7852 conditional->false_expression
7853 = create_implicit_cast(false_expression, result_type);
7854 conditional->base.type = result_type;
7859 * Parse an extension expression.
7861 static expression_t *parse_extension(void)
7863 eat(T___extension__);
7865 bool old_gcc_extension = in_gcc_extension;
7866 in_gcc_extension = true;
7867 expression_t *expression = parse_sub_expression(PREC_UNARY);
7868 in_gcc_extension = old_gcc_extension;
7873 * Parse a __builtin_classify_type() expression.
7875 static expression_t *parse_builtin_classify_type(void)
7877 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7878 result->base.type = type_int;
7880 eat(T___builtin_classify_type);
7882 expect('(', end_error);
7883 add_anchor_token(')');
7884 expression_t *expression = parse_expression();
7885 rem_anchor_token(')');
7886 expect(')', end_error);
7887 result->classify_type.type_expression = expression;
7891 return create_invalid_expression();
7895 * Parse a delete expression
7896 * ISO/IEC 14882:1998(E) §5.3.5
7898 static expression_t *parse_delete(void)
7900 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7901 result->base.type = type_void;
7905 if (token.type == '[') {
7907 result->kind = EXPR_UNARY_DELETE_ARRAY;
7908 expect(']', end_error);
7912 expression_t *const value = parse_sub_expression(PREC_CAST);
7913 result->unary.value = value;
7915 type_t *const type = skip_typeref(value->base.type);
7916 if (!is_type_pointer(type)) {
7917 if (is_type_valid(type)) {
7918 errorf(&value->base.source_position,
7919 "operand of delete must have pointer type");
7921 } else if (warning.other &&
7922 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7923 warningf(&value->base.source_position,
7924 "deleting 'void*' is undefined");
7931 * Parse a throw expression
7932 * ISO/IEC 14882:1998(E) §15:1
7934 static expression_t *parse_throw(void)
7936 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7937 result->base.type = type_void;
7941 expression_t *value = NULL;
7942 switch (token.type) {
7944 value = parse_assignment_expression();
7945 /* ISO/IEC 14882:1998(E) §15.1:3 */
7946 type_t *const orig_type = value->base.type;
7947 type_t *const type = skip_typeref(orig_type);
7948 if (is_type_incomplete(type)) {
7949 errorf(&value->base.source_position,
7950 "cannot throw object of incomplete type '%T'", orig_type);
7951 } else if (is_type_pointer(type)) {
7952 type_t *const points_to = skip_typeref(type->pointer.points_to);
7953 if (is_type_incomplete(points_to) &&
7954 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7955 errorf(&value->base.source_position,
7956 "cannot throw pointer to incomplete type '%T'", orig_type);
7964 result->unary.value = value;
7969 static bool check_pointer_arithmetic(const source_position_t *source_position,
7970 type_t *pointer_type,
7971 type_t *orig_pointer_type)
7973 type_t *points_to = pointer_type->pointer.points_to;
7974 points_to = skip_typeref(points_to);
7976 if (is_type_incomplete(points_to)) {
7977 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7978 errorf(source_position,
7979 "arithmetic with pointer to incomplete type '%T' not allowed",
7982 } else if (warning.pointer_arith) {
7983 warningf(source_position,
7984 "pointer of type '%T' used in arithmetic",
7987 } else if (is_type_function(points_to)) {
7989 errorf(source_position,
7990 "arithmetic with pointer to function type '%T' not allowed",
7993 } else if (warning.pointer_arith) {
7994 warningf(source_position,
7995 "pointer to a function '%T' used in arithmetic",
8002 static bool is_lvalue(const expression_t *expression)
8004 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8005 switch (expression->kind) {
8006 case EXPR_ARRAY_ACCESS:
8007 case EXPR_COMPOUND_LITERAL:
8008 case EXPR_REFERENCE:
8010 case EXPR_UNARY_DEREFERENCE:
8014 type_t *type = skip_typeref(expression->base.type);
8016 /* ISO/IEC 14882:1998(E) §3.10:3 */
8017 is_type_reference(type) ||
8018 /* Claim it is an lvalue, if the type is invalid. There was a parse
8019 * error before, which maybe prevented properly recognizing it as
8021 !is_type_valid(type);
8026 static void semantic_incdec(unary_expression_t *expression)
8028 type_t *const orig_type = expression->value->base.type;
8029 type_t *const type = skip_typeref(orig_type);
8030 if (is_type_pointer(type)) {
8031 if (!check_pointer_arithmetic(&expression->base.source_position,
8035 } else if (!is_type_real(type) && is_type_valid(type)) {
8036 /* TODO: improve error message */
8037 errorf(&expression->base.source_position,
8038 "operation needs an arithmetic or pointer type");
8041 if (!is_lvalue(expression->value)) {
8042 /* TODO: improve error message */
8043 errorf(&expression->base.source_position, "lvalue required as operand");
8045 expression->base.type = orig_type;
8048 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8050 type_t *const orig_type = expression->value->base.type;
8051 type_t *const type = skip_typeref(orig_type);
8052 if (!is_type_arithmetic(type)) {
8053 if (is_type_valid(type)) {
8054 /* TODO: improve error message */
8055 errorf(&expression->base.source_position,
8056 "operation needs an arithmetic type");
8061 expression->base.type = orig_type;
8064 static void semantic_unexpr_plus(unary_expression_t *expression)
8066 semantic_unexpr_arithmetic(expression);
8067 if (warning.traditional)
8068 warningf(&expression->base.source_position,
8069 "traditional C rejects the unary plus operator");
8072 static void semantic_not(unary_expression_t *expression)
8074 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8075 semantic_condition(expression->value, "operand of !");
8076 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8079 static void semantic_unexpr_integer(unary_expression_t *expression)
8081 type_t *const orig_type = expression->value->base.type;
8082 type_t *const type = skip_typeref(orig_type);
8083 if (!is_type_integer(type)) {
8084 if (is_type_valid(type)) {
8085 errorf(&expression->base.source_position,
8086 "operand of ~ must be of integer type");
8091 expression->base.type = orig_type;
8094 static void semantic_dereference(unary_expression_t *expression)
8096 type_t *const orig_type = expression->value->base.type;
8097 type_t *const type = skip_typeref(orig_type);
8098 if (!is_type_pointer(type)) {
8099 if (is_type_valid(type)) {
8100 errorf(&expression->base.source_position,
8101 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8106 type_t *result_type = type->pointer.points_to;
8107 result_type = automatic_type_conversion(result_type);
8108 expression->base.type = result_type;
8112 * Record that an address is taken (expression represents an lvalue).
8114 * @param expression the expression
8115 * @param may_be_register if true, the expression might be an register
8117 static void set_address_taken(expression_t *expression, bool may_be_register)
8119 if (expression->kind != EXPR_REFERENCE)
8122 entity_t *const entity = expression->reference.entity;
8124 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8127 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8128 && !may_be_register) {
8129 errorf(&expression->base.source_position,
8130 "address of register %s '%Y' requested",
8131 get_entity_kind_name(entity->kind), entity->base.symbol);
8134 if (entity->kind == ENTITY_VARIABLE) {
8135 entity->variable.address_taken = true;
8137 assert(entity->kind == ENTITY_PARAMETER);
8138 entity->parameter.address_taken = true;
8143 * Check the semantic of the address taken expression.
8145 static void semantic_take_addr(unary_expression_t *expression)
8147 expression_t *value = expression->value;
8148 value->base.type = revert_automatic_type_conversion(value);
8150 type_t *orig_type = value->base.type;
8151 type_t *type = skip_typeref(orig_type);
8152 if (!is_type_valid(type))
8156 if (!is_lvalue(value)) {
8157 errorf(&expression->base.source_position, "'&' requires an lvalue");
8159 if (type->kind == TYPE_BITFIELD) {
8160 errorf(&expression->base.source_position,
8161 "'&' not allowed on object with bitfield type '%T'",
8165 set_address_taken(value, false);
8167 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8170 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8171 static expression_t *parse_##unexpression_type(void) \
8173 expression_t *unary_expression \
8174 = allocate_expression_zero(unexpression_type); \
8176 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8178 sfunc(&unary_expression->unary); \
8180 return unary_expression; \
8183 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8184 semantic_unexpr_arithmetic)
8185 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8186 semantic_unexpr_plus)
8187 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8189 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8190 semantic_dereference)
8191 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8193 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8194 semantic_unexpr_integer)
8195 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8197 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8200 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8202 static expression_t *parse_##unexpression_type(expression_t *left) \
8204 expression_t *unary_expression \
8205 = allocate_expression_zero(unexpression_type); \
8207 unary_expression->unary.value = left; \
8209 sfunc(&unary_expression->unary); \
8211 return unary_expression; \
8214 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8215 EXPR_UNARY_POSTFIX_INCREMENT,
8217 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8218 EXPR_UNARY_POSTFIX_DECREMENT,
8221 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8223 /* TODO: handle complex + imaginary types */
8225 type_left = get_unqualified_type(type_left);
8226 type_right = get_unqualified_type(type_right);
8228 /* §6.3.1.8 Usual arithmetic conversions */
8229 if (type_left == type_long_double || type_right == type_long_double) {
8230 return type_long_double;
8231 } else if (type_left == type_double || type_right == type_double) {
8233 } else if (type_left == type_float || type_right == type_float) {
8237 type_left = promote_integer(type_left);
8238 type_right = promote_integer(type_right);
8240 if (type_left == type_right)
8243 bool const signed_left = is_type_signed(type_left);
8244 bool const signed_right = is_type_signed(type_right);
8245 int const rank_left = get_rank(type_left);
8246 int const rank_right = get_rank(type_right);
8248 if (signed_left == signed_right)
8249 return rank_left >= rank_right ? type_left : type_right;
8258 u_rank = rank_right;
8259 u_type = type_right;
8261 s_rank = rank_right;
8262 s_type = type_right;
8267 if (u_rank >= s_rank)
8270 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8272 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8273 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8277 case ATOMIC_TYPE_INT: return type_unsigned_int;
8278 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8279 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8281 default: panic("invalid atomic type");
8286 * Check the semantic restrictions for a binary expression.
8288 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8290 expression_t *const left = expression->left;
8291 expression_t *const right = expression->right;
8292 type_t *const orig_type_left = left->base.type;
8293 type_t *const orig_type_right = right->base.type;
8294 type_t *const type_left = skip_typeref(orig_type_left);
8295 type_t *const type_right = skip_typeref(orig_type_right);
8297 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8298 /* TODO: improve error message */
8299 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8300 errorf(&expression->base.source_position,
8301 "operation needs arithmetic types");
8306 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8307 expression->left = create_implicit_cast(left, arithmetic_type);
8308 expression->right = create_implicit_cast(right, arithmetic_type);
8309 expression->base.type = arithmetic_type;
8312 static void warn_div_by_zero(binary_expression_t const *const expression)
8314 if (!warning.div_by_zero ||
8315 !is_type_integer(expression->base.type))
8318 expression_t const *const right = expression->right;
8319 /* The type of the right operand can be different for /= */
8320 if (is_type_integer(right->base.type) &&
8321 is_constant_expression(right) &&
8322 fold_constant(right) == 0) {
8323 warningf(&expression->base.source_position, "division by zero");
8328 * Check the semantic restrictions for a div/mod expression.
8330 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8332 semantic_binexpr_arithmetic(expression);
8333 warn_div_by_zero(expression);
8336 static void warn_addsub_in_shift(const expression_t *const expr)
8338 if (expr->base.parenthesized)
8342 switch (expr->kind) {
8343 case EXPR_BINARY_ADD: op = '+'; break;
8344 case EXPR_BINARY_SUB: op = '-'; break;
8348 warningf(&expr->base.source_position,
8349 "suggest parentheses around '%c' inside shift", op);
8352 static bool semantic_shift(binary_expression_t *expression)
8354 expression_t *const left = expression->left;
8355 expression_t *const right = expression->right;
8356 type_t *const orig_type_left = left->base.type;
8357 type_t *const orig_type_right = right->base.type;
8358 type_t * type_left = skip_typeref(orig_type_left);
8359 type_t * type_right = skip_typeref(orig_type_right);
8361 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8362 /* TODO: improve error message */
8363 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8364 errorf(&expression->base.source_position,
8365 "operands of shift operation must have integer types");
8370 type_left = promote_integer(type_left);
8372 if (is_constant_expression(right)) {
8373 long count = fold_constant(right);
8375 warningf(&right->base.source_position,
8376 "shift count must be non-negative");
8377 } else if ((unsigned long)count >=
8378 get_atomic_type_size(type_left->atomic.akind) * 8) {
8379 warningf(&right->base.source_position,
8380 "shift count must be less than type width");
8384 type_right = promote_integer(type_right);
8385 expression->right = create_implicit_cast(right, type_right);
8390 static void semantic_shift_op(binary_expression_t *expression)
8392 expression_t *const left = expression->left;
8393 expression_t *const right = expression->right;
8395 if (!semantic_shift(expression))
8398 if (warning.parentheses) {
8399 warn_addsub_in_shift(left);
8400 warn_addsub_in_shift(right);
8403 type_t *const orig_type_left = left->base.type;
8404 type_t * type_left = skip_typeref(orig_type_left);
8406 type_left = promote_integer(type_left);
8407 expression->left = create_implicit_cast(left, type_left);
8408 expression->base.type = type_left;
8411 static void semantic_add(binary_expression_t *expression)
8413 expression_t *const left = expression->left;
8414 expression_t *const right = expression->right;
8415 type_t *const orig_type_left = left->base.type;
8416 type_t *const orig_type_right = right->base.type;
8417 type_t *const type_left = skip_typeref(orig_type_left);
8418 type_t *const type_right = skip_typeref(orig_type_right);
8421 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8422 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8423 expression->left = create_implicit_cast(left, arithmetic_type);
8424 expression->right = create_implicit_cast(right, arithmetic_type);
8425 expression->base.type = arithmetic_type;
8426 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8427 check_pointer_arithmetic(&expression->base.source_position,
8428 type_left, orig_type_left);
8429 expression->base.type = type_left;
8430 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8431 check_pointer_arithmetic(&expression->base.source_position,
8432 type_right, orig_type_right);
8433 expression->base.type = type_right;
8434 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8435 errorf(&expression->base.source_position,
8436 "invalid operands to binary + ('%T', '%T')",
8437 orig_type_left, orig_type_right);
8441 static void semantic_sub(binary_expression_t *expression)
8443 expression_t *const left = expression->left;
8444 expression_t *const right = expression->right;
8445 type_t *const orig_type_left = left->base.type;
8446 type_t *const orig_type_right = right->base.type;
8447 type_t *const type_left = skip_typeref(orig_type_left);
8448 type_t *const type_right = skip_typeref(orig_type_right);
8449 source_position_t const *const pos = &expression->base.source_position;
8452 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8453 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8454 expression->left = create_implicit_cast(left, arithmetic_type);
8455 expression->right = create_implicit_cast(right, arithmetic_type);
8456 expression->base.type = arithmetic_type;
8457 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8458 check_pointer_arithmetic(&expression->base.source_position,
8459 type_left, orig_type_left);
8460 expression->base.type = type_left;
8461 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8462 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8463 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8464 if (!types_compatible(unqual_left, unqual_right)) {
8466 "subtracting pointers to incompatible types '%T' and '%T'",
8467 orig_type_left, orig_type_right);
8468 } else if (!is_type_object(unqual_left)) {
8469 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8470 errorf(pos, "subtracting pointers to non-object types '%T'",
8472 } else if (warning.other) {
8473 warningf(pos, "subtracting pointers to void");
8476 expression->base.type = type_ptrdiff_t;
8477 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8478 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8479 orig_type_left, orig_type_right);
8483 static void warn_string_literal_address(expression_t const* expr)
8485 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8486 expr = expr->unary.value;
8487 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8489 expr = expr->unary.value;
8492 if (expr->kind == EXPR_STRING_LITERAL ||
8493 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8494 warningf(&expr->base.source_position,
8495 "comparison with string literal results in unspecified behaviour");
8499 static void warn_comparison_in_comparison(const expression_t *const expr)
8501 if (expr->base.parenthesized)
8503 switch (expr->base.kind) {
8504 case EXPR_BINARY_LESS:
8505 case EXPR_BINARY_GREATER:
8506 case EXPR_BINARY_LESSEQUAL:
8507 case EXPR_BINARY_GREATEREQUAL:
8508 case EXPR_BINARY_NOTEQUAL:
8509 case EXPR_BINARY_EQUAL:
8510 warningf(&expr->base.source_position,
8511 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8518 static bool maybe_negative(expression_t const *const expr)
8521 !is_constant_expression(expr) ||
8522 fold_constant(expr) < 0;
8526 * Check the semantics of comparison expressions.
8528 * @param expression The expression to check.
8530 static void semantic_comparison(binary_expression_t *expression)
8532 expression_t *left = expression->left;
8533 expression_t *right = expression->right;
8535 if (warning.address) {
8536 warn_string_literal_address(left);
8537 warn_string_literal_address(right);
8539 expression_t const* const func_left = get_reference_address(left);
8540 if (func_left != NULL && is_null_pointer_constant(right)) {
8541 warningf(&expression->base.source_position,
8542 "the address of '%Y' will never be NULL",
8543 func_left->reference.entity->base.symbol);
8546 expression_t const* const func_right = get_reference_address(right);
8547 if (func_right != NULL && is_null_pointer_constant(right)) {
8548 warningf(&expression->base.source_position,
8549 "the address of '%Y' will never be NULL",
8550 func_right->reference.entity->base.symbol);
8554 if (warning.parentheses) {
8555 warn_comparison_in_comparison(left);
8556 warn_comparison_in_comparison(right);
8559 type_t *orig_type_left = left->base.type;
8560 type_t *orig_type_right = right->base.type;
8561 type_t *type_left = skip_typeref(orig_type_left);
8562 type_t *type_right = skip_typeref(orig_type_right);
8564 /* TODO non-arithmetic types */
8565 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8566 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8568 /* test for signed vs unsigned compares */
8569 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8570 bool const signed_left = is_type_signed(type_left);
8571 bool const signed_right = is_type_signed(type_right);
8572 if (signed_left != signed_right) {
8573 /* FIXME long long needs better const folding magic */
8574 /* TODO check whether constant value can be represented by other type */
8575 if ((signed_left && maybe_negative(left)) ||
8576 (signed_right && maybe_negative(right))) {
8577 warningf(&expression->base.source_position,
8578 "comparison between signed and unsigned");
8583 expression->left = create_implicit_cast(left, arithmetic_type);
8584 expression->right = create_implicit_cast(right, arithmetic_type);
8585 expression->base.type = arithmetic_type;
8586 if (warning.float_equal &&
8587 (expression->base.kind == EXPR_BINARY_EQUAL ||
8588 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8589 is_type_float(arithmetic_type)) {
8590 warningf(&expression->base.source_position,
8591 "comparing floating point with == or != is unsafe");
8593 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8594 /* TODO check compatibility */
8595 } else if (is_type_pointer(type_left)) {
8596 expression->right = create_implicit_cast(right, type_left);
8597 } else if (is_type_pointer(type_right)) {
8598 expression->left = create_implicit_cast(left, type_right);
8599 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8600 type_error_incompatible("invalid operands in comparison",
8601 &expression->base.source_position,
8602 type_left, type_right);
8604 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8608 * Checks if a compound type has constant fields.
8610 static bool has_const_fields(const compound_type_t *type)
8612 compound_t *compound = type->compound;
8613 entity_t *entry = compound->members.entities;
8615 for (; entry != NULL; entry = entry->base.next) {
8616 if (!is_declaration(entry))
8619 const type_t *decl_type = skip_typeref(entry->declaration.type);
8620 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8627 static bool is_valid_assignment_lhs(expression_t const* const left)
8629 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8630 type_t *const type_left = skip_typeref(orig_type_left);
8632 if (!is_lvalue(left)) {
8633 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8638 if (left->kind == EXPR_REFERENCE
8639 && left->reference.entity->kind == ENTITY_FUNCTION) {
8640 errorf(HERE, "cannot assign to function '%E'", left);
8644 if (is_type_array(type_left)) {
8645 errorf(HERE, "cannot assign to array '%E'", left);
8648 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8649 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8653 if (is_type_incomplete(type_left)) {
8654 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8655 left, orig_type_left);
8658 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8659 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8660 left, orig_type_left);
8667 static void semantic_arithmetic_assign(binary_expression_t *expression)
8669 expression_t *left = expression->left;
8670 expression_t *right = expression->right;
8671 type_t *orig_type_left = left->base.type;
8672 type_t *orig_type_right = right->base.type;
8674 if (!is_valid_assignment_lhs(left))
8677 type_t *type_left = skip_typeref(orig_type_left);
8678 type_t *type_right = skip_typeref(orig_type_right);
8680 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8681 /* TODO: improve error message */
8682 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8683 errorf(&expression->base.source_position,
8684 "operation needs arithmetic types");
8689 /* combined instructions are tricky. We can't create an implicit cast on
8690 * the left side, because we need the uncasted form for the store.
8691 * The ast2firm pass has to know that left_type must be right_type
8692 * for the arithmetic operation and create a cast by itself */
8693 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8694 expression->right = create_implicit_cast(right, arithmetic_type);
8695 expression->base.type = type_left;
8698 static void semantic_divmod_assign(binary_expression_t *expression)
8700 semantic_arithmetic_assign(expression);
8701 warn_div_by_zero(expression);
8704 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8706 expression_t *const left = expression->left;
8707 expression_t *const right = expression->right;
8708 type_t *const orig_type_left = left->base.type;
8709 type_t *const orig_type_right = right->base.type;
8710 type_t *const type_left = skip_typeref(orig_type_left);
8711 type_t *const type_right = skip_typeref(orig_type_right);
8713 if (!is_valid_assignment_lhs(left))
8716 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8717 /* combined instructions are tricky. We can't create an implicit cast on
8718 * the left side, because we need the uncasted form for the store.
8719 * The ast2firm pass has to know that left_type must be right_type
8720 * for the arithmetic operation and create a cast by itself */
8721 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8722 expression->right = create_implicit_cast(right, arithmetic_type);
8723 expression->base.type = type_left;
8724 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8725 check_pointer_arithmetic(&expression->base.source_position,
8726 type_left, orig_type_left);
8727 expression->base.type = type_left;
8728 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8729 errorf(&expression->base.source_position,
8730 "incompatible types '%T' and '%T' in assignment",
8731 orig_type_left, orig_type_right);
8735 static void semantic_integer_assign(binary_expression_t *expression)
8737 expression_t *left = expression->left;
8738 expression_t *right = expression->right;
8739 type_t *orig_type_left = left->base.type;
8740 type_t *orig_type_right = right->base.type;
8742 if (!is_valid_assignment_lhs(left))
8745 type_t *type_left = skip_typeref(orig_type_left);
8746 type_t *type_right = skip_typeref(orig_type_right);
8748 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8749 /* TODO: improve error message */
8750 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8751 errorf(&expression->base.source_position,
8752 "operation needs integer types");
8757 /* combined instructions are tricky. We can't create an implicit cast on
8758 * the left side, because we need the uncasted form for the store.
8759 * The ast2firm pass has to know that left_type must be right_type
8760 * for the arithmetic operation and create a cast by itself */
8761 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8762 expression->right = create_implicit_cast(right, arithmetic_type);
8763 expression->base.type = type_left;
8766 static void semantic_shift_assign(binary_expression_t *expression)
8768 expression_t *left = expression->left;
8770 if (!is_valid_assignment_lhs(left))
8773 if (!semantic_shift(expression))
8776 expression->base.type = skip_typeref(left->base.type);
8779 static void warn_logical_and_within_or(const expression_t *const expr)
8781 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8783 if (expr->base.parenthesized)
8785 warningf(&expr->base.source_position,
8786 "suggest parentheses around && within ||");
8790 * Check the semantic restrictions of a logical expression.
8792 static void semantic_logical_op(binary_expression_t *expression)
8794 /* §6.5.13:2 Each of the operands shall have scalar type.
8795 * §6.5.14:2 Each of the operands shall have scalar type. */
8796 semantic_condition(expression->left, "left operand of logical operator");
8797 semantic_condition(expression->right, "right operand of logical operator");
8798 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8799 warning.parentheses) {
8800 warn_logical_and_within_or(expression->left);
8801 warn_logical_and_within_or(expression->right);
8803 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8807 * Check the semantic restrictions of a binary assign expression.
8809 static void semantic_binexpr_assign(binary_expression_t *expression)
8811 expression_t *left = expression->left;
8812 type_t *orig_type_left = left->base.type;
8814 if (!is_valid_assignment_lhs(left))
8817 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8818 report_assign_error(error, orig_type_left, expression->right,
8819 "assignment", &left->base.source_position);
8820 expression->right = create_implicit_cast(expression->right, orig_type_left);
8821 expression->base.type = orig_type_left;
8825 * Determine if the outermost operation (or parts thereof) of the given
8826 * expression has no effect in order to generate a warning about this fact.
8827 * Therefore in some cases this only examines some of the operands of the
8828 * expression (see comments in the function and examples below).
8830 * f() + 23; // warning, because + has no effect
8831 * x || f(); // no warning, because x controls execution of f()
8832 * x ? y : f(); // warning, because y has no effect
8833 * (void)x; // no warning to be able to suppress the warning
8834 * This function can NOT be used for an "expression has definitely no effect"-
8836 static bool expression_has_effect(const expression_t *const expr)
8838 switch (expr->kind) {
8839 case EXPR_UNKNOWN: break;
8840 case EXPR_INVALID: return true; /* do NOT warn */
8841 case EXPR_REFERENCE: return false;
8842 case EXPR_REFERENCE_ENUM_VALUE: return false;
8843 /* suppress the warning for microsoft __noop operations */
8844 case EXPR_CONST: return expr->conste.is_ms_noop;
8845 case EXPR_CHARACTER_CONSTANT: return false;
8846 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8847 case EXPR_STRING_LITERAL: return false;
8848 case EXPR_WIDE_STRING_LITERAL: return false;
8849 case EXPR_LABEL_ADDRESS: return false;
8852 const call_expression_t *const call = &expr->call;
8853 if (call->function->kind != EXPR_REFERENCE)
8856 switch (call->function->reference.entity->function.btk) {
8857 /* FIXME: which builtins have no effect? */
8858 default: return true;
8862 /* Generate the warning if either the left or right hand side of a
8863 * conditional expression has no effect */
8864 case EXPR_CONDITIONAL: {
8865 conditional_expression_t const *const cond = &expr->conditional;
8866 expression_t const *const t = cond->true_expression;
8868 (t == NULL || expression_has_effect(t)) &&
8869 expression_has_effect(cond->false_expression);
8872 case EXPR_SELECT: return false;
8873 case EXPR_ARRAY_ACCESS: return false;
8874 case EXPR_SIZEOF: return false;
8875 case EXPR_CLASSIFY_TYPE: return false;
8876 case EXPR_ALIGNOF: return false;
8878 case EXPR_FUNCNAME: return false;
8879 case EXPR_BUILTIN_CONSTANT_P: return false;
8880 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8881 case EXPR_OFFSETOF: return false;
8882 case EXPR_VA_START: return true;
8883 case EXPR_VA_ARG: return true;
8884 case EXPR_VA_COPY: return true;
8885 case EXPR_STATEMENT: return true; // TODO
8886 case EXPR_COMPOUND_LITERAL: return false;
8888 case EXPR_UNARY_NEGATE: return false;
8889 case EXPR_UNARY_PLUS: return false;
8890 case EXPR_UNARY_BITWISE_NEGATE: return false;
8891 case EXPR_UNARY_NOT: return false;
8892 case EXPR_UNARY_DEREFERENCE: return false;
8893 case EXPR_UNARY_TAKE_ADDRESS: return false;
8894 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8895 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8896 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8897 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8899 /* Treat void casts as if they have an effect in order to being able to
8900 * suppress the warning */
8901 case EXPR_UNARY_CAST: {
8902 type_t *const type = skip_typeref(expr->base.type);
8903 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8906 case EXPR_UNARY_CAST_IMPLICIT: return true;
8907 case EXPR_UNARY_ASSUME: return true;
8908 case EXPR_UNARY_DELETE: return true;
8909 case EXPR_UNARY_DELETE_ARRAY: return true;
8910 case EXPR_UNARY_THROW: return true;
8912 case EXPR_BINARY_ADD: return false;
8913 case EXPR_BINARY_SUB: return false;
8914 case EXPR_BINARY_MUL: return false;
8915 case EXPR_BINARY_DIV: return false;
8916 case EXPR_BINARY_MOD: return false;
8917 case EXPR_BINARY_EQUAL: return false;
8918 case EXPR_BINARY_NOTEQUAL: return false;
8919 case EXPR_BINARY_LESS: return false;
8920 case EXPR_BINARY_LESSEQUAL: return false;
8921 case EXPR_BINARY_GREATER: return false;
8922 case EXPR_BINARY_GREATEREQUAL: return false;
8923 case EXPR_BINARY_BITWISE_AND: return false;
8924 case EXPR_BINARY_BITWISE_OR: return false;
8925 case EXPR_BINARY_BITWISE_XOR: return false;
8926 case EXPR_BINARY_SHIFTLEFT: return false;
8927 case EXPR_BINARY_SHIFTRIGHT: return false;
8928 case EXPR_BINARY_ASSIGN: return true;
8929 case EXPR_BINARY_MUL_ASSIGN: return true;
8930 case EXPR_BINARY_DIV_ASSIGN: return true;
8931 case EXPR_BINARY_MOD_ASSIGN: return true;
8932 case EXPR_BINARY_ADD_ASSIGN: return true;
8933 case EXPR_BINARY_SUB_ASSIGN: return true;
8934 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8935 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8936 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8937 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8938 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8940 /* Only examine the right hand side of && and ||, because the left hand
8941 * side already has the effect of controlling the execution of the right
8943 case EXPR_BINARY_LOGICAL_AND:
8944 case EXPR_BINARY_LOGICAL_OR:
8945 /* Only examine the right hand side of a comma expression, because the left
8946 * hand side has a separate warning */
8947 case EXPR_BINARY_COMMA:
8948 return expression_has_effect(expr->binary.right);
8950 case EXPR_BINARY_ISGREATER: return false;
8951 case EXPR_BINARY_ISGREATEREQUAL: return false;
8952 case EXPR_BINARY_ISLESS: return false;
8953 case EXPR_BINARY_ISLESSEQUAL: return false;
8954 case EXPR_BINARY_ISLESSGREATER: return false;
8955 case EXPR_BINARY_ISUNORDERED: return false;
8958 internal_errorf(HERE, "unexpected expression");
8961 static void semantic_comma(binary_expression_t *expression)
8963 if (warning.unused_value) {
8964 const expression_t *const left = expression->left;
8965 if (!expression_has_effect(left)) {
8966 warningf(&left->base.source_position,
8967 "left-hand operand of comma expression has no effect");
8970 expression->base.type = expression->right->base.type;
8974 * @param prec_r precedence of the right operand
8976 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8977 static expression_t *parse_##binexpression_type(expression_t *left) \
8979 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8980 binexpr->binary.left = left; \
8983 expression_t *right = parse_sub_expression(prec_r); \
8985 binexpr->binary.right = right; \
8986 sfunc(&binexpr->binary); \
8991 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8992 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8993 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8994 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8995 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8996 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8997 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8998 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8999 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9000 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9001 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9002 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9003 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9004 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9005 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9006 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9007 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9008 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9009 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9010 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9011 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9012 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9013 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9014 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9015 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9016 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9017 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9018 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9019 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9020 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9023 static expression_t *parse_sub_expression(precedence_t precedence)
9025 if (token.type < 0) {
9026 return expected_expression_error();
9029 expression_parser_function_t *parser
9030 = &expression_parsers[token.type];
9031 source_position_t source_position = token.source_position;
9034 if (parser->parser != NULL) {
9035 left = parser->parser();
9037 left = parse_primary_expression();
9039 assert(left != NULL);
9040 left->base.source_position = source_position;
9043 if (token.type < 0) {
9044 return expected_expression_error();
9047 parser = &expression_parsers[token.type];
9048 if (parser->infix_parser == NULL)
9050 if (parser->infix_precedence < precedence)
9053 left = parser->infix_parser(left);
9055 assert(left != NULL);
9056 assert(left->kind != EXPR_UNKNOWN);
9057 left->base.source_position = source_position;
9064 * Parse an expression.
9066 static expression_t *parse_expression(void)
9068 return parse_sub_expression(PREC_EXPRESSION);
9072 * Register a parser for a prefix-like operator.
9074 * @param parser the parser function
9075 * @param token_type the token type of the prefix token
9077 static void register_expression_parser(parse_expression_function parser,
9080 expression_parser_function_t *entry = &expression_parsers[token_type];
9082 if (entry->parser != NULL) {
9083 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9084 panic("trying to register multiple expression parsers for a token");
9086 entry->parser = parser;
9090 * Register a parser for an infix operator with given precedence.
9092 * @param parser the parser function
9093 * @param token_type the token type of the infix operator
9094 * @param precedence the precedence of the operator
9096 static void register_infix_parser(parse_expression_infix_function parser,
9097 int token_type, precedence_t precedence)
9099 expression_parser_function_t *entry = &expression_parsers[token_type];
9101 if (entry->infix_parser != NULL) {
9102 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9103 panic("trying to register multiple infix expression parsers for a "
9106 entry->infix_parser = parser;
9107 entry->infix_precedence = precedence;
9111 * Initialize the expression parsers.
9113 static void init_expression_parsers(void)
9115 memset(&expression_parsers, 0, sizeof(expression_parsers));
9117 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9118 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9119 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9120 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9121 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9122 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9123 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9124 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9125 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9126 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9127 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9128 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9129 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9130 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9131 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9132 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9133 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9134 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9135 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9136 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9137 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9138 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9139 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9140 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9141 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9142 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9143 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9144 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9145 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9146 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9147 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9148 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9149 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9150 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9151 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9152 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9153 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9155 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9156 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9157 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9158 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9159 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9160 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9161 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9162 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9163 register_expression_parser(parse_sizeof, T_sizeof);
9164 register_expression_parser(parse_alignof, T___alignof__);
9165 register_expression_parser(parse_extension, T___extension__);
9166 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9167 register_expression_parser(parse_delete, T_delete);
9168 register_expression_parser(parse_throw, T_throw);
9172 * Parse a asm statement arguments specification.
9174 static asm_argument_t *parse_asm_arguments(bool is_out)
9176 asm_argument_t *result = NULL;
9177 asm_argument_t **anchor = &result;
9179 while (token.type == T_STRING_LITERAL || token.type == '[') {
9180 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9181 memset(argument, 0, sizeof(argument[0]));
9183 if (token.type == '[') {
9185 if (token.type != T_IDENTIFIER) {
9186 parse_error_expected("while parsing asm argument",
9187 T_IDENTIFIER, NULL);
9190 argument->symbol = token.v.symbol;
9192 expect(']', end_error);
9195 argument->constraints = parse_string_literals();
9196 expect('(', end_error);
9197 add_anchor_token(')');
9198 expression_t *expression = parse_expression();
9199 rem_anchor_token(')');
9201 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9202 * change size or type representation (e.g. int -> long is ok, but
9203 * int -> float is not) */
9204 if (expression->kind == EXPR_UNARY_CAST) {
9205 type_t *const type = expression->base.type;
9206 type_kind_t const kind = type->kind;
9207 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9210 if (kind == TYPE_ATOMIC) {
9211 atomic_type_kind_t const akind = type->atomic.akind;
9212 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9213 size = get_atomic_type_size(akind);
9215 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9216 size = get_atomic_type_size(get_intptr_kind());
9220 expression_t *const value = expression->unary.value;
9221 type_t *const value_type = value->base.type;
9222 type_kind_t const value_kind = value_type->kind;
9224 unsigned value_flags;
9225 unsigned value_size;
9226 if (value_kind == TYPE_ATOMIC) {
9227 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9228 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9229 value_size = get_atomic_type_size(value_akind);
9230 } else if (value_kind == TYPE_POINTER) {
9231 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9232 value_size = get_atomic_type_size(get_intptr_kind());
9237 if (value_flags != flags || value_size != size)
9241 } while (expression->kind == EXPR_UNARY_CAST);
9245 if (!is_lvalue(expression)) {
9246 errorf(&expression->base.source_position,
9247 "asm output argument is not an lvalue");
9250 if (argument->constraints.begin[0] == '+')
9251 mark_vars_read(expression, NULL);
9253 mark_vars_read(expression, NULL);
9255 argument->expression = expression;
9256 expect(')', end_error);
9258 set_address_taken(expression, true);
9261 anchor = &argument->next;
9263 if (token.type != ',')
9274 * Parse a asm statement clobber specification.
9276 static asm_clobber_t *parse_asm_clobbers(void)
9278 asm_clobber_t *result = NULL;
9279 asm_clobber_t *last = NULL;
9281 while (token.type == T_STRING_LITERAL) {
9282 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9283 clobber->clobber = parse_string_literals();
9286 last->next = clobber;
9292 if (token.type != ',')
9301 * Parse an asm statement.
9303 static statement_t *parse_asm_statement(void)
9305 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9306 asm_statement_t *asm_statement = &statement->asms;
9310 if (token.type == T_volatile) {
9312 asm_statement->is_volatile = true;
9315 expect('(', end_error);
9316 add_anchor_token(')');
9317 add_anchor_token(':');
9318 asm_statement->asm_text = parse_string_literals();
9320 if (token.type != ':') {
9321 rem_anchor_token(':');
9326 asm_statement->outputs = parse_asm_arguments(true);
9327 if (token.type != ':') {
9328 rem_anchor_token(':');
9333 asm_statement->inputs = parse_asm_arguments(false);
9334 if (token.type != ':') {
9335 rem_anchor_token(':');
9338 rem_anchor_token(':');
9341 asm_statement->clobbers = parse_asm_clobbers();
9344 rem_anchor_token(')');
9345 expect(')', end_error);
9346 expect(';', end_error);
9348 if (asm_statement->outputs == NULL) {
9349 /* GCC: An 'asm' instruction without any output operands will be treated
9350 * identically to a volatile 'asm' instruction. */
9351 asm_statement->is_volatile = true;
9356 return create_invalid_statement();
9360 * Parse a case statement.
9362 static statement_t *parse_case_statement(void)
9364 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9365 source_position_t *const pos = &statement->base.source_position;
9369 expression_t *const expression = parse_expression();
9370 statement->case_label.expression = expression;
9371 if (!is_constant_expression(expression)) {
9372 /* This check does not prevent the error message in all cases of an
9373 * prior error while parsing the expression. At least it catches the
9374 * common case of a mistyped enum entry. */
9375 if (is_type_valid(skip_typeref(expression->base.type))) {
9376 errorf(pos, "case label does not reduce to an integer constant");
9378 statement->case_label.is_bad = true;
9380 long const val = fold_constant(expression);
9381 statement->case_label.first_case = val;
9382 statement->case_label.last_case = val;
9386 if (token.type == T_DOTDOTDOT) {
9388 expression_t *const end_range = parse_expression();
9389 statement->case_label.end_range = end_range;
9390 if (!is_constant_expression(end_range)) {
9391 /* This check does not prevent the error message in all cases of an
9392 * prior error while parsing the expression. At least it catches the
9393 * common case of a mistyped enum entry. */
9394 if (is_type_valid(skip_typeref(end_range->base.type))) {
9395 errorf(pos, "case range does not reduce to an integer constant");
9397 statement->case_label.is_bad = true;
9399 long const val = fold_constant(end_range);
9400 statement->case_label.last_case = val;
9402 if (warning.other && val < statement->case_label.first_case) {
9403 statement->case_label.is_empty_range = true;
9404 warningf(pos, "empty range specified");
9410 PUSH_PARENT(statement);
9412 expect(':', end_error);
9415 if (current_switch != NULL) {
9416 if (! statement->case_label.is_bad) {
9417 /* Check for duplicate case values */
9418 case_label_statement_t *c = &statement->case_label;
9419 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9420 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9423 if (c->last_case < l->first_case || c->first_case > l->last_case)
9426 errorf(pos, "duplicate case value (previously used %P)",
9427 &l->base.source_position);
9431 /* link all cases into the switch statement */
9432 if (current_switch->last_case == NULL) {
9433 current_switch->first_case = &statement->case_label;
9435 current_switch->last_case->next = &statement->case_label;
9437 current_switch->last_case = &statement->case_label;
9439 errorf(pos, "case label not within a switch statement");
9442 statement_t *const inner_stmt = parse_statement();
9443 statement->case_label.statement = inner_stmt;
9444 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9445 errorf(&inner_stmt->base.source_position, "declaration after case label");
9453 * Parse a default statement.
9455 static statement_t *parse_default_statement(void)
9457 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9461 PUSH_PARENT(statement);
9463 expect(':', end_error);
9464 if (current_switch != NULL) {
9465 const case_label_statement_t *def_label = current_switch->default_label;
9466 if (def_label != NULL) {
9467 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9468 &def_label->base.source_position);
9470 current_switch->default_label = &statement->case_label;
9472 /* link all cases into the switch statement */
9473 if (current_switch->last_case == NULL) {
9474 current_switch->first_case = &statement->case_label;
9476 current_switch->last_case->next = &statement->case_label;
9478 current_switch->last_case = &statement->case_label;
9481 errorf(&statement->base.source_position,
9482 "'default' label not within a switch statement");
9485 statement_t *const inner_stmt = parse_statement();
9486 statement->case_label.statement = inner_stmt;
9487 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9488 errorf(&inner_stmt->base.source_position, "declaration after default label");
9495 return create_invalid_statement();
9499 * Parse a label statement.
9501 static statement_t *parse_label_statement(void)
9503 assert(token.type == T_IDENTIFIER);
9504 symbol_t *symbol = token.v.symbol;
9505 label_t *label = get_label(symbol);
9507 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9508 statement->label.label = label;
9512 PUSH_PARENT(statement);
9514 /* if statement is already set then the label is defined twice,
9515 * otherwise it was just mentioned in a goto/local label declaration so far
9517 if (label->statement != NULL) {
9518 errorf(HERE, "duplicate label '%Y' (declared %P)",
9519 symbol, &label->base.source_position);
9521 label->base.source_position = token.source_position;
9522 label->statement = statement;
9527 if (token.type == '}') {
9528 /* TODO only warn? */
9529 if (warning.other && false) {
9530 warningf(HERE, "label at end of compound statement");
9531 statement->label.statement = create_empty_statement();
9533 errorf(HERE, "label at end of compound statement");
9534 statement->label.statement = create_invalid_statement();
9536 } else if (token.type == ';') {
9537 /* Eat an empty statement here, to avoid the warning about an empty
9538 * statement after a label. label:; is commonly used to have a label
9539 * before a closing brace. */
9540 statement->label.statement = create_empty_statement();
9543 statement_t *const inner_stmt = parse_statement();
9544 statement->label.statement = inner_stmt;
9545 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9546 errorf(&inner_stmt->base.source_position, "declaration after label");
9550 /* remember the labels in a list for later checking */
9551 *label_anchor = &statement->label;
9552 label_anchor = &statement->label.next;
9559 * Parse an if statement.
9561 static statement_t *parse_if(void)
9563 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9567 PUSH_PARENT(statement);
9569 add_anchor_token('{');
9571 expect('(', end_error);
9572 add_anchor_token(')');
9573 expression_t *const expr = parse_expression();
9574 statement->ifs.condition = expr;
9575 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9577 semantic_condition(expr, "condition of 'if'-statment");
9578 mark_vars_read(expr, NULL);
9579 rem_anchor_token(')');
9580 expect(')', end_error);
9583 rem_anchor_token('{');
9585 add_anchor_token(T_else);
9586 statement_t *const true_stmt = parse_statement();
9587 statement->ifs.true_statement = true_stmt;
9588 rem_anchor_token(T_else);
9590 if (token.type == T_else) {
9592 statement->ifs.false_statement = parse_statement();
9593 } else if (warning.parentheses &&
9594 true_stmt->kind == STATEMENT_IF &&
9595 true_stmt->ifs.false_statement != NULL) {
9596 warningf(&true_stmt->base.source_position,
9597 "suggest explicit braces to avoid ambiguous 'else'");
9605 * Check that all enums are handled in a switch.
9607 * @param statement the switch statement to check
9609 static void check_enum_cases(const switch_statement_t *statement)
9611 const type_t *type = skip_typeref(statement->expression->base.type);
9612 if (! is_type_enum(type))
9614 const enum_type_t *enumt = &type->enumt;
9616 /* if we have a default, no warnings */
9617 if (statement->default_label != NULL)
9620 /* FIXME: calculation of value should be done while parsing */
9621 /* TODO: quadratic algorithm here. Change to an n log n one */
9622 long last_value = -1;
9623 const entity_t *entry = enumt->enume->base.next;
9624 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9625 entry = entry->base.next) {
9626 const expression_t *expression = entry->enum_value.value;
9627 long value = expression != NULL ? fold_constant(expression) : last_value + 1;
9629 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9630 if (l->expression == NULL)
9632 if (l->first_case <= value && value <= l->last_case) {
9638 warningf(&statement->base.source_position,
9639 "enumeration value '%Y' not handled in switch",
9640 entry->base.symbol);
9647 * Parse a switch statement.
9649 static statement_t *parse_switch(void)
9651 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9655 PUSH_PARENT(statement);
9657 expect('(', end_error);
9658 add_anchor_token(')');
9659 expression_t *const expr = parse_expression();
9660 mark_vars_read(expr, NULL);
9661 type_t * type = skip_typeref(expr->base.type);
9662 if (is_type_integer(type)) {
9663 type = promote_integer(type);
9664 if (warning.traditional) {
9665 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9666 warningf(&expr->base.source_position,
9667 "'%T' switch expression not converted to '%T' in ISO C",
9671 } else if (is_type_valid(type)) {
9672 errorf(&expr->base.source_position,
9673 "switch quantity is not an integer, but '%T'", type);
9674 type = type_error_type;
9676 statement->switchs.expression = create_implicit_cast(expr, type);
9677 expect(')', end_error);
9678 rem_anchor_token(')');
9680 switch_statement_t *rem = current_switch;
9681 current_switch = &statement->switchs;
9682 statement->switchs.body = parse_statement();
9683 current_switch = rem;
9685 if (warning.switch_default &&
9686 statement->switchs.default_label == NULL) {
9687 warningf(&statement->base.source_position, "switch has no default case");
9689 if (warning.switch_enum)
9690 check_enum_cases(&statement->switchs);
9696 return create_invalid_statement();
9699 static statement_t *parse_loop_body(statement_t *const loop)
9701 statement_t *const rem = current_loop;
9702 current_loop = loop;
9704 statement_t *const body = parse_statement();
9711 * Parse a while statement.
9713 static statement_t *parse_while(void)
9715 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9719 PUSH_PARENT(statement);
9721 expect('(', end_error);
9722 add_anchor_token(')');
9723 expression_t *const cond = parse_expression();
9724 statement->whiles.condition = cond;
9725 /* §6.8.5:2 The controlling expression of an iteration statement shall
9726 * have scalar type. */
9727 semantic_condition(cond, "condition of 'while'-statement");
9728 mark_vars_read(cond, NULL);
9729 rem_anchor_token(')');
9730 expect(')', end_error);
9732 statement->whiles.body = parse_loop_body(statement);
9738 return create_invalid_statement();
9742 * Parse a do statement.
9744 static statement_t *parse_do(void)
9746 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9750 PUSH_PARENT(statement);
9752 add_anchor_token(T_while);
9753 statement->do_while.body = parse_loop_body(statement);
9754 rem_anchor_token(T_while);
9756 expect(T_while, end_error);
9757 expect('(', end_error);
9758 add_anchor_token(')');
9759 expression_t *const cond = parse_expression();
9760 statement->do_while.condition = cond;
9761 /* §6.8.5:2 The controlling expression of an iteration statement shall
9762 * have scalar type. */
9763 semantic_condition(cond, "condition of 'do-while'-statement");
9764 mark_vars_read(cond, NULL);
9765 rem_anchor_token(')');
9766 expect(')', end_error);
9767 expect(';', end_error);
9773 return create_invalid_statement();
9777 * Parse a for statement.
9779 static statement_t *parse_for(void)
9781 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9785 expect('(', end_error1);
9786 add_anchor_token(')');
9788 PUSH_PARENT(statement);
9790 size_t const top = environment_top();
9791 scope_t *old_scope = scope_push(&statement->fors.scope);
9793 bool old_gcc_extension;
9794 while (token.type == T___extension__) {
9796 in_gcc_extension = true;
9799 if (token.type == ';') {
9801 } else if (is_declaration_specifier(&token, false)) {
9802 parse_declaration(record_entity, DECL_FLAGS_NONE);
9804 add_anchor_token(';');
9805 expression_t *const init = parse_expression();
9806 statement->fors.initialisation = init;
9807 mark_vars_read(init, ENT_ANY);
9808 if (warning.unused_value && !expression_has_effect(init)) {
9809 warningf(&init->base.source_position,
9810 "initialisation of 'for'-statement has no effect");
9812 rem_anchor_token(';');
9813 expect(';', end_error2);
9815 in_gcc_extension = old_gcc_extension;
9817 if (token.type != ';') {
9818 add_anchor_token(';');
9819 expression_t *const cond = parse_expression();
9820 statement->fors.condition = cond;
9821 /* §6.8.5:2 The controlling expression of an iteration statement
9822 * shall have scalar type. */
9823 semantic_condition(cond, "condition of 'for'-statement");
9824 mark_vars_read(cond, NULL);
9825 rem_anchor_token(';');
9827 expect(';', end_error2);
9828 if (token.type != ')') {
9829 expression_t *const step = parse_expression();
9830 statement->fors.step = step;
9831 mark_vars_read(step, ENT_ANY);
9832 if (warning.unused_value && !expression_has_effect(step)) {
9833 warningf(&step->base.source_position,
9834 "step of 'for'-statement has no effect");
9837 expect(')', end_error2);
9838 rem_anchor_token(')');
9839 statement->fors.body = parse_loop_body(statement);
9841 assert(current_scope == &statement->fors.scope);
9842 scope_pop(old_scope);
9843 environment_pop_to(top);
9850 rem_anchor_token(')');
9851 assert(current_scope == &statement->fors.scope);
9852 scope_pop(old_scope);
9853 environment_pop_to(top);
9857 return create_invalid_statement();
9861 * Parse a goto statement.
9863 static statement_t *parse_goto(void)
9865 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9868 if (GNU_MODE && token.type == '*') {
9870 expression_t *expression = parse_expression();
9871 mark_vars_read(expression, NULL);
9873 /* Argh: although documentation says the expression must be of type void*,
9874 * gcc accepts anything that can be casted into void* without error */
9875 type_t *type = expression->base.type;
9877 if (type != type_error_type) {
9878 if (!is_type_pointer(type) && !is_type_integer(type)) {
9879 errorf(&expression->base.source_position,
9880 "cannot convert to a pointer type");
9881 } else if (warning.other && type != type_void_ptr) {
9882 warningf(&expression->base.source_position,
9883 "type of computed goto expression should be 'void*' not '%T'", type);
9885 expression = create_implicit_cast(expression, type_void_ptr);
9888 statement->gotos.expression = expression;
9889 } else if (token.type == T_IDENTIFIER) {
9890 symbol_t *symbol = token.v.symbol;
9892 statement->gotos.label = get_label(symbol);
9895 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9897 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9902 /* remember the goto's in a list for later checking */
9903 *goto_anchor = &statement->gotos;
9904 goto_anchor = &statement->gotos.next;
9906 expect(';', end_error);
9910 return create_invalid_statement();
9914 * Parse a continue statement.
9916 static statement_t *parse_continue(void)
9918 if (current_loop == NULL) {
9919 errorf(HERE, "continue statement not within loop");
9922 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9925 expect(';', end_error);
9932 * Parse a break statement.
9934 static statement_t *parse_break(void)
9936 if (current_switch == NULL && current_loop == NULL) {
9937 errorf(HERE, "break statement not within loop or switch");
9940 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9943 expect(';', end_error);
9950 * Parse a __leave statement.
9952 static statement_t *parse_leave_statement(void)
9954 if (current_try == NULL) {
9955 errorf(HERE, "__leave statement not within __try");
9958 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9961 expect(';', end_error);
9968 * Check if a given entity represents a local variable.
9970 static bool is_local_variable(const entity_t *entity)
9972 if (entity->kind != ENTITY_VARIABLE)
9975 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9976 case STORAGE_CLASS_AUTO:
9977 case STORAGE_CLASS_REGISTER: {
9978 const type_t *type = skip_typeref(entity->declaration.type);
9979 if (is_type_function(type)) {
9991 * Check if a given expression represents a local variable.
9993 static bool expression_is_local_variable(const expression_t *expression)
9995 if (expression->base.kind != EXPR_REFERENCE) {
9998 const entity_t *entity = expression->reference.entity;
9999 return is_local_variable(entity);
10003 * Check if a given expression represents a local variable and
10004 * return its declaration then, else return NULL.
10006 entity_t *expression_is_variable(const expression_t *expression)
10008 if (expression->base.kind != EXPR_REFERENCE) {
10011 entity_t *entity = expression->reference.entity;
10012 if (entity->kind != ENTITY_VARIABLE)
10019 * Parse a return statement.
10021 static statement_t *parse_return(void)
10025 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10027 expression_t *return_value = NULL;
10028 if (token.type != ';') {
10029 return_value = parse_expression();
10030 mark_vars_read(return_value, NULL);
10033 const type_t *const func_type = skip_typeref(current_function->base.type);
10034 assert(is_type_function(func_type));
10035 type_t *const return_type = skip_typeref(func_type->function.return_type);
10037 source_position_t const *const pos = &statement->base.source_position;
10038 if (return_value != NULL) {
10039 type_t *return_value_type = skip_typeref(return_value->base.type);
10041 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10042 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10043 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10044 /* Only warn in C mode, because GCC does the same */
10045 if (c_mode & _CXX || strict_mode) {
10047 "'return' with a value, in function returning 'void'");
10048 } else if (warning.other) {
10050 "'return' with a value, in function returning 'void'");
10052 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10053 /* Only warn in C mode, because GCC does the same */
10056 "'return' with expression in function returning 'void'");
10057 } else if (warning.other) {
10059 "'return' with expression in function returning 'void'");
10063 assign_error_t error = semantic_assign(return_type, return_value);
10064 report_assign_error(error, return_type, return_value, "'return'",
10067 return_value = create_implicit_cast(return_value, return_type);
10068 /* check for returning address of a local var */
10069 if (warning.other && return_value != NULL
10070 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10071 const expression_t *expression = return_value->unary.value;
10072 if (expression_is_local_variable(expression)) {
10073 warningf(pos, "function returns address of local variable");
10076 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10077 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10078 if (c_mode & _CXX || strict_mode) {
10080 "'return' without value, in function returning non-void");
10083 "'return' without value, in function returning non-void");
10086 statement->returns.value = return_value;
10088 expect(';', end_error);
10095 * Parse a declaration statement.
10097 static statement_t *parse_declaration_statement(void)
10099 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10101 entity_t *before = current_scope->last_entity;
10103 parse_external_declaration();
10105 parse_declaration(record_entity, DECL_FLAGS_NONE);
10108 declaration_statement_t *const decl = &statement->declaration;
10109 entity_t *const begin =
10110 before != NULL ? before->base.next : current_scope->entities;
10111 decl->declarations_begin = begin;
10112 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10118 * Parse an expression statement, ie. expr ';'.
10120 static statement_t *parse_expression_statement(void)
10122 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10124 expression_t *const expr = parse_expression();
10125 statement->expression.expression = expr;
10126 mark_vars_read(expr, ENT_ANY);
10128 expect(';', end_error);
10135 * Parse a microsoft __try { } __finally { } or
10136 * __try{ } __except() { }
10138 static statement_t *parse_ms_try_statment(void)
10140 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10143 PUSH_PARENT(statement);
10145 ms_try_statement_t *rem = current_try;
10146 current_try = &statement->ms_try;
10147 statement->ms_try.try_statement = parse_compound_statement(false);
10152 if (token.type == T___except) {
10154 expect('(', end_error);
10155 add_anchor_token(')');
10156 expression_t *const expr = parse_expression();
10157 mark_vars_read(expr, NULL);
10158 type_t * type = skip_typeref(expr->base.type);
10159 if (is_type_integer(type)) {
10160 type = promote_integer(type);
10161 } else if (is_type_valid(type)) {
10162 errorf(&expr->base.source_position,
10163 "__expect expression is not an integer, but '%T'", type);
10164 type = type_error_type;
10166 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10167 rem_anchor_token(')');
10168 expect(')', end_error);
10169 statement->ms_try.final_statement = parse_compound_statement(false);
10170 } else if (token.type == T__finally) {
10172 statement->ms_try.final_statement = parse_compound_statement(false);
10174 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10175 return create_invalid_statement();
10179 return create_invalid_statement();
10182 static statement_t *parse_empty_statement(void)
10184 if (warning.empty_statement) {
10185 warningf(HERE, "statement is empty");
10187 statement_t *const statement = create_empty_statement();
10192 static statement_t *parse_local_label_declaration(void)
10194 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10198 entity_t *begin = NULL, *end = NULL;
10201 if (token.type != T_IDENTIFIER) {
10202 parse_error_expected("while parsing local label declaration",
10203 T_IDENTIFIER, NULL);
10206 symbol_t *symbol = token.v.symbol;
10207 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10208 if (entity != NULL && entity->base.parent_scope == current_scope) {
10209 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10210 symbol, &entity->base.source_position);
10212 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10214 entity->base.parent_scope = current_scope;
10215 entity->base.namespc = NAMESPACE_LABEL;
10216 entity->base.source_position = token.source_position;
10217 entity->base.symbol = symbol;
10220 end->base.next = entity;
10225 environment_push(entity);
10229 if (token.type != ',')
10235 statement->declaration.declarations_begin = begin;
10236 statement->declaration.declarations_end = end;
10240 static void parse_namespace_definition(void)
10244 entity_t *entity = NULL;
10245 symbol_t *symbol = NULL;
10247 if (token.type == T_IDENTIFIER) {
10248 symbol = token.v.symbol;
10251 entity = get_entity(symbol, NAMESPACE_NORMAL);
10252 if (entity != NULL &&
10253 entity->kind != ENTITY_NAMESPACE &&
10254 entity->base.parent_scope == current_scope) {
10255 if (!is_error_entity(entity)) {
10256 error_redefined_as_different_kind(&token.source_position,
10257 entity, ENTITY_NAMESPACE);
10263 if (entity == NULL) {
10264 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10265 entity->base.symbol = symbol;
10266 entity->base.source_position = token.source_position;
10267 entity->base.namespc = NAMESPACE_NORMAL;
10268 entity->base.parent_scope = current_scope;
10271 if (token.type == '=') {
10272 /* TODO: parse namespace alias */
10273 panic("namespace alias definition not supported yet");
10276 environment_push(entity);
10277 append_entity(current_scope, entity);
10279 size_t const top = environment_top();
10280 scope_t *old_scope = scope_push(&entity->namespacee.members);
10282 expect('{', end_error);
10284 expect('}', end_error);
10287 assert(current_scope == &entity->namespacee.members);
10288 scope_pop(old_scope);
10289 environment_pop_to(top);
10293 * Parse a statement.
10294 * There's also parse_statement() which additionally checks for
10295 * "statement has no effect" warnings
10297 static statement_t *intern_parse_statement(void)
10299 statement_t *statement = NULL;
10301 /* declaration or statement */
10302 add_anchor_token(';');
10303 switch (token.type) {
10304 case T_IDENTIFIER: {
10305 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10306 if (la1_type == ':') {
10307 statement = parse_label_statement();
10308 } else if (is_typedef_symbol(token.v.symbol)) {
10309 statement = parse_declaration_statement();
10311 /* it's an identifier, the grammar says this must be an
10312 * expression statement. However it is common that users mistype
10313 * declaration types, so we guess a bit here to improve robustness
10314 * for incorrect programs */
10315 switch (la1_type) {
10318 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10319 goto expression_statment;
10324 statement = parse_declaration_statement();
10328 expression_statment:
10329 statement = parse_expression_statement();
10336 case T___extension__:
10337 /* This can be a prefix to a declaration or an expression statement.
10338 * We simply eat it now and parse the rest with tail recursion. */
10341 } while (token.type == T___extension__);
10342 bool old_gcc_extension = in_gcc_extension;
10343 in_gcc_extension = true;
10344 statement = intern_parse_statement();
10345 in_gcc_extension = old_gcc_extension;
10349 statement = parse_declaration_statement();
10353 statement = parse_local_label_declaration();
10356 case ';': statement = parse_empty_statement(); break;
10357 case '{': statement = parse_compound_statement(false); break;
10358 case T___leave: statement = parse_leave_statement(); break;
10359 case T___try: statement = parse_ms_try_statment(); break;
10360 case T_asm: statement = parse_asm_statement(); break;
10361 case T_break: statement = parse_break(); break;
10362 case T_case: statement = parse_case_statement(); break;
10363 case T_continue: statement = parse_continue(); break;
10364 case T_default: statement = parse_default_statement(); break;
10365 case T_do: statement = parse_do(); break;
10366 case T_for: statement = parse_for(); break;
10367 case T_goto: statement = parse_goto(); break;
10368 case T_if: statement = parse_if(); break;
10369 case T_return: statement = parse_return(); break;
10370 case T_switch: statement = parse_switch(); break;
10371 case T_while: statement = parse_while(); break;
10374 statement = parse_expression_statement();
10378 errorf(HERE, "unexpected token %K while parsing statement", &token);
10379 statement = create_invalid_statement();
10384 rem_anchor_token(';');
10386 assert(statement != NULL
10387 && statement->base.source_position.input_name != NULL);
10393 * parse a statement and emits "statement has no effect" warning if needed
10394 * (This is really a wrapper around intern_parse_statement with check for 1
10395 * single warning. It is needed, because for statement expressions we have
10396 * to avoid the warning on the last statement)
10398 static statement_t *parse_statement(void)
10400 statement_t *statement = intern_parse_statement();
10402 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10403 expression_t *expression = statement->expression.expression;
10404 if (!expression_has_effect(expression)) {
10405 warningf(&expression->base.source_position,
10406 "statement has no effect");
10414 * Parse a compound statement.
10416 static statement_t *parse_compound_statement(bool inside_expression_statement)
10418 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10420 PUSH_PARENT(statement);
10423 add_anchor_token('}');
10424 /* tokens, which can start a statement */
10425 /* TODO MS, __builtin_FOO */
10426 add_anchor_token('!');
10427 add_anchor_token('&');
10428 add_anchor_token('(');
10429 add_anchor_token('*');
10430 add_anchor_token('+');
10431 add_anchor_token('-');
10432 add_anchor_token('{');
10433 add_anchor_token('~');
10434 add_anchor_token(T_CHARACTER_CONSTANT);
10435 add_anchor_token(T_COLONCOLON);
10436 add_anchor_token(T_FLOATINGPOINT);
10437 add_anchor_token(T_IDENTIFIER);
10438 add_anchor_token(T_INTEGER);
10439 add_anchor_token(T_MINUSMINUS);
10440 add_anchor_token(T_PLUSPLUS);
10441 add_anchor_token(T_STRING_LITERAL);
10442 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10443 add_anchor_token(T_WIDE_STRING_LITERAL);
10444 add_anchor_token(T__Bool);
10445 add_anchor_token(T__Complex);
10446 add_anchor_token(T__Imaginary);
10447 add_anchor_token(T___FUNCTION__);
10448 add_anchor_token(T___PRETTY_FUNCTION__);
10449 add_anchor_token(T___alignof__);
10450 add_anchor_token(T___attribute__);
10451 add_anchor_token(T___builtin_va_start);
10452 add_anchor_token(T___extension__);
10453 add_anchor_token(T___func__);
10454 add_anchor_token(T___imag__);
10455 add_anchor_token(T___label__);
10456 add_anchor_token(T___real__);
10457 add_anchor_token(T___thread);
10458 add_anchor_token(T_asm);
10459 add_anchor_token(T_auto);
10460 add_anchor_token(T_bool);
10461 add_anchor_token(T_break);
10462 add_anchor_token(T_case);
10463 add_anchor_token(T_char);
10464 add_anchor_token(T_class);
10465 add_anchor_token(T_const);
10466 add_anchor_token(T_const_cast);
10467 add_anchor_token(T_continue);
10468 add_anchor_token(T_default);
10469 add_anchor_token(T_delete);
10470 add_anchor_token(T_double);
10471 add_anchor_token(T_do);
10472 add_anchor_token(T_dynamic_cast);
10473 add_anchor_token(T_enum);
10474 add_anchor_token(T_extern);
10475 add_anchor_token(T_false);
10476 add_anchor_token(T_float);
10477 add_anchor_token(T_for);
10478 add_anchor_token(T_goto);
10479 add_anchor_token(T_if);
10480 add_anchor_token(T_inline);
10481 add_anchor_token(T_int);
10482 add_anchor_token(T_long);
10483 add_anchor_token(T_new);
10484 add_anchor_token(T_operator);
10485 add_anchor_token(T_register);
10486 add_anchor_token(T_reinterpret_cast);
10487 add_anchor_token(T_restrict);
10488 add_anchor_token(T_return);
10489 add_anchor_token(T_short);
10490 add_anchor_token(T_signed);
10491 add_anchor_token(T_sizeof);
10492 add_anchor_token(T_static);
10493 add_anchor_token(T_static_cast);
10494 add_anchor_token(T_struct);
10495 add_anchor_token(T_switch);
10496 add_anchor_token(T_template);
10497 add_anchor_token(T_this);
10498 add_anchor_token(T_throw);
10499 add_anchor_token(T_true);
10500 add_anchor_token(T_try);
10501 add_anchor_token(T_typedef);
10502 add_anchor_token(T_typeid);
10503 add_anchor_token(T_typename);
10504 add_anchor_token(T_typeof);
10505 add_anchor_token(T_union);
10506 add_anchor_token(T_unsigned);
10507 add_anchor_token(T_using);
10508 add_anchor_token(T_void);
10509 add_anchor_token(T_volatile);
10510 add_anchor_token(T_wchar_t);
10511 add_anchor_token(T_while);
10513 size_t const top = environment_top();
10514 scope_t *old_scope = scope_push(&statement->compound.scope);
10516 statement_t **anchor = &statement->compound.statements;
10517 bool only_decls_so_far = true;
10518 while (token.type != '}') {
10519 if (token.type == T_EOF) {
10520 errorf(&statement->base.source_position,
10521 "EOF while parsing compound statement");
10524 statement_t *sub_statement = intern_parse_statement();
10525 if (is_invalid_statement(sub_statement)) {
10526 /* an error occurred. if we are at an anchor, return */
10532 if (warning.declaration_after_statement) {
10533 if (sub_statement->kind != STATEMENT_DECLARATION) {
10534 only_decls_so_far = false;
10535 } else if (!only_decls_so_far) {
10536 warningf(&sub_statement->base.source_position,
10537 "ISO C90 forbids mixed declarations and code");
10541 *anchor = sub_statement;
10543 while (sub_statement->base.next != NULL)
10544 sub_statement = sub_statement->base.next;
10546 anchor = &sub_statement->base.next;
10550 /* look over all statements again to produce no effect warnings */
10551 if (warning.unused_value) {
10552 statement_t *sub_statement = statement->compound.statements;
10553 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10554 if (sub_statement->kind != STATEMENT_EXPRESSION)
10556 /* don't emit a warning for the last expression in an expression
10557 * statement as it has always an effect */
10558 if (inside_expression_statement && sub_statement->base.next == NULL)
10561 expression_t *expression = sub_statement->expression.expression;
10562 if (!expression_has_effect(expression)) {
10563 warningf(&expression->base.source_position,
10564 "statement has no effect");
10570 rem_anchor_token(T_while);
10571 rem_anchor_token(T_wchar_t);
10572 rem_anchor_token(T_volatile);
10573 rem_anchor_token(T_void);
10574 rem_anchor_token(T_using);
10575 rem_anchor_token(T_unsigned);
10576 rem_anchor_token(T_union);
10577 rem_anchor_token(T_typeof);
10578 rem_anchor_token(T_typename);
10579 rem_anchor_token(T_typeid);
10580 rem_anchor_token(T_typedef);
10581 rem_anchor_token(T_try);
10582 rem_anchor_token(T_true);
10583 rem_anchor_token(T_throw);
10584 rem_anchor_token(T_this);
10585 rem_anchor_token(T_template);
10586 rem_anchor_token(T_switch);
10587 rem_anchor_token(T_struct);
10588 rem_anchor_token(T_static_cast);
10589 rem_anchor_token(T_static);
10590 rem_anchor_token(T_sizeof);
10591 rem_anchor_token(T_signed);
10592 rem_anchor_token(T_short);
10593 rem_anchor_token(T_return);
10594 rem_anchor_token(T_restrict);
10595 rem_anchor_token(T_reinterpret_cast);
10596 rem_anchor_token(T_register);
10597 rem_anchor_token(T_operator);
10598 rem_anchor_token(T_new);
10599 rem_anchor_token(T_long);
10600 rem_anchor_token(T_int);
10601 rem_anchor_token(T_inline);
10602 rem_anchor_token(T_if);
10603 rem_anchor_token(T_goto);
10604 rem_anchor_token(T_for);
10605 rem_anchor_token(T_float);
10606 rem_anchor_token(T_false);
10607 rem_anchor_token(T_extern);
10608 rem_anchor_token(T_enum);
10609 rem_anchor_token(T_dynamic_cast);
10610 rem_anchor_token(T_do);
10611 rem_anchor_token(T_double);
10612 rem_anchor_token(T_delete);
10613 rem_anchor_token(T_default);
10614 rem_anchor_token(T_continue);
10615 rem_anchor_token(T_const_cast);
10616 rem_anchor_token(T_const);
10617 rem_anchor_token(T_class);
10618 rem_anchor_token(T_char);
10619 rem_anchor_token(T_case);
10620 rem_anchor_token(T_break);
10621 rem_anchor_token(T_bool);
10622 rem_anchor_token(T_auto);
10623 rem_anchor_token(T_asm);
10624 rem_anchor_token(T___thread);
10625 rem_anchor_token(T___real__);
10626 rem_anchor_token(T___label__);
10627 rem_anchor_token(T___imag__);
10628 rem_anchor_token(T___func__);
10629 rem_anchor_token(T___extension__);
10630 rem_anchor_token(T___builtin_va_start);
10631 rem_anchor_token(T___attribute__);
10632 rem_anchor_token(T___alignof__);
10633 rem_anchor_token(T___PRETTY_FUNCTION__);
10634 rem_anchor_token(T___FUNCTION__);
10635 rem_anchor_token(T__Imaginary);
10636 rem_anchor_token(T__Complex);
10637 rem_anchor_token(T__Bool);
10638 rem_anchor_token(T_WIDE_STRING_LITERAL);
10639 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10640 rem_anchor_token(T_STRING_LITERAL);
10641 rem_anchor_token(T_PLUSPLUS);
10642 rem_anchor_token(T_MINUSMINUS);
10643 rem_anchor_token(T_INTEGER);
10644 rem_anchor_token(T_IDENTIFIER);
10645 rem_anchor_token(T_FLOATINGPOINT);
10646 rem_anchor_token(T_COLONCOLON);
10647 rem_anchor_token(T_CHARACTER_CONSTANT);
10648 rem_anchor_token('~');
10649 rem_anchor_token('{');
10650 rem_anchor_token('-');
10651 rem_anchor_token('+');
10652 rem_anchor_token('*');
10653 rem_anchor_token('(');
10654 rem_anchor_token('&');
10655 rem_anchor_token('!');
10656 rem_anchor_token('}');
10657 assert(current_scope == &statement->compound.scope);
10658 scope_pop(old_scope);
10659 environment_pop_to(top);
10666 * Check for unused global static functions and variables
10668 static void check_unused_globals(void)
10670 if (!warning.unused_function && !warning.unused_variable)
10673 for (const entity_t *entity = file_scope->entities; entity != NULL;
10674 entity = entity->base.next) {
10675 if (!is_declaration(entity))
10678 const declaration_t *declaration = &entity->declaration;
10679 if (declaration->used ||
10680 declaration->modifiers & DM_UNUSED ||
10681 declaration->modifiers & DM_USED ||
10682 declaration->storage_class != STORAGE_CLASS_STATIC)
10685 type_t *const type = declaration->type;
10687 if (entity->kind == ENTITY_FUNCTION) {
10688 /* inhibit warning for static inline functions */
10689 if (entity->function.is_inline)
10692 s = entity->function.statement != NULL ? "defined" : "declared";
10697 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10698 type, declaration->base.symbol, s);
10702 static void parse_global_asm(void)
10704 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10707 expect('(', end_error);
10709 statement->asms.asm_text = parse_string_literals();
10710 statement->base.next = unit->global_asm;
10711 unit->global_asm = statement;
10713 expect(')', end_error);
10714 expect(';', end_error);
10719 static void parse_linkage_specification(void)
10722 assert(token.type == T_STRING_LITERAL);
10724 const char *linkage = parse_string_literals().begin;
10726 linkage_kind_t old_linkage = current_linkage;
10727 linkage_kind_t new_linkage;
10728 if (strcmp(linkage, "C") == 0) {
10729 new_linkage = LINKAGE_C;
10730 } else if (strcmp(linkage, "C++") == 0) {
10731 new_linkage = LINKAGE_CXX;
10733 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10734 new_linkage = LINKAGE_INVALID;
10736 current_linkage = new_linkage;
10738 if (token.type == '{') {
10741 expect('}', end_error);
10747 assert(current_linkage == new_linkage);
10748 current_linkage = old_linkage;
10751 static void parse_external(void)
10753 switch (token.type) {
10754 DECLARATION_START_NO_EXTERN
10756 case T___extension__:
10757 /* tokens below are for implicit int */
10758 case '&': /* & x; -> int& x; (and error later, because C++ has no
10760 case '*': /* * x; -> int* x; */
10761 case '(': /* (x); -> int (x); */
10762 parse_external_declaration();
10766 if (look_ahead(1)->type == T_STRING_LITERAL) {
10767 parse_linkage_specification();
10769 parse_external_declaration();
10774 parse_global_asm();
10778 parse_namespace_definition();
10782 if (!strict_mode) {
10784 warningf(HERE, "stray ';' outside of function");
10791 errorf(HERE, "stray %K outside of function", &token);
10792 if (token.type == '(' || token.type == '{' || token.type == '[')
10793 eat_until_matching_token(token.type);
10799 static void parse_externals(void)
10801 add_anchor_token('}');
10802 add_anchor_token(T_EOF);
10805 unsigned char token_anchor_copy[T_LAST_TOKEN];
10806 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10809 while (token.type != T_EOF && token.type != '}') {
10811 bool anchor_leak = false;
10812 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10813 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10815 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10816 anchor_leak = true;
10819 if (in_gcc_extension) {
10820 errorf(HERE, "Leaked __extension__");
10821 anchor_leak = true;
10831 rem_anchor_token(T_EOF);
10832 rem_anchor_token('}');
10836 * Parse a translation unit.
10838 static void parse_translation_unit(void)
10840 add_anchor_token(T_EOF);
10845 if (token.type == T_EOF)
10848 errorf(HERE, "stray %K outside of function", &token);
10849 if (token.type == '(' || token.type == '{' || token.type == '[')
10850 eat_until_matching_token(token.type);
10858 * @return the translation unit or NULL if errors occurred.
10860 void start_parsing(void)
10862 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10863 label_stack = NEW_ARR_F(stack_entry_t, 0);
10864 diagnostic_count = 0;
10868 type_set_output(stderr);
10869 ast_set_output(stderr);
10871 assert(unit == NULL);
10872 unit = allocate_ast_zero(sizeof(unit[0]));
10874 assert(file_scope == NULL);
10875 file_scope = &unit->scope;
10877 assert(current_scope == NULL);
10878 scope_push(&unit->scope);
10880 create_gnu_builtins();
10882 create_microsoft_intrinsics();
10885 translation_unit_t *finish_parsing(void)
10887 assert(current_scope == &unit->scope);
10890 assert(file_scope == &unit->scope);
10891 check_unused_globals();
10894 DEL_ARR_F(environment_stack);
10895 DEL_ARR_F(label_stack);
10897 translation_unit_t *result = unit;
10902 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10903 * are given length one. */
10904 static void complete_incomplete_arrays(void)
10906 size_t n = ARR_LEN(incomplete_arrays);
10907 for (size_t i = 0; i != n; ++i) {
10908 declaration_t *const decl = incomplete_arrays[i];
10909 type_t *const orig_type = decl->type;
10910 type_t *const type = skip_typeref(orig_type);
10912 if (!is_type_incomplete(type))
10915 if (warning.other) {
10916 warningf(&decl->base.source_position,
10917 "array '%#T' assumed to have one element",
10918 orig_type, decl->base.symbol);
10921 type_t *const new_type = duplicate_type(type);
10922 new_type->array.size_constant = true;
10923 new_type->array.has_implicit_size = true;
10924 new_type->array.size = 1;
10926 type_t *const result = identify_new_type(new_type);
10928 decl->type = result;
10934 lookahead_bufpos = 0;
10935 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10938 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10939 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10940 parse_translation_unit();
10941 complete_incomplete_arrays();
10942 DEL_ARR_F(incomplete_arrays);
10943 incomplete_arrays = NULL;
10947 * create a builtin function.
10949 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10951 symbol_t *symbol = symbol_table_insert(name);
10952 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10953 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10954 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10955 entity->declaration.type = function_type;
10956 entity->declaration.implicit = true;
10957 entity->base.symbol = symbol;
10958 entity->base.source_position = builtin_source_position;
10960 entity->function.btk = kind;
10962 record_entity(entity, /*is_definition=*/false);
10968 * Create predefined gnu builtins.
10970 static void create_gnu_builtins(void)
10972 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10974 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10975 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10976 GNU_BUILTIN(inf, make_function_0_type(type_double));
10977 GNU_BUILTIN(inff, make_function_0_type(type_float));
10978 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
10979 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
10980 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
10981 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
10982 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
10983 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
10984 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10985 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10986 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
10987 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
10988 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
10989 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
10990 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
10991 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
10992 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
10998 * Create predefined MS intrinsics.
11000 static void create_microsoft_intrinsics(void)
11002 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11004 /* intrinsics for all architectures */
11005 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11006 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11007 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11008 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11009 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11010 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11011 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11013 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11014 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11015 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11016 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11019 MS_BUILTIN(_enable, make_function_0_type(type_void));
11020 MS_BUILTIN(_disable, make_function_0_type(type_void));
11021 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11022 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11023 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11024 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11025 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11026 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11027 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11028 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11029 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11030 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11031 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11033 if (machine_size <= 32) {
11034 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11035 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11037 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11038 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11045 * Initialize the parser.
11047 void init_parser(void)
11049 sym_anonymous = symbol_table_insert("<anonymous>");
11051 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11053 init_expression_parsers();
11054 obstack_init(&temp_obst);
11056 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11057 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11061 * Terminate the parser.
11063 void exit_parser(void)
11065 obstack_free(&temp_obst, NULL);