2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
41 #include "adt/bitfiddle.h"
42 #include "adt/error.h"
43 #include "adt/array.h"
45 //#define PRINT_TOKENS
46 #define MAX_LOOKAHEAD 1
51 entity_namespace_t namespc;
54 typedef struct declaration_specifiers_t declaration_specifiers_t;
55 struct declaration_specifiers_t {
56 source_position_t source_position;
57 storage_class_t storage_class;
58 unsigned char alignment; /**< Alignment, 0 if not set. */
60 bool thread_local : 1; /**< GCC __thread */
61 attribute_t *attributes; /**< list of attributes */
66 * An environment for parsing initializers (and compound literals).
68 typedef struct parse_initializer_env_t {
69 type_t *type; /**< the type of the initializer. In case of an
70 array type with unspecified size this gets
71 adjusted to the actual size. */
72 entity_t *entity; /**< the variable that is initialized if any */
73 bool must_be_constant;
74 } parse_initializer_env_t;
76 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
78 /** The current token. */
80 /** The lookahead ring-buffer. */
81 static token_t lookahead_buffer[MAX_LOOKAHEAD];
82 /** Position of the next token in the lookahead buffer. */
83 static size_t lookahead_bufpos;
84 static stack_entry_t *environment_stack = NULL;
85 static stack_entry_t *label_stack = NULL;
86 static scope_t *file_scope = NULL;
87 static scope_t *current_scope = NULL;
88 /** Point to the current function declaration if inside a function. */
89 static function_t *current_function = NULL;
90 static entity_t *current_init_decl = NULL;
91 static switch_statement_t *current_switch = NULL;
92 static statement_t *current_loop = NULL;
93 static statement_t *current_parent = NULL;
94 static ms_try_statement_t *current_try = NULL;
95 static linkage_kind_t current_linkage = LINKAGE_INVALID;
96 static goto_statement_t *goto_first = NULL;
97 static goto_statement_t **goto_anchor = NULL;
98 static label_statement_t *label_first = NULL;
99 static label_statement_t **label_anchor = NULL;
100 /** current translation unit. */
101 static translation_unit_t *unit = NULL;
102 /** true if we are in a type property context (evaluation only for type. */
103 static bool in_type_prop = false;
104 /** true in we are in a __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
111 #define PUSH_PARENT(stmt) \
112 statement_t *const prev_parent = current_parent; \
113 ((void)(current_parent = (stmt)))
114 #define POP_PARENT ((void)(current_parent = prev_parent))
116 /** special symbol used for anonymous entities. */
117 static symbol_t *sym_anonymous = NULL;
119 /** The token anchor set */
120 static unsigned char token_anchor_set[T_LAST_TOKEN];
122 /** The current source position. */
123 #define HERE (&token.source_position)
125 /** true if we are in GCC mode. */
126 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
128 static statement_t *parse_compound_statement(bool inside_expression_statement);
129 static statement_t *parse_statement(void);
131 static expression_t *parse_sub_expression(precedence_t);
132 static expression_t *parse_expression(void);
133 static type_t *parse_typename(void);
134 static void parse_externals(void);
135 static void parse_external(void);
137 static void parse_compound_type_entries(compound_t *compound_declaration);
139 static void check_call_argument(type_t *expected_type,
140 call_argument_t *argument, unsigned pos);
142 typedef enum declarator_flags_t {
144 DECL_MAY_BE_ABSTRACT = 1U << 0,
145 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
146 DECL_IS_PARAMETER = 1U << 2
147 } declarator_flags_t;
149 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
150 declarator_flags_t flags);
152 static entity_t *record_entity(entity_t *entity, bool is_definition);
154 static void semantic_comparison(binary_expression_t *expression);
156 static void create_gnu_builtins(void);
157 static void create_microsoft_intrinsics(void);
159 #define STORAGE_CLASSES \
160 STORAGE_CLASSES_NO_EXTERN \
163 #define STORAGE_CLASSES_NO_EXTERN \
170 #define TYPE_QUALIFIERS \
175 case T__forceinline: \
176 case T___attribute__:
178 #define COMPLEX_SPECIFIERS \
180 #define IMAGINARY_SPECIFIERS \
183 #define TYPE_SPECIFIERS \
185 case T___builtin_va_list: \
210 #define DECLARATION_START \
215 #define DECLARATION_START_NO_EXTERN \
216 STORAGE_CLASSES_NO_EXTERN \
220 #define TYPENAME_START \
224 #define EXPRESSION_START \
233 case T_CHARACTER_CONSTANT: \
234 case T_FLOATINGPOINT: \
238 case T_STRING_LITERAL: \
239 case T_WIDE_CHARACTER_CONSTANT: \
240 case T_WIDE_STRING_LITERAL: \
241 case T___FUNCDNAME__: \
242 case T___FUNCSIG__: \
243 case T___FUNCTION__: \
244 case T___PRETTY_FUNCTION__: \
245 case T___alignof__: \
246 case T___builtin_classify_type: \
247 case T___builtin_constant_p: \
248 case T___builtin_isgreater: \
249 case T___builtin_isgreaterequal: \
250 case T___builtin_isless: \
251 case T___builtin_islessequal: \
252 case T___builtin_islessgreater: \
253 case T___builtin_isunordered: \
254 case T___builtin_offsetof: \
255 case T___builtin_va_arg: \
256 case T___builtin_va_start: \
257 case T___builtin_va_copy: \
268 * Allocate an AST node with given size and
269 * initialize all fields with zero.
271 static void *allocate_ast_zero(size_t size)
273 void *res = allocate_ast(size);
274 memset(res, 0, size);
279 * Returns the size of an entity node.
281 * @param kind the entity kind
283 static size_t get_entity_struct_size(entity_kind_t kind)
285 static const size_t sizes[] = {
286 [ENTITY_VARIABLE] = sizeof(variable_t),
287 [ENTITY_PARAMETER] = sizeof(parameter_t),
288 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
289 [ENTITY_FUNCTION] = sizeof(function_t),
290 [ENTITY_TYPEDEF] = sizeof(typedef_t),
291 [ENTITY_STRUCT] = sizeof(compound_t),
292 [ENTITY_UNION] = sizeof(compound_t),
293 [ENTITY_ENUM] = sizeof(enum_t),
294 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
295 [ENTITY_LABEL] = sizeof(label_t),
296 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
297 [ENTITY_NAMESPACE] = sizeof(namespace_t)
299 assert(kind < lengthof(sizes));
300 assert(sizes[kind] != 0);
305 * Allocate an entity of given kind and initialize all
308 * @param kind the kind of the entity to allocate
310 static entity_t *allocate_entity_zero(entity_kind_t kind)
312 size_t size = get_entity_struct_size(kind);
313 entity_t *entity = allocate_ast_zero(size);
319 * Returns the size of a statement node.
321 * @param kind the statement kind
323 static size_t get_statement_struct_size(statement_kind_t kind)
325 static const size_t sizes[] = {
326 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
327 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
328 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
329 [STATEMENT_RETURN] = sizeof(return_statement_t),
330 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
331 [STATEMENT_IF] = sizeof(if_statement_t),
332 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
333 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
334 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
335 [STATEMENT_BREAK] = sizeof(statement_base_t),
336 [STATEMENT_GOTO] = sizeof(goto_statement_t),
337 [STATEMENT_LABEL] = sizeof(label_statement_t),
338 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
339 [STATEMENT_WHILE] = sizeof(while_statement_t),
340 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
341 [STATEMENT_FOR] = sizeof(for_statement_t),
342 [STATEMENT_ASM] = sizeof(asm_statement_t),
343 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
344 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
346 assert(kind < lengthof(sizes));
347 assert(sizes[kind] != 0);
352 * Returns the size of an expression node.
354 * @param kind the expression kind
356 static size_t get_expression_struct_size(expression_kind_t kind)
358 static const size_t sizes[] = {
359 [EXPR_INVALID] = sizeof(expression_base_t),
360 [EXPR_REFERENCE] = sizeof(reference_expression_t),
361 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
362 [EXPR_CONST] = sizeof(const_expression_t),
363 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
364 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
365 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
366 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
367 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
368 [EXPR_CALL] = sizeof(call_expression_t),
369 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
370 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
371 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
372 [EXPR_SELECT] = sizeof(select_expression_t),
373 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
374 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
375 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
376 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
377 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
378 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
379 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
380 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
381 [EXPR_VA_START] = sizeof(va_start_expression_t),
382 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
383 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
384 [EXPR_STATEMENT] = sizeof(statement_expression_t),
385 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
387 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
388 return sizes[EXPR_UNARY_FIRST];
390 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
391 return sizes[EXPR_BINARY_FIRST];
393 assert(kind < lengthof(sizes));
394 assert(sizes[kind] != 0);
399 * Allocate a statement node of given kind and initialize all
400 * fields with zero. Sets its source position to the position
401 * of the current token.
403 static statement_t *allocate_statement_zero(statement_kind_t kind)
405 size_t size = get_statement_struct_size(kind);
406 statement_t *res = allocate_ast_zero(size);
408 res->base.kind = kind;
409 res->base.parent = current_parent;
410 res->base.source_position = token.source_position;
415 * Allocate an expression node of given kind and initialize all
418 * @param kind the kind of the expression to allocate
420 static expression_t *allocate_expression_zero(expression_kind_t kind)
422 size_t size = get_expression_struct_size(kind);
423 expression_t *res = allocate_ast_zero(size);
425 res->base.kind = kind;
426 res->base.type = type_error_type;
427 res->base.source_position = token.source_position;
432 * Creates a new invalid expression at the source position
433 * of the current token.
435 static expression_t *create_invalid_expression(void)
437 return allocate_expression_zero(EXPR_INVALID);
441 * Creates a new invalid statement.
443 static statement_t *create_invalid_statement(void)
445 return allocate_statement_zero(STATEMENT_INVALID);
449 * Allocate a new empty statement.
451 static statement_t *create_empty_statement(void)
453 return allocate_statement_zero(STATEMENT_EMPTY);
457 * Returns the size of a type node.
459 * @param kind the type kind
461 static size_t get_type_struct_size(type_kind_t kind)
463 static const size_t sizes[] = {
464 [TYPE_ATOMIC] = sizeof(atomic_type_t),
465 [TYPE_COMPLEX] = sizeof(complex_type_t),
466 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
467 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
468 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
469 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
470 [TYPE_ENUM] = sizeof(enum_type_t),
471 [TYPE_FUNCTION] = sizeof(function_type_t),
472 [TYPE_POINTER] = sizeof(pointer_type_t),
473 [TYPE_ARRAY] = sizeof(array_type_t),
474 [TYPE_BUILTIN] = sizeof(builtin_type_t),
475 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
476 [TYPE_TYPEOF] = sizeof(typeof_type_t),
478 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
479 assert(kind <= TYPE_TYPEOF);
480 assert(sizes[kind] != 0);
485 * Allocate a type node of given kind and initialize all
488 * @param kind type kind to allocate
490 static type_t *allocate_type_zero(type_kind_t kind)
492 size_t size = get_type_struct_size(kind);
493 type_t *res = obstack_alloc(type_obst, size);
494 memset(res, 0, size);
495 res->base.kind = kind;
500 static function_parameter_t *allocate_parameter(type_t *const type)
502 function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
503 memset(param, 0, sizeof(*param));
509 * Returns the size of an initializer node.
511 * @param kind the initializer kind
513 static size_t get_initializer_size(initializer_kind_t kind)
515 static const size_t sizes[] = {
516 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
517 [INITIALIZER_STRING] = sizeof(initializer_string_t),
518 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
519 [INITIALIZER_LIST] = sizeof(initializer_list_t),
520 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
522 assert(kind < lengthof(sizes));
523 assert(sizes[kind] != 0);
528 * Allocate an initializer node of given kind and initialize all
531 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
533 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
540 * Returns the index of the top element of the environment stack.
542 static size_t environment_top(void)
544 return ARR_LEN(environment_stack);
548 * Returns the index of the top element of the global label stack.
550 static size_t label_top(void)
552 return ARR_LEN(label_stack);
556 * Return the next token.
558 static inline void next_token(void)
560 token = lookahead_buffer[lookahead_bufpos];
561 lookahead_buffer[lookahead_bufpos] = lexer_token;
564 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
567 print_token(stderr, &token);
568 fprintf(stderr, "\n");
572 static inline bool next_if(int const type)
574 if (token.type == type) {
583 * Return the next token with a given lookahead.
585 static inline const token_t *look_ahead(size_t num)
587 assert(0 < num && num <= MAX_LOOKAHEAD);
588 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
589 return &lookahead_buffer[pos];
593 * Adds a token type to the token type anchor set (a multi-set).
595 static void add_anchor_token(int token_type)
597 assert(0 <= token_type && token_type < T_LAST_TOKEN);
598 ++token_anchor_set[token_type];
602 * Set the number of tokens types of the given type
603 * to zero and return the old count.
605 static int save_and_reset_anchor_state(int token_type)
607 assert(0 <= token_type && token_type < T_LAST_TOKEN);
608 int count = token_anchor_set[token_type];
609 token_anchor_set[token_type] = 0;
614 * Restore the number of token types to the given count.
616 static void restore_anchor_state(int token_type, int count)
618 assert(0 <= token_type && token_type < T_LAST_TOKEN);
619 token_anchor_set[token_type] = count;
623 * Remove a token type from the token type anchor set (a multi-set).
625 static void rem_anchor_token(int token_type)
627 assert(0 <= token_type && token_type < T_LAST_TOKEN);
628 assert(token_anchor_set[token_type] != 0);
629 --token_anchor_set[token_type];
633 * Return true if the token type of the current token is
636 static bool at_anchor(void)
640 return token_anchor_set[token.type];
644 * Eat tokens until a matching token type is found.
646 static void eat_until_matching_token(int type)
650 case '(': end_token = ')'; break;
651 case '{': end_token = '}'; break;
652 case '[': end_token = ']'; break;
653 default: end_token = type; break;
656 unsigned parenthesis_count = 0;
657 unsigned brace_count = 0;
658 unsigned bracket_count = 0;
659 while (token.type != end_token ||
660 parenthesis_count != 0 ||
662 bracket_count != 0) {
663 switch (token.type) {
665 case '(': ++parenthesis_count; break;
666 case '{': ++brace_count; break;
667 case '[': ++bracket_count; break;
670 if (parenthesis_count > 0)
680 if (bracket_count > 0)
683 if (token.type == end_token &&
684 parenthesis_count == 0 &&
698 * Eat input tokens until an anchor is found.
700 static void eat_until_anchor(void)
702 while (token_anchor_set[token.type] == 0) {
703 if (token.type == '(' || token.type == '{' || token.type == '[')
704 eat_until_matching_token(token.type);
710 * Eat a whole block from input tokens.
712 static void eat_block(void)
714 eat_until_matching_token('{');
718 #define eat(token_type) (assert(token.type == (token_type)), next_token())
721 * Report a parse error because an expected token was not found.
724 #if defined __GNUC__ && __GNUC__ >= 4
725 __attribute__((sentinel))
727 void parse_error_expected(const char *message, ...)
729 if (message != NULL) {
730 errorf(HERE, "%s", message);
733 va_start(ap, message);
734 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
739 * Report an incompatible type.
741 static void type_error_incompatible(const char *msg,
742 const source_position_t *source_position, type_t *type1, type_t *type2)
744 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
749 * Expect the current token is the expected token.
750 * If not, generate an error, eat the current statement,
751 * and goto the end_error label.
753 #define expect(expected, error_label) \
755 if (UNLIKELY(token.type != (expected))) { \
756 parse_error_expected(NULL, (expected), NULL); \
757 add_anchor_token(expected); \
758 eat_until_anchor(); \
759 next_if((expected)); \
760 rem_anchor_token(expected); \
767 * Push a given scope on the scope stack and make it the
770 static scope_t *scope_push(scope_t *new_scope)
772 if (current_scope != NULL) {
773 new_scope->depth = current_scope->depth + 1;
776 scope_t *old_scope = current_scope;
777 current_scope = new_scope;
782 * Pop the current scope from the scope stack.
784 static void scope_pop(scope_t *old_scope)
786 current_scope = old_scope;
790 * Search an entity by its symbol in a given namespace.
792 static entity_t *get_entity(const symbol_t *const symbol,
793 namespace_tag_t namespc)
795 entity_t *entity = symbol->entity;
796 for (; entity != NULL; entity = entity->base.symbol_next) {
797 if (entity->base.namespc == namespc)
804 /* §6.2.3:1 24) There is only one name space for tags even though three are
806 static entity_t *get_tag(symbol_t const *const symbol,
807 entity_kind_tag_t const kind)
809 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
810 if (entity != NULL && entity->kind != kind) {
812 "'%Y' defined as wrong kind of tag (previous definition %P)",
813 symbol, &entity->base.source_position);
820 * pushs an entity on the environment stack and links the corresponding symbol
823 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
825 symbol_t *symbol = entity->base.symbol;
826 entity_namespace_t namespc = entity->base.namespc;
827 assert(namespc != NAMESPACE_INVALID);
829 /* replace/add entity into entity list of the symbol */
832 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
837 /* replace an entry? */
838 if (iter->base.namespc == namespc) {
839 entity->base.symbol_next = iter->base.symbol_next;
845 /* remember old declaration */
847 entry.symbol = symbol;
848 entry.old_entity = iter;
849 entry.namespc = namespc;
850 ARR_APP1(stack_entry_t, *stack_ptr, entry);
854 * Push an entity on the environment stack.
856 static void environment_push(entity_t *entity)
858 assert(entity->base.source_position.input_name != NULL);
859 assert(entity->base.parent_scope != NULL);
860 stack_push(&environment_stack, entity);
864 * Push a declaration on the global label stack.
866 * @param declaration the declaration
868 static void label_push(entity_t *label)
870 /* we abuse the parameters scope as parent for the labels */
871 label->base.parent_scope = ¤t_function->parameters;
872 stack_push(&label_stack, label);
876 * pops symbols from the environment stack until @p new_top is the top element
878 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
880 stack_entry_t *stack = *stack_ptr;
881 size_t top = ARR_LEN(stack);
884 assert(new_top <= top);
888 for (i = top; i > new_top; --i) {
889 stack_entry_t *entry = &stack[i - 1];
891 entity_t *old_entity = entry->old_entity;
892 symbol_t *symbol = entry->symbol;
893 entity_namespace_t namespc = entry->namespc;
895 /* replace with old_entity/remove */
898 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
900 assert(iter != NULL);
901 /* replace an entry? */
902 if (iter->base.namespc == namespc)
906 /* restore definition from outer scopes (if there was one) */
907 if (old_entity != NULL) {
908 old_entity->base.symbol_next = iter->base.symbol_next;
909 *anchor = old_entity;
911 /* remove entry from list */
912 *anchor = iter->base.symbol_next;
916 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
920 * Pop all entries from the environment stack until the new_top
923 * @param new_top the new stack top
925 static void environment_pop_to(size_t new_top)
927 stack_pop_to(&environment_stack, new_top);
931 * Pop all entries from the global label stack until the new_top
934 * @param new_top the new stack top
936 static void label_pop_to(size_t new_top)
938 stack_pop_to(&label_stack, new_top);
941 static int get_akind_rank(atomic_type_kind_t akind)
947 * Return the type rank for an atomic type.
949 static int get_rank(const type_t *type)
951 assert(!is_typeref(type));
952 if (type->kind == TYPE_ENUM)
953 return get_akind_rank(type->enumt.akind);
955 assert(type->kind == TYPE_ATOMIC);
956 return get_akind_rank(type->atomic.akind);
960 * §6.3.1.1:2 Do integer promotion for a given type.
962 * @param type the type to promote
963 * @return the promoted type
965 static type_t *promote_integer(type_t *type)
967 if (type->kind == TYPE_BITFIELD)
968 type = type->bitfield.base_type;
970 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
977 * Create a cast expression.
979 * @param expression the expression to cast
980 * @param dest_type the destination type
982 static expression_t *create_cast_expression(expression_t *expression,
985 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
987 cast->unary.value = expression;
988 cast->base.type = dest_type;
994 * Check if a given expression represents a null pointer constant.
996 * @param expression the expression to check
998 static bool is_null_pointer_constant(const expression_t *expression)
1000 /* skip void* cast */
1001 if (expression->kind == EXPR_UNARY_CAST ||
1002 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1003 type_t *const type = skip_typeref(expression->base.type);
1004 if (types_compatible(type, type_void_ptr))
1005 expression = expression->unary.value;
1008 type_t *const type = skip_typeref(expression->base.type);
1010 is_type_integer(type) &&
1011 is_constant_expression(expression) &&
1012 !fold_constant_to_bool(expression);
1016 * Create an implicit cast expression.
1018 * @param expression the expression to cast
1019 * @param dest_type the destination type
1021 static expression_t *create_implicit_cast(expression_t *expression,
1024 type_t *const source_type = expression->base.type;
1026 if (source_type == dest_type)
1029 return create_cast_expression(expression, dest_type);
1032 typedef enum assign_error_t {
1034 ASSIGN_ERROR_INCOMPATIBLE,
1035 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1036 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1037 ASSIGN_WARNING_POINTER_FROM_INT,
1038 ASSIGN_WARNING_INT_FROM_POINTER
1041 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1042 const expression_t *const right,
1043 const char *context,
1044 const source_position_t *source_position)
1046 type_t *const orig_type_right = right->base.type;
1047 type_t *const type_left = skip_typeref(orig_type_left);
1048 type_t *const type_right = skip_typeref(orig_type_right);
1051 case ASSIGN_SUCCESS:
1053 case ASSIGN_ERROR_INCOMPATIBLE:
1054 errorf(source_position,
1055 "destination type '%T' in %s is incompatible with type '%T'",
1056 orig_type_left, context, orig_type_right);
1059 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1060 if (warning.other) {
1061 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1062 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1064 /* the left type has all qualifiers from the right type */
1065 unsigned missing_qualifiers
1066 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1067 warningf(source_position,
1068 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1069 orig_type_left, context, orig_type_right, missing_qualifiers);
1074 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1075 if (warning.other) {
1076 warningf(source_position,
1077 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1078 orig_type_left, context, right, orig_type_right);
1082 case ASSIGN_WARNING_POINTER_FROM_INT:
1083 if (warning.other) {
1084 warningf(source_position,
1085 "%s makes pointer '%T' from integer '%T' without a cast",
1086 context, orig_type_left, orig_type_right);
1090 case ASSIGN_WARNING_INT_FROM_POINTER:
1091 if (warning.other) {
1092 warningf(source_position,
1093 "%s makes integer '%T' from pointer '%T' without a cast",
1094 context, orig_type_left, orig_type_right);
1099 panic("invalid error value");
1103 /** Implements the rules from §6.5.16.1 */
1104 static assign_error_t semantic_assign(type_t *orig_type_left,
1105 const expression_t *const right)
1107 type_t *const orig_type_right = right->base.type;
1108 type_t *const type_left = skip_typeref(orig_type_left);
1109 type_t *const type_right = skip_typeref(orig_type_right);
1111 if (is_type_pointer(type_left)) {
1112 if (is_null_pointer_constant(right)) {
1113 return ASSIGN_SUCCESS;
1114 } else if (is_type_pointer(type_right)) {
1115 type_t *points_to_left
1116 = skip_typeref(type_left->pointer.points_to);
1117 type_t *points_to_right
1118 = skip_typeref(type_right->pointer.points_to);
1119 assign_error_t res = ASSIGN_SUCCESS;
1121 /* the left type has all qualifiers from the right type */
1122 unsigned missing_qualifiers
1123 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1124 if (missing_qualifiers != 0) {
1125 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1128 points_to_left = get_unqualified_type(points_to_left);
1129 points_to_right = get_unqualified_type(points_to_right);
1131 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1134 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1135 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1136 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1139 if (!types_compatible(points_to_left, points_to_right)) {
1140 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1144 } else if (is_type_integer(type_right)) {
1145 return ASSIGN_WARNING_POINTER_FROM_INT;
1147 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1148 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1149 && is_type_pointer(type_right))) {
1150 return ASSIGN_SUCCESS;
1151 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1152 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1153 type_t *const unqual_type_left = get_unqualified_type(type_left);
1154 type_t *const unqual_type_right = get_unqualified_type(type_right);
1155 if (types_compatible(unqual_type_left, unqual_type_right)) {
1156 return ASSIGN_SUCCESS;
1158 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1159 return ASSIGN_WARNING_INT_FROM_POINTER;
1162 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1163 return ASSIGN_SUCCESS;
1165 return ASSIGN_ERROR_INCOMPATIBLE;
1168 static expression_t *parse_constant_expression(void)
1170 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1172 if (!is_constant_expression(result)) {
1173 errorf(&result->base.source_position,
1174 "expression '%E' is not constant", result);
1180 static expression_t *parse_assignment_expression(void)
1182 return parse_sub_expression(PREC_ASSIGNMENT);
1185 static string_t parse_string_literals(void)
1187 assert(token.type == T_STRING_LITERAL);
1188 string_t result = token.v.string;
1192 while (token.type == T_STRING_LITERAL) {
1193 result = concat_strings(&result, &token.v.string);
1201 * compare two string, ignoring double underscores on the second.
1203 static int strcmp_underscore(const char *s1, const char *s2)
1205 if (s2[0] == '_' && s2[1] == '_') {
1206 size_t len2 = strlen(s2);
1207 size_t len1 = strlen(s1);
1208 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1209 return strncmp(s1, s2+2, len2-4);
1213 return strcmp(s1, s2);
1216 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1218 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1219 attribute->kind = kind;
1224 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1227 * __attribute__ ( ( attribute-list ) )
1231 * attribute_list , attrib
1236 * any-word ( identifier )
1237 * any-word ( identifier , nonempty-expr-list )
1238 * any-word ( expr-list )
1240 * where the "identifier" must not be declared as a type, and
1241 * "any-word" may be any identifier (including one declared as a
1242 * type), a reserved word storage class specifier, type specifier or
1243 * type qualifier. ??? This still leaves out most reserved keywords
1244 * (following the old parser), shouldn't we include them, and why not
1245 * allow identifiers declared as types to start the arguments?
1247 * Matze: this all looks confusing and little systematic, so we're even less
1248 * strict and parse any list of things which are identifiers or
1249 * (assignment-)expressions.
1251 static attribute_argument_t *parse_attribute_arguments(void)
1253 attribute_argument_t *first = NULL;
1254 attribute_argument_t *last = NULL;
1255 if (token.type != ')') do {
1256 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1258 /* is it an identifier */
1259 if (token.type == T_IDENTIFIER
1260 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1261 symbol_t *symbol = token.v.symbol;
1262 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1263 argument->v.symbol = symbol;
1266 /* must be an expression */
1267 expression_t *expression = parse_assignment_expression();
1269 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1270 argument->v.expression = expression;
1273 /* append argument */
1277 last->next = argument;
1280 } while (next_if(','));
1281 expect(')', end_error);
1290 static attribute_t *parse_attribute_asm(void)
1294 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1296 expect('(', end_error);
1297 attribute->a.arguments = parse_attribute_arguments();
1304 static symbol_t *get_symbol_from_token(void)
1306 switch(token.type) {
1308 return token.v.symbol;
1337 /* maybe we need more tokens ... add them on demand */
1338 return get_token_symbol(&token);
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 */
1376 attribute->a.arguments = parse_attribute_arguments();
1384 static attribute_t *parse_attribute_gnu(void)
1386 attribute_t *first = NULL;
1387 attribute_t *last = NULL;
1389 eat(T___attribute__);
1390 expect('(', end_error);
1391 expect('(', end_error);
1393 if (token.type != ')') do {
1394 attribute_t *attribute = parse_attribute_gnu_single();
1395 if (attribute == NULL)
1401 last->next = attribute;
1404 } while (next_if(','));
1405 expect(')', end_error);
1406 expect(')', end_error);
1412 /** Parse attributes. */
1413 static attribute_t *parse_attributes(attribute_t *first)
1415 attribute_t *last = first;
1418 while (last->next != NULL)
1422 attribute_t *attribute;
1423 switch (token.type) {
1424 case T___attribute__:
1425 attribute = parse_attribute_gnu();
1429 attribute = parse_attribute_asm();
1434 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1439 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1442 case T__forceinline:
1444 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1449 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1454 /* TODO record modifier */
1456 warningf(HERE, "Ignoring declaration modifier %K", &token);
1457 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1467 last->next = attribute;
1473 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1475 static entity_t *determine_lhs_ent(expression_t *const expr,
1478 switch (expr->kind) {
1479 case EXPR_REFERENCE: {
1480 entity_t *const entity = expr->reference.entity;
1481 /* we should only find variables as lvalues... */
1482 if (entity->base.kind != ENTITY_VARIABLE
1483 && entity->base.kind != ENTITY_PARAMETER)
1489 case EXPR_ARRAY_ACCESS: {
1490 expression_t *const ref = expr->array_access.array_ref;
1491 entity_t * ent = NULL;
1492 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1493 ent = determine_lhs_ent(ref, lhs_ent);
1496 mark_vars_read(expr->select.compound, lhs_ent);
1498 mark_vars_read(expr->array_access.index, lhs_ent);
1503 if (is_type_compound(skip_typeref(expr->base.type))) {
1504 return determine_lhs_ent(expr->select.compound, lhs_ent);
1506 mark_vars_read(expr->select.compound, lhs_ent);
1511 case EXPR_UNARY_DEREFERENCE: {
1512 expression_t *const val = expr->unary.value;
1513 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1515 return determine_lhs_ent(val->unary.value, lhs_ent);
1517 mark_vars_read(val, NULL);
1523 mark_vars_read(expr, NULL);
1528 #define ENT_ANY ((entity_t*)-1)
1531 * Mark declarations, which are read. This is used to detect variables, which
1535 * x is not marked as "read", because it is only read to calculate its own new
1539 * x and y are not detected as "not read", because multiple variables are
1542 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1544 switch (expr->kind) {
1545 case EXPR_REFERENCE: {
1546 entity_t *const entity = expr->reference.entity;
1547 if (entity->kind != ENTITY_VARIABLE
1548 && entity->kind != ENTITY_PARAMETER)
1551 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1552 if (entity->kind == ENTITY_VARIABLE) {
1553 entity->variable.read = true;
1555 entity->parameter.read = true;
1562 // TODO respect pure/const
1563 mark_vars_read(expr->call.function, NULL);
1564 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1565 mark_vars_read(arg->expression, NULL);
1569 case EXPR_CONDITIONAL:
1570 // TODO lhs_decl should depend on whether true/false have an effect
1571 mark_vars_read(expr->conditional.condition, NULL);
1572 if (expr->conditional.true_expression != NULL)
1573 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1574 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1578 if (lhs_ent == ENT_ANY
1579 && !is_type_compound(skip_typeref(expr->base.type)))
1581 mark_vars_read(expr->select.compound, lhs_ent);
1584 case EXPR_ARRAY_ACCESS: {
1585 expression_t *const ref = expr->array_access.array_ref;
1586 mark_vars_read(ref, lhs_ent);
1587 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1588 mark_vars_read(expr->array_access.index, lhs_ent);
1593 mark_vars_read(expr->va_arge.ap, lhs_ent);
1597 mark_vars_read(expr->va_copye.src, lhs_ent);
1600 case EXPR_UNARY_CAST:
1601 /* Special case: Use void cast to mark a variable as "read" */
1602 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1607 case EXPR_UNARY_THROW:
1608 if (expr->unary.value == NULL)
1611 case EXPR_UNARY_DEREFERENCE:
1612 case EXPR_UNARY_DELETE:
1613 case EXPR_UNARY_DELETE_ARRAY:
1614 if (lhs_ent == ENT_ANY)
1618 case EXPR_UNARY_NEGATE:
1619 case EXPR_UNARY_PLUS:
1620 case EXPR_UNARY_BITWISE_NEGATE:
1621 case EXPR_UNARY_NOT:
1622 case EXPR_UNARY_TAKE_ADDRESS:
1623 case EXPR_UNARY_POSTFIX_INCREMENT:
1624 case EXPR_UNARY_POSTFIX_DECREMENT:
1625 case EXPR_UNARY_PREFIX_INCREMENT:
1626 case EXPR_UNARY_PREFIX_DECREMENT:
1627 case EXPR_UNARY_CAST_IMPLICIT:
1628 case EXPR_UNARY_ASSUME:
1630 mark_vars_read(expr->unary.value, lhs_ent);
1633 case EXPR_BINARY_ADD:
1634 case EXPR_BINARY_SUB:
1635 case EXPR_BINARY_MUL:
1636 case EXPR_BINARY_DIV:
1637 case EXPR_BINARY_MOD:
1638 case EXPR_BINARY_EQUAL:
1639 case EXPR_BINARY_NOTEQUAL:
1640 case EXPR_BINARY_LESS:
1641 case EXPR_BINARY_LESSEQUAL:
1642 case EXPR_BINARY_GREATER:
1643 case EXPR_BINARY_GREATEREQUAL:
1644 case EXPR_BINARY_BITWISE_AND:
1645 case EXPR_BINARY_BITWISE_OR:
1646 case EXPR_BINARY_BITWISE_XOR:
1647 case EXPR_BINARY_LOGICAL_AND:
1648 case EXPR_BINARY_LOGICAL_OR:
1649 case EXPR_BINARY_SHIFTLEFT:
1650 case EXPR_BINARY_SHIFTRIGHT:
1651 case EXPR_BINARY_COMMA:
1652 case EXPR_BINARY_ISGREATER:
1653 case EXPR_BINARY_ISGREATEREQUAL:
1654 case EXPR_BINARY_ISLESS:
1655 case EXPR_BINARY_ISLESSEQUAL:
1656 case EXPR_BINARY_ISLESSGREATER:
1657 case EXPR_BINARY_ISUNORDERED:
1658 mark_vars_read(expr->binary.left, lhs_ent);
1659 mark_vars_read(expr->binary.right, lhs_ent);
1662 case EXPR_BINARY_ASSIGN:
1663 case EXPR_BINARY_MUL_ASSIGN:
1664 case EXPR_BINARY_DIV_ASSIGN:
1665 case EXPR_BINARY_MOD_ASSIGN:
1666 case EXPR_BINARY_ADD_ASSIGN:
1667 case EXPR_BINARY_SUB_ASSIGN:
1668 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1669 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1670 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1671 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1672 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1673 if (lhs_ent == ENT_ANY)
1675 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1676 mark_vars_read(expr->binary.right, lhs_ent);
1681 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1687 case EXPR_CHARACTER_CONSTANT:
1688 case EXPR_WIDE_CHARACTER_CONSTANT:
1689 case EXPR_STRING_LITERAL:
1690 case EXPR_WIDE_STRING_LITERAL:
1691 case EXPR_COMPOUND_LITERAL: // TODO init?
1693 case EXPR_CLASSIFY_TYPE:
1696 case EXPR_BUILTIN_CONSTANT_P:
1697 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1699 case EXPR_STATEMENT: // TODO
1700 case EXPR_LABEL_ADDRESS:
1701 case EXPR_REFERENCE_ENUM_VALUE:
1705 panic("unhandled expression");
1708 static designator_t *parse_designation(void)
1710 designator_t *result = NULL;
1711 designator_t *last = NULL;
1714 designator_t *designator;
1715 switch (token.type) {
1717 designator = allocate_ast_zero(sizeof(designator[0]));
1718 designator->source_position = token.source_position;
1720 add_anchor_token(']');
1721 designator->array_index = parse_constant_expression();
1722 rem_anchor_token(']');
1723 expect(']', end_error);
1726 designator = allocate_ast_zero(sizeof(designator[0]));
1727 designator->source_position = token.source_position;
1729 if (token.type != T_IDENTIFIER) {
1730 parse_error_expected("while parsing designator",
1731 T_IDENTIFIER, NULL);
1734 designator->symbol = token.v.symbol;
1738 expect('=', end_error);
1742 assert(designator != NULL);
1744 last->next = designator;
1746 result = designator;
1754 static initializer_t *initializer_from_string(array_type_t *type,
1755 const string_t *const string)
1757 /* TODO: check len vs. size of array type */
1760 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1761 initializer->string.string = *string;
1766 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1767 wide_string_t *const string)
1769 /* TODO: check len vs. size of array type */
1772 initializer_t *const initializer =
1773 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1774 initializer->wide_string.string = *string;
1780 * Build an initializer from a given expression.
1782 static initializer_t *initializer_from_expression(type_t *orig_type,
1783 expression_t *expression)
1785 /* TODO check that expression is a constant expression */
1787 /* §6.7.8.14/15 char array may be initialized by string literals */
1788 type_t *type = skip_typeref(orig_type);
1789 type_t *expr_type_orig = expression->base.type;
1790 type_t *expr_type = skip_typeref(expr_type_orig);
1791 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1792 array_type_t *const array_type = &type->array;
1793 type_t *const element_type = skip_typeref(array_type->element_type);
1795 if (element_type->kind == TYPE_ATOMIC) {
1796 atomic_type_kind_t akind = element_type->atomic.akind;
1797 switch (expression->kind) {
1798 case EXPR_STRING_LITERAL:
1799 if (akind == ATOMIC_TYPE_CHAR
1800 || akind == ATOMIC_TYPE_SCHAR
1801 || akind == ATOMIC_TYPE_UCHAR) {
1802 return initializer_from_string(array_type,
1803 &expression->string.value);
1807 case EXPR_WIDE_STRING_LITERAL: {
1808 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1809 if (get_unqualified_type(element_type) == bare_wchar_type) {
1810 return initializer_from_wide_string(array_type,
1811 &expression->wide_string.value);
1822 assign_error_t error = semantic_assign(type, expression);
1823 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1825 report_assign_error(error, type, expression, "initializer",
1826 &expression->base.source_position);
1828 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1829 result->value.value = create_implicit_cast(expression, type);
1835 * Checks if a given expression can be used as an constant initializer.
1837 static bool is_initializer_constant(const expression_t *expression)
1839 return is_constant_expression(expression)
1840 || is_address_constant(expression);
1844 * Parses an scalar initializer.
1846 * §6.7.8.11; eat {} without warning
1848 static initializer_t *parse_scalar_initializer(type_t *type,
1849 bool must_be_constant)
1851 /* there might be extra {} hierarchies */
1855 warningf(HERE, "extra curly braces around scalar initializer");
1858 } while (next_if('{'));
1861 expression_t *expression = parse_assignment_expression();
1862 mark_vars_read(expression, NULL);
1863 if (must_be_constant && !is_initializer_constant(expression)) {
1864 errorf(&expression->base.source_position,
1865 "initialisation expression '%E' is not constant",
1869 initializer_t *initializer = initializer_from_expression(type, expression);
1871 if (initializer == NULL) {
1872 errorf(&expression->base.source_position,
1873 "expression '%E' (type '%T') doesn't match expected type '%T'",
1874 expression, expression->base.type, type);
1879 bool additional_warning_displayed = false;
1880 while (braces > 0) {
1882 if (token.type != '}') {
1883 if (!additional_warning_displayed && warning.other) {
1884 warningf(HERE, "additional elements in scalar initializer");
1885 additional_warning_displayed = true;
1896 * An entry in the type path.
1898 typedef struct type_path_entry_t type_path_entry_t;
1899 struct type_path_entry_t {
1900 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1902 size_t index; /**< For array types: the current index. */
1903 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1908 * A type path expression a position inside compound or array types.
1910 typedef struct type_path_t type_path_t;
1911 struct type_path_t {
1912 type_path_entry_t *path; /**< An flexible array containing the current path. */
1913 type_t *top_type; /**< type of the element the path points */
1914 size_t max_index; /**< largest index in outermost array */
1918 * Prints a type path for debugging.
1920 static __attribute__((unused)) void debug_print_type_path(
1921 const type_path_t *path)
1923 size_t len = ARR_LEN(path->path);
1925 for (size_t i = 0; i < len; ++i) {
1926 const type_path_entry_t *entry = & path->path[i];
1928 type_t *type = skip_typeref(entry->type);
1929 if (is_type_compound(type)) {
1930 /* in gcc mode structs can have no members */
1931 if (entry->v.compound_entry == NULL) {
1935 fprintf(stderr, ".%s",
1936 entry->v.compound_entry->base.symbol->string);
1937 } else if (is_type_array(type)) {
1938 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1940 fprintf(stderr, "-INVALID-");
1943 if (path->top_type != NULL) {
1944 fprintf(stderr, " (");
1945 print_type(path->top_type);
1946 fprintf(stderr, ")");
1951 * Return the top type path entry, ie. in a path
1952 * (type).a.b returns the b.
1954 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1956 size_t len = ARR_LEN(path->path);
1958 return &path->path[len-1];
1962 * Enlarge the type path by an (empty) element.
1964 static type_path_entry_t *append_to_type_path(type_path_t *path)
1966 size_t len = ARR_LEN(path->path);
1967 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1969 type_path_entry_t *result = & path->path[len];
1970 memset(result, 0, sizeof(result[0]));
1975 * Descending into a sub-type. Enter the scope of the current top_type.
1977 static void descend_into_subtype(type_path_t *path)
1979 type_t *orig_top_type = path->top_type;
1980 type_t *top_type = skip_typeref(orig_top_type);
1982 type_path_entry_t *top = append_to_type_path(path);
1983 top->type = top_type;
1985 if (is_type_compound(top_type)) {
1986 compound_t *compound = top_type->compound.compound;
1987 entity_t *entry = compound->members.entities;
1989 if (entry != NULL) {
1990 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1991 top->v.compound_entry = &entry->declaration;
1992 path->top_type = entry->declaration.type;
1994 path->top_type = NULL;
1996 } else if (is_type_array(top_type)) {
1998 path->top_type = top_type->array.element_type;
2000 assert(!is_type_valid(top_type));
2005 * Pop an entry from the given type path, ie. returning from
2006 * (type).a.b to (type).a
2008 static void ascend_from_subtype(type_path_t *path)
2010 type_path_entry_t *top = get_type_path_top(path);
2012 path->top_type = top->type;
2014 size_t len = ARR_LEN(path->path);
2015 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2019 * Pop entries from the given type path until the given
2020 * path level is reached.
2022 static void ascend_to(type_path_t *path, size_t top_path_level)
2024 size_t len = ARR_LEN(path->path);
2026 while (len > top_path_level) {
2027 ascend_from_subtype(path);
2028 len = ARR_LEN(path->path);
2032 static bool walk_designator(type_path_t *path, const designator_t *designator,
2033 bool used_in_offsetof)
2035 for (; designator != NULL; designator = designator->next) {
2036 type_path_entry_t *top = get_type_path_top(path);
2037 type_t *orig_type = top->type;
2039 type_t *type = skip_typeref(orig_type);
2041 if (designator->symbol != NULL) {
2042 symbol_t *symbol = designator->symbol;
2043 if (!is_type_compound(type)) {
2044 if (is_type_valid(type)) {
2045 errorf(&designator->source_position,
2046 "'.%Y' designator used for non-compound type '%T'",
2050 top->type = type_error_type;
2051 top->v.compound_entry = NULL;
2052 orig_type = type_error_type;
2054 compound_t *compound = type->compound.compound;
2055 entity_t *iter = compound->members.entities;
2056 for (; iter != NULL; iter = iter->base.next) {
2057 if (iter->base.symbol == symbol) {
2062 errorf(&designator->source_position,
2063 "'%T' has no member named '%Y'", orig_type, symbol);
2066 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2067 if (used_in_offsetof) {
2068 type_t *real_type = skip_typeref(iter->declaration.type);
2069 if (real_type->kind == TYPE_BITFIELD) {
2070 errorf(&designator->source_position,
2071 "offsetof designator '%Y' may not specify bitfield",
2077 top->type = orig_type;
2078 top->v.compound_entry = &iter->declaration;
2079 orig_type = iter->declaration.type;
2082 expression_t *array_index = designator->array_index;
2083 assert(designator->array_index != NULL);
2085 if (!is_type_array(type)) {
2086 if (is_type_valid(type)) {
2087 errorf(&designator->source_position,
2088 "[%E] designator used for non-array type '%T'",
2089 array_index, orig_type);
2094 long index = fold_constant_to_int(array_index);
2095 if (!used_in_offsetof) {
2097 errorf(&designator->source_position,
2098 "array index [%E] must be positive", array_index);
2099 } else if (type->array.size_constant) {
2100 long array_size = type->array.size;
2101 if (index >= array_size) {
2102 errorf(&designator->source_position,
2103 "designator [%E] (%d) exceeds array size %d",
2104 array_index, index, array_size);
2109 top->type = orig_type;
2110 top->v.index = (size_t) index;
2111 orig_type = type->array.element_type;
2113 path->top_type = orig_type;
2115 if (designator->next != NULL) {
2116 descend_into_subtype(path);
2125 static void advance_current_object(type_path_t *path, size_t top_path_level)
2127 type_path_entry_t *top = get_type_path_top(path);
2129 type_t *type = skip_typeref(top->type);
2130 if (is_type_union(type)) {
2131 /* in unions only the first element is initialized */
2132 top->v.compound_entry = NULL;
2133 } else if (is_type_struct(type)) {
2134 declaration_t *entry = top->v.compound_entry;
2136 entity_t *next_entity = entry->base.next;
2137 if (next_entity != NULL) {
2138 assert(is_declaration(next_entity));
2139 entry = &next_entity->declaration;
2144 top->v.compound_entry = entry;
2145 if (entry != NULL) {
2146 path->top_type = entry->type;
2149 } else if (is_type_array(type)) {
2150 assert(is_type_array(type));
2154 if (!type->array.size_constant || top->v.index < type->array.size) {
2158 assert(!is_type_valid(type));
2162 /* we're past the last member of the current sub-aggregate, try if we
2163 * can ascend in the type hierarchy and continue with another subobject */
2164 size_t len = ARR_LEN(path->path);
2166 if (len > top_path_level) {
2167 ascend_from_subtype(path);
2168 advance_current_object(path, top_path_level);
2170 path->top_type = NULL;
2175 * skip any {...} blocks until a closing bracket is reached.
2177 static void skip_initializers(void)
2181 while (token.type != '}') {
2182 if (token.type == T_EOF)
2184 if (token.type == '{') {
2192 static initializer_t *create_empty_initializer(void)
2194 static initializer_t empty_initializer
2195 = { .list = { { INITIALIZER_LIST }, 0 } };
2196 return &empty_initializer;
2200 * Parse a part of an initialiser for a struct or union,
2202 static initializer_t *parse_sub_initializer(type_path_t *path,
2203 type_t *outer_type, size_t top_path_level,
2204 parse_initializer_env_t *env)
2206 if (token.type == '}') {
2207 /* empty initializer */
2208 return create_empty_initializer();
2211 type_t *orig_type = path->top_type;
2212 type_t *type = NULL;
2214 if (orig_type == NULL) {
2215 /* We are initializing an empty compound. */
2217 type = skip_typeref(orig_type);
2220 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2223 designator_t *designator = NULL;
2224 if (token.type == '.' || token.type == '[') {
2225 designator = parse_designation();
2226 goto finish_designator;
2227 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2228 /* GNU-style designator ("identifier: value") */
2229 designator = allocate_ast_zero(sizeof(designator[0]));
2230 designator->source_position = token.source_position;
2231 designator->symbol = token.v.symbol;
2236 /* reset path to toplevel, evaluate designator from there */
2237 ascend_to(path, top_path_level);
2238 if (!walk_designator(path, designator, false)) {
2239 /* can't continue after designation error */
2243 initializer_t *designator_initializer
2244 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2245 designator_initializer->designator.designator = designator;
2246 ARR_APP1(initializer_t*, initializers, designator_initializer);
2248 orig_type = path->top_type;
2249 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2254 if (token.type == '{') {
2255 if (type != NULL && is_type_scalar(type)) {
2256 sub = parse_scalar_initializer(type, env->must_be_constant);
2260 if (env->entity != NULL) {
2262 "extra brace group at end of initializer for '%Y'",
2263 env->entity->base.symbol);
2265 errorf(HERE, "extra brace group at end of initializer");
2268 descend_into_subtype(path);
2270 add_anchor_token('}');
2271 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2273 rem_anchor_token('}');
2276 ascend_from_subtype(path);
2277 expect('}', end_error);
2279 expect('}', end_error);
2280 goto error_parse_next;
2284 /* must be an expression */
2285 expression_t *expression = parse_assignment_expression();
2286 mark_vars_read(expression, NULL);
2288 if (env->must_be_constant && !is_initializer_constant(expression)) {
2289 errorf(&expression->base.source_position,
2290 "Initialisation expression '%E' is not constant",
2295 /* we are already outside, ... */
2296 if (outer_type == NULL)
2297 goto error_parse_next;
2298 type_t *const outer_type_skip = skip_typeref(outer_type);
2299 if (is_type_compound(outer_type_skip) &&
2300 !outer_type_skip->compound.compound->complete) {
2301 goto error_parse_next;
2306 /* handle { "string" } special case */
2307 if ((expression->kind == EXPR_STRING_LITERAL
2308 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2309 && outer_type != NULL) {
2310 sub = initializer_from_expression(outer_type, expression);
2313 if (token.type != '}' && warning.other) {
2314 warningf(HERE, "excessive elements in initializer for type '%T'",
2317 /* TODO: eat , ... */
2322 /* descend into subtypes until expression matches type */
2324 orig_type = path->top_type;
2325 type = skip_typeref(orig_type);
2327 sub = initializer_from_expression(orig_type, expression);
2331 if (!is_type_valid(type)) {
2334 if (is_type_scalar(type)) {
2335 errorf(&expression->base.source_position,
2336 "expression '%E' doesn't match expected type '%T'",
2337 expression, orig_type);
2341 descend_into_subtype(path);
2345 /* update largest index of top array */
2346 const type_path_entry_t *first = &path->path[0];
2347 type_t *first_type = first->type;
2348 first_type = skip_typeref(first_type);
2349 if (is_type_array(first_type)) {
2350 size_t index = first->v.index;
2351 if (index > path->max_index)
2352 path->max_index = index;
2356 /* append to initializers list */
2357 ARR_APP1(initializer_t*, initializers, sub);
2360 if (warning.other) {
2361 if (env->entity != NULL) {
2362 warningf(HERE, "excess elements in initializer for '%Y'",
2363 env->entity->base.symbol);
2365 warningf(HERE, "excess elements in initializer");
2371 if (token.type == '}') {
2374 expect(',', end_error);
2375 if (token.type == '}') {
2380 /* advance to the next declaration if we are not at the end */
2381 advance_current_object(path, top_path_level);
2382 orig_type = path->top_type;
2383 if (orig_type != NULL)
2384 type = skip_typeref(orig_type);
2390 size_t len = ARR_LEN(initializers);
2391 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2392 initializer_t *result = allocate_ast_zero(size);
2393 result->kind = INITIALIZER_LIST;
2394 result->list.len = len;
2395 memcpy(&result->list.initializers, initializers,
2396 len * sizeof(initializers[0]));
2398 DEL_ARR_F(initializers);
2399 ascend_to(path, top_path_level+1);
2404 skip_initializers();
2405 DEL_ARR_F(initializers);
2406 ascend_to(path, top_path_level+1);
2411 * Parses an initializer. Parsers either a compound literal
2412 * (env->declaration == NULL) or an initializer of a declaration.
2414 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2416 type_t *type = skip_typeref(env->type);
2417 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2418 initializer_t *result;
2420 if (is_type_scalar(type)) {
2421 result = parse_scalar_initializer(type, env->must_be_constant);
2422 } else if (token.type == '{') {
2426 memset(&path, 0, sizeof(path));
2427 path.top_type = env->type;
2428 path.path = NEW_ARR_F(type_path_entry_t, 0);
2430 descend_into_subtype(&path);
2432 add_anchor_token('}');
2433 result = parse_sub_initializer(&path, env->type, 1, env);
2434 rem_anchor_token('}');
2436 max_index = path.max_index;
2437 DEL_ARR_F(path.path);
2439 expect('}', end_error);
2441 /* parse_scalar_initializer() also works in this case: we simply
2442 * have an expression without {} around it */
2443 result = parse_scalar_initializer(type, env->must_be_constant);
2446 /* §6.7.8:22 array initializers for arrays with unknown size determine
2447 * the array type size */
2448 if (is_type_array(type) && type->array.size_expression == NULL
2449 && result != NULL) {
2451 switch (result->kind) {
2452 case INITIALIZER_LIST:
2453 assert(max_index != 0xdeadbeaf);
2454 size = max_index + 1;
2457 case INITIALIZER_STRING:
2458 size = result->string.string.size;
2461 case INITIALIZER_WIDE_STRING:
2462 size = result->wide_string.string.size;
2465 case INITIALIZER_DESIGNATOR:
2466 case INITIALIZER_VALUE:
2467 /* can happen for parse errors */
2472 internal_errorf(HERE, "invalid initializer type");
2475 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2476 cnst->base.type = type_size_t;
2477 cnst->conste.v.int_value = size;
2479 type_t *new_type = duplicate_type(type);
2481 new_type->array.size_expression = cnst;
2482 new_type->array.size_constant = true;
2483 new_type->array.has_implicit_size = true;
2484 new_type->array.size = size;
2485 env->type = new_type;
2493 static void append_entity(scope_t *scope, entity_t *entity)
2495 if (scope->last_entity != NULL) {
2496 scope->last_entity->base.next = entity;
2498 scope->entities = entity;
2500 scope->last_entity = entity;
2504 static compound_t *parse_compound_type_specifier(bool is_struct)
2506 eat(is_struct ? T_struct : T_union);
2508 symbol_t *symbol = NULL;
2509 compound_t *compound = NULL;
2510 attribute_t *attributes = NULL;
2512 if (token.type == T___attribute__) {
2513 attributes = parse_attributes(NULL);
2516 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2517 if (token.type == T_IDENTIFIER) {
2518 /* the compound has a name, check if we have seen it already */
2519 symbol = token.v.symbol;
2522 entity_t *entity = get_tag(symbol, kind);
2523 if (entity != NULL) {
2524 compound = &entity->compound;
2525 if (compound->base.parent_scope != current_scope &&
2526 (token.type == '{' || token.type == ';')) {
2527 /* we're in an inner scope and have a definition. Shadow
2528 * existing definition in outer scope */
2530 } else if (compound->complete && token.type == '{') {
2531 assert(symbol != NULL);
2532 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2533 is_struct ? "struct" : "union", symbol,
2534 &compound->base.source_position);
2535 /* clear members in the hope to avoid further errors */
2536 compound->members.entities = NULL;
2539 } else if (token.type != '{') {
2541 parse_error_expected("while parsing struct type specifier",
2542 T_IDENTIFIER, '{', NULL);
2544 parse_error_expected("while parsing union type specifier",
2545 T_IDENTIFIER, '{', NULL);
2551 if (compound == NULL) {
2552 entity_t *entity = allocate_entity_zero(kind);
2553 compound = &entity->compound;
2555 compound->alignment = 1;
2556 compound->base.namespc = NAMESPACE_TAG;
2557 compound->base.source_position = token.source_position;
2558 compound->base.symbol = symbol;
2559 compound->base.parent_scope = current_scope;
2560 if (symbol != NULL) {
2561 environment_push(entity);
2563 append_entity(current_scope, entity);
2566 if (token.type == '{') {
2567 parse_compound_type_entries(compound);
2569 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2570 if (symbol == NULL) {
2571 assert(anonymous_entity == NULL);
2572 anonymous_entity = (entity_t*)compound;
2576 if (attributes != NULL) {
2577 handle_entity_attributes(attributes, (entity_t*) compound);
2583 static void parse_enum_entries(type_t *const enum_type)
2587 if (token.type == '}') {
2588 errorf(HERE, "empty enum not allowed");
2593 add_anchor_token('}');
2595 if (token.type != T_IDENTIFIER) {
2596 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2598 rem_anchor_token('}');
2602 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2603 entity->enum_value.enum_type = enum_type;
2604 entity->base.symbol = token.v.symbol;
2605 entity->base.source_position = token.source_position;
2609 expression_t *value = parse_constant_expression();
2611 value = create_implicit_cast(value, enum_type);
2612 entity->enum_value.value = value;
2617 record_entity(entity, false);
2618 } while (next_if(',') && token.type != '}');
2619 rem_anchor_token('}');
2621 expect('}', end_error);
2627 static type_t *parse_enum_specifier(void)
2633 if (token.type == T_IDENTIFIER) {
2634 symbol = token.v.symbol;
2637 entity = get_tag(symbol, ENTITY_ENUM);
2638 if (entity != NULL) {
2639 if (entity->base.parent_scope != current_scope &&
2640 (token.type == '{' || token.type == ';')) {
2641 /* we're in an inner scope and have a definition. Shadow
2642 * existing definition in outer scope */
2644 } else if (entity->enume.complete && token.type == '{') {
2645 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2646 symbol, &entity->base.source_position);
2649 } else if (token.type != '{') {
2650 parse_error_expected("while parsing enum type specifier",
2651 T_IDENTIFIER, '{', NULL);
2658 if (entity == NULL) {
2659 entity = allocate_entity_zero(ENTITY_ENUM);
2660 entity->base.namespc = NAMESPACE_TAG;
2661 entity->base.source_position = token.source_position;
2662 entity->base.symbol = symbol;
2663 entity->base.parent_scope = current_scope;
2666 type_t *const type = allocate_type_zero(TYPE_ENUM);
2667 type->enumt.enume = &entity->enume;
2668 type->enumt.akind = ATOMIC_TYPE_INT;
2670 if (token.type == '{') {
2671 if (symbol != NULL) {
2672 environment_push(entity);
2674 append_entity(current_scope, entity);
2675 entity->enume.complete = true;
2677 parse_enum_entries(type);
2678 parse_attributes(NULL);
2680 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2681 if (symbol == NULL) {
2682 assert(anonymous_entity == NULL);
2683 anonymous_entity = entity;
2685 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2686 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2694 * if a symbol is a typedef to another type, return true
2696 static bool is_typedef_symbol(symbol_t *symbol)
2698 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2699 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2702 static type_t *parse_typeof(void)
2708 expect('(', end_error);
2709 add_anchor_token(')');
2711 expression_t *expression = NULL;
2713 bool old_type_prop = in_type_prop;
2714 bool old_gcc_extension = in_gcc_extension;
2715 in_type_prop = true;
2717 while (next_if(T___extension__)) {
2718 /* This can be a prefix to a typename or an expression. */
2719 in_gcc_extension = true;
2721 switch (token.type) {
2723 if (is_typedef_symbol(token.v.symbol)) {
2724 type = parse_typename();
2726 expression = parse_expression();
2727 type = revert_automatic_type_conversion(expression);
2732 type = parse_typename();
2736 expression = parse_expression();
2737 type = expression->base.type;
2740 in_type_prop = old_type_prop;
2741 in_gcc_extension = old_gcc_extension;
2743 rem_anchor_token(')');
2744 expect(')', end_error);
2746 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2747 typeof_type->typeoft.expression = expression;
2748 typeof_type->typeoft.typeof_type = type;
2755 typedef enum specifiers_t {
2756 SPECIFIER_SIGNED = 1 << 0,
2757 SPECIFIER_UNSIGNED = 1 << 1,
2758 SPECIFIER_LONG = 1 << 2,
2759 SPECIFIER_INT = 1 << 3,
2760 SPECIFIER_DOUBLE = 1 << 4,
2761 SPECIFIER_CHAR = 1 << 5,
2762 SPECIFIER_WCHAR_T = 1 << 6,
2763 SPECIFIER_SHORT = 1 << 7,
2764 SPECIFIER_LONG_LONG = 1 << 8,
2765 SPECIFIER_FLOAT = 1 << 9,
2766 SPECIFIER_BOOL = 1 << 10,
2767 SPECIFIER_VOID = 1 << 11,
2768 SPECIFIER_INT8 = 1 << 12,
2769 SPECIFIER_INT16 = 1 << 13,
2770 SPECIFIER_INT32 = 1 << 14,
2771 SPECIFIER_INT64 = 1 << 15,
2772 SPECIFIER_INT128 = 1 << 16,
2773 SPECIFIER_COMPLEX = 1 << 17,
2774 SPECIFIER_IMAGINARY = 1 << 18,
2777 static type_t *create_builtin_type(symbol_t *const symbol,
2778 type_t *const real_type)
2780 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2781 type->builtin.symbol = symbol;
2782 type->builtin.real_type = real_type;
2783 return identify_new_type(type);
2786 static type_t *get_typedef_type(symbol_t *symbol)
2788 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2789 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2792 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2793 type->typedeft.typedefe = &entity->typedefe;
2798 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2800 expect('(', end_error);
2802 attribute_property_argument_t *property
2803 = allocate_ast_zero(sizeof(*property));
2806 if (token.type != T_IDENTIFIER) {
2807 parse_error_expected("while parsing property declspec",
2808 T_IDENTIFIER, NULL);
2813 symbol_t *symbol = token.v.symbol;
2815 if (strcmp(symbol->string, "put") == 0) {
2817 } else if (strcmp(symbol->string, "get") == 0) {
2820 errorf(HERE, "expected put or get in property declspec");
2823 expect('=', end_error);
2824 if (token.type != T_IDENTIFIER) {
2825 parse_error_expected("while parsing property declspec",
2826 T_IDENTIFIER, NULL);
2830 property->put_symbol = token.v.symbol;
2832 property->get_symbol = token.v.symbol;
2835 } while (next_if(','));
2837 attribute->a.property = property;
2839 expect(')', end_error);
2845 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2847 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2848 if (next_if(T_restrict)) {
2849 kind = ATTRIBUTE_MS_RESTRICT;
2850 } else if (token.type == T_IDENTIFIER) {
2851 const char *name = token.v.symbol->string;
2853 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2855 const char *attribute_name = get_attribute_name(k);
2856 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2862 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2863 warningf(HERE, "unknown __declspec '%s' ignored", name);
2866 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2870 attribute_t *attribute = allocate_attribute_zero(kind);
2872 if (kind == ATTRIBUTE_MS_PROPERTY) {
2873 return parse_attribute_ms_property(attribute);
2876 /* parse arguments */
2878 attribute->a.arguments = parse_attribute_arguments();
2883 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2887 expect('(', end_error);
2892 add_anchor_token(')');
2894 attribute_t *last = first;
2897 while (last->next != NULL)
2901 attribute_t *attribute
2902 = parse_microsoft_extended_decl_modifier_single();
2903 if (attribute == NULL)
2909 last->next = attribute;
2912 } while (next_if(','));
2914 rem_anchor_token(')');
2915 expect(')', end_error);
2919 rem_anchor_token(')');
2923 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2925 entity_t *entity = allocate_entity_zero(kind);
2926 entity->base.source_position = *HERE;
2927 entity->base.symbol = symbol;
2928 if (is_declaration(entity)) {
2929 entity->declaration.type = type_error_type;
2930 entity->declaration.implicit = true;
2931 } else if (kind == ENTITY_TYPEDEF) {
2932 entity->typedefe.type = type_error_type;
2933 entity->typedefe.builtin = true;
2935 if (kind != ENTITY_COMPOUND_MEMBER)
2936 record_entity(entity, false);
2940 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2942 type_t *type = NULL;
2943 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2944 unsigned type_specifiers = 0;
2945 bool newtype = false;
2946 bool saw_error = false;
2947 bool old_gcc_extension = in_gcc_extension;
2949 specifiers->source_position = token.source_position;
2952 specifiers->attributes = parse_attributes(specifiers->attributes);
2954 switch (token.type) {
2956 #define MATCH_STORAGE_CLASS(token, class) \
2958 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2959 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2961 specifiers->storage_class = class; \
2962 if (specifiers->thread_local) \
2963 goto check_thread_storage_class; \
2967 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2968 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2969 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2970 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2971 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2974 specifiers->attributes
2975 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2979 if (specifiers->thread_local) {
2980 errorf(HERE, "duplicate '__thread'");
2982 specifiers->thread_local = true;
2983 check_thread_storage_class:
2984 switch (specifiers->storage_class) {
2985 case STORAGE_CLASS_EXTERN:
2986 case STORAGE_CLASS_NONE:
2987 case STORAGE_CLASS_STATIC:
2991 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2992 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2993 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2994 wrong_thread_stoarge_class:
2995 errorf(HERE, "'__thread' used with '%s'", wrong);
3002 /* type qualifiers */
3003 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
3005 qualifiers |= qualifier; \
3009 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3010 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3011 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3012 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3013 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3014 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3015 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3016 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3018 case T___extension__:
3020 in_gcc_extension = true;
3023 /* type specifiers */
3024 #define MATCH_SPECIFIER(token, specifier, name) \
3026 if (type_specifiers & specifier) { \
3027 errorf(HERE, "multiple " name " type specifiers given"); \
3029 type_specifiers |= specifier; \
3034 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3035 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3036 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3037 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3038 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3039 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3040 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3041 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3042 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3043 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3044 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3045 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3046 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3047 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3048 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3049 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3050 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3051 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3055 specifiers->is_inline = true;
3059 case T__forceinline:
3061 specifiers->modifiers |= DM_FORCEINLINE;
3066 if (type_specifiers & SPECIFIER_LONG_LONG) {
3067 errorf(HERE, "multiple type specifiers given");
3068 } else if (type_specifiers & SPECIFIER_LONG) {
3069 type_specifiers |= SPECIFIER_LONG_LONG;
3071 type_specifiers |= SPECIFIER_LONG;
3076 #define CHECK_DOUBLE_TYPE() \
3077 if ( type != NULL) \
3078 errorf(HERE, "multiple data types in declaration specifiers");
3081 CHECK_DOUBLE_TYPE();
3082 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3084 type->compound.compound = parse_compound_type_specifier(true);
3087 CHECK_DOUBLE_TYPE();
3088 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3089 type->compound.compound = parse_compound_type_specifier(false);
3092 CHECK_DOUBLE_TYPE();
3093 type = parse_enum_specifier();
3096 CHECK_DOUBLE_TYPE();
3097 type = parse_typeof();
3099 case T___builtin_va_list:
3100 CHECK_DOUBLE_TYPE();
3101 type = duplicate_type(type_valist);
3105 case T_IDENTIFIER: {
3106 /* only parse identifier if we haven't found a type yet */
3107 if (type != NULL || type_specifiers != 0) {
3108 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3109 * declaration, so it doesn't generate errors about expecting '(' or
3111 switch (look_ahead(1)->type) {
3118 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3122 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3127 goto finish_specifiers;
3131 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3132 if (typedef_type == NULL) {
3133 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3134 * declaration, so it doesn't generate 'implicit int' followed by more
3135 * errors later on. */
3136 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3142 errorf(HERE, "%K does not name a type", &token);
3145 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3147 type = allocate_type_zero(TYPE_TYPEDEF);
3148 type->typedeft.typedefe = &entity->typedefe;
3152 if (la1_type == '&' || la1_type == '*')
3153 goto finish_specifiers;
3158 goto finish_specifiers;
3163 type = typedef_type;
3167 /* function specifier */
3169 goto finish_specifiers;
3174 specifiers->attributes = parse_attributes(specifiers->attributes);
3176 in_gcc_extension = old_gcc_extension;
3178 if (type == NULL || (saw_error && type_specifiers != 0)) {
3179 atomic_type_kind_t atomic_type;
3181 /* match valid basic types */
3182 switch (type_specifiers) {
3183 case SPECIFIER_VOID:
3184 atomic_type = ATOMIC_TYPE_VOID;
3186 case SPECIFIER_WCHAR_T:
3187 atomic_type = ATOMIC_TYPE_WCHAR_T;
3189 case SPECIFIER_CHAR:
3190 atomic_type = ATOMIC_TYPE_CHAR;
3192 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3193 atomic_type = ATOMIC_TYPE_SCHAR;
3195 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3196 atomic_type = ATOMIC_TYPE_UCHAR;
3198 case SPECIFIER_SHORT:
3199 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3200 case SPECIFIER_SHORT | SPECIFIER_INT:
3201 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3202 atomic_type = ATOMIC_TYPE_SHORT;
3204 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3205 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3206 atomic_type = ATOMIC_TYPE_USHORT;
3209 case SPECIFIER_SIGNED:
3210 case SPECIFIER_SIGNED | SPECIFIER_INT:
3211 atomic_type = ATOMIC_TYPE_INT;
3213 case SPECIFIER_UNSIGNED:
3214 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3215 atomic_type = ATOMIC_TYPE_UINT;
3217 case SPECIFIER_LONG:
3218 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3219 case SPECIFIER_LONG | SPECIFIER_INT:
3220 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3221 atomic_type = ATOMIC_TYPE_LONG;
3223 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3224 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3225 atomic_type = ATOMIC_TYPE_ULONG;
3228 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3229 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3230 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3231 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3233 atomic_type = ATOMIC_TYPE_LONGLONG;
3234 goto warn_about_long_long;
3236 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3237 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3239 atomic_type = ATOMIC_TYPE_ULONGLONG;
3240 warn_about_long_long:
3241 if (warning.long_long) {
3242 warningf(&specifiers->source_position,
3243 "ISO C90 does not support 'long long'");
3247 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3248 atomic_type = unsigned_int8_type_kind;
3251 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3252 atomic_type = unsigned_int16_type_kind;
3255 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3256 atomic_type = unsigned_int32_type_kind;
3259 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3260 atomic_type = unsigned_int64_type_kind;
3263 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3264 atomic_type = unsigned_int128_type_kind;
3267 case SPECIFIER_INT8:
3268 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3269 atomic_type = int8_type_kind;
3272 case SPECIFIER_INT16:
3273 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3274 atomic_type = int16_type_kind;
3277 case SPECIFIER_INT32:
3278 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3279 atomic_type = int32_type_kind;
3282 case SPECIFIER_INT64:
3283 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3284 atomic_type = int64_type_kind;
3287 case SPECIFIER_INT128:
3288 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3289 atomic_type = int128_type_kind;
3292 case SPECIFIER_FLOAT:
3293 atomic_type = ATOMIC_TYPE_FLOAT;
3295 case SPECIFIER_DOUBLE:
3296 atomic_type = ATOMIC_TYPE_DOUBLE;
3298 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3299 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3301 case SPECIFIER_BOOL:
3302 atomic_type = ATOMIC_TYPE_BOOL;
3304 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3305 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3306 atomic_type = ATOMIC_TYPE_FLOAT;
3308 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3309 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3310 atomic_type = ATOMIC_TYPE_DOUBLE;
3312 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3313 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3314 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3317 /* invalid specifier combination, give an error message */
3318 if (type_specifiers == 0) {
3322 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3323 if (!(c_mode & _CXX) && !strict_mode) {
3324 if (warning.implicit_int) {
3325 warningf(HERE, "no type specifiers in declaration, using 'int'");
3327 atomic_type = ATOMIC_TYPE_INT;
3330 errorf(HERE, "no type specifiers given in declaration");
3332 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3333 (type_specifiers & SPECIFIER_UNSIGNED)) {
3334 errorf(HERE, "signed and unsigned specifiers given");
3335 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3336 errorf(HERE, "only integer types can be signed or unsigned");
3338 errorf(HERE, "multiple datatypes in declaration");
3343 if (type_specifiers & SPECIFIER_COMPLEX) {
3344 type = allocate_type_zero(TYPE_COMPLEX);
3345 type->complex.akind = atomic_type;
3346 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3347 type = allocate_type_zero(TYPE_IMAGINARY);
3348 type->imaginary.akind = atomic_type;
3350 type = allocate_type_zero(TYPE_ATOMIC);
3351 type->atomic.akind = atomic_type;
3354 } else if (type_specifiers != 0) {
3355 errorf(HERE, "multiple datatypes in declaration");
3358 /* FIXME: check type qualifiers here */
3359 type->base.qualifiers = qualifiers;
3362 type = identify_new_type(type);
3364 type = typehash_insert(type);
3367 if (specifiers->attributes != NULL)
3368 type = handle_type_attributes(specifiers->attributes, type);
3369 specifiers->type = type;
3373 specifiers->type = type_error_type;
3376 static type_qualifiers_t parse_type_qualifiers(void)
3378 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3381 switch (token.type) {
3382 /* type qualifiers */
3383 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3384 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3385 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3386 /* microsoft extended type modifiers */
3387 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3388 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3389 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3390 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3391 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3400 * Parses an K&R identifier list
3402 static void parse_identifier_list(scope_t *scope)
3405 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3406 entity->base.source_position = token.source_position;
3407 entity->base.namespc = NAMESPACE_NORMAL;
3408 entity->base.symbol = token.v.symbol;
3409 /* a K&R parameter has no type, yet */
3413 append_entity(scope, entity);
3414 } while (next_if(',') && token.type == T_IDENTIFIER);
3417 static entity_t *parse_parameter(void)
3419 declaration_specifiers_t specifiers;
3420 memset(&specifiers, 0, sizeof(specifiers));
3422 parse_declaration_specifiers(&specifiers);
3424 entity_t *entity = parse_declarator(&specifiers,
3425 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3426 anonymous_entity = NULL;
3430 static void semantic_parameter_incomplete(const entity_t *entity)
3432 assert(entity->kind == ENTITY_PARAMETER);
3434 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3435 * list in a function declarator that is part of a
3436 * definition of that function shall not have
3437 * incomplete type. */
3438 type_t *type = skip_typeref(entity->declaration.type);
3439 if (is_type_incomplete(type)) {
3440 errorf(&entity->base.source_position,
3441 "parameter '%#T' has incomplete type",
3442 entity->declaration.type, entity->base.symbol);
3446 static bool has_parameters(void)
3448 /* func(void) is not a parameter */
3449 if (token.type == T_IDENTIFIER) {
3450 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3453 if (entity->kind != ENTITY_TYPEDEF)
3455 if (skip_typeref(entity->typedefe.type) != type_void)
3457 } else if (token.type != T_void) {
3460 if (look_ahead(1)->type != ')')
3467 * Parses function type parameters (and optionally creates variable_t entities
3468 * for them in a scope)
3470 static void parse_parameters(function_type_t *type, scope_t *scope)
3473 add_anchor_token(')');
3474 int saved_comma_state = save_and_reset_anchor_state(',');
3476 if (token.type == T_IDENTIFIER &&
3477 !is_typedef_symbol(token.v.symbol)) {
3478 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3479 if (la1_type == ',' || la1_type == ')') {
3480 type->kr_style_parameters = true;
3481 parse_identifier_list(scope);
3482 goto parameters_finished;
3486 if (token.type == ')') {
3487 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3488 if (!(c_mode & _CXX))
3489 type->unspecified_parameters = true;
3490 goto parameters_finished;
3493 if (has_parameters()) {
3494 function_parameter_t **anchor = &type->parameters;
3496 switch (token.type) {
3499 type->variadic = true;
3500 goto parameters_finished;
3503 case T___extension__:
3506 entity_t *entity = parse_parameter();
3507 if (entity->kind == ENTITY_TYPEDEF) {
3508 errorf(&entity->base.source_position,
3509 "typedef not allowed as function parameter");
3512 assert(is_declaration(entity));
3514 semantic_parameter_incomplete(entity);
3516 function_parameter_t *const parameter =
3517 allocate_parameter(entity->declaration.type);
3519 if (scope != NULL) {
3520 append_entity(scope, entity);
3523 *anchor = parameter;
3524 anchor = ¶meter->next;
3529 goto parameters_finished;
3531 } while (next_if(','));
3535 parameters_finished:
3536 rem_anchor_token(')');
3537 expect(')', end_error);
3540 restore_anchor_state(',', saved_comma_state);
3543 typedef enum construct_type_kind_t {
3546 CONSTRUCT_REFERENCE,
3549 } construct_type_kind_t;
3551 typedef union construct_type_t construct_type_t;
3553 typedef struct construct_type_base_t {
3554 construct_type_kind_t kind;
3555 construct_type_t *next;
3556 } construct_type_base_t;
3558 typedef struct parsed_pointer_t {
3559 construct_type_base_t base;
3560 type_qualifiers_t type_qualifiers;
3561 variable_t *base_variable; /**< MS __based extension. */
3564 typedef struct parsed_reference_t {
3565 construct_type_base_t base;
3566 } parsed_reference_t;
3568 typedef struct construct_function_type_t {
3569 construct_type_base_t base;
3570 type_t *function_type;
3571 } construct_function_type_t;
3573 typedef struct parsed_array_t {
3574 construct_type_base_t base;
3575 type_qualifiers_t type_qualifiers;
3581 union construct_type_t {
3582 construct_type_kind_t kind;
3583 construct_type_base_t base;
3584 parsed_pointer_t pointer;
3585 parsed_reference_t reference;
3586 construct_function_type_t function;
3587 parsed_array_t array;
3590 static construct_type_t *parse_pointer_declarator(void)
3594 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3595 memset(pointer, 0, sizeof(pointer[0]));
3596 pointer->base.kind = CONSTRUCT_POINTER;
3597 pointer->type_qualifiers = parse_type_qualifiers();
3598 //pointer->base_variable = base_variable;
3600 return (construct_type_t*) pointer;
3603 static construct_type_t *parse_reference_declarator(void)
3607 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3608 parsed_reference_t *reference = &cons->reference;
3609 memset(reference, 0, sizeof(*reference));
3610 cons->kind = CONSTRUCT_REFERENCE;
3615 static construct_type_t *parse_array_declarator(void)
3618 add_anchor_token(']');
3620 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3621 parsed_array_t *array = &cons->array;
3622 memset(array, 0, sizeof(*array));
3623 cons->kind = CONSTRUCT_ARRAY;
3625 if (next_if(T_static))
3626 array->is_static = true;
3628 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3629 if (type_qualifiers != 0 && next_if(T_static))
3630 array->is_static = true;
3631 array->type_qualifiers = type_qualifiers;
3633 if (token.type == '*' && look_ahead(1)->type == ']') {
3634 array->is_variable = true;
3636 } else if (token.type != ']') {
3637 expression_t *const size = parse_assignment_expression();
3639 /* §6.7.5.2:1 Array size must have integer type */
3640 type_t *const orig_type = size->base.type;
3641 type_t *const type = skip_typeref(orig_type);
3642 if (!is_type_integer(type) && is_type_valid(type)) {
3643 errorf(&size->base.source_position,
3644 "array size '%E' must have integer type but has type '%T'",
3649 mark_vars_read(size, NULL);
3652 rem_anchor_token(']');
3653 expect(']', end_error);
3659 static construct_type_t *parse_function_declarator(scope_t *scope)
3661 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3662 function_type_t *ftype = &type->function;
3664 ftype->linkage = current_linkage;
3665 ftype->calling_convention = CC_DEFAULT;
3667 parse_parameters(ftype, scope);
3669 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3670 construct_function_type_t *function = &cons->function;
3671 memset(function, 0, sizeof(*function));
3672 cons->kind = CONSTRUCT_FUNCTION;
3673 function->function_type = type;
3678 typedef struct parse_declarator_env_t {
3679 bool may_be_abstract : 1;
3680 bool must_be_abstract : 1;
3681 decl_modifiers_t modifiers;
3683 source_position_t source_position;
3685 attribute_t *attributes;
3686 } parse_declarator_env_t;
3688 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3690 /* construct a single linked list of construct_type_t's which describe
3691 * how to construct the final declarator type */
3692 construct_type_t *first = NULL;
3693 construct_type_t **anchor = &first;
3695 env->attributes = parse_attributes(env->attributes);
3698 construct_type_t *type;
3699 //variable_t *based = NULL; /* MS __based extension */
3700 switch (token.type) {
3702 if (!(c_mode & _CXX))
3703 errorf(HERE, "references are only available for C++");
3704 type = parse_reference_declarator();
3709 source_position_t const pos = *HERE;
3711 expect('(', end_error);
3712 add_anchor_token(')');
3713 based = parse_microsoft_based();
3714 rem_anchor_token(')');
3715 expect(')', end_error);
3716 if (token.type != '*') {
3717 if (token.type == T__based) {
3718 errorf(&pos, "__based type modifier specified more than once");
3719 } else if (warning.other) {
3721 "__based does not precede a pointer declarator, ignored");
3726 panic("based currently disabled");
3732 type = parse_pointer_declarator();
3736 goto ptr_operator_end;
3740 anchor = &type->base.next;
3742 /* TODO: find out if this is correct */
3743 env->attributes = parse_attributes(env->attributes);
3748 modifiers |= env->modifiers;
3749 env->modifiers = modifiers;
3752 construct_type_t *inner_types = NULL;
3754 switch (token.type) {
3756 if (env->must_be_abstract) {
3757 errorf(HERE, "no identifier expected in typename");
3759 env->symbol = token.v.symbol;
3760 env->source_position = token.source_position;
3765 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3766 * interpreted as ``function with no parameter specification'', rather
3767 * than redundant parentheses around the omitted identifier. */
3768 if (look_ahead(1)->type != ')') {
3770 add_anchor_token(')');
3771 inner_types = parse_inner_declarator(env);
3772 if (inner_types != NULL) {
3773 /* All later declarators only modify the return type */
3774 env->must_be_abstract = true;
3776 rem_anchor_token(')');
3777 expect(')', end_error);
3781 if (env->may_be_abstract)
3783 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3788 construct_type_t **const p = anchor;
3791 construct_type_t *type;
3792 switch (token.type) {
3794 scope_t *scope = NULL;
3795 if (!env->must_be_abstract) {
3796 scope = &env->parameters;
3799 type = parse_function_declarator(scope);
3803 type = parse_array_declarator();
3806 goto declarator_finished;
3809 /* insert in the middle of the list (at p) */
3810 type->base.next = *p;
3813 anchor = &type->base.next;
3816 declarator_finished:
3817 /* append inner_types at the end of the list, we don't to set anchor anymore
3818 * as it's not needed anymore */
3819 *anchor = inner_types;
3826 static type_t *construct_declarator_type(construct_type_t *construct_list, type_t *type)
3828 construct_type_t *iter = construct_list;
3829 for (; iter != NULL; iter = iter->base.next) {
3830 switch (iter->kind) {
3831 case CONSTRUCT_INVALID:
3833 case CONSTRUCT_FUNCTION: {
3834 construct_function_type_t *function = &iter->function;
3835 type_t *function_type = function->function_type;
3837 function_type->function.return_type = type;
3839 type_t *skipped_return_type = skip_typeref(type);
3841 if (is_type_function(skipped_return_type)) {
3842 errorf(HERE, "function returning function is not allowed");
3843 } else if (is_type_array(skipped_return_type)) {
3844 errorf(HERE, "function returning array is not allowed");
3846 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3848 "type qualifiers in return type of function type are meaningless");
3852 /* The function type was constructed earlier. Freeing it here will
3853 * destroy other types. */
3854 type = typehash_insert(function_type);
3858 case CONSTRUCT_POINTER: {
3859 if (is_type_reference(skip_typeref(type)))
3860 errorf(HERE, "cannot declare a pointer to reference");
3862 parsed_pointer_t *pointer = &iter->pointer;
3863 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3867 case CONSTRUCT_REFERENCE:
3868 if (is_type_reference(skip_typeref(type)))
3869 errorf(HERE, "cannot declare a reference to reference");
3871 type = make_reference_type(type);
3874 case CONSTRUCT_ARRAY: {
3875 if (is_type_reference(skip_typeref(type)))
3876 errorf(HERE, "cannot declare an array of references");
3878 parsed_array_t *array = &iter->array;
3879 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3881 expression_t *size_expression = array->size;
3882 if (size_expression != NULL) {
3884 = create_implicit_cast(size_expression, type_size_t);
3887 array_type->base.qualifiers = array->type_qualifiers;
3888 array_type->array.element_type = type;
3889 array_type->array.is_static = array->is_static;
3890 array_type->array.is_variable = array->is_variable;
3891 array_type->array.size_expression = size_expression;
3893 if (size_expression != NULL) {
3894 if (is_constant_expression(size_expression)) {
3896 = fold_constant_to_int(size_expression);
3897 array_type->array.size = size;
3898 array_type->array.size_constant = true;
3899 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3900 * have a value greater than zero. */
3902 if (size < 0 || !GNU_MODE) {
3903 errorf(&size_expression->base.source_position,
3904 "size of array must be greater than zero");
3905 } else if (warning.other) {
3906 warningf(&size_expression->base.source_position,
3907 "zero length arrays are a GCC extension");
3911 array_type->array.is_vla = true;
3915 type_t *skipped_type = skip_typeref(type);
3917 if (is_type_incomplete(skipped_type)) {
3918 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3919 } else if (is_type_function(skipped_type)) {
3920 errorf(HERE, "array of functions is not allowed");
3922 type = identify_new_type(array_type);
3926 internal_errorf(HERE, "invalid type construction found");
3932 static type_t *automatic_type_conversion(type_t *orig_type);
3934 static type_t *semantic_parameter(const source_position_t *pos,
3936 const declaration_specifiers_t *specifiers,
3939 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3940 * shall be adjusted to ``qualified pointer to type'',
3942 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3943 * type'' shall be adjusted to ``pointer to function
3944 * returning type'', as in 6.3.2.1. */
3945 type = automatic_type_conversion(type);
3947 if (specifiers->is_inline && is_type_valid(type)) {
3948 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3951 /* §6.9.1:6 The declarations in the declaration list shall contain
3952 * no storage-class specifier other than register and no
3953 * initializations. */
3954 if (specifiers->thread_local || (
3955 specifiers->storage_class != STORAGE_CLASS_NONE &&
3956 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3958 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3961 /* delay test for incomplete type, because we might have (void)
3962 * which is legal but incomplete... */
3967 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3968 declarator_flags_t flags)
3970 parse_declarator_env_t env;
3971 memset(&env, 0, sizeof(env));
3972 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3974 construct_type_t *construct_type = parse_inner_declarator(&env);
3976 construct_declarator_type(construct_type, specifiers->type);
3977 type_t *type = skip_typeref(orig_type);
3979 if (construct_type != NULL) {
3980 obstack_free(&temp_obst, construct_type);
3983 attribute_t *attributes = parse_attributes(env.attributes);
3984 /* append (shared) specifier attribute behind attributes of this
3986 if (attributes != NULL) {
3987 attribute_t *last = attributes;
3988 while (last->next != NULL)
3990 last->next = specifiers->attributes;
3992 attributes = specifiers->attributes;
3996 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3997 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3998 entity->base.symbol = env.symbol;
3999 entity->base.source_position = env.source_position;
4000 entity->typedefe.type = orig_type;
4002 if (anonymous_entity != NULL) {
4003 if (is_type_compound(type)) {
4004 assert(anonymous_entity->compound.alias == NULL);
4005 assert(anonymous_entity->kind == ENTITY_STRUCT ||
4006 anonymous_entity->kind == ENTITY_UNION);
4007 anonymous_entity->compound.alias = entity;
4008 anonymous_entity = NULL;
4009 } else if (is_type_enum(type)) {
4010 assert(anonymous_entity->enume.alias == NULL);
4011 assert(anonymous_entity->kind == ENTITY_ENUM);
4012 anonymous_entity->enume.alias = entity;
4013 anonymous_entity = NULL;
4017 /* create a declaration type entity */
4018 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
4019 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
4021 if (env.symbol != NULL) {
4022 if (specifiers->is_inline && is_type_valid(type)) {
4023 errorf(&env.source_position,
4024 "compound member '%Y' declared 'inline'", env.symbol);
4027 if (specifiers->thread_local ||
4028 specifiers->storage_class != STORAGE_CLASS_NONE) {
4029 errorf(&env.source_position,
4030 "compound member '%Y' must have no storage class",
4034 } else if (flags & DECL_IS_PARAMETER) {
4035 orig_type = semantic_parameter(&env.source_position, orig_type,
4036 specifiers, env.symbol);
4038 entity = allocate_entity_zero(ENTITY_PARAMETER);
4039 } else if (is_type_function(type)) {
4040 entity = allocate_entity_zero(ENTITY_FUNCTION);
4042 entity->function.is_inline = specifiers->is_inline;
4043 entity->function.parameters = env.parameters;
4045 if (env.symbol != NULL) {
4046 /* this needs fixes for C++ */
4047 bool in_function_scope = current_function != NULL;
4049 if (specifiers->thread_local || (
4050 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4051 specifiers->storage_class != STORAGE_CLASS_NONE &&
4052 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4054 errorf(&env.source_position,
4055 "invalid storage class for function '%Y'", env.symbol);
4059 entity = allocate_entity_zero(ENTITY_VARIABLE);
4061 entity->variable.thread_local = specifiers->thread_local;
4063 if (env.symbol != NULL) {
4064 if (specifiers->is_inline && is_type_valid(type)) {
4065 errorf(&env.source_position,
4066 "variable '%Y' declared 'inline'", env.symbol);
4069 bool invalid_storage_class = false;
4070 if (current_scope == file_scope) {
4071 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4072 specifiers->storage_class != STORAGE_CLASS_NONE &&
4073 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4074 invalid_storage_class = true;
4077 if (specifiers->thread_local &&
4078 specifiers->storage_class == STORAGE_CLASS_NONE) {
4079 invalid_storage_class = true;
4082 if (invalid_storage_class) {
4083 errorf(&env.source_position,
4084 "invalid storage class for variable '%Y'", env.symbol);
4089 if (env.symbol != NULL) {
4090 entity->base.symbol = env.symbol;
4091 entity->base.source_position = env.source_position;
4093 entity->base.source_position = specifiers->source_position;
4095 entity->base.namespc = NAMESPACE_NORMAL;
4096 entity->declaration.type = orig_type;
4097 entity->declaration.alignment = get_type_alignment(orig_type);
4098 entity->declaration.modifiers = env.modifiers;
4099 entity->declaration.attributes = attributes;
4101 storage_class_t storage_class = specifiers->storage_class;
4102 entity->declaration.declared_storage_class = storage_class;
4104 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4105 storage_class = STORAGE_CLASS_AUTO;
4106 entity->declaration.storage_class = storage_class;
4109 if (attributes != NULL) {
4110 handle_entity_attributes(attributes, entity);
4116 static type_t *parse_abstract_declarator(type_t *base_type)
4118 parse_declarator_env_t env;
4119 memset(&env, 0, sizeof(env));
4120 env.may_be_abstract = true;
4121 env.must_be_abstract = true;
4123 construct_type_t *construct_type = parse_inner_declarator(&env);
4125 type_t *result = construct_declarator_type(construct_type, base_type);
4126 if (construct_type != NULL) {
4127 obstack_free(&temp_obst, construct_type);
4129 result = handle_type_attributes(env.attributes, result);
4135 * Check if the declaration of main is suspicious. main should be a
4136 * function with external linkage, returning int, taking either zero
4137 * arguments, two, or three arguments of appropriate types, ie.
4139 * int main([ int argc, char **argv [, char **env ] ]).
4141 * @param decl the declaration to check
4142 * @param type the function type of the declaration
4144 static void check_main(const entity_t *entity)
4146 const source_position_t *pos = &entity->base.source_position;
4147 if (entity->kind != ENTITY_FUNCTION) {
4148 warningf(pos, "'main' is not a function");
4152 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4153 warningf(pos, "'main' is normally a non-static function");
4156 type_t *type = skip_typeref(entity->declaration.type);
4157 assert(is_type_function(type));
4159 function_type_t *func_type = &type->function;
4160 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4161 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4162 func_type->return_type);
4164 const function_parameter_t *parm = func_type->parameters;
4166 type_t *const first_type = parm->type;
4167 if (!types_compatible(skip_typeref(first_type), type_int)) {
4169 "first argument of 'main' should be 'int', but is '%T'",
4174 type_t *const second_type = parm->type;
4175 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4176 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4180 type_t *const third_type = parm->type;
4181 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4182 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4186 goto warn_arg_count;
4190 warningf(pos, "'main' takes only zero, two or three arguments");
4196 * Check if a symbol is the equal to "main".
4198 static bool is_sym_main(const symbol_t *const sym)
4200 return strcmp(sym->string, "main") == 0;
4203 static void error_redefined_as_different_kind(const source_position_t *pos,
4204 const entity_t *old, entity_kind_t new_kind)
4206 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4207 get_entity_kind_name(old->kind), old->base.symbol,
4208 get_entity_kind_name(new_kind), &old->base.source_position);
4211 static bool is_error_entity(entity_t *const ent)
4213 if (is_declaration(ent)) {
4214 return is_type_valid(skip_typeref(ent->declaration.type));
4215 } else if (ent->kind == ENTITY_TYPEDEF) {
4216 return is_type_valid(skip_typeref(ent->typedefe.type));
4221 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4223 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4224 if (attributes_equal(tattr, attr))
4231 * test wether new_list contains any attributes not included in old_list
4233 static bool has_new_attributes(const attribute_t *old_list,
4234 const attribute_t *new_list)
4236 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4237 if (!contains_attribute(old_list, attr))
4244 * Merge in attributes from an attribute list (probably from a previous
4245 * declaration with the same name). Warning: destroys the old structure
4246 * of the attribute list - don't reuse attributes after this call.
4248 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4251 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4253 if (contains_attribute(decl->attributes, attr))
4256 /* move attribute to new declarations attributes list */
4257 attr->next = decl->attributes;
4258 decl->attributes = attr;
4263 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4264 * for various problems that occur for multiple definitions
4266 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4268 const symbol_t *const symbol = entity->base.symbol;
4269 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4270 const source_position_t *pos = &entity->base.source_position;
4272 /* can happen in error cases */
4276 entity_t *const previous_entity = get_entity(symbol, namespc);
4277 /* pushing the same entity twice will break the stack structure */
4278 assert(previous_entity != entity);
4280 if (entity->kind == ENTITY_FUNCTION) {
4281 type_t *const orig_type = entity->declaration.type;
4282 type_t *const type = skip_typeref(orig_type);
4284 assert(is_type_function(type));
4285 if (type->function.unspecified_parameters &&
4286 warning.strict_prototypes &&
4287 previous_entity == NULL) {
4288 warningf(pos, "function declaration '%#T' is not a prototype",
4292 if (warning.main && current_scope == file_scope
4293 && is_sym_main(symbol)) {
4298 if (is_declaration(entity) &&
4299 warning.nested_externs &&
4300 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4301 current_scope != file_scope) {
4302 warningf(pos, "nested extern declaration of '%#T'",
4303 entity->declaration.type, symbol);
4306 if (previous_entity != NULL) {
4307 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4308 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4309 assert(previous_entity->kind == ENTITY_PARAMETER);
4311 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4312 entity->declaration.type, symbol,
4313 previous_entity->declaration.type, symbol,
4314 &previous_entity->base.source_position);
4318 if (previous_entity->base.parent_scope == current_scope) {
4319 if (previous_entity->kind != entity->kind) {
4320 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4321 error_redefined_as_different_kind(pos, previous_entity,
4326 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4327 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4328 symbol, &previous_entity->base.source_position);
4331 if (previous_entity->kind == ENTITY_TYPEDEF) {
4332 /* TODO: C++ allows this for exactly the same type */
4333 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4334 symbol, &previous_entity->base.source_position);
4338 /* at this point we should have only VARIABLES or FUNCTIONS */
4339 assert(is_declaration(previous_entity) && is_declaration(entity));
4341 declaration_t *const prev_decl = &previous_entity->declaration;
4342 declaration_t *const decl = &entity->declaration;
4344 /* can happen for K&R style declarations */
4345 if (prev_decl->type == NULL &&
4346 previous_entity->kind == ENTITY_PARAMETER &&
4347 entity->kind == ENTITY_PARAMETER) {
4348 prev_decl->type = decl->type;
4349 prev_decl->storage_class = decl->storage_class;
4350 prev_decl->declared_storage_class = decl->declared_storage_class;
4351 prev_decl->modifiers = decl->modifiers;
4352 return previous_entity;
4355 type_t *const orig_type = decl->type;
4356 assert(orig_type != NULL);
4357 type_t *const type = skip_typeref(orig_type);
4358 type_t *const prev_type = skip_typeref(prev_decl->type);
4360 if (!types_compatible(type, prev_type)) {
4362 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4363 orig_type, symbol, prev_decl->type, symbol,
4364 &previous_entity->base.source_position);
4366 unsigned old_storage_class = prev_decl->storage_class;
4368 if (warning.redundant_decls &&
4371 !(prev_decl->modifiers & DM_USED) &&
4372 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4373 warningf(&previous_entity->base.source_position,
4374 "unnecessary static forward declaration for '%#T'",
4375 prev_decl->type, symbol);
4378 storage_class_t new_storage_class = decl->storage_class;
4380 /* pretend no storage class means extern for function
4381 * declarations (except if the previous declaration is neither
4382 * none nor extern) */
4383 if (entity->kind == ENTITY_FUNCTION) {
4384 /* the previous declaration could have unspecified parameters or
4385 * be a typedef, so use the new type */
4386 if (prev_type->function.unspecified_parameters || is_definition)
4387 prev_decl->type = type;
4389 switch (old_storage_class) {
4390 case STORAGE_CLASS_NONE:
4391 old_storage_class = STORAGE_CLASS_EXTERN;
4394 case STORAGE_CLASS_EXTERN:
4395 if (is_definition) {
4396 if (warning.missing_prototypes &&
4397 prev_type->function.unspecified_parameters &&
4398 !is_sym_main(symbol)) {
4399 warningf(pos, "no previous prototype for '%#T'",
4402 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4403 new_storage_class = STORAGE_CLASS_EXTERN;
4410 } else if (is_type_incomplete(prev_type)) {
4411 prev_decl->type = type;
4414 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4415 new_storage_class == STORAGE_CLASS_EXTERN) {
4417 warn_redundant_declaration: ;
4419 = has_new_attributes(prev_decl->attributes,
4421 if (has_new_attrs) {
4422 merge_in_attributes(decl, prev_decl->attributes);
4423 } else if (!is_definition &&
4424 warning.redundant_decls &&
4425 is_type_valid(prev_type) &&
4426 strcmp(previous_entity->base.source_position.input_name,
4427 "<builtin>") != 0) {
4429 "redundant declaration for '%Y' (declared %P)",
4430 symbol, &previous_entity->base.source_position);
4432 } else if (current_function == NULL) {
4433 if (old_storage_class != STORAGE_CLASS_STATIC &&
4434 new_storage_class == STORAGE_CLASS_STATIC) {
4436 "static declaration of '%Y' follows non-static declaration (declared %P)",
4437 symbol, &previous_entity->base.source_position);
4438 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4439 prev_decl->storage_class = STORAGE_CLASS_NONE;
4440 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4442 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4444 goto error_redeclaration;
4445 goto warn_redundant_declaration;
4447 } else if (is_type_valid(prev_type)) {
4448 if (old_storage_class == new_storage_class) {
4449 error_redeclaration:
4450 errorf(pos, "redeclaration of '%Y' (declared %P)",
4451 symbol, &previous_entity->base.source_position);
4454 "redeclaration of '%Y' with different linkage (declared %P)",
4455 symbol, &previous_entity->base.source_position);
4460 prev_decl->modifiers |= decl->modifiers;
4461 if (entity->kind == ENTITY_FUNCTION) {
4462 previous_entity->function.is_inline |= entity->function.is_inline;
4464 return previous_entity;
4467 if (warning.shadow) {
4468 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4469 get_entity_kind_name(entity->kind), symbol,
4470 get_entity_kind_name(previous_entity->kind),
4471 &previous_entity->base.source_position);
4475 if (entity->kind == ENTITY_FUNCTION) {
4476 if (is_definition &&
4477 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4478 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4479 warningf(pos, "no previous prototype for '%#T'",
4480 entity->declaration.type, symbol);
4481 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4482 warningf(pos, "no previous declaration for '%#T'",
4483 entity->declaration.type, symbol);
4486 } else if (warning.missing_declarations &&
4487 entity->kind == ENTITY_VARIABLE &&
4488 current_scope == file_scope) {
4489 declaration_t *declaration = &entity->declaration;
4490 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4491 warningf(pos, "no previous declaration for '%#T'",
4492 declaration->type, symbol);
4497 assert(entity->base.parent_scope == NULL);
4498 assert(current_scope != NULL);
4500 entity->base.parent_scope = current_scope;
4501 entity->base.namespc = NAMESPACE_NORMAL;
4502 environment_push(entity);
4503 append_entity(current_scope, entity);
4508 static void parser_error_multiple_definition(entity_t *entity,
4509 const source_position_t *source_position)
4511 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4512 entity->base.symbol, &entity->base.source_position);
4515 static bool is_declaration_specifier(const token_t *token,
4516 bool only_specifiers_qualifiers)
4518 switch (token->type) {
4523 return is_typedef_symbol(token->v.symbol);
4525 case T___extension__:
4527 return !only_specifiers_qualifiers;
4534 static void parse_init_declarator_rest(entity_t *entity)
4536 assert(is_declaration(entity));
4537 declaration_t *const declaration = &entity->declaration;
4541 type_t *orig_type = declaration->type;
4542 type_t *type = skip_typeref(orig_type);
4544 if (entity->kind == ENTITY_VARIABLE
4545 && entity->variable.initializer != NULL) {
4546 parser_error_multiple_definition(entity, HERE);
4549 bool must_be_constant = false;
4550 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4551 entity->base.parent_scope == file_scope) {
4552 must_be_constant = true;
4555 if (is_type_function(type)) {
4556 errorf(&entity->base.source_position,
4557 "function '%#T' is initialized like a variable",
4558 orig_type, entity->base.symbol);
4559 orig_type = type_error_type;
4562 parse_initializer_env_t env;
4563 env.type = orig_type;
4564 env.must_be_constant = must_be_constant;
4565 env.entity = entity;
4566 current_init_decl = entity;
4568 initializer_t *initializer = parse_initializer(&env);
4569 current_init_decl = NULL;
4571 if (entity->kind == ENTITY_VARIABLE) {
4572 /* §6.7.5:22 array initializers for arrays with unknown size
4573 * determine the array type size */
4574 declaration->type = env.type;
4575 entity->variable.initializer = initializer;
4579 /* parse rest of a declaration without any declarator */
4580 static void parse_anonymous_declaration_rest(
4581 const declaration_specifiers_t *specifiers)
4584 anonymous_entity = NULL;
4586 if (warning.other) {
4587 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4588 specifiers->thread_local) {
4589 warningf(&specifiers->source_position,
4590 "useless storage class in empty declaration");
4593 type_t *type = specifiers->type;
4594 switch (type->kind) {
4595 case TYPE_COMPOUND_STRUCT:
4596 case TYPE_COMPOUND_UNION: {
4597 if (type->compound.compound->base.symbol == NULL) {
4598 warningf(&specifiers->source_position,
4599 "unnamed struct/union that defines no instances");
4608 warningf(&specifiers->source_position, "empty declaration");
4614 static void check_variable_type_complete(entity_t *ent)
4616 if (ent->kind != ENTITY_VARIABLE)
4619 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4620 * type for the object shall be complete [...] */
4621 declaration_t *decl = &ent->declaration;
4622 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4623 decl->storage_class == STORAGE_CLASS_STATIC)
4626 type_t *const orig_type = decl->type;
4627 type_t *const type = skip_typeref(orig_type);
4628 if (!is_type_incomplete(type))
4631 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4632 * are given length one. */
4633 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4634 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4638 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4639 orig_type, ent->base.symbol);
4643 static void parse_declaration_rest(entity_t *ndeclaration,
4644 const declaration_specifiers_t *specifiers,
4645 parsed_declaration_func finished_declaration,
4646 declarator_flags_t flags)
4648 add_anchor_token(';');
4649 add_anchor_token(',');
4651 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4653 if (token.type == '=') {
4654 parse_init_declarator_rest(entity);
4655 } else if (entity->kind == ENTITY_VARIABLE) {
4656 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4657 * [...] where the extern specifier is explicitly used. */
4658 declaration_t *decl = &entity->declaration;
4659 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4660 type_t *type = decl->type;
4661 if (is_type_reference(skip_typeref(type))) {
4662 errorf(&entity->base.source_position,
4663 "reference '%#T' must be initialized",
4664 type, entity->base.symbol);
4669 check_variable_type_complete(entity);
4674 add_anchor_token('=');
4675 ndeclaration = parse_declarator(specifiers, flags);
4676 rem_anchor_token('=');
4678 expect(';', end_error);
4681 anonymous_entity = NULL;
4682 rem_anchor_token(';');
4683 rem_anchor_token(',');
4686 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4688 symbol_t *symbol = entity->base.symbol;
4689 if (symbol == NULL) {
4690 errorf(HERE, "anonymous declaration not valid as function parameter");
4694 assert(entity->base.namespc == NAMESPACE_NORMAL);
4695 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4696 if (previous_entity == NULL
4697 || previous_entity->base.parent_scope != current_scope) {
4698 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4703 if (is_definition) {
4704 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4707 return record_entity(entity, false);
4710 static void parse_declaration(parsed_declaration_func finished_declaration,
4711 declarator_flags_t flags)
4713 declaration_specifiers_t specifiers;
4714 memset(&specifiers, 0, sizeof(specifiers));
4716 add_anchor_token(';');
4717 parse_declaration_specifiers(&specifiers);
4718 rem_anchor_token(';');
4720 if (token.type == ';') {
4721 parse_anonymous_declaration_rest(&specifiers);
4723 entity_t *entity = parse_declarator(&specifiers, flags);
4724 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4729 static type_t *get_default_promoted_type(type_t *orig_type)
4731 type_t *result = orig_type;
4733 type_t *type = skip_typeref(orig_type);
4734 if (is_type_integer(type)) {
4735 result = promote_integer(type);
4736 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4737 result = type_double;
4743 static void parse_kr_declaration_list(entity_t *entity)
4745 if (entity->kind != ENTITY_FUNCTION)
4748 type_t *type = skip_typeref(entity->declaration.type);
4749 assert(is_type_function(type));
4750 if (!type->function.kr_style_parameters)
4753 add_anchor_token('{');
4755 /* push function parameters */
4756 size_t const top = environment_top();
4757 scope_t *old_scope = scope_push(&entity->function.parameters);
4759 entity_t *parameter = entity->function.parameters.entities;
4760 for ( ; parameter != NULL; parameter = parameter->base.next) {
4761 assert(parameter->base.parent_scope == NULL);
4762 parameter->base.parent_scope = current_scope;
4763 environment_push(parameter);
4766 /* parse declaration list */
4768 switch (token.type) {
4770 case T___extension__:
4771 /* This covers symbols, which are no type, too, and results in
4772 * better error messages. The typical cases are misspelled type
4773 * names and missing includes. */
4775 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4783 /* pop function parameters */
4784 assert(current_scope == &entity->function.parameters);
4785 scope_pop(old_scope);
4786 environment_pop_to(top);
4788 /* update function type */
4789 type_t *new_type = duplicate_type(type);
4791 function_parameter_t *parameters = NULL;
4792 function_parameter_t **anchor = ¶meters;
4794 /* did we have an earlier prototype? */
4795 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4796 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4799 function_parameter_t *proto_parameter = NULL;
4800 if (proto_type != NULL) {
4801 type_t *proto_type_type = proto_type->declaration.type;
4802 proto_parameter = proto_type_type->function.parameters;
4803 /* If a K&R function definition has a variadic prototype earlier, then
4804 * make the function definition variadic, too. This should conform to
4805 * §6.7.5.3:15 and §6.9.1:8. */
4806 new_type->function.variadic = proto_type_type->function.variadic;
4808 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4810 new_type->function.unspecified_parameters = true;
4813 bool need_incompatible_warning = false;
4814 parameter = entity->function.parameters.entities;
4815 for (; parameter != NULL; parameter = parameter->base.next,
4817 proto_parameter == NULL ? NULL : proto_parameter->next) {
4818 if (parameter->kind != ENTITY_PARAMETER)
4821 type_t *parameter_type = parameter->declaration.type;
4822 if (parameter_type == NULL) {
4824 errorf(HERE, "no type specified for function parameter '%Y'",
4825 parameter->base.symbol);
4826 parameter_type = type_error_type;
4828 if (warning.implicit_int) {
4829 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4830 parameter->base.symbol);
4832 parameter_type = type_int;
4834 parameter->declaration.type = parameter_type;
4837 semantic_parameter_incomplete(parameter);
4839 /* we need the default promoted types for the function type */
4840 type_t *not_promoted = parameter_type;
4841 parameter_type = get_default_promoted_type(parameter_type);
4843 /* gcc special: if the type of the prototype matches the unpromoted
4844 * type don't promote */
4845 if (!strict_mode && proto_parameter != NULL) {
4846 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4847 type_t *promo_skip = skip_typeref(parameter_type);
4848 type_t *param_skip = skip_typeref(not_promoted);
4849 if (!types_compatible(proto_p_type, promo_skip)
4850 && types_compatible(proto_p_type, param_skip)) {
4852 need_incompatible_warning = true;
4853 parameter_type = not_promoted;
4856 function_parameter_t *const parameter
4857 = allocate_parameter(parameter_type);
4859 *anchor = parameter;
4860 anchor = ¶meter->next;
4863 new_type->function.parameters = parameters;
4864 new_type = identify_new_type(new_type);
4866 if (warning.other && need_incompatible_warning) {
4867 type_t *proto_type_type = proto_type->declaration.type;
4869 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4870 proto_type_type, proto_type->base.symbol,
4871 new_type, entity->base.symbol,
4872 &proto_type->base.source_position);
4875 entity->declaration.type = new_type;
4877 rem_anchor_token('{');
4880 static bool first_err = true;
4883 * When called with first_err set, prints the name of the current function,
4886 static void print_in_function(void)
4890 diagnosticf("%s: In function '%Y':\n",
4891 current_function->base.base.source_position.input_name,
4892 current_function->base.base.symbol);
4897 * Check if all labels are defined in the current function.
4898 * Check if all labels are used in the current function.
4900 static void check_labels(void)
4902 for (const goto_statement_t *goto_statement = goto_first;
4903 goto_statement != NULL;
4904 goto_statement = goto_statement->next) {
4905 /* skip computed gotos */
4906 if (goto_statement->expression != NULL)
4909 label_t *label = goto_statement->label;
4912 if (label->base.source_position.input_name == NULL) {
4913 print_in_function();
4914 errorf(&goto_statement->base.source_position,
4915 "label '%Y' used but not defined", label->base.symbol);
4919 if (warning.unused_label) {
4920 for (const label_statement_t *label_statement = label_first;
4921 label_statement != NULL;
4922 label_statement = label_statement->next) {
4923 label_t *label = label_statement->label;
4925 if (! label->used) {
4926 print_in_function();
4927 warningf(&label_statement->base.source_position,
4928 "label '%Y' defined but not used", label->base.symbol);
4934 static void warn_unused_entity(entity_t *entity, entity_t *last)
4936 entity_t const *const end = last != NULL ? last->base.next : NULL;
4937 for (; entity != end; entity = entity->base.next) {
4938 if (!is_declaration(entity))
4941 declaration_t *declaration = &entity->declaration;
4942 if (declaration->implicit)
4945 if (!declaration->used) {
4946 print_in_function();
4947 const char *what = get_entity_kind_name(entity->kind);
4948 warningf(&entity->base.source_position, "%s '%Y' is unused",
4949 what, entity->base.symbol);
4950 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4951 print_in_function();
4952 const char *what = get_entity_kind_name(entity->kind);
4953 warningf(&entity->base.source_position, "%s '%Y' is never read",
4954 what, entity->base.symbol);
4959 static void check_unused_variables(statement_t *const stmt, void *const env)
4963 switch (stmt->kind) {
4964 case STATEMENT_DECLARATION: {
4965 declaration_statement_t const *const decls = &stmt->declaration;
4966 warn_unused_entity(decls->declarations_begin,
4967 decls->declarations_end);
4972 warn_unused_entity(stmt->fors.scope.entities, NULL);
4981 * Check declarations of current_function for unused entities.
4983 static void check_declarations(void)
4985 if (warning.unused_parameter) {
4986 const scope_t *scope = ¤t_function->parameters;
4988 /* do not issue unused warnings for main */
4989 if (!is_sym_main(current_function->base.base.symbol)) {
4990 warn_unused_entity(scope->entities, NULL);
4993 if (warning.unused_variable) {
4994 walk_statements(current_function->statement, check_unused_variables,
4999 static int determine_truth(expression_t const* const cond)
5002 !is_constant_expression(cond) ? 0 :
5003 fold_constant_to_bool(cond) ? 1 :
5007 static void check_reachable(statement_t *);
5008 static bool reaches_end;
5010 static bool expression_returns(expression_t const *const expr)
5012 switch (expr->kind) {
5014 expression_t const *const func = expr->call.function;
5015 if (func->kind == EXPR_REFERENCE) {
5016 entity_t *entity = func->reference.entity;
5017 if (entity->kind == ENTITY_FUNCTION
5018 && entity->declaration.modifiers & DM_NORETURN)
5022 if (!expression_returns(func))
5025 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
5026 if (!expression_returns(arg->expression))
5033 case EXPR_REFERENCE:
5034 case EXPR_REFERENCE_ENUM_VALUE:
5036 case EXPR_CHARACTER_CONSTANT:
5037 case EXPR_WIDE_CHARACTER_CONSTANT:
5038 case EXPR_STRING_LITERAL:
5039 case EXPR_WIDE_STRING_LITERAL:
5040 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
5041 case EXPR_LABEL_ADDRESS:
5042 case EXPR_CLASSIFY_TYPE:
5043 case EXPR_SIZEOF: // TODO handle obscure VLA case
5046 case EXPR_BUILTIN_CONSTANT_P:
5047 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5052 case EXPR_STATEMENT: {
5053 bool old_reaches_end = reaches_end;
5054 reaches_end = false;
5055 check_reachable(expr->statement.statement);
5056 bool returns = reaches_end;
5057 reaches_end = old_reaches_end;
5061 case EXPR_CONDITIONAL:
5062 // TODO handle constant expression
5064 if (!expression_returns(expr->conditional.condition))
5067 if (expr->conditional.true_expression != NULL
5068 && expression_returns(expr->conditional.true_expression))
5071 return expression_returns(expr->conditional.false_expression);
5074 return expression_returns(expr->select.compound);
5076 case EXPR_ARRAY_ACCESS:
5078 expression_returns(expr->array_access.array_ref) &&
5079 expression_returns(expr->array_access.index);
5082 return expression_returns(expr->va_starte.ap);
5085 return expression_returns(expr->va_arge.ap);
5088 return expression_returns(expr->va_copye.src);
5090 EXPR_UNARY_CASES_MANDATORY
5091 return expression_returns(expr->unary.value);
5093 case EXPR_UNARY_THROW:
5097 // TODO handle constant lhs of && and ||
5099 expression_returns(expr->binary.left) &&
5100 expression_returns(expr->binary.right);
5106 panic("unhandled expression");
5109 static bool initializer_returns(initializer_t const *const init)
5111 switch (init->kind) {
5112 case INITIALIZER_VALUE:
5113 return expression_returns(init->value.value);
5115 case INITIALIZER_LIST: {
5116 initializer_t * const* i = init->list.initializers;
5117 initializer_t * const* const end = i + init->list.len;
5118 bool returns = true;
5119 for (; i != end; ++i) {
5120 if (!initializer_returns(*i))
5126 case INITIALIZER_STRING:
5127 case INITIALIZER_WIDE_STRING:
5128 case INITIALIZER_DESIGNATOR: // designators have no payload
5131 panic("unhandled initializer");
5134 static bool noreturn_candidate;
5136 static void check_reachable(statement_t *const stmt)
5138 if (stmt->base.reachable)
5140 if (stmt->kind != STATEMENT_DO_WHILE)
5141 stmt->base.reachable = true;
5143 statement_t *last = stmt;
5145 switch (stmt->kind) {
5146 case STATEMENT_INVALID:
5147 case STATEMENT_EMPTY:
5149 next = stmt->base.next;
5152 case STATEMENT_DECLARATION: {
5153 declaration_statement_t const *const decl = &stmt->declaration;
5154 entity_t const * ent = decl->declarations_begin;
5155 entity_t const *const last = decl->declarations_end;
5157 for (;; ent = ent->base.next) {
5158 if (ent->kind == ENTITY_VARIABLE &&
5159 ent->variable.initializer != NULL &&
5160 !initializer_returns(ent->variable.initializer)) {
5167 next = stmt->base.next;
5171 case STATEMENT_COMPOUND:
5172 next = stmt->compound.statements;
5174 next = stmt->base.next;
5177 case STATEMENT_RETURN: {
5178 expression_t const *const val = stmt->returns.value;
5179 if (val == NULL || expression_returns(val))
5180 noreturn_candidate = false;
5184 case STATEMENT_IF: {
5185 if_statement_t const *const ifs = &stmt->ifs;
5186 expression_t const *const cond = ifs->condition;
5188 if (!expression_returns(cond))
5191 int const val = determine_truth(cond);
5194 check_reachable(ifs->true_statement);
5199 if (ifs->false_statement != NULL) {
5200 check_reachable(ifs->false_statement);
5204 next = stmt->base.next;
5208 case STATEMENT_SWITCH: {
5209 switch_statement_t const *const switchs = &stmt->switchs;
5210 expression_t const *const expr = switchs->expression;
5212 if (!expression_returns(expr))
5215 if (is_constant_expression(expr)) {
5216 long const val = fold_constant_to_int(expr);
5217 case_label_statement_t * defaults = NULL;
5218 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5219 if (i->expression == NULL) {
5224 if (i->first_case <= val && val <= i->last_case) {
5225 check_reachable((statement_t*)i);
5230 if (defaults != NULL) {
5231 check_reachable((statement_t*)defaults);
5235 bool has_default = false;
5236 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5237 if (i->expression == NULL)
5240 check_reachable((statement_t*)i);
5247 next = stmt->base.next;
5251 case STATEMENT_EXPRESSION: {
5252 /* Check for noreturn function call */
5253 expression_t const *const expr = stmt->expression.expression;
5254 if (!expression_returns(expr))
5257 next = stmt->base.next;
5261 case STATEMENT_CONTINUE:
5262 for (statement_t *parent = stmt;;) {
5263 parent = parent->base.parent;
5264 if (parent == NULL) /* continue not within loop */
5268 switch (parent->kind) {
5269 case STATEMENT_WHILE: goto continue_while;
5270 case STATEMENT_DO_WHILE: goto continue_do_while;
5271 case STATEMENT_FOR: goto continue_for;
5277 case STATEMENT_BREAK:
5278 for (statement_t *parent = stmt;;) {
5279 parent = parent->base.parent;
5280 if (parent == NULL) /* break not within loop/switch */
5283 switch (parent->kind) {
5284 case STATEMENT_SWITCH:
5285 case STATEMENT_WHILE:
5286 case STATEMENT_DO_WHILE:
5289 next = parent->base.next;
5290 goto found_break_parent;
5298 case STATEMENT_GOTO:
5299 if (stmt->gotos.expression) {
5300 if (!expression_returns(stmt->gotos.expression))
5303 statement_t *parent = stmt->base.parent;
5304 if (parent == NULL) /* top level goto */
5308 next = stmt->gotos.label->statement;
5309 if (next == NULL) /* missing label */
5314 case STATEMENT_LABEL:
5315 next = stmt->label.statement;
5318 case STATEMENT_CASE_LABEL:
5319 next = stmt->case_label.statement;
5322 case STATEMENT_WHILE: {
5323 while_statement_t const *const whiles = &stmt->whiles;
5324 expression_t const *const cond = whiles->condition;
5326 if (!expression_returns(cond))
5329 int const val = determine_truth(cond);
5332 check_reachable(whiles->body);
5337 next = stmt->base.next;
5341 case STATEMENT_DO_WHILE:
5342 next = stmt->do_while.body;
5345 case STATEMENT_FOR: {
5346 for_statement_t *const fors = &stmt->fors;
5348 if (fors->condition_reachable)
5350 fors->condition_reachable = true;
5352 expression_t const *const cond = fors->condition;
5357 } else if (expression_returns(cond)) {
5358 val = determine_truth(cond);
5364 check_reachable(fors->body);
5369 next = stmt->base.next;
5373 case STATEMENT_MS_TRY: {
5374 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5375 check_reachable(ms_try->try_statement);
5376 next = ms_try->final_statement;
5380 case STATEMENT_LEAVE: {
5381 statement_t *parent = stmt;
5383 parent = parent->base.parent;
5384 if (parent == NULL) /* __leave not within __try */
5387 if (parent->kind == STATEMENT_MS_TRY) {
5389 next = parent->ms_try.final_statement;
5397 panic("invalid statement kind");
5400 while (next == NULL) {
5401 next = last->base.parent;
5403 noreturn_candidate = false;
5405 type_t *const type = skip_typeref(current_function->base.type);
5406 assert(is_type_function(type));
5407 type_t *const ret = skip_typeref(type->function.return_type);
5408 if (warning.return_type &&
5409 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5410 is_type_valid(ret) &&
5411 !is_sym_main(current_function->base.base.symbol)) {
5412 warningf(&stmt->base.source_position,
5413 "control reaches end of non-void function");
5418 switch (next->kind) {
5419 case STATEMENT_INVALID:
5420 case STATEMENT_EMPTY:
5421 case STATEMENT_DECLARATION:
5422 case STATEMENT_EXPRESSION:
5424 case STATEMENT_RETURN:
5425 case STATEMENT_CONTINUE:
5426 case STATEMENT_BREAK:
5427 case STATEMENT_GOTO:
5428 case STATEMENT_LEAVE:
5429 panic("invalid control flow in function");
5431 case STATEMENT_COMPOUND:
5432 if (next->compound.stmt_expr) {
5438 case STATEMENT_SWITCH:
5439 case STATEMENT_LABEL:
5440 case STATEMENT_CASE_LABEL:
5442 next = next->base.next;
5445 case STATEMENT_WHILE: {
5447 if (next->base.reachable)
5449 next->base.reachable = true;
5451 while_statement_t const *const whiles = &next->whiles;
5452 expression_t const *const cond = whiles->condition;
5454 if (!expression_returns(cond))
5457 int const val = determine_truth(cond);
5460 check_reachable(whiles->body);
5466 next = next->base.next;
5470 case STATEMENT_DO_WHILE: {
5472 if (next->base.reachable)
5474 next->base.reachable = true;
5476 do_while_statement_t const *const dw = &next->do_while;
5477 expression_t const *const cond = dw->condition;
5479 if (!expression_returns(cond))
5482 int const val = determine_truth(cond);
5485 check_reachable(dw->body);
5491 next = next->base.next;
5495 case STATEMENT_FOR: {
5497 for_statement_t *const fors = &next->fors;
5499 fors->step_reachable = true;
5501 if (fors->condition_reachable)
5503 fors->condition_reachable = true;
5505 expression_t const *const cond = fors->condition;
5510 } else if (expression_returns(cond)) {
5511 val = determine_truth(cond);
5517 check_reachable(fors->body);
5523 next = next->base.next;
5527 case STATEMENT_MS_TRY:
5529 next = next->ms_try.final_statement;
5534 check_reachable(next);
5537 static void check_unreachable(statement_t* const stmt, void *const env)
5541 switch (stmt->kind) {
5542 case STATEMENT_DO_WHILE:
5543 if (!stmt->base.reachable) {
5544 expression_t const *const cond = stmt->do_while.condition;
5545 if (determine_truth(cond) >= 0) {
5546 warningf(&cond->base.source_position,
5547 "condition of do-while-loop is unreachable");
5552 case STATEMENT_FOR: {
5553 for_statement_t const* const fors = &stmt->fors;
5555 // if init and step are unreachable, cond is unreachable, too
5556 if (!stmt->base.reachable && !fors->step_reachable) {
5557 warningf(&stmt->base.source_position, "statement is unreachable");
5559 if (!stmt->base.reachable && fors->initialisation != NULL) {
5560 warningf(&fors->initialisation->base.source_position,
5561 "initialisation of for-statement is unreachable");
5564 if (!fors->condition_reachable && fors->condition != NULL) {
5565 warningf(&fors->condition->base.source_position,
5566 "condition of for-statement is unreachable");
5569 if (!fors->step_reachable && fors->step != NULL) {
5570 warningf(&fors->step->base.source_position,
5571 "step of for-statement is unreachable");
5577 case STATEMENT_COMPOUND:
5578 if (stmt->compound.statements != NULL)
5580 goto warn_unreachable;
5582 case STATEMENT_DECLARATION: {
5583 /* Only warn if there is at least one declarator with an initializer.
5584 * This typically occurs in switch statements. */
5585 declaration_statement_t const *const decl = &stmt->declaration;
5586 entity_t const * ent = decl->declarations_begin;
5587 entity_t const *const last = decl->declarations_end;
5589 for (;; ent = ent->base.next) {
5590 if (ent->kind == ENTITY_VARIABLE &&
5591 ent->variable.initializer != NULL) {
5592 goto warn_unreachable;
5602 if (!stmt->base.reachable)
5603 warningf(&stmt->base.source_position, "statement is unreachable");
5608 static void parse_external_declaration(void)
5610 /* function-definitions and declarations both start with declaration
5612 declaration_specifiers_t specifiers;
5613 memset(&specifiers, 0, sizeof(specifiers));
5615 add_anchor_token(';');
5616 parse_declaration_specifiers(&specifiers);
5617 rem_anchor_token(';');
5619 /* must be a declaration */
5620 if (token.type == ';') {
5621 parse_anonymous_declaration_rest(&specifiers);
5625 add_anchor_token(',');
5626 add_anchor_token('=');
5627 add_anchor_token(';');
5628 add_anchor_token('{');
5630 /* declarator is common to both function-definitions and declarations */
5631 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5633 rem_anchor_token('{');
5634 rem_anchor_token(';');
5635 rem_anchor_token('=');
5636 rem_anchor_token(',');
5638 /* must be a declaration */
5639 switch (token.type) {
5643 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5648 /* must be a function definition */
5649 parse_kr_declaration_list(ndeclaration);
5651 if (token.type != '{') {
5652 parse_error_expected("while parsing function definition", '{', NULL);
5653 eat_until_matching_token(';');
5657 assert(is_declaration(ndeclaration));
5658 type_t *const orig_type = ndeclaration->declaration.type;
5659 type_t * type = skip_typeref(orig_type);
5661 if (!is_type_function(type)) {
5662 if (is_type_valid(type)) {
5663 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5664 type, ndeclaration->base.symbol);
5668 } else if (is_typeref(orig_type)) {
5670 errorf(&ndeclaration->base.source_position,
5671 "type of function definition '%#T' is a typedef",
5672 orig_type, ndeclaration->base.symbol);
5675 if (warning.aggregate_return &&
5676 is_type_compound(skip_typeref(type->function.return_type))) {
5677 warningf(HERE, "function '%Y' returns an aggregate",
5678 ndeclaration->base.symbol);
5680 if (warning.traditional && !type->function.unspecified_parameters) {
5681 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5682 ndeclaration->base.symbol);
5684 if (warning.old_style_definition && type->function.unspecified_parameters) {
5685 warningf(HERE, "old-style function definition '%Y'",
5686 ndeclaration->base.symbol);
5689 /* §6.7.5.3:14 a function definition with () means no
5690 * parameters (and not unspecified parameters) */
5691 if (type->function.unspecified_parameters &&
5692 type->function.parameters == NULL) {
5693 type_t *copy = duplicate_type(type);
5694 copy->function.unspecified_parameters = false;
5695 type = identify_new_type(copy);
5697 ndeclaration->declaration.type = type;
5700 entity_t *const entity = record_entity(ndeclaration, true);
5701 assert(entity->kind == ENTITY_FUNCTION);
5702 assert(ndeclaration->kind == ENTITY_FUNCTION);
5704 function_t *function = &entity->function;
5705 if (ndeclaration != entity) {
5706 function->parameters = ndeclaration->function.parameters;
5708 assert(is_declaration(entity));
5709 type = skip_typeref(entity->declaration.type);
5711 /* push function parameters and switch scope */
5712 size_t const top = environment_top();
5713 scope_t *old_scope = scope_push(&function->parameters);
5715 entity_t *parameter = function->parameters.entities;
5716 for (; parameter != NULL; parameter = parameter->base.next) {
5717 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5718 parameter->base.parent_scope = current_scope;
5720 assert(parameter->base.parent_scope == NULL
5721 || parameter->base.parent_scope == current_scope);
5722 parameter->base.parent_scope = current_scope;
5723 if (parameter->base.symbol == NULL) {
5724 errorf(¶meter->base.source_position, "parameter name omitted");
5727 environment_push(parameter);
5730 if (function->statement != NULL) {
5731 parser_error_multiple_definition(entity, HERE);
5734 /* parse function body */
5735 int label_stack_top = label_top();
5736 function_t *old_current_function = current_function;
5737 current_function = function;
5738 current_parent = NULL;
5741 goto_anchor = &goto_first;
5743 label_anchor = &label_first;
5745 statement_t *const body = parse_compound_statement(false);
5746 function->statement = body;
5749 check_declarations();
5750 if (warning.return_type ||
5751 warning.unreachable_code ||
5752 (warning.missing_noreturn
5753 && !(function->base.modifiers & DM_NORETURN))) {
5754 noreturn_candidate = true;
5755 check_reachable(body);
5756 if (warning.unreachable_code)
5757 walk_statements(body, check_unreachable, NULL);
5758 if (warning.missing_noreturn &&
5759 noreturn_candidate &&
5760 !(function->base.modifiers & DM_NORETURN)) {
5761 warningf(&body->base.source_position,
5762 "function '%#T' is candidate for attribute 'noreturn'",
5763 type, entity->base.symbol);
5767 assert(current_parent == NULL);
5768 assert(current_function == function);
5769 current_function = old_current_function;
5770 label_pop_to(label_stack_top);
5773 assert(current_scope == &function->parameters);
5774 scope_pop(old_scope);
5775 environment_pop_to(top);
5778 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5779 source_position_t *source_position,
5780 const symbol_t *symbol)
5782 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5784 type->bitfield.base_type = base_type;
5785 type->bitfield.size_expression = size;
5788 type_t *skipped_type = skip_typeref(base_type);
5789 if (!is_type_integer(skipped_type)) {
5790 errorf(HERE, "bitfield base type '%T' is not an integer type",
5794 bit_size = get_type_size(base_type) * 8;
5797 if (is_constant_expression(size)) {
5798 long v = fold_constant_to_int(size);
5799 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5802 errorf(source_position, "negative width in bit-field '%Y'",
5804 } else if (v == 0 && symbol != NULL) {
5805 errorf(source_position, "zero width for bit-field '%Y'",
5807 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5808 errorf(source_position, "width of '%Y' exceeds its type",
5811 type->bitfield.bit_size = v;
5818 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5820 entity_t *iter = compound->members.entities;
5821 for (; iter != NULL; iter = iter->base.next) {
5822 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5825 if (iter->base.symbol == symbol) {
5827 } else if (iter->base.symbol == NULL) {
5828 /* search in anonymous structs and unions */
5829 type_t *type = skip_typeref(iter->declaration.type);
5830 if (is_type_compound(type)) {
5831 if (find_compound_entry(type->compound.compound, symbol)
5842 static void check_deprecated(const source_position_t *source_position,
5843 const entity_t *entity)
5845 if (!warning.deprecated_declarations)
5847 if (!is_declaration(entity))
5849 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5852 char const *const prefix = get_entity_kind_name(entity->kind);
5853 const char *deprecated_string
5854 = get_deprecated_string(entity->declaration.attributes);
5855 if (deprecated_string != NULL) {
5856 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5857 prefix, entity->base.symbol, &entity->base.source_position,
5860 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5861 entity->base.symbol, &entity->base.source_position);
5866 static expression_t *create_select(const source_position_t *pos,
5868 type_qualifiers_t qualifiers,
5871 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5873 check_deprecated(pos, entry);
5875 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5876 select->select.compound = addr;
5877 select->select.compound_entry = entry;
5879 type_t *entry_type = entry->declaration.type;
5880 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5882 /* we always do the auto-type conversions; the & and sizeof parser contains
5883 * code to revert this! */
5884 select->base.type = automatic_type_conversion(res_type);
5885 if (res_type->kind == TYPE_BITFIELD) {
5886 select->base.type = res_type->bitfield.base_type;
5893 * Find entry with symbol in compound. Search anonymous structs and unions and
5894 * creates implicit select expressions for them.
5895 * Returns the adress for the innermost compound.
5897 static expression_t *find_create_select(const source_position_t *pos,
5899 type_qualifiers_t qualifiers,
5900 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 symbol_t *iter_symbol = iter->base.symbol;
5908 if (iter_symbol == NULL) {
5909 type_t *type = iter->declaration.type;
5910 if (type->kind != TYPE_COMPOUND_STRUCT
5911 && type->kind != TYPE_COMPOUND_UNION)
5914 compound_t *sub_compound = type->compound.compound;
5916 if (find_compound_entry(sub_compound, symbol) == NULL)
5919 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5920 sub_addr->base.source_position = *pos;
5921 sub_addr->select.implicit = true;
5922 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5926 if (iter_symbol == symbol) {
5927 return create_select(pos, addr, qualifiers, iter);
5934 static void parse_compound_declarators(compound_t *compound,
5935 const declaration_specifiers_t *specifiers)
5940 if (token.type == ':') {
5941 source_position_t source_position = *HERE;
5944 type_t *base_type = specifiers->type;
5945 expression_t *size = parse_constant_expression();
5947 type_t *type = make_bitfield_type(base_type, size,
5948 &source_position, NULL);
5950 attribute_t *attributes = parse_attributes(NULL);
5951 if (attributes != NULL) {
5952 attribute_t *last = attributes;
5953 while (last->next != NULL)
5955 last->next = specifiers->attributes;
5957 attributes = specifiers->attributes;
5960 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5961 entity->base.namespc = NAMESPACE_NORMAL;
5962 entity->base.source_position = source_position;
5963 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5964 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5965 entity->declaration.type = type;
5966 entity->declaration.attributes = attributes;
5968 if (attributes != NULL) {
5969 handle_entity_attributes(attributes, entity);
5971 append_entity(&compound->members, entity);
5973 entity = parse_declarator(specifiers,
5974 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5975 if (entity->kind == ENTITY_TYPEDEF) {
5976 errorf(&entity->base.source_position,
5977 "typedef not allowed as compound member");
5979 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5981 /* make sure we don't define a symbol multiple times */
5982 symbol_t *symbol = entity->base.symbol;
5983 if (symbol != NULL) {
5984 entity_t *prev = find_compound_entry(compound, symbol);
5986 errorf(&entity->base.source_position,
5987 "multiple declarations of symbol '%Y' (declared %P)",
5988 symbol, &prev->base.source_position);
5992 if (token.type == ':') {
5993 source_position_t source_position = *HERE;
5995 expression_t *size = parse_constant_expression();
5997 type_t *type = entity->declaration.type;
5998 type_t *bitfield_type = make_bitfield_type(type, size,
5999 &source_position, entity->base.symbol);
6001 attribute_t *attributes = parse_attributes(NULL);
6002 entity->declaration.type = bitfield_type;
6003 handle_entity_attributes(attributes, entity);
6005 type_t *orig_type = entity->declaration.type;
6006 type_t *type = skip_typeref(orig_type);
6007 if (is_type_function(type)) {
6008 errorf(&entity->base.source_position,
6009 "compound member '%Y' must not have function type '%T'",
6010 entity->base.symbol, orig_type);
6011 } else if (is_type_incomplete(type)) {
6012 /* §6.7.2.1:16 flexible array member */
6013 if (!is_type_array(type) ||
6014 token.type != ';' ||
6015 look_ahead(1)->type != '}') {
6016 errorf(&entity->base.source_position,
6017 "compound member '%Y' has incomplete type '%T'",
6018 entity->base.symbol, orig_type);
6023 append_entity(&compound->members, entity);
6026 } while (next_if(','));
6027 expect(';', end_error);
6030 anonymous_entity = NULL;
6033 static void parse_compound_type_entries(compound_t *compound)
6036 add_anchor_token('}');
6038 while (token.type != '}') {
6039 if (token.type == T_EOF) {
6040 errorf(HERE, "EOF while parsing struct");
6043 declaration_specifiers_t specifiers;
6044 memset(&specifiers, 0, sizeof(specifiers));
6045 parse_declaration_specifiers(&specifiers);
6047 parse_compound_declarators(compound, &specifiers);
6049 rem_anchor_token('}');
6053 compound->complete = true;
6056 static type_t *parse_typename(void)
6058 declaration_specifiers_t specifiers;
6059 memset(&specifiers, 0, sizeof(specifiers));
6060 parse_declaration_specifiers(&specifiers);
6061 if (specifiers.storage_class != STORAGE_CLASS_NONE ||
6062 specifiers.thread_local) {
6063 /* TODO: improve error message, user does probably not know what a
6064 * storage class is...
6066 errorf(HERE, "typename may not have a storage class");
6069 type_t *result = parse_abstract_declarator(specifiers.type);
6077 typedef expression_t* (*parse_expression_function)(void);
6078 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6080 typedef struct expression_parser_function_t expression_parser_function_t;
6081 struct expression_parser_function_t {
6082 parse_expression_function parser;
6083 precedence_t infix_precedence;
6084 parse_expression_infix_function infix_parser;
6087 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6090 * Prints an error message if an expression was expected but not read
6092 static expression_t *expected_expression_error(void)
6094 /* skip the error message if the error token was read */
6095 if (token.type != T_ERROR) {
6096 errorf(HERE, "expected expression, got token %K", &token);
6100 return create_invalid_expression();
6104 * Parse a string constant.
6106 static expression_t *parse_string_const(void)
6109 if (token.type == T_STRING_LITERAL) {
6110 string_t res = token.v.string;
6112 while (token.type == T_STRING_LITERAL) {
6113 res = concat_strings(&res, &token.v.string);
6116 if (token.type != T_WIDE_STRING_LITERAL) {
6117 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6118 /* note: that we use type_char_ptr here, which is already the
6119 * automatic converted type. revert_automatic_type_conversion
6120 * will construct the array type */
6121 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6122 cnst->string.value = res;
6126 wres = concat_string_wide_string(&res, &token.v.wide_string);
6128 wres = token.v.wide_string;
6133 switch (token.type) {
6134 case T_WIDE_STRING_LITERAL:
6135 wres = concat_wide_strings(&wres, &token.v.wide_string);
6138 case T_STRING_LITERAL:
6139 wres = concat_wide_string_string(&wres, &token.v.string);
6143 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6144 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6145 cnst->wide_string.value = wres;
6154 * Parse a boolean constant.
6156 static expression_t *parse_bool_const(bool value)
6158 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6159 cnst->base.type = type_bool;
6160 cnst->conste.v.int_value = value;
6168 * Parse an integer constant.
6170 static expression_t *parse_int_const(void)
6172 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6173 cnst->base.type = token.datatype;
6174 cnst->conste.v.int_value = token.v.intvalue;
6182 * Parse a character constant.
6184 static expression_t *parse_character_constant(void)
6186 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6187 cnst->base.type = token.datatype;
6188 cnst->conste.v.character = token.v.string;
6190 if (cnst->conste.v.character.size != 1) {
6192 errorf(HERE, "more than 1 character in character constant");
6193 } else if (warning.multichar) {
6194 warningf(HERE, "multi-character character constant");
6203 * Parse a wide character constant.
6205 static expression_t *parse_wide_character_constant(void)
6207 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6208 cnst->base.type = token.datatype;
6209 cnst->conste.v.wide_character = token.v.wide_string;
6211 if (cnst->conste.v.wide_character.size != 1) {
6213 errorf(HERE, "more than 1 character in character constant");
6214 } else if (warning.multichar) {
6215 warningf(HERE, "multi-character character constant");
6224 * Parse a float constant.
6226 static expression_t *parse_float_const(void)
6228 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6229 cnst->base.type = token.datatype;
6230 cnst->conste.v.float_value = token.v.floatvalue;
6237 static entity_t *create_implicit_function(symbol_t *symbol,
6238 const source_position_t *source_position)
6240 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6241 ntype->function.return_type = type_int;
6242 ntype->function.unspecified_parameters = true;
6243 ntype->function.linkage = LINKAGE_C;
6244 type_t *type = identify_new_type(ntype);
6246 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6247 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6248 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6249 entity->declaration.type = type;
6250 entity->declaration.implicit = true;
6251 entity->base.symbol = symbol;
6252 entity->base.source_position = *source_position;
6254 if (current_scope != NULL) {
6255 bool strict_prototypes_old = warning.strict_prototypes;
6256 warning.strict_prototypes = false;
6257 record_entity(entity, false);
6258 warning.strict_prototypes = strict_prototypes_old;
6265 * Creates a return_type (func)(argument_type) function type if not
6268 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6269 type_t *argument_type2)
6271 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6272 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6273 parameter1->next = parameter2;
6275 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6276 type->function.return_type = return_type;
6277 type->function.parameters = parameter1;
6279 return identify_new_type(type);
6283 * Creates a return_type (func)(argument_type) function type if not
6286 * @param return_type the return type
6287 * @param argument_type the argument type
6289 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6291 function_parameter_t *const parameter = allocate_parameter(argument_type);
6293 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6294 type->function.return_type = return_type;
6295 type->function.parameters = parameter;
6297 return identify_new_type(type);
6301 * Creates a return_type (func)(argument_type, ...) function type if not
6304 * @param return_type the return type
6305 * @param argument_type the argument type
6307 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6309 function_parameter_t *const parameter = allocate_parameter(argument_type);
6311 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6312 type->function.return_type = return_type;
6313 type->function.parameters = parameter;
6314 type->function.variadic = true;
6316 return identify_new_type(type);
6320 * Creates a return_type (func)(void) function type if not
6323 * @param return_type the return type
6325 static type_t *make_function_0_type(type_t *return_type)
6327 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6328 type->function.return_type = return_type;
6329 type->function.parameters = NULL;
6331 return identify_new_type(type);
6335 * Creates a NO_RETURN return_type (func)(void) function type if not
6338 * @param return_type the return type
6340 static type_t *make_function_0_type_noreturn(type_t *return_type)
6342 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6343 type->function.return_type = return_type;
6344 type->function.parameters = NULL;
6345 type->function.modifiers |= DM_NORETURN;
6346 return identify_new_type(type);
6350 * Performs automatic type cast as described in §6.3.2.1.
6352 * @param orig_type the original type
6354 static type_t *automatic_type_conversion(type_t *orig_type)
6356 type_t *type = skip_typeref(orig_type);
6357 if (is_type_array(type)) {
6358 array_type_t *array_type = &type->array;
6359 type_t *element_type = array_type->element_type;
6360 unsigned qualifiers = array_type->base.qualifiers;
6362 return make_pointer_type(element_type, qualifiers);
6365 if (is_type_function(type)) {
6366 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6373 * reverts the automatic casts of array to pointer types and function
6374 * to function-pointer types as defined §6.3.2.1
6376 type_t *revert_automatic_type_conversion(const expression_t *expression)
6378 switch (expression->kind) {
6379 case EXPR_REFERENCE: {
6380 entity_t *entity = expression->reference.entity;
6381 if (is_declaration(entity)) {
6382 return entity->declaration.type;
6383 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6384 return entity->enum_value.enum_type;
6386 panic("no declaration or enum in reference");
6391 entity_t *entity = expression->select.compound_entry;
6392 assert(is_declaration(entity));
6393 type_t *type = entity->declaration.type;
6394 return get_qualified_type(type,
6395 expression->base.type->base.qualifiers);
6398 case EXPR_UNARY_DEREFERENCE: {
6399 const expression_t *const value = expression->unary.value;
6400 type_t *const type = skip_typeref(value->base.type);
6401 if (!is_type_pointer(type))
6402 return type_error_type;
6403 return type->pointer.points_to;
6406 case EXPR_ARRAY_ACCESS: {
6407 const expression_t *array_ref = expression->array_access.array_ref;
6408 type_t *type_left = skip_typeref(array_ref->base.type);
6409 if (!is_type_pointer(type_left))
6410 return type_error_type;
6411 return type_left->pointer.points_to;
6414 case EXPR_STRING_LITERAL: {
6415 size_t size = expression->string.value.size;
6416 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6419 case EXPR_WIDE_STRING_LITERAL: {
6420 size_t size = expression->wide_string.value.size;
6421 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6424 case EXPR_COMPOUND_LITERAL:
6425 return expression->compound_literal.type;
6428 return expression->base.type;
6433 * Find an entity matching a symbol in a scope.
6434 * Uses current scope if scope is NULL
6436 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6437 namespace_tag_t namespc)
6439 if (scope == NULL) {
6440 return get_entity(symbol, namespc);
6443 /* we should optimize here, if scope grows above a certain size we should
6444 construct a hashmap here... */
6445 entity_t *entity = scope->entities;
6446 for ( ; entity != NULL; entity = entity->base.next) {
6447 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6454 static entity_t *parse_qualified_identifier(void)
6456 /* namespace containing the symbol */
6458 source_position_t pos;
6459 const scope_t *lookup_scope = NULL;
6461 if (next_if(T_COLONCOLON))
6462 lookup_scope = &unit->scope;
6466 if (token.type != T_IDENTIFIER) {
6467 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6468 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6470 symbol = token.v.symbol;
6475 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6477 if (!next_if(T_COLONCOLON))
6480 switch (entity->kind) {
6481 case ENTITY_NAMESPACE:
6482 lookup_scope = &entity->namespacee.members;
6487 lookup_scope = &entity->compound.members;
6490 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6491 symbol, get_entity_kind_name(entity->kind));
6496 if (entity == NULL) {
6497 if (!strict_mode && token.type == '(') {
6498 /* an implicitly declared function */
6499 if (warning.error_implicit_function_declaration) {
6500 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6501 } else if (warning.implicit_function_declaration) {
6502 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6505 entity = create_implicit_function(symbol, &pos);
6507 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6508 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6515 /* skip further qualifications */
6516 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6518 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6521 static expression_t *parse_reference(void)
6523 entity_t *entity = parse_qualified_identifier();
6526 if (is_declaration(entity)) {
6527 orig_type = entity->declaration.type;
6528 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6529 orig_type = entity->enum_value.enum_type;
6531 panic("expected declaration or enum value in reference");
6534 /* we always do the auto-type conversions; the & and sizeof parser contains
6535 * code to revert this! */
6536 type_t *type = automatic_type_conversion(orig_type);
6538 expression_kind_t kind = EXPR_REFERENCE;
6539 if (entity->kind == ENTITY_ENUM_VALUE)
6540 kind = EXPR_REFERENCE_ENUM_VALUE;
6542 expression_t *expression = allocate_expression_zero(kind);
6543 expression->reference.entity = entity;
6544 expression->base.type = type;
6546 /* this declaration is used */
6547 if (is_declaration(entity)) {
6548 entity->declaration.used = true;
6551 if (entity->base.parent_scope != file_scope
6552 && (current_function != NULL
6553 && entity->base.parent_scope->depth < current_function->parameters.depth)
6554 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6555 if (entity->kind == ENTITY_VARIABLE) {
6556 /* access of a variable from an outer function */
6557 entity->variable.address_taken = true;
6558 } else if (entity->kind == ENTITY_PARAMETER) {
6559 entity->parameter.address_taken = true;
6561 current_function->need_closure = true;
6564 check_deprecated(HERE, entity);
6566 if (warning.init_self && entity == current_init_decl && !in_type_prop
6567 && entity->kind == ENTITY_VARIABLE) {
6568 current_init_decl = NULL;
6569 warningf(HERE, "variable '%#T' is initialized by itself",
6570 entity->declaration.type, entity->base.symbol);
6576 static bool semantic_cast(expression_t *cast)
6578 expression_t *expression = cast->unary.value;
6579 type_t *orig_dest_type = cast->base.type;
6580 type_t *orig_type_right = expression->base.type;
6581 type_t const *dst_type = skip_typeref(orig_dest_type);
6582 type_t const *src_type = skip_typeref(orig_type_right);
6583 source_position_t const *pos = &cast->base.source_position;
6585 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6586 if (dst_type == type_void)
6589 /* only integer and pointer can be casted to pointer */
6590 if (is_type_pointer(dst_type) &&
6591 !is_type_pointer(src_type) &&
6592 !is_type_integer(src_type) &&
6593 is_type_valid(src_type)) {
6594 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6598 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6599 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6603 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6604 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6608 if (warning.cast_qual &&
6609 is_type_pointer(src_type) &&
6610 is_type_pointer(dst_type)) {
6611 type_t *src = skip_typeref(src_type->pointer.points_to);
6612 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6613 unsigned missing_qualifiers =
6614 src->base.qualifiers & ~dst->base.qualifiers;
6615 if (missing_qualifiers != 0) {
6617 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6618 missing_qualifiers, orig_type_right);
6624 static expression_t *parse_compound_literal(type_t *type)
6626 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6628 parse_initializer_env_t env;
6631 env.must_be_constant = false;
6632 initializer_t *initializer = parse_initializer(&env);
6635 expression->compound_literal.initializer = initializer;
6636 expression->compound_literal.type = type;
6637 expression->base.type = automatic_type_conversion(type);
6643 * Parse a cast expression.
6645 static expression_t *parse_cast(void)
6647 add_anchor_token(')');
6649 source_position_t source_position = token.source_position;
6651 type_t *type = parse_typename();
6653 rem_anchor_token(')');
6654 expect(')', end_error);
6656 if (token.type == '{') {
6657 return parse_compound_literal(type);
6660 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6661 cast->base.source_position = source_position;
6663 expression_t *value = parse_sub_expression(PREC_CAST);
6664 cast->base.type = type;
6665 cast->unary.value = value;
6667 if (! semantic_cast(cast)) {
6668 /* TODO: record the error in the AST. else it is impossible to detect it */
6673 return create_invalid_expression();
6677 * Parse a statement expression.
6679 static expression_t *parse_statement_expression(void)
6681 add_anchor_token(')');
6683 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6685 statement_t *statement = parse_compound_statement(true);
6686 statement->compound.stmt_expr = true;
6687 expression->statement.statement = statement;
6689 /* find last statement and use its type */
6690 type_t *type = type_void;
6691 const statement_t *stmt = statement->compound.statements;
6693 while (stmt->base.next != NULL)
6694 stmt = stmt->base.next;
6696 if (stmt->kind == STATEMENT_EXPRESSION) {
6697 type = stmt->expression.expression->base.type;
6699 } else if (warning.other) {
6700 warningf(&expression->base.source_position, "empty statement expression ({})");
6702 expression->base.type = type;
6704 rem_anchor_token(')');
6705 expect(')', end_error);
6712 * Parse a parenthesized expression.
6714 static expression_t *parse_parenthesized_expression(void)
6718 switch (token.type) {
6720 /* gcc extension: a statement expression */
6721 return parse_statement_expression();
6725 return parse_cast();
6727 if (is_typedef_symbol(token.v.symbol)) {
6728 return parse_cast();
6732 add_anchor_token(')');
6733 expression_t *result = parse_expression();
6734 result->base.parenthesized = true;
6735 rem_anchor_token(')');
6736 expect(')', end_error);
6742 static expression_t *parse_function_keyword(void)
6746 if (current_function == NULL) {
6747 errorf(HERE, "'__func__' used outside of a function");
6750 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6751 expression->base.type = type_char_ptr;
6752 expression->funcname.kind = FUNCNAME_FUNCTION;
6759 static expression_t *parse_pretty_function_keyword(void)
6761 if (current_function == NULL) {
6762 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6765 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6766 expression->base.type = type_char_ptr;
6767 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6769 eat(T___PRETTY_FUNCTION__);
6774 static expression_t *parse_funcsig_keyword(void)
6776 if (current_function == NULL) {
6777 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6780 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6781 expression->base.type = type_char_ptr;
6782 expression->funcname.kind = FUNCNAME_FUNCSIG;
6789 static expression_t *parse_funcdname_keyword(void)
6791 if (current_function == NULL) {
6792 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6795 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6796 expression->base.type = type_char_ptr;
6797 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6799 eat(T___FUNCDNAME__);
6804 static designator_t *parse_designator(void)
6806 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6807 result->source_position = *HERE;
6809 if (token.type != T_IDENTIFIER) {
6810 parse_error_expected("while parsing member designator",
6811 T_IDENTIFIER, NULL);
6814 result->symbol = token.v.symbol;
6817 designator_t *last_designator = result;
6820 if (token.type != T_IDENTIFIER) {
6821 parse_error_expected("while parsing member designator",
6822 T_IDENTIFIER, NULL);
6825 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6826 designator->source_position = *HERE;
6827 designator->symbol = token.v.symbol;
6830 last_designator->next = designator;
6831 last_designator = designator;
6835 add_anchor_token(']');
6836 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6837 designator->source_position = *HERE;
6838 designator->array_index = parse_expression();
6839 rem_anchor_token(']');
6840 expect(']', end_error);
6841 if (designator->array_index == NULL) {
6845 last_designator->next = designator;
6846 last_designator = designator;
6858 * Parse the __builtin_offsetof() expression.
6860 static expression_t *parse_offsetof(void)
6862 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6863 expression->base.type = type_size_t;
6865 eat(T___builtin_offsetof);
6867 expect('(', end_error);
6868 add_anchor_token(',');
6869 type_t *type = parse_typename();
6870 rem_anchor_token(',');
6871 expect(',', end_error);
6872 add_anchor_token(')');
6873 designator_t *designator = parse_designator();
6874 rem_anchor_token(')');
6875 expect(')', end_error);
6877 expression->offsetofe.type = type;
6878 expression->offsetofe.designator = designator;
6881 memset(&path, 0, sizeof(path));
6882 path.top_type = type;
6883 path.path = NEW_ARR_F(type_path_entry_t, 0);
6885 descend_into_subtype(&path);
6887 if (!walk_designator(&path, designator, true)) {
6888 return create_invalid_expression();
6891 DEL_ARR_F(path.path);
6895 return create_invalid_expression();
6899 * Parses a _builtin_va_start() expression.
6901 static expression_t *parse_va_start(void)
6903 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6905 eat(T___builtin_va_start);
6907 expect('(', end_error);
6908 add_anchor_token(',');
6909 expression->va_starte.ap = parse_assignment_expression();
6910 rem_anchor_token(',');
6911 expect(',', end_error);
6912 expression_t *const expr = parse_assignment_expression();
6913 if (expr->kind == EXPR_REFERENCE) {
6914 entity_t *const entity = expr->reference.entity;
6915 if (!current_function->base.type->function.variadic) {
6916 errorf(&expr->base.source_position,
6917 "'va_start' used in non-variadic function");
6918 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6919 entity->base.next != NULL ||
6920 entity->kind != ENTITY_PARAMETER) {
6921 errorf(&expr->base.source_position,
6922 "second argument of 'va_start' must be last parameter of the current function");
6924 expression->va_starte.parameter = &entity->variable;
6926 expect(')', end_error);
6929 expect(')', end_error);
6931 return create_invalid_expression();
6935 * Parses a __builtin_va_arg() expression.
6937 static expression_t *parse_va_arg(void)
6939 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6941 eat(T___builtin_va_arg);
6943 expect('(', end_error);
6945 ap.expression = parse_assignment_expression();
6946 expression->va_arge.ap = ap.expression;
6947 check_call_argument(type_valist, &ap, 1);
6949 expect(',', end_error);
6950 expression->base.type = parse_typename();
6951 expect(')', end_error);
6955 return create_invalid_expression();
6959 * Parses a __builtin_va_copy() expression.
6961 static expression_t *parse_va_copy(void)
6963 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6965 eat(T___builtin_va_copy);
6967 expect('(', end_error);
6968 expression_t *dst = parse_assignment_expression();
6969 assign_error_t error = semantic_assign(type_valist, dst);
6970 report_assign_error(error, type_valist, dst, "call argument 1",
6971 &dst->base.source_position);
6972 expression->va_copye.dst = dst;
6974 expect(',', end_error);
6976 call_argument_t src;
6977 src.expression = parse_assignment_expression();
6978 check_call_argument(type_valist, &src, 2);
6979 expression->va_copye.src = src.expression;
6980 expect(')', end_error);
6984 return create_invalid_expression();
6988 * Parses a __builtin_constant_p() expression.
6990 static expression_t *parse_builtin_constant(void)
6992 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6994 eat(T___builtin_constant_p);
6996 expect('(', end_error);
6997 add_anchor_token(')');
6998 expression->builtin_constant.value = parse_assignment_expression();
6999 rem_anchor_token(')');
7000 expect(')', end_error);
7001 expression->base.type = type_int;
7005 return create_invalid_expression();
7009 * Parses a __builtin_types_compatible_p() expression.
7011 static expression_t *parse_builtin_types_compatible(void)
7013 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
7015 eat(T___builtin_types_compatible_p);
7017 expect('(', end_error);
7018 add_anchor_token(')');
7019 add_anchor_token(',');
7020 expression->builtin_types_compatible.left = parse_typename();
7021 rem_anchor_token(',');
7022 expect(',', end_error);
7023 expression->builtin_types_compatible.right = parse_typename();
7024 rem_anchor_token(')');
7025 expect(')', end_error);
7026 expression->base.type = type_int;
7030 return create_invalid_expression();
7034 * Parses a __builtin_is_*() compare expression.
7036 static expression_t *parse_compare_builtin(void)
7038 expression_t *expression;
7040 switch (token.type) {
7041 case T___builtin_isgreater:
7042 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7044 case T___builtin_isgreaterequal:
7045 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7047 case T___builtin_isless:
7048 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7050 case T___builtin_islessequal:
7051 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7053 case T___builtin_islessgreater:
7054 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7056 case T___builtin_isunordered:
7057 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7060 internal_errorf(HERE, "invalid compare builtin found");
7062 expression->base.source_position = *HERE;
7065 expect('(', end_error);
7066 expression->binary.left = parse_assignment_expression();
7067 expect(',', end_error);
7068 expression->binary.right = parse_assignment_expression();
7069 expect(')', end_error);
7071 type_t *const orig_type_left = expression->binary.left->base.type;
7072 type_t *const orig_type_right = expression->binary.right->base.type;
7074 type_t *const type_left = skip_typeref(orig_type_left);
7075 type_t *const type_right = skip_typeref(orig_type_right);
7076 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7077 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7078 type_error_incompatible("invalid operands in comparison",
7079 &expression->base.source_position, orig_type_left, orig_type_right);
7082 semantic_comparison(&expression->binary);
7087 return create_invalid_expression();
7091 * Parses a MS assume() expression.
7093 static expression_t *parse_assume(void)
7095 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7099 expect('(', end_error);
7100 add_anchor_token(')');
7101 expression->unary.value = parse_assignment_expression();
7102 rem_anchor_token(')');
7103 expect(')', end_error);
7105 expression->base.type = type_void;
7108 return create_invalid_expression();
7112 * Return the declaration for a given label symbol or create a new one.
7114 * @param symbol the symbol of the label
7116 static label_t *get_label(symbol_t *symbol)
7119 assert(current_function != NULL);
7121 label = get_entity(symbol, NAMESPACE_LABEL);
7122 /* if we found a local label, we already created the declaration */
7123 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7124 if (label->base.parent_scope != current_scope) {
7125 assert(label->base.parent_scope->depth < current_scope->depth);
7126 current_function->goto_to_outer = true;
7128 return &label->label;
7131 label = get_entity(symbol, NAMESPACE_LABEL);
7132 /* if we found a label in the same function, then we already created the
7135 && label->base.parent_scope == ¤t_function->parameters) {
7136 return &label->label;
7139 /* otherwise we need to create a new one */
7140 label = allocate_entity_zero(ENTITY_LABEL);
7141 label->base.namespc = NAMESPACE_LABEL;
7142 label->base.symbol = symbol;
7146 return &label->label;
7150 * Parses a GNU && label address expression.
7152 static expression_t *parse_label_address(void)
7154 source_position_t source_position = token.source_position;
7156 if (token.type != T_IDENTIFIER) {
7157 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7160 symbol_t *symbol = token.v.symbol;
7163 label_t *label = get_label(symbol);
7165 label->address_taken = true;
7167 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7168 expression->base.source_position = source_position;
7170 /* label address is threaten as a void pointer */
7171 expression->base.type = type_void_ptr;
7172 expression->label_address.label = label;
7175 return create_invalid_expression();
7179 * Parse a microsoft __noop expression.
7181 static expression_t *parse_noop_expression(void)
7183 /* the result is a (int)0 */
7184 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7185 cnst->base.type = type_int;
7186 cnst->conste.v.int_value = 0;
7187 cnst->conste.is_ms_noop = true;
7191 if (token.type == '(') {
7192 /* parse arguments */
7194 add_anchor_token(')');
7195 add_anchor_token(',');
7197 if (token.type != ')') do {
7198 (void)parse_assignment_expression();
7199 } while (next_if(','));
7201 rem_anchor_token(',');
7202 rem_anchor_token(')');
7203 expect(')', end_error);
7210 * Parses a primary expression.
7212 static expression_t *parse_primary_expression(void)
7214 switch (token.type) {
7215 case T_false: return parse_bool_const(false);
7216 case T_true: return parse_bool_const(true);
7217 case T_INTEGER: return parse_int_const();
7218 case T_CHARACTER_CONSTANT: return parse_character_constant();
7219 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7220 case T_FLOATINGPOINT: return parse_float_const();
7221 case T_STRING_LITERAL:
7222 case T_WIDE_STRING_LITERAL: return parse_string_const();
7223 case T___FUNCTION__:
7224 case T___func__: return parse_function_keyword();
7225 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7226 case T___FUNCSIG__: return parse_funcsig_keyword();
7227 case T___FUNCDNAME__: return parse_funcdname_keyword();
7228 case T___builtin_offsetof: return parse_offsetof();
7229 case T___builtin_va_start: return parse_va_start();
7230 case T___builtin_va_arg: return parse_va_arg();
7231 case T___builtin_va_copy: return parse_va_copy();
7232 case T___builtin_isgreater:
7233 case T___builtin_isgreaterequal:
7234 case T___builtin_isless:
7235 case T___builtin_islessequal:
7236 case T___builtin_islessgreater:
7237 case T___builtin_isunordered: return parse_compare_builtin();
7238 case T___builtin_constant_p: return parse_builtin_constant();
7239 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7240 case T__assume: return parse_assume();
7243 return parse_label_address();
7246 case '(': return parse_parenthesized_expression();
7247 case T___noop: return parse_noop_expression();
7249 /* Gracefully handle type names while parsing expressions. */
7251 return parse_reference();
7253 if (!is_typedef_symbol(token.v.symbol)) {
7254 return parse_reference();
7258 source_position_t const pos = *HERE;
7259 type_t const *const type = parse_typename();
7260 errorf(&pos, "encountered type '%T' while parsing expression", type);
7261 return create_invalid_expression();
7265 errorf(HERE, "unexpected token %K, expected an expression", &token);
7266 return create_invalid_expression();
7270 * Check if the expression has the character type and issue a warning then.
7272 static void check_for_char_index_type(const expression_t *expression)
7274 type_t *const type = expression->base.type;
7275 const type_t *const base_type = skip_typeref(type);
7277 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7278 warning.char_subscripts) {
7279 warningf(&expression->base.source_position,
7280 "array subscript has type '%T'", type);
7284 static expression_t *parse_array_expression(expression_t *left)
7286 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7289 add_anchor_token(']');
7291 expression_t *inside = parse_expression();
7293 type_t *const orig_type_left = left->base.type;
7294 type_t *const orig_type_inside = inside->base.type;
7296 type_t *const type_left = skip_typeref(orig_type_left);
7297 type_t *const type_inside = skip_typeref(orig_type_inside);
7299 type_t *return_type;
7300 array_access_expression_t *array_access = &expression->array_access;
7301 if (is_type_pointer(type_left)) {
7302 return_type = type_left->pointer.points_to;
7303 array_access->array_ref = left;
7304 array_access->index = inside;
7305 check_for_char_index_type(inside);
7306 } else if (is_type_pointer(type_inside)) {
7307 return_type = type_inside->pointer.points_to;
7308 array_access->array_ref = inside;
7309 array_access->index = left;
7310 array_access->flipped = true;
7311 check_for_char_index_type(left);
7313 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7315 "array access on object with non-pointer types '%T', '%T'",
7316 orig_type_left, orig_type_inside);
7318 return_type = type_error_type;
7319 array_access->array_ref = left;
7320 array_access->index = inside;
7323 expression->base.type = automatic_type_conversion(return_type);
7325 rem_anchor_token(']');
7326 expect(']', end_error);
7331 static expression_t *parse_typeprop(expression_kind_t const kind)
7333 expression_t *tp_expression = allocate_expression_zero(kind);
7334 tp_expression->base.type = type_size_t;
7336 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7338 /* we only refer to a type property, mark this case */
7339 bool old = in_type_prop;
7340 in_type_prop = true;
7343 expression_t *expression;
7344 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7346 add_anchor_token(')');
7347 orig_type = parse_typename();
7348 rem_anchor_token(')');
7349 expect(')', end_error);
7351 if (token.type == '{') {
7352 /* It was not sizeof(type) after all. It is sizeof of an expression
7353 * starting with a compound literal */
7354 expression = parse_compound_literal(orig_type);
7355 goto typeprop_expression;
7358 expression = parse_sub_expression(PREC_UNARY);
7360 typeprop_expression:
7361 tp_expression->typeprop.tp_expression = expression;
7363 orig_type = revert_automatic_type_conversion(expression);
7364 expression->base.type = orig_type;
7367 tp_expression->typeprop.type = orig_type;
7368 type_t const* const type = skip_typeref(orig_type);
7369 char const* const wrong_type =
7370 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7371 is_type_incomplete(type) ? "incomplete" :
7372 type->kind == TYPE_FUNCTION ? "function designator" :
7373 type->kind == TYPE_BITFIELD ? "bitfield" :
7375 if (wrong_type != NULL) {
7376 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7377 errorf(&tp_expression->base.source_position,
7378 "operand of %s expression must not be of %s type '%T'",
7379 what, wrong_type, orig_type);
7384 return tp_expression;
7387 static expression_t *parse_sizeof(void)
7389 return parse_typeprop(EXPR_SIZEOF);
7392 static expression_t *parse_alignof(void)
7394 return parse_typeprop(EXPR_ALIGNOF);
7397 static expression_t *parse_select_expression(expression_t *addr)
7399 assert(token.type == '.' || token.type == T_MINUSGREATER);
7400 bool select_left_arrow = (token.type == T_MINUSGREATER);
7403 if (token.type != T_IDENTIFIER) {
7404 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7405 return create_invalid_expression();
7407 symbol_t *symbol = token.v.symbol;
7410 type_t *const orig_type = addr->base.type;
7411 type_t *const type = skip_typeref(orig_type);
7414 bool saw_error = false;
7415 if (is_type_pointer(type)) {
7416 if (!select_left_arrow) {
7418 "request for member '%Y' in something not a struct or union, but '%T'",
7422 type_left = skip_typeref(type->pointer.points_to);
7424 if (select_left_arrow && is_type_valid(type)) {
7425 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7431 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7432 type_left->kind != TYPE_COMPOUND_UNION) {
7434 if (is_type_valid(type_left) && !saw_error) {
7436 "request for member '%Y' in something not a struct or union, but '%T'",
7439 return create_invalid_expression();
7442 compound_t *compound = type_left->compound.compound;
7443 if (!compound->complete) {
7444 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7446 return create_invalid_expression();
7449 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7450 expression_t *result
7451 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7453 if (result == NULL) {
7454 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7455 return create_invalid_expression();
7461 static void check_call_argument(type_t *expected_type,
7462 call_argument_t *argument, unsigned pos)
7464 type_t *expected_type_skip = skip_typeref(expected_type);
7465 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7466 expression_t *arg_expr = argument->expression;
7467 type_t *arg_type = skip_typeref(arg_expr->base.type);
7469 /* handle transparent union gnu extension */
7470 if (is_type_union(expected_type_skip)
7471 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7472 compound_t *union_decl = expected_type_skip->compound.compound;
7473 type_t *best_type = NULL;
7474 entity_t *entry = union_decl->members.entities;
7475 for ( ; entry != NULL; entry = entry->base.next) {
7476 assert(is_declaration(entry));
7477 type_t *decl_type = entry->declaration.type;
7478 error = semantic_assign(decl_type, arg_expr);
7479 if (error == ASSIGN_ERROR_INCOMPATIBLE
7480 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7483 if (error == ASSIGN_SUCCESS) {
7484 best_type = decl_type;
7485 } else if (best_type == NULL) {
7486 best_type = decl_type;
7490 if (best_type != NULL) {
7491 expected_type = best_type;
7495 error = semantic_assign(expected_type, arg_expr);
7496 argument->expression = create_implicit_cast(arg_expr, expected_type);
7498 if (error != ASSIGN_SUCCESS) {
7499 /* report exact scope in error messages (like "in argument 3") */
7501 snprintf(buf, sizeof(buf), "call argument %u", pos);
7502 report_assign_error(error, expected_type, arg_expr, buf,
7503 &arg_expr->base.source_position);
7504 } else if (warning.traditional || warning.conversion) {
7505 type_t *const promoted_type = get_default_promoted_type(arg_type);
7506 if (!types_compatible(expected_type_skip, promoted_type) &&
7507 !types_compatible(expected_type_skip, type_void_ptr) &&
7508 !types_compatible(type_void_ptr, promoted_type)) {
7509 /* Deliberately show the skipped types in this warning */
7510 warningf(&arg_expr->base.source_position,
7511 "passing call argument %u as '%T' rather than '%T' due to prototype",
7512 pos, expected_type_skip, promoted_type);
7518 * Handle the semantic restrictions of builtin calls
7520 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7521 switch (call->function->reference.entity->function.btk) {
7522 case bk_gnu_builtin_return_address:
7523 case bk_gnu_builtin_frame_address: {
7524 /* argument must be constant */
7525 call_argument_t *argument = call->arguments;
7527 if (! is_constant_expression(argument->expression)) {
7528 errorf(&call->base.source_position,
7529 "argument of '%Y' must be a constant expression",
7530 call->function->reference.entity->base.symbol);
7534 case bk_gnu_builtin_prefetch: {
7535 /* second and third argument must be constant if existent */
7536 call_argument_t *rw = call->arguments->next;
7537 call_argument_t *locality = NULL;
7540 if (! is_constant_expression(rw->expression)) {
7541 errorf(&call->base.source_position,
7542 "second argument of '%Y' must be a constant expression",
7543 call->function->reference.entity->base.symbol);
7545 locality = rw->next;
7547 if (locality != NULL) {
7548 if (! is_constant_expression(locality->expression)) {
7549 errorf(&call->base.source_position,
7550 "third argument of '%Y' must be a constant expression",
7551 call->function->reference.entity->base.symbol);
7553 locality = rw->next;
7563 * Parse a call expression, ie. expression '( ... )'.
7565 * @param expression the function address
7567 static expression_t *parse_call_expression(expression_t *expression)
7569 expression_t *result = allocate_expression_zero(EXPR_CALL);
7570 call_expression_t *call = &result->call;
7571 call->function = expression;
7573 type_t *const orig_type = expression->base.type;
7574 type_t *const type = skip_typeref(orig_type);
7576 function_type_t *function_type = NULL;
7577 if (is_type_pointer(type)) {
7578 type_t *const to_type = skip_typeref(type->pointer.points_to);
7580 if (is_type_function(to_type)) {
7581 function_type = &to_type->function;
7582 call->base.type = function_type->return_type;
7586 if (function_type == NULL && is_type_valid(type)) {
7588 "called object '%E' (type '%T') is not a pointer to a function",
7589 expression, orig_type);
7592 /* parse arguments */
7594 add_anchor_token(')');
7595 add_anchor_token(',');
7597 if (token.type != ')') {
7598 call_argument_t **anchor = &call->arguments;
7600 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7601 argument->expression = parse_assignment_expression();
7604 anchor = &argument->next;
7605 } while (next_if(','));
7607 rem_anchor_token(',');
7608 rem_anchor_token(')');
7609 expect(')', end_error);
7611 if (function_type == NULL)
7614 /* check type and count of call arguments */
7615 function_parameter_t *parameter = function_type->parameters;
7616 call_argument_t *argument = call->arguments;
7617 if (!function_type->unspecified_parameters) {
7618 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7619 parameter = parameter->next, argument = argument->next) {
7620 check_call_argument(parameter->type, argument, ++pos);
7623 if (parameter != NULL) {
7624 errorf(HERE, "too few arguments to function '%E'", expression);
7625 } else if (argument != NULL && !function_type->variadic) {
7626 errorf(HERE, "too many arguments to function '%E'", expression);
7630 /* do default promotion for other arguments */
7631 for (; argument != NULL; argument = argument->next) {
7632 type_t *type = argument->expression->base.type;
7634 type = get_default_promoted_type(type);
7636 argument->expression
7637 = create_implicit_cast(argument->expression, type);
7640 check_format(&result->call);
7642 if (warning.aggregate_return &&
7643 is_type_compound(skip_typeref(function_type->return_type))) {
7644 warningf(&result->base.source_position,
7645 "function call has aggregate value");
7648 if (call->function->kind == EXPR_REFERENCE) {
7649 reference_expression_t *reference = &call->function->reference;
7650 if (reference->entity->kind == ENTITY_FUNCTION &&
7651 reference->entity->function.btk != bk_none)
7652 handle_builtin_argument_restrictions(call);
7659 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7661 static bool same_compound_type(const type_t *type1, const type_t *type2)
7664 is_type_compound(type1) &&
7665 type1->kind == type2->kind &&
7666 type1->compound.compound == type2->compound.compound;
7669 static expression_t const *get_reference_address(expression_t const *expr)
7671 bool regular_take_address = true;
7673 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7674 expr = expr->unary.value;
7676 regular_take_address = false;
7679 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7682 expr = expr->unary.value;
7685 if (expr->kind != EXPR_REFERENCE)
7688 /* special case for functions which are automatically converted to a
7689 * pointer to function without an extra TAKE_ADDRESS operation */
7690 if (!regular_take_address &&
7691 expr->reference.entity->kind != ENTITY_FUNCTION) {
7698 static void warn_reference_address_as_bool(expression_t const* expr)
7700 if (!warning.address)
7703 expr = get_reference_address(expr);
7705 warningf(&expr->base.source_position,
7706 "the address of '%Y' will always evaluate as 'true'",
7707 expr->reference.entity->base.symbol);
7711 static void warn_assignment_in_condition(const expression_t *const expr)
7713 if (!warning.parentheses)
7715 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7717 if (expr->base.parenthesized)
7719 warningf(&expr->base.source_position,
7720 "suggest parentheses around assignment used as truth value");
7723 static void semantic_condition(expression_t const *const expr,
7724 char const *const context)
7726 type_t *const type = skip_typeref(expr->base.type);
7727 if (is_type_scalar(type)) {
7728 warn_reference_address_as_bool(expr);
7729 warn_assignment_in_condition(expr);
7730 } else if (is_type_valid(type)) {
7731 errorf(&expr->base.source_position,
7732 "%s must have scalar type", context);
7737 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7739 * @param expression the conditional expression
7741 static expression_t *parse_conditional_expression(expression_t *expression)
7743 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7745 conditional_expression_t *conditional = &result->conditional;
7746 conditional->condition = expression;
7749 add_anchor_token(':');
7751 /* §6.5.15:2 The first operand shall have scalar type. */
7752 semantic_condition(expression, "condition of conditional operator");
7754 expression_t *true_expression = expression;
7755 bool gnu_cond = false;
7756 if (GNU_MODE && token.type == ':') {
7759 true_expression = parse_expression();
7761 rem_anchor_token(':');
7762 expect(':', end_error);
7764 expression_t *false_expression =
7765 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7767 type_t *const orig_true_type = true_expression->base.type;
7768 type_t *const orig_false_type = false_expression->base.type;
7769 type_t *const true_type = skip_typeref(orig_true_type);
7770 type_t *const false_type = skip_typeref(orig_false_type);
7773 type_t *result_type;
7774 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7775 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7776 /* ISO/IEC 14882:1998(E) §5.16:2 */
7777 if (true_expression->kind == EXPR_UNARY_THROW) {
7778 result_type = false_type;
7779 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7780 result_type = true_type;
7782 if (warning.other && (
7783 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7784 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7786 warningf(&conditional->base.source_position,
7787 "ISO C forbids conditional expression with only one void side");
7789 result_type = type_void;
7791 } else if (is_type_arithmetic(true_type)
7792 && is_type_arithmetic(false_type)) {
7793 result_type = semantic_arithmetic(true_type, false_type);
7795 true_expression = create_implicit_cast(true_expression, result_type);
7796 false_expression = create_implicit_cast(false_expression, result_type);
7798 conditional->true_expression = true_expression;
7799 conditional->false_expression = false_expression;
7800 conditional->base.type = result_type;
7801 } else if (same_compound_type(true_type, false_type)) {
7802 /* just take 1 of the 2 types */
7803 result_type = true_type;
7804 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7805 type_t *pointer_type;
7807 expression_t *other_expression;
7808 if (is_type_pointer(true_type) &&
7809 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7810 pointer_type = true_type;
7811 other_type = false_type;
7812 other_expression = false_expression;
7814 pointer_type = false_type;
7815 other_type = true_type;
7816 other_expression = true_expression;
7819 if (is_null_pointer_constant(other_expression)) {
7820 result_type = pointer_type;
7821 } else if (is_type_pointer(other_type)) {
7822 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7823 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7826 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7827 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7829 } else if (types_compatible(get_unqualified_type(to1),
7830 get_unqualified_type(to2))) {
7833 if (warning.other) {
7834 warningf(&conditional->base.source_position,
7835 "pointer types '%T' and '%T' in conditional expression are incompatible",
7836 true_type, false_type);
7841 type_t *const type =
7842 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7843 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7844 } else if (is_type_integer(other_type)) {
7845 if (warning.other) {
7846 warningf(&conditional->base.source_position,
7847 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7849 result_type = pointer_type;
7851 if (is_type_valid(other_type)) {
7852 type_error_incompatible("while parsing conditional",
7853 &expression->base.source_position, true_type, false_type);
7855 result_type = type_error_type;
7858 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7859 type_error_incompatible("while parsing conditional",
7860 &conditional->base.source_position, true_type,
7863 result_type = type_error_type;
7866 conditional->true_expression
7867 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7868 conditional->false_expression
7869 = create_implicit_cast(false_expression, result_type);
7870 conditional->base.type = result_type;
7875 * Parse an extension expression.
7877 static expression_t *parse_extension(void)
7879 eat(T___extension__);
7881 bool old_gcc_extension = in_gcc_extension;
7882 in_gcc_extension = true;
7883 expression_t *expression = parse_sub_expression(PREC_UNARY);
7884 in_gcc_extension = old_gcc_extension;
7889 * Parse a __builtin_classify_type() expression.
7891 static expression_t *parse_builtin_classify_type(void)
7893 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7894 result->base.type = type_int;
7896 eat(T___builtin_classify_type);
7898 expect('(', end_error);
7899 add_anchor_token(')');
7900 expression_t *expression = parse_expression();
7901 rem_anchor_token(')');
7902 expect(')', end_error);
7903 result->classify_type.type_expression = expression;
7907 return create_invalid_expression();
7911 * Parse a delete expression
7912 * ISO/IEC 14882:1998(E) §5.3.5
7914 static expression_t *parse_delete(void)
7916 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7917 result->base.type = type_void;
7922 result->kind = EXPR_UNARY_DELETE_ARRAY;
7923 expect(']', end_error);
7927 expression_t *const value = parse_sub_expression(PREC_CAST);
7928 result->unary.value = value;
7930 type_t *const type = skip_typeref(value->base.type);
7931 if (!is_type_pointer(type)) {
7932 if (is_type_valid(type)) {
7933 errorf(&value->base.source_position,
7934 "operand of delete must have pointer type");
7936 } else if (warning.other &&
7937 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7938 warningf(&value->base.source_position,
7939 "deleting 'void*' is undefined");
7946 * Parse a throw expression
7947 * ISO/IEC 14882:1998(E) §15:1
7949 static expression_t *parse_throw(void)
7951 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7952 result->base.type = type_void;
7956 expression_t *value = NULL;
7957 switch (token.type) {
7959 value = parse_assignment_expression();
7960 /* ISO/IEC 14882:1998(E) §15.1:3 */
7961 type_t *const orig_type = value->base.type;
7962 type_t *const type = skip_typeref(orig_type);
7963 if (is_type_incomplete(type)) {
7964 errorf(&value->base.source_position,
7965 "cannot throw object of incomplete type '%T'", orig_type);
7966 } else if (is_type_pointer(type)) {
7967 type_t *const points_to = skip_typeref(type->pointer.points_to);
7968 if (is_type_incomplete(points_to) &&
7969 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7970 errorf(&value->base.source_position,
7971 "cannot throw pointer to incomplete type '%T'", orig_type);
7979 result->unary.value = value;
7984 static bool check_pointer_arithmetic(const source_position_t *source_position,
7985 type_t *pointer_type,
7986 type_t *orig_pointer_type)
7988 type_t *points_to = pointer_type->pointer.points_to;
7989 points_to = skip_typeref(points_to);
7991 if (is_type_incomplete(points_to)) {
7992 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7993 errorf(source_position,
7994 "arithmetic with pointer to incomplete type '%T' not allowed",
7997 } else if (warning.pointer_arith) {
7998 warningf(source_position,
7999 "pointer of type '%T' used in arithmetic",
8002 } else if (is_type_function(points_to)) {
8004 errorf(source_position,
8005 "arithmetic with pointer to function type '%T' not allowed",
8008 } else if (warning.pointer_arith) {
8009 warningf(source_position,
8010 "pointer to a function '%T' used in arithmetic",
8017 static bool is_lvalue(const expression_t *expression)
8019 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
8020 switch (expression->kind) {
8021 case EXPR_ARRAY_ACCESS:
8022 case EXPR_COMPOUND_LITERAL:
8023 case EXPR_REFERENCE:
8025 case EXPR_UNARY_DEREFERENCE:
8029 type_t *type = skip_typeref(expression->base.type);
8031 /* ISO/IEC 14882:1998(E) §3.10:3 */
8032 is_type_reference(type) ||
8033 /* Claim it is an lvalue, if the type is invalid. There was a parse
8034 * error before, which maybe prevented properly recognizing it as
8036 !is_type_valid(type);
8041 static void semantic_incdec(unary_expression_t *expression)
8043 type_t *const orig_type = expression->value->base.type;
8044 type_t *const type = skip_typeref(orig_type);
8045 if (is_type_pointer(type)) {
8046 if (!check_pointer_arithmetic(&expression->base.source_position,
8050 } else if (!is_type_real(type) && is_type_valid(type)) {
8051 /* TODO: improve error message */
8052 errorf(&expression->base.source_position,
8053 "operation needs an arithmetic or pointer type");
8056 if (!is_lvalue(expression->value)) {
8057 /* TODO: improve error message */
8058 errorf(&expression->base.source_position, "lvalue required as operand");
8060 expression->base.type = orig_type;
8063 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8065 type_t *const orig_type = expression->value->base.type;
8066 type_t *const type = skip_typeref(orig_type);
8067 if (!is_type_arithmetic(type)) {
8068 if (is_type_valid(type)) {
8069 /* TODO: improve error message */
8070 errorf(&expression->base.source_position,
8071 "operation needs an arithmetic type");
8076 expression->base.type = orig_type;
8079 static void semantic_unexpr_plus(unary_expression_t *expression)
8081 semantic_unexpr_arithmetic(expression);
8082 if (warning.traditional)
8083 warningf(&expression->base.source_position,
8084 "traditional C rejects the unary plus operator");
8087 static void semantic_not(unary_expression_t *expression)
8089 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8090 semantic_condition(expression->value, "operand of !");
8091 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8094 static void semantic_unexpr_integer(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_integer(type)) {
8099 if (is_type_valid(type)) {
8100 errorf(&expression->base.source_position,
8101 "operand of ~ must be of integer type");
8106 expression->base.type = orig_type;
8109 static void semantic_dereference(unary_expression_t *expression)
8111 type_t *const orig_type = expression->value->base.type;
8112 type_t *const type = skip_typeref(orig_type);
8113 if (!is_type_pointer(type)) {
8114 if (is_type_valid(type)) {
8115 errorf(&expression->base.source_position,
8116 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8121 type_t *result_type = type->pointer.points_to;
8122 result_type = automatic_type_conversion(result_type);
8123 expression->base.type = result_type;
8127 * Record that an address is taken (expression represents an lvalue).
8129 * @param expression the expression
8130 * @param may_be_register if true, the expression might be an register
8132 static void set_address_taken(expression_t *expression, bool may_be_register)
8134 if (expression->kind != EXPR_REFERENCE)
8137 entity_t *const entity = expression->reference.entity;
8139 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8142 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8143 && !may_be_register) {
8144 errorf(&expression->base.source_position,
8145 "address of register %s '%Y' requested",
8146 get_entity_kind_name(entity->kind), entity->base.symbol);
8149 if (entity->kind == ENTITY_VARIABLE) {
8150 entity->variable.address_taken = true;
8152 assert(entity->kind == ENTITY_PARAMETER);
8153 entity->parameter.address_taken = true;
8158 * Check the semantic of the address taken expression.
8160 static void semantic_take_addr(unary_expression_t *expression)
8162 expression_t *value = expression->value;
8163 value->base.type = revert_automatic_type_conversion(value);
8165 type_t *orig_type = value->base.type;
8166 type_t *type = skip_typeref(orig_type);
8167 if (!is_type_valid(type))
8171 if (!is_lvalue(value)) {
8172 errorf(&expression->base.source_position, "'&' requires an lvalue");
8174 if (type->kind == TYPE_BITFIELD) {
8175 errorf(&expression->base.source_position,
8176 "'&' not allowed on object with bitfield type '%T'",
8180 set_address_taken(value, false);
8182 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8185 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8186 static expression_t *parse_##unexpression_type(void) \
8188 expression_t *unary_expression \
8189 = allocate_expression_zero(unexpression_type); \
8191 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8193 sfunc(&unary_expression->unary); \
8195 return unary_expression; \
8198 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8199 semantic_unexpr_arithmetic)
8200 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8201 semantic_unexpr_plus)
8202 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8204 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8205 semantic_dereference)
8206 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8208 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8209 semantic_unexpr_integer)
8210 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8212 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8215 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8217 static expression_t *parse_##unexpression_type(expression_t *left) \
8219 expression_t *unary_expression \
8220 = allocate_expression_zero(unexpression_type); \
8222 unary_expression->unary.value = left; \
8224 sfunc(&unary_expression->unary); \
8226 return unary_expression; \
8229 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8230 EXPR_UNARY_POSTFIX_INCREMENT,
8232 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8233 EXPR_UNARY_POSTFIX_DECREMENT,
8236 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8238 /* TODO: handle complex + imaginary types */
8240 type_left = get_unqualified_type(type_left);
8241 type_right = get_unqualified_type(type_right);
8243 /* §6.3.1.8 Usual arithmetic conversions */
8244 if (type_left == type_long_double || type_right == type_long_double) {
8245 return type_long_double;
8246 } else if (type_left == type_double || type_right == type_double) {
8248 } else if (type_left == type_float || type_right == type_float) {
8252 type_left = promote_integer(type_left);
8253 type_right = promote_integer(type_right);
8255 if (type_left == type_right)
8258 bool const signed_left = is_type_signed(type_left);
8259 bool const signed_right = is_type_signed(type_right);
8260 int const rank_left = get_rank(type_left);
8261 int const rank_right = get_rank(type_right);
8263 if (signed_left == signed_right)
8264 return rank_left >= rank_right ? type_left : type_right;
8273 u_rank = rank_right;
8274 u_type = type_right;
8276 s_rank = rank_right;
8277 s_type = type_right;
8282 if (u_rank >= s_rank)
8285 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8287 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8288 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8292 case ATOMIC_TYPE_INT: return type_unsigned_int;
8293 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8294 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8296 default: panic("invalid atomic type");
8301 * Check the semantic restrictions for a binary expression.
8303 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8305 expression_t *const left = expression->left;
8306 expression_t *const right = expression->right;
8307 type_t *const orig_type_left = left->base.type;
8308 type_t *const orig_type_right = right->base.type;
8309 type_t *const type_left = skip_typeref(orig_type_left);
8310 type_t *const type_right = skip_typeref(orig_type_right);
8312 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8313 /* TODO: improve error message */
8314 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8315 errorf(&expression->base.source_position,
8316 "operation needs arithmetic types");
8321 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8322 expression->left = create_implicit_cast(left, arithmetic_type);
8323 expression->right = create_implicit_cast(right, arithmetic_type);
8324 expression->base.type = arithmetic_type;
8327 static void warn_div_by_zero(binary_expression_t const *const expression)
8329 if (!warning.div_by_zero ||
8330 !is_type_integer(expression->base.type))
8333 expression_t const *const right = expression->right;
8334 /* The type of the right operand can be different for /= */
8335 if (is_type_integer(right->base.type) &&
8336 is_constant_expression(right) &&
8337 !fold_constant_to_bool(right)) {
8338 warningf(&expression->base.source_position, "division by zero");
8343 * Check the semantic restrictions for a div/mod expression.
8345 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8347 semantic_binexpr_arithmetic(expression);
8348 warn_div_by_zero(expression);
8351 static void warn_addsub_in_shift(const expression_t *const expr)
8353 if (expr->base.parenthesized)
8357 switch (expr->kind) {
8358 case EXPR_BINARY_ADD: op = '+'; break;
8359 case EXPR_BINARY_SUB: op = '-'; break;
8363 warningf(&expr->base.source_position,
8364 "suggest parentheses around '%c' inside shift", op);
8367 static bool semantic_shift(binary_expression_t *expression)
8369 expression_t *const left = expression->left;
8370 expression_t *const right = expression->right;
8371 type_t *const orig_type_left = left->base.type;
8372 type_t *const orig_type_right = right->base.type;
8373 type_t * type_left = skip_typeref(orig_type_left);
8374 type_t * type_right = skip_typeref(orig_type_right);
8376 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8377 /* TODO: improve error message */
8378 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8379 errorf(&expression->base.source_position,
8380 "operands of shift operation must have integer types");
8385 type_left = promote_integer(type_left);
8387 if (is_constant_expression(right)) {
8388 long count = fold_constant_to_int(right);
8390 warningf(&right->base.source_position,
8391 "shift count must be non-negative");
8392 } else if ((unsigned long)count >=
8393 get_atomic_type_size(type_left->atomic.akind) * 8) {
8394 warningf(&right->base.source_position,
8395 "shift count must be less than type width");
8399 type_right = promote_integer(type_right);
8400 expression->right = create_implicit_cast(right, type_right);
8405 static void semantic_shift_op(binary_expression_t *expression)
8407 expression_t *const left = expression->left;
8408 expression_t *const right = expression->right;
8410 if (!semantic_shift(expression))
8413 if (warning.parentheses) {
8414 warn_addsub_in_shift(left);
8415 warn_addsub_in_shift(right);
8418 type_t *const orig_type_left = left->base.type;
8419 type_t * type_left = skip_typeref(orig_type_left);
8421 type_left = promote_integer(type_left);
8422 expression->left = create_implicit_cast(left, type_left);
8423 expression->base.type = type_left;
8426 static void semantic_add(binary_expression_t *expression)
8428 expression_t *const left = expression->left;
8429 expression_t *const right = expression->right;
8430 type_t *const orig_type_left = left->base.type;
8431 type_t *const orig_type_right = right->base.type;
8432 type_t *const type_left = skip_typeref(orig_type_left);
8433 type_t *const type_right = skip_typeref(orig_type_right);
8436 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8437 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8438 expression->left = create_implicit_cast(left, arithmetic_type);
8439 expression->right = create_implicit_cast(right, arithmetic_type);
8440 expression->base.type = arithmetic_type;
8441 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8442 check_pointer_arithmetic(&expression->base.source_position,
8443 type_left, orig_type_left);
8444 expression->base.type = type_left;
8445 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8446 check_pointer_arithmetic(&expression->base.source_position,
8447 type_right, orig_type_right);
8448 expression->base.type = type_right;
8449 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8450 errorf(&expression->base.source_position,
8451 "invalid operands to binary + ('%T', '%T')",
8452 orig_type_left, orig_type_right);
8456 static void semantic_sub(binary_expression_t *expression)
8458 expression_t *const left = expression->left;
8459 expression_t *const right = expression->right;
8460 type_t *const orig_type_left = left->base.type;
8461 type_t *const orig_type_right = right->base.type;
8462 type_t *const type_left = skip_typeref(orig_type_left);
8463 type_t *const type_right = skip_typeref(orig_type_right);
8464 source_position_t const *const pos = &expression->base.source_position;
8467 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8468 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8469 expression->left = create_implicit_cast(left, arithmetic_type);
8470 expression->right = create_implicit_cast(right, arithmetic_type);
8471 expression->base.type = arithmetic_type;
8472 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8473 check_pointer_arithmetic(&expression->base.source_position,
8474 type_left, orig_type_left);
8475 expression->base.type = type_left;
8476 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8477 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8478 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8479 if (!types_compatible(unqual_left, unqual_right)) {
8481 "subtracting pointers to incompatible types '%T' and '%T'",
8482 orig_type_left, orig_type_right);
8483 } else if (!is_type_object(unqual_left)) {
8484 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8485 errorf(pos, "subtracting pointers to non-object types '%T'",
8487 } else if (warning.other) {
8488 warningf(pos, "subtracting pointers to void");
8491 expression->base.type = type_ptrdiff_t;
8492 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8493 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8494 orig_type_left, orig_type_right);
8498 static void warn_string_literal_address(expression_t const* expr)
8500 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8501 expr = expr->unary.value;
8502 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8504 expr = expr->unary.value;
8507 if (expr->kind == EXPR_STRING_LITERAL ||
8508 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8509 warningf(&expr->base.source_position,
8510 "comparison with string literal results in unspecified behaviour");
8514 static void warn_comparison_in_comparison(const expression_t *const expr)
8516 if (expr->base.parenthesized)
8518 switch (expr->base.kind) {
8519 case EXPR_BINARY_LESS:
8520 case EXPR_BINARY_GREATER:
8521 case EXPR_BINARY_LESSEQUAL:
8522 case EXPR_BINARY_GREATEREQUAL:
8523 case EXPR_BINARY_NOTEQUAL:
8524 case EXPR_BINARY_EQUAL:
8525 warningf(&expr->base.source_position,
8526 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8533 static bool maybe_negative(expression_t const *const expr)
8536 !is_constant_expression(expr) ||
8537 fold_constant_to_int(expr) < 0;
8541 * Check the semantics of comparison expressions.
8543 * @param expression The expression to check.
8545 static void semantic_comparison(binary_expression_t *expression)
8547 expression_t *left = expression->left;
8548 expression_t *right = expression->right;
8550 if (warning.address) {
8551 warn_string_literal_address(left);
8552 warn_string_literal_address(right);
8554 expression_t const* const func_left = get_reference_address(left);
8555 if (func_left != NULL && is_null_pointer_constant(right)) {
8556 warningf(&expression->base.source_position,
8557 "the address of '%Y' will never be NULL",
8558 func_left->reference.entity->base.symbol);
8561 expression_t const* const func_right = get_reference_address(right);
8562 if (func_right != NULL && is_null_pointer_constant(right)) {
8563 warningf(&expression->base.source_position,
8564 "the address of '%Y' will never be NULL",
8565 func_right->reference.entity->base.symbol);
8569 if (warning.parentheses) {
8570 warn_comparison_in_comparison(left);
8571 warn_comparison_in_comparison(right);
8574 type_t *orig_type_left = left->base.type;
8575 type_t *orig_type_right = right->base.type;
8576 type_t *type_left = skip_typeref(orig_type_left);
8577 type_t *type_right = skip_typeref(orig_type_right);
8579 /* TODO non-arithmetic types */
8580 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8581 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8583 /* test for signed vs unsigned compares */
8584 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8585 bool const signed_left = is_type_signed(type_left);
8586 bool const signed_right = is_type_signed(type_right);
8587 if (signed_left != signed_right) {
8588 /* FIXME long long needs better const folding magic */
8589 /* TODO check whether constant value can be represented by other type */
8590 if ((signed_left && maybe_negative(left)) ||
8591 (signed_right && maybe_negative(right))) {
8592 warningf(&expression->base.source_position,
8593 "comparison between signed and unsigned");
8598 expression->left = create_implicit_cast(left, arithmetic_type);
8599 expression->right = create_implicit_cast(right, arithmetic_type);
8600 expression->base.type = arithmetic_type;
8601 if (warning.float_equal &&
8602 (expression->base.kind == EXPR_BINARY_EQUAL ||
8603 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8604 is_type_float(arithmetic_type)) {
8605 warningf(&expression->base.source_position,
8606 "comparing floating point with == or != is unsafe");
8608 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8609 /* TODO check compatibility */
8610 } else if (is_type_pointer(type_left)) {
8611 expression->right = create_implicit_cast(right, type_left);
8612 } else if (is_type_pointer(type_right)) {
8613 expression->left = create_implicit_cast(left, type_right);
8614 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8615 type_error_incompatible("invalid operands in comparison",
8616 &expression->base.source_position,
8617 type_left, type_right);
8619 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8623 * Checks if a compound type has constant fields.
8625 static bool has_const_fields(const compound_type_t *type)
8627 compound_t *compound = type->compound;
8628 entity_t *entry = compound->members.entities;
8630 for (; entry != NULL; entry = entry->base.next) {
8631 if (!is_declaration(entry))
8634 const type_t *decl_type = skip_typeref(entry->declaration.type);
8635 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8642 static bool is_valid_assignment_lhs(expression_t const* const left)
8644 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8645 type_t *const type_left = skip_typeref(orig_type_left);
8647 if (!is_lvalue(left)) {
8648 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8653 if (left->kind == EXPR_REFERENCE
8654 && left->reference.entity->kind == ENTITY_FUNCTION) {
8655 errorf(HERE, "cannot assign to function '%E'", left);
8659 if (is_type_array(type_left)) {
8660 errorf(HERE, "cannot assign to array '%E'", left);
8663 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8664 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8668 if (is_type_incomplete(type_left)) {
8669 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8670 left, orig_type_left);
8673 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8674 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8675 left, orig_type_left);
8682 static void semantic_arithmetic_assign(binary_expression_t *expression)
8684 expression_t *left = expression->left;
8685 expression_t *right = expression->right;
8686 type_t *orig_type_left = left->base.type;
8687 type_t *orig_type_right = right->base.type;
8689 if (!is_valid_assignment_lhs(left))
8692 type_t *type_left = skip_typeref(orig_type_left);
8693 type_t *type_right = skip_typeref(orig_type_right);
8695 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8696 /* TODO: improve error message */
8697 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8698 errorf(&expression->base.source_position,
8699 "operation needs arithmetic types");
8704 /* combined instructions are tricky. We can't create an implicit cast on
8705 * the left side, because we need the uncasted form for the store.
8706 * The ast2firm pass has to know that left_type must be right_type
8707 * for the arithmetic operation and create a cast by itself */
8708 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8709 expression->right = create_implicit_cast(right, arithmetic_type);
8710 expression->base.type = type_left;
8713 static void semantic_divmod_assign(binary_expression_t *expression)
8715 semantic_arithmetic_assign(expression);
8716 warn_div_by_zero(expression);
8719 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8721 expression_t *const left = expression->left;
8722 expression_t *const right = expression->right;
8723 type_t *const orig_type_left = left->base.type;
8724 type_t *const orig_type_right = right->base.type;
8725 type_t *const type_left = skip_typeref(orig_type_left);
8726 type_t *const type_right = skip_typeref(orig_type_right);
8728 if (!is_valid_assignment_lhs(left))
8731 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8732 /* combined instructions are tricky. We can't create an implicit cast on
8733 * the left side, because we need the uncasted form for the store.
8734 * The ast2firm pass has to know that left_type must be right_type
8735 * for the arithmetic operation and create a cast by itself */
8736 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8737 expression->right = create_implicit_cast(right, arithmetic_type);
8738 expression->base.type = type_left;
8739 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8740 check_pointer_arithmetic(&expression->base.source_position,
8741 type_left, orig_type_left);
8742 expression->base.type = type_left;
8743 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8744 errorf(&expression->base.source_position,
8745 "incompatible types '%T' and '%T' in assignment",
8746 orig_type_left, orig_type_right);
8750 static void semantic_integer_assign(binary_expression_t *expression)
8752 expression_t *left = expression->left;
8753 expression_t *right = expression->right;
8754 type_t *orig_type_left = left->base.type;
8755 type_t *orig_type_right = right->base.type;
8757 if (!is_valid_assignment_lhs(left))
8760 type_t *type_left = skip_typeref(orig_type_left);
8761 type_t *type_right = skip_typeref(orig_type_right);
8763 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8764 /* TODO: improve error message */
8765 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8766 errorf(&expression->base.source_position,
8767 "operation needs integer types");
8772 /* combined instructions are tricky. We can't create an implicit cast on
8773 * the left side, because we need the uncasted form for the store.
8774 * The ast2firm pass has to know that left_type must be right_type
8775 * for the arithmetic operation and create a cast by itself */
8776 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8777 expression->right = create_implicit_cast(right, arithmetic_type);
8778 expression->base.type = type_left;
8781 static void semantic_shift_assign(binary_expression_t *expression)
8783 expression_t *left = expression->left;
8785 if (!is_valid_assignment_lhs(left))
8788 if (!semantic_shift(expression))
8791 expression->base.type = skip_typeref(left->base.type);
8794 static void warn_logical_and_within_or(const expression_t *const expr)
8796 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8798 if (expr->base.parenthesized)
8800 warningf(&expr->base.source_position,
8801 "suggest parentheses around && within ||");
8805 * Check the semantic restrictions of a logical expression.
8807 static void semantic_logical_op(binary_expression_t *expression)
8809 /* §6.5.13:2 Each of the operands shall have scalar type.
8810 * §6.5.14:2 Each of the operands shall have scalar type. */
8811 semantic_condition(expression->left, "left operand of logical operator");
8812 semantic_condition(expression->right, "right operand of logical operator");
8813 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8814 warning.parentheses) {
8815 warn_logical_and_within_or(expression->left);
8816 warn_logical_and_within_or(expression->right);
8818 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8822 * Check the semantic restrictions of a binary assign expression.
8824 static void semantic_binexpr_assign(binary_expression_t *expression)
8826 expression_t *left = expression->left;
8827 type_t *orig_type_left = left->base.type;
8829 if (!is_valid_assignment_lhs(left))
8832 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8833 report_assign_error(error, orig_type_left, expression->right,
8834 "assignment", &left->base.source_position);
8835 expression->right = create_implicit_cast(expression->right, orig_type_left);
8836 expression->base.type = orig_type_left;
8840 * Determine if the outermost operation (or parts thereof) of the given
8841 * expression has no effect in order to generate a warning about this fact.
8842 * Therefore in some cases this only examines some of the operands of the
8843 * expression (see comments in the function and examples below).
8845 * f() + 23; // warning, because + has no effect
8846 * x || f(); // no warning, because x controls execution of f()
8847 * x ? y : f(); // warning, because y has no effect
8848 * (void)x; // no warning to be able to suppress the warning
8849 * This function can NOT be used for an "expression has definitely no effect"-
8851 static bool expression_has_effect(const expression_t *const expr)
8853 switch (expr->kind) {
8854 case EXPR_UNKNOWN: break;
8855 case EXPR_INVALID: return true; /* do NOT warn */
8856 case EXPR_REFERENCE: return false;
8857 case EXPR_REFERENCE_ENUM_VALUE: return false;
8858 /* suppress the warning for microsoft __noop operations */
8859 case EXPR_CONST: return expr->conste.is_ms_noop;
8860 case EXPR_CHARACTER_CONSTANT: return false;
8861 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8862 case EXPR_STRING_LITERAL: return false;
8863 case EXPR_WIDE_STRING_LITERAL: return false;
8864 case EXPR_LABEL_ADDRESS: return false;
8867 const call_expression_t *const call = &expr->call;
8868 if (call->function->kind != EXPR_REFERENCE)
8871 switch (call->function->reference.entity->function.btk) {
8872 /* FIXME: which builtins have no effect? */
8873 default: return true;
8877 /* Generate the warning if either the left or right hand side of a
8878 * conditional expression has no effect */
8879 case EXPR_CONDITIONAL: {
8880 conditional_expression_t const *const cond = &expr->conditional;
8881 expression_t const *const t = cond->true_expression;
8883 (t == NULL || expression_has_effect(t)) &&
8884 expression_has_effect(cond->false_expression);
8887 case EXPR_SELECT: return false;
8888 case EXPR_ARRAY_ACCESS: return false;
8889 case EXPR_SIZEOF: return false;
8890 case EXPR_CLASSIFY_TYPE: return false;
8891 case EXPR_ALIGNOF: return false;
8893 case EXPR_FUNCNAME: return false;
8894 case EXPR_BUILTIN_CONSTANT_P: return false;
8895 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8896 case EXPR_OFFSETOF: return false;
8897 case EXPR_VA_START: return true;
8898 case EXPR_VA_ARG: return true;
8899 case EXPR_VA_COPY: return true;
8900 case EXPR_STATEMENT: return true; // TODO
8901 case EXPR_COMPOUND_LITERAL: return false;
8903 case EXPR_UNARY_NEGATE: return false;
8904 case EXPR_UNARY_PLUS: return false;
8905 case EXPR_UNARY_BITWISE_NEGATE: return false;
8906 case EXPR_UNARY_NOT: return false;
8907 case EXPR_UNARY_DEREFERENCE: return false;
8908 case EXPR_UNARY_TAKE_ADDRESS: return false;
8909 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8910 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8911 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8912 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8914 /* Treat void casts as if they have an effect in order to being able to
8915 * suppress the warning */
8916 case EXPR_UNARY_CAST: {
8917 type_t *const type = skip_typeref(expr->base.type);
8918 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8921 case EXPR_UNARY_CAST_IMPLICIT: return true;
8922 case EXPR_UNARY_ASSUME: return true;
8923 case EXPR_UNARY_DELETE: return true;
8924 case EXPR_UNARY_DELETE_ARRAY: return true;
8925 case EXPR_UNARY_THROW: return true;
8927 case EXPR_BINARY_ADD: return false;
8928 case EXPR_BINARY_SUB: return false;
8929 case EXPR_BINARY_MUL: return false;
8930 case EXPR_BINARY_DIV: return false;
8931 case EXPR_BINARY_MOD: return false;
8932 case EXPR_BINARY_EQUAL: return false;
8933 case EXPR_BINARY_NOTEQUAL: return false;
8934 case EXPR_BINARY_LESS: return false;
8935 case EXPR_BINARY_LESSEQUAL: return false;
8936 case EXPR_BINARY_GREATER: return false;
8937 case EXPR_BINARY_GREATEREQUAL: return false;
8938 case EXPR_BINARY_BITWISE_AND: return false;
8939 case EXPR_BINARY_BITWISE_OR: return false;
8940 case EXPR_BINARY_BITWISE_XOR: return false;
8941 case EXPR_BINARY_SHIFTLEFT: return false;
8942 case EXPR_BINARY_SHIFTRIGHT: return false;
8943 case EXPR_BINARY_ASSIGN: return true;
8944 case EXPR_BINARY_MUL_ASSIGN: return true;
8945 case EXPR_BINARY_DIV_ASSIGN: return true;
8946 case EXPR_BINARY_MOD_ASSIGN: return true;
8947 case EXPR_BINARY_ADD_ASSIGN: return true;
8948 case EXPR_BINARY_SUB_ASSIGN: return true;
8949 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8950 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8951 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8952 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8953 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8955 /* Only examine the right hand side of && and ||, because the left hand
8956 * side already has the effect of controlling the execution of the right
8958 case EXPR_BINARY_LOGICAL_AND:
8959 case EXPR_BINARY_LOGICAL_OR:
8960 /* Only examine the right hand side of a comma expression, because the left
8961 * hand side has a separate warning */
8962 case EXPR_BINARY_COMMA:
8963 return expression_has_effect(expr->binary.right);
8965 case EXPR_BINARY_ISGREATER: return false;
8966 case EXPR_BINARY_ISGREATEREQUAL: return false;
8967 case EXPR_BINARY_ISLESS: return false;
8968 case EXPR_BINARY_ISLESSEQUAL: return false;
8969 case EXPR_BINARY_ISLESSGREATER: return false;
8970 case EXPR_BINARY_ISUNORDERED: return false;
8973 internal_errorf(HERE, "unexpected expression");
8976 static void semantic_comma(binary_expression_t *expression)
8978 if (warning.unused_value) {
8979 const expression_t *const left = expression->left;
8980 if (!expression_has_effect(left)) {
8981 warningf(&left->base.source_position,
8982 "left-hand operand of comma expression has no effect");
8985 expression->base.type = expression->right->base.type;
8989 * @param prec_r precedence of the right operand
8991 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8992 static expression_t *parse_##binexpression_type(expression_t *left) \
8994 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8995 binexpr->binary.left = left; \
8998 expression_t *right = parse_sub_expression(prec_r); \
9000 binexpr->binary.right = right; \
9001 sfunc(&binexpr->binary); \
9006 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
9007 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
9008 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
9009 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
9010 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9011 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9012 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9013 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9014 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9015 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9016 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9017 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9018 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9019 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
9020 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
9021 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
9022 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9023 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9024 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9025 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9026 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9027 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9028 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9029 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9030 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9031 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9032 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9033 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9034 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9035 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9038 static expression_t *parse_sub_expression(precedence_t precedence)
9040 if (token.type < 0) {
9041 return expected_expression_error();
9044 expression_parser_function_t *parser
9045 = &expression_parsers[token.type];
9046 source_position_t source_position = token.source_position;
9049 if (parser->parser != NULL) {
9050 left = parser->parser();
9052 left = parse_primary_expression();
9054 assert(left != NULL);
9055 left->base.source_position = source_position;
9058 if (token.type < 0) {
9059 return expected_expression_error();
9062 parser = &expression_parsers[token.type];
9063 if (parser->infix_parser == NULL)
9065 if (parser->infix_precedence < precedence)
9068 left = parser->infix_parser(left);
9070 assert(left != NULL);
9071 assert(left->kind != EXPR_UNKNOWN);
9072 left->base.source_position = source_position;
9079 * Parse an expression.
9081 static expression_t *parse_expression(void)
9083 return parse_sub_expression(PREC_EXPRESSION);
9087 * Register a parser for a prefix-like operator.
9089 * @param parser the parser function
9090 * @param token_type the token type of the prefix token
9092 static void register_expression_parser(parse_expression_function parser,
9095 expression_parser_function_t *entry = &expression_parsers[token_type];
9097 if (entry->parser != NULL) {
9098 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9099 panic("trying to register multiple expression parsers for a token");
9101 entry->parser = parser;
9105 * Register a parser for an infix operator with given precedence.
9107 * @param parser the parser function
9108 * @param token_type the token type of the infix operator
9109 * @param precedence the precedence of the operator
9111 static void register_infix_parser(parse_expression_infix_function parser,
9112 int token_type, precedence_t precedence)
9114 expression_parser_function_t *entry = &expression_parsers[token_type];
9116 if (entry->infix_parser != NULL) {
9117 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9118 panic("trying to register multiple infix expression parsers for a "
9121 entry->infix_parser = parser;
9122 entry->infix_precedence = precedence;
9126 * Initialize the expression parsers.
9128 static void init_expression_parsers(void)
9130 memset(&expression_parsers, 0, sizeof(expression_parsers));
9132 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9133 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9134 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9135 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9136 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9137 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9138 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9139 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9140 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9141 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9142 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9143 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9144 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9145 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9146 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9147 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9148 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9149 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9150 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9151 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9152 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9153 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9154 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9155 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9156 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9157 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9158 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9159 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9160 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9161 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9162 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9163 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9164 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9165 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9166 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9167 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9168 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9170 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9171 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9172 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9173 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9174 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9175 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9176 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9177 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9178 register_expression_parser(parse_sizeof, T_sizeof);
9179 register_expression_parser(parse_alignof, T___alignof__);
9180 register_expression_parser(parse_extension, T___extension__);
9181 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9182 register_expression_parser(parse_delete, T_delete);
9183 register_expression_parser(parse_throw, T_throw);
9187 * Parse a asm statement arguments specification.
9189 static asm_argument_t *parse_asm_arguments(bool is_out)
9191 asm_argument_t *result = NULL;
9192 asm_argument_t **anchor = &result;
9194 while (token.type == T_STRING_LITERAL || token.type == '[') {
9195 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9196 memset(argument, 0, sizeof(argument[0]));
9199 if (token.type != T_IDENTIFIER) {
9200 parse_error_expected("while parsing asm argument",
9201 T_IDENTIFIER, NULL);
9204 argument->symbol = token.v.symbol;
9206 expect(']', end_error);
9209 argument->constraints = parse_string_literals();
9210 expect('(', end_error);
9211 add_anchor_token(')');
9212 expression_t *expression = parse_expression();
9213 rem_anchor_token(')');
9215 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9216 * change size or type representation (e.g. int -> long is ok, but
9217 * int -> float is not) */
9218 if (expression->kind == EXPR_UNARY_CAST) {
9219 type_t *const type = expression->base.type;
9220 type_kind_t const kind = type->kind;
9221 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9224 if (kind == TYPE_ATOMIC) {
9225 atomic_type_kind_t const akind = type->atomic.akind;
9226 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9227 size = get_atomic_type_size(akind);
9229 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9230 size = get_atomic_type_size(get_intptr_kind());
9234 expression_t *const value = expression->unary.value;
9235 type_t *const value_type = value->base.type;
9236 type_kind_t const value_kind = value_type->kind;
9238 unsigned value_flags;
9239 unsigned value_size;
9240 if (value_kind == TYPE_ATOMIC) {
9241 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9242 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9243 value_size = get_atomic_type_size(value_akind);
9244 } else if (value_kind == TYPE_POINTER) {
9245 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9246 value_size = get_atomic_type_size(get_intptr_kind());
9251 if (value_flags != flags || value_size != size)
9255 } while (expression->kind == EXPR_UNARY_CAST);
9259 if (!is_lvalue(expression)) {
9260 errorf(&expression->base.source_position,
9261 "asm output argument is not an lvalue");
9264 if (argument->constraints.begin[0] == '+')
9265 mark_vars_read(expression, NULL);
9267 mark_vars_read(expression, NULL);
9269 argument->expression = expression;
9270 expect(')', end_error);
9272 set_address_taken(expression, true);
9275 anchor = &argument->next;
9287 * Parse a asm statement clobber specification.
9289 static asm_clobber_t *parse_asm_clobbers(void)
9291 asm_clobber_t *result = NULL;
9292 asm_clobber_t *last = NULL;
9294 while (token.type == T_STRING_LITERAL) {
9295 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9296 clobber->clobber = parse_string_literals();
9299 last->next = clobber;
9313 * Parse an asm statement.
9315 static statement_t *parse_asm_statement(void)
9317 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9318 asm_statement_t *asm_statement = &statement->asms;
9322 if (next_if(T_volatile))
9323 asm_statement->is_volatile = true;
9325 expect('(', end_error);
9326 add_anchor_token(')');
9327 add_anchor_token(':');
9328 asm_statement->asm_text = parse_string_literals();
9330 if (!next_if(':')) {
9331 rem_anchor_token(':');
9335 asm_statement->outputs = parse_asm_arguments(true);
9336 if (!next_if(':')) {
9337 rem_anchor_token(':');
9341 asm_statement->inputs = parse_asm_arguments(false);
9342 if (!next_if(':')) {
9343 rem_anchor_token(':');
9346 rem_anchor_token(':');
9348 asm_statement->clobbers = parse_asm_clobbers();
9351 rem_anchor_token(')');
9352 expect(')', end_error);
9353 expect(';', end_error);
9355 if (asm_statement->outputs == NULL) {
9356 /* GCC: An 'asm' instruction without any output operands will be treated
9357 * identically to a volatile 'asm' instruction. */
9358 asm_statement->is_volatile = true;
9363 return create_invalid_statement();
9367 * Parse a case statement.
9369 static statement_t *parse_case_statement(void)
9371 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9372 source_position_t *const pos = &statement->base.source_position;
9376 expression_t *const expression = parse_expression();
9377 statement->case_label.expression = expression;
9378 if (!is_constant_expression(expression)) {
9379 /* This check does not prevent the error message in all cases of an
9380 * prior error while parsing the expression. At least it catches the
9381 * common case of a mistyped enum entry. */
9382 if (is_type_valid(skip_typeref(expression->base.type))) {
9383 errorf(pos, "case label does not reduce to an integer constant");
9385 statement->case_label.is_bad = true;
9387 long const val = fold_constant_to_int(expression);
9388 statement->case_label.first_case = val;
9389 statement->case_label.last_case = val;
9393 if (next_if(T_DOTDOTDOT)) {
9394 expression_t *const end_range = parse_expression();
9395 statement->case_label.end_range = end_range;
9396 if (!is_constant_expression(end_range)) {
9397 /* This check does not prevent the error message in all cases of an
9398 * prior error while parsing the expression. At least it catches the
9399 * common case of a mistyped enum entry. */
9400 if (is_type_valid(skip_typeref(end_range->base.type))) {
9401 errorf(pos, "case range does not reduce to an integer constant");
9403 statement->case_label.is_bad = true;
9405 long const val = fold_constant_to_int(end_range);
9406 statement->case_label.last_case = val;
9408 if (warning.other && val < statement->case_label.first_case) {
9409 statement->case_label.is_empty_range = true;
9410 warningf(pos, "empty range specified");
9416 PUSH_PARENT(statement);
9418 expect(':', end_error);
9421 if (current_switch != NULL) {
9422 if (! statement->case_label.is_bad) {
9423 /* Check for duplicate case values */
9424 case_label_statement_t *c = &statement->case_label;
9425 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9426 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9429 if (c->last_case < l->first_case || c->first_case > l->last_case)
9432 errorf(pos, "duplicate case value (previously used %P)",
9433 &l->base.source_position);
9437 /* link all cases into the switch statement */
9438 if (current_switch->last_case == NULL) {
9439 current_switch->first_case = &statement->case_label;
9441 current_switch->last_case->next = &statement->case_label;
9443 current_switch->last_case = &statement->case_label;
9445 errorf(pos, "case label not within a switch statement");
9448 statement_t *const inner_stmt = parse_statement();
9449 statement->case_label.statement = inner_stmt;
9450 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9451 errorf(&inner_stmt->base.source_position, "declaration after case label");
9459 * Parse a default statement.
9461 static statement_t *parse_default_statement(void)
9463 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9467 PUSH_PARENT(statement);
9469 expect(':', end_error);
9470 if (current_switch != NULL) {
9471 const case_label_statement_t *def_label = current_switch->default_label;
9472 if (def_label != NULL) {
9473 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9474 &def_label->base.source_position);
9476 current_switch->default_label = &statement->case_label;
9478 /* link all cases into the switch statement */
9479 if (current_switch->last_case == NULL) {
9480 current_switch->first_case = &statement->case_label;
9482 current_switch->last_case->next = &statement->case_label;
9484 current_switch->last_case = &statement->case_label;
9487 errorf(&statement->base.source_position,
9488 "'default' label not within a switch statement");
9491 statement_t *const inner_stmt = parse_statement();
9492 statement->case_label.statement = inner_stmt;
9493 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9494 errorf(&inner_stmt->base.source_position, "declaration after default label");
9501 return create_invalid_statement();
9505 * Parse a label statement.
9507 static statement_t *parse_label_statement(void)
9509 assert(token.type == T_IDENTIFIER);
9510 symbol_t *symbol = token.v.symbol;
9511 label_t *label = get_label(symbol);
9513 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9514 statement->label.label = label;
9518 PUSH_PARENT(statement);
9520 /* if statement is already set then the label is defined twice,
9521 * otherwise it was just mentioned in a goto/local label declaration so far
9523 if (label->statement != NULL) {
9524 errorf(HERE, "duplicate label '%Y' (declared %P)",
9525 symbol, &label->base.source_position);
9527 label->base.source_position = token.source_position;
9528 label->statement = statement;
9533 if (token.type == '}') {
9534 /* TODO only warn? */
9535 if (warning.other && false) {
9536 warningf(HERE, "label at end of compound statement");
9537 statement->label.statement = create_empty_statement();
9539 errorf(HERE, "label at end of compound statement");
9540 statement->label.statement = create_invalid_statement();
9542 } else if (token.type == ';') {
9543 /* Eat an empty statement here, to avoid the warning about an empty
9544 * statement after a label. label:; is commonly used to have a label
9545 * before a closing brace. */
9546 statement->label.statement = create_empty_statement();
9549 statement_t *const inner_stmt = parse_statement();
9550 statement->label.statement = inner_stmt;
9551 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9552 errorf(&inner_stmt->base.source_position, "declaration after label");
9556 /* remember the labels in a list for later checking */
9557 *label_anchor = &statement->label;
9558 label_anchor = &statement->label.next;
9565 * Parse an if statement.
9567 static statement_t *parse_if(void)
9569 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9573 PUSH_PARENT(statement);
9575 add_anchor_token('{');
9577 expect('(', end_error);
9578 add_anchor_token(')');
9579 expression_t *const expr = parse_expression();
9580 statement->ifs.condition = expr;
9581 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9583 semantic_condition(expr, "condition of 'if'-statment");
9584 mark_vars_read(expr, NULL);
9585 rem_anchor_token(')');
9586 expect(')', end_error);
9589 rem_anchor_token('{');
9591 add_anchor_token(T_else);
9592 statement_t *const true_stmt = parse_statement();
9593 statement->ifs.true_statement = true_stmt;
9594 rem_anchor_token(T_else);
9596 if (next_if(T_else)) {
9597 statement->ifs.false_statement = parse_statement();
9598 } else if (warning.parentheses &&
9599 true_stmt->kind == STATEMENT_IF &&
9600 true_stmt->ifs.false_statement != NULL) {
9601 warningf(&true_stmt->base.source_position,
9602 "suggest explicit braces to avoid ambiguous 'else'");
9610 * Check that all enums are handled in a switch.
9612 * @param statement the switch statement to check
9614 static void check_enum_cases(const switch_statement_t *statement)
9616 const type_t *type = skip_typeref(statement->expression->base.type);
9617 if (! is_type_enum(type))
9619 const enum_type_t *enumt = &type->enumt;
9621 /* if we have a default, no warnings */
9622 if (statement->default_label != NULL)
9625 /* FIXME: calculation of value should be done while parsing */
9626 /* TODO: quadratic algorithm here. Change to an n log n one */
9627 long last_value = -1;
9628 const entity_t *entry = enumt->enume->base.next;
9629 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9630 entry = entry->base.next) {
9631 const expression_t *expression = entry->enum_value.value;
9632 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9634 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9635 if (l->expression == NULL)
9637 if (l->first_case <= value && value <= l->last_case) {
9643 warningf(&statement->base.source_position,
9644 "enumeration value '%Y' not handled in switch",
9645 entry->base.symbol);
9652 * Parse a switch statement.
9654 static statement_t *parse_switch(void)
9656 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9660 PUSH_PARENT(statement);
9662 expect('(', end_error);
9663 add_anchor_token(')');
9664 expression_t *const expr = parse_expression();
9665 mark_vars_read(expr, NULL);
9666 type_t * type = skip_typeref(expr->base.type);
9667 if (is_type_integer(type)) {
9668 type = promote_integer(type);
9669 if (warning.traditional) {
9670 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9671 warningf(&expr->base.source_position,
9672 "'%T' switch expression not converted to '%T' in ISO C",
9676 } else if (is_type_valid(type)) {
9677 errorf(&expr->base.source_position,
9678 "switch quantity is not an integer, but '%T'", type);
9679 type = type_error_type;
9681 statement->switchs.expression = create_implicit_cast(expr, type);
9682 expect(')', end_error);
9683 rem_anchor_token(')');
9685 switch_statement_t *rem = current_switch;
9686 current_switch = &statement->switchs;
9687 statement->switchs.body = parse_statement();
9688 current_switch = rem;
9690 if (warning.switch_default &&
9691 statement->switchs.default_label == NULL) {
9692 warningf(&statement->base.source_position, "switch has no default case");
9694 if (warning.switch_enum)
9695 check_enum_cases(&statement->switchs);
9701 return create_invalid_statement();
9704 static statement_t *parse_loop_body(statement_t *const loop)
9706 statement_t *const rem = current_loop;
9707 current_loop = loop;
9709 statement_t *const body = parse_statement();
9716 * Parse a while statement.
9718 static statement_t *parse_while(void)
9720 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9724 PUSH_PARENT(statement);
9726 expect('(', end_error);
9727 add_anchor_token(')');
9728 expression_t *const cond = parse_expression();
9729 statement->whiles.condition = cond;
9730 /* §6.8.5:2 The controlling expression of an iteration statement shall
9731 * have scalar type. */
9732 semantic_condition(cond, "condition of 'while'-statement");
9733 mark_vars_read(cond, NULL);
9734 rem_anchor_token(')');
9735 expect(')', end_error);
9737 statement->whiles.body = parse_loop_body(statement);
9743 return create_invalid_statement();
9747 * Parse a do statement.
9749 static statement_t *parse_do(void)
9751 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9755 PUSH_PARENT(statement);
9757 add_anchor_token(T_while);
9758 statement->do_while.body = parse_loop_body(statement);
9759 rem_anchor_token(T_while);
9761 expect(T_while, end_error);
9762 expect('(', end_error);
9763 add_anchor_token(')');
9764 expression_t *const cond = parse_expression();
9765 statement->do_while.condition = cond;
9766 /* §6.8.5:2 The controlling expression of an iteration statement shall
9767 * have scalar type. */
9768 semantic_condition(cond, "condition of 'do-while'-statement");
9769 mark_vars_read(cond, NULL);
9770 rem_anchor_token(')');
9771 expect(')', end_error);
9772 expect(';', end_error);
9778 return create_invalid_statement();
9782 * Parse a for statement.
9784 static statement_t *parse_for(void)
9786 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9790 expect('(', end_error1);
9791 add_anchor_token(')');
9793 PUSH_PARENT(statement);
9795 size_t const top = environment_top();
9796 scope_t *old_scope = scope_push(&statement->fors.scope);
9798 bool old_gcc_extension = in_gcc_extension;
9799 while (next_if(T___extension__)) {
9800 in_gcc_extension = true;
9804 } else if (is_declaration_specifier(&token, false)) {
9805 parse_declaration(record_entity, DECL_FLAGS_NONE);
9807 add_anchor_token(';');
9808 expression_t *const init = parse_expression();
9809 statement->fors.initialisation = init;
9810 mark_vars_read(init, ENT_ANY);
9811 if (warning.unused_value && !expression_has_effect(init)) {
9812 warningf(&init->base.source_position,
9813 "initialisation of 'for'-statement has no effect");
9815 rem_anchor_token(';');
9816 expect(';', end_error2);
9818 in_gcc_extension = old_gcc_extension;
9820 if (token.type != ';') {
9821 add_anchor_token(';');
9822 expression_t *const cond = parse_expression();
9823 statement->fors.condition = cond;
9824 /* §6.8.5:2 The controlling expression of an iteration statement
9825 * shall have scalar type. */
9826 semantic_condition(cond, "condition of 'for'-statement");
9827 mark_vars_read(cond, NULL);
9828 rem_anchor_token(';');
9830 expect(';', end_error2);
9831 if (token.type != ')') {
9832 expression_t *const step = parse_expression();
9833 statement->fors.step = step;
9834 mark_vars_read(step, ENT_ANY);
9835 if (warning.unused_value && !expression_has_effect(step)) {
9836 warningf(&step->base.source_position,
9837 "step of 'for'-statement has no effect");
9840 expect(')', end_error2);
9841 rem_anchor_token(')');
9842 statement->fors.body = parse_loop_body(statement);
9844 assert(current_scope == &statement->fors.scope);
9845 scope_pop(old_scope);
9846 environment_pop_to(top);
9853 rem_anchor_token(')');
9854 assert(current_scope == &statement->fors.scope);
9855 scope_pop(old_scope);
9856 environment_pop_to(top);
9860 return create_invalid_statement();
9864 * Parse a goto statement.
9866 static statement_t *parse_goto(void)
9868 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9871 if (GNU_MODE && next_if('*')) {
9872 expression_t *expression = parse_expression();
9873 mark_vars_read(expression, NULL);
9875 /* Argh: although documentation says the expression must be of type void*,
9876 * gcc accepts anything that can be casted into void* without error */
9877 type_t *type = expression->base.type;
9879 if (type != type_error_type) {
9880 if (!is_type_pointer(type) && !is_type_integer(type)) {
9881 errorf(&expression->base.source_position,
9882 "cannot convert to a pointer type");
9883 } else if (warning.other && type != type_void_ptr) {
9884 warningf(&expression->base.source_position,
9885 "type of computed goto expression should be 'void*' not '%T'", type);
9887 expression = create_implicit_cast(expression, type_void_ptr);
9890 statement->gotos.expression = expression;
9891 } else if (token.type == T_IDENTIFIER) {
9892 symbol_t *symbol = token.v.symbol;
9894 statement->gotos.label = get_label(symbol);
9897 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9899 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9904 /* remember the goto's in a list for later checking */
9905 *goto_anchor = &statement->gotos;
9906 goto_anchor = &statement->gotos.next;
9908 expect(';', end_error);
9912 return create_invalid_statement();
9916 * Parse a continue statement.
9918 static statement_t *parse_continue(void)
9920 if (current_loop == NULL) {
9921 errorf(HERE, "continue statement not within loop");
9924 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9927 expect(';', end_error);
9934 * Parse a break statement.
9936 static statement_t *parse_break(void)
9938 if (current_switch == NULL && current_loop == NULL) {
9939 errorf(HERE, "break statement not within loop or switch");
9942 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9945 expect(';', end_error);
9952 * Parse a __leave statement.
9954 static statement_t *parse_leave_statement(void)
9956 if (current_try == NULL) {
9957 errorf(HERE, "__leave statement not within __try");
9960 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9963 expect(';', end_error);
9970 * Check if a given entity represents a local variable.
9972 static bool is_local_variable(const entity_t *entity)
9974 if (entity->kind != ENTITY_VARIABLE)
9977 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9978 case STORAGE_CLASS_AUTO:
9979 case STORAGE_CLASS_REGISTER: {
9980 const type_t *type = skip_typeref(entity->declaration.type);
9981 if (is_type_function(type)) {
9993 * Check if a given expression represents a local variable.
9995 static bool expression_is_local_variable(const expression_t *expression)
9997 if (expression->base.kind != EXPR_REFERENCE) {
10000 const entity_t *entity = expression->reference.entity;
10001 return is_local_variable(entity);
10005 * Check if a given expression represents a local variable and
10006 * return its declaration then, else return NULL.
10008 entity_t *expression_is_variable(const expression_t *expression)
10010 if (expression->base.kind != EXPR_REFERENCE) {
10013 entity_t *entity = expression->reference.entity;
10014 if (entity->kind != ENTITY_VARIABLE)
10021 * Parse a return statement.
10023 static statement_t *parse_return(void)
10027 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10029 expression_t *return_value = NULL;
10030 if (token.type != ';') {
10031 return_value = parse_expression();
10032 mark_vars_read(return_value, NULL);
10035 const type_t *const func_type = skip_typeref(current_function->base.type);
10036 assert(is_type_function(func_type));
10037 type_t *const return_type = skip_typeref(func_type->function.return_type);
10039 source_position_t const *const pos = &statement->base.source_position;
10040 if (return_value != NULL) {
10041 type_t *return_value_type = skip_typeref(return_value->base.type);
10043 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10044 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10045 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10046 /* Only warn in C mode, because GCC does the same */
10047 if (c_mode & _CXX || strict_mode) {
10049 "'return' with a value, in function returning 'void'");
10050 } else if (warning.other) {
10052 "'return' with a value, in function returning 'void'");
10054 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10055 /* Only warn in C mode, because GCC does the same */
10058 "'return' with expression in function returning 'void'");
10059 } else if (warning.other) {
10061 "'return' with expression in function returning 'void'");
10065 assign_error_t error = semantic_assign(return_type, return_value);
10066 report_assign_error(error, return_type, return_value, "'return'",
10069 return_value = create_implicit_cast(return_value, return_type);
10070 /* check for returning address of a local var */
10071 if (warning.other && return_value != NULL
10072 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10073 const expression_t *expression = return_value->unary.value;
10074 if (expression_is_local_variable(expression)) {
10075 warningf(pos, "function returns address of local variable");
10078 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10079 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10080 if (c_mode & _CXX || strict_mode) {
10082 "'return' without value, in function returning non-void");
10085 "'return' without value, in function returning non-void");
10088 statement->returns.value = return_value;
10090 expect(';', end_error);
10097 * Parse a declaration statement.
10099 static statement_t *parse_declaration_statement(void)
10101 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10103 entity_t *before = current_scope->last_entity;
10105 parse_external_declaration();
10107 parse_declaration(record_entity, DECL_FLAGS_NONE);
10110 declaration_statement_t *const decl = &statement->declaration;
10111 entity_t *const begin =
10112 before != NULL ? before->base.next : current_scope->entities;
10113 decl->declarations_begin = begin;
10114 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10120 * Parse an expression statement, ie. expr ';'.
10122 static statement_t *parse_expression_statement(void)
10124 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10126 expression_t *const expr = parse_expression();
10127 statement->expression.expression = expr;
10128 mark_vars_read(expr, ENT_ANY);
10130 expect(';', end_error);
10137 * Parse a microsoft __try { } __finally { } or
10138 * __try{ } __except() { }
10140 static statement_t *parse_ms_try_statment(void)
10142 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10145 PUSH_PARENT(statement);
10147 ms_try_statement_t *rem = current_try;
10148 current_try = &statement->ms_try;
10149 statement->ms_try.try_statement = parse_compound_statement(false);
10154 if (next_if(T___except)) {
10155 expect('(', end_error);
10156 add_anchor_token(')');
10157 expression_t *const expr = parse_expression();
10158 mark_vars_read(expr, NULL);
10159 type_t * type = skip_typeref(expr->base.type);
10160 if (is_type_integer(type)) {
10161 type = promote_integer(type);
10162 } else if (is_type_valid(type)) {
10163 errorf(&expr->base.source_position,
10164 "__expect expression is not an integer, but '%T'", type);
10165 type = type_error_type;
10167 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10168 rem_anchor_token(')');
10169 expect(')', end_error);
10170 statement->ms_try.final_statement = parse_compound_statement(false);
10171 } else if (next_if(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);
10228 } while (next_if(','));
10231 statement->declaration.declarations_begin = begin;
10232 statement->declaration.declarations_end = end;
10236 static void parse_namespace_definition(void)
10240 entity_t *entity = NULL;
10241 symbol_t *symbol = NULL;
10243 if (token.type == T_IDENTIFIER) {
10244 symbol = token.v.symbol;
10247 entity = get_entity(symbol, NAMESPACE_NORMAL);
10248 if (entity != NULL &&
10249 entity->kind != ENTITY_NAMESPACE &&
10250 entity->base.parent_scope == current_scope) {
10251 if (!is_error_entity(entity)) {
10252 error_redefined_as_different_kind(&token.source_position,
10253 entity, ENTITY_NAMESPACE);
10259 if (entity == NULL) {
10260 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10261 entity->base.symbol = symbol;
10262 entity->base.source_position = token.source_position;
10263 entity->base.namespc = NAMESPACE_NORMAL;
10264 entity->base.parent_scope = current_scope;
10267 if (token.type == '=') {
10268 /* TODO: parse namespace alias */
10269 panic("namespace alias definition not supported yet");
10272 environment_push(entity);
10273 append_entity(current_scope, entity);
10275 size_t const top = environment_top();
10276 scope_t *old_scope = scope_push(&entity->namespacee.members);
10278 expect('{', end_error);
10280 expect('}', end_error);
10283 assert(current_scope == &entity->namespacee.members);
10284 scope_pop(old_scope);
10285 environment_pop_to(top);
10289 * Parse a statement.
10290 * There's also parse_statement() which additionally checks for
10291 * "statement has no effect" warnings
10293 static statement_t *intern_parse_statement(void)
10295 statement_t *statement = NULL;
10297 /* declaration or statement */
10298 add_anchor_token(';');
10299 switch (token.type) {
10300 case T_IDENTIFIER: {
10301 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10302 if (la1_type == ':') {
10303 statement = parse_label_statement();
10304 } else if (is_typedef_symbol(token.v.symbol)) {
10305 statement = parse_declaration_statement();
10307 /* it's an identifier, the grammar says this must be an
10308 * expression statement. However it is common that users mistype
10309 * declaration types, so we guess a bit here to improve robustness
10310 * for incorrect programs */
10311 switch (la1_type) {
10314 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10315 goto expression_statment;
10320 statement = parse_declaration_statement();
10324 expression_statment:
10325 statement = parse_expression_statement();
10332 case T___extension__:
10333 /* This can be a prefix to a declaration or an expression statement.
10334 * We simply eat it now and parse the rest with tail recursion. */
10335 while (next_if(T___extension__)) {}
10336 bool old_gcc_extension = in_gcc_extension;
10337 in_gcc_extension = true;
10338 statement = intern_parse_statement();
10339 in_gcc_extension = old_gcc_extension;
10343 statement = parse_declaration_statement();
10347 statement = parse_local_label_declaration();
10350 case ';': statement = parse_empty_statement(); break;
10351 case '{': statement = parse_compound_statement(false); break;
10352 case T___leave: statement = parse_leave_statement(); break;
10353 case T___try: statement = parse_ms_try_statment(); break;
10354 case T_asm: statement = parse_asm_statement(); break;
10355 case T_break: statement = parse_break(); break;
10356 case T_case: statement = parse_case_statement(); break;
10357 case T_continue: statement = parse_continue(); break;
10358 case T_default: statement = parse_default_statement(); break;
10359 case T_do: statement = parse_do(); break;
10360 case T_for: statement = parse_for(); break;
10361 case T_goto: statement = parse_goto(); break;
10362 case T_if: statement = parse_if(); break;
10363 case T_return: statement = parse_return(); break;
10364 case T_switch: statement = parse_switch(); break;
10365 case T_while: statement = parse_while(); break;
10368 statement = parse_expression_statement();
10372 errorf(HERE, "unexpected token %K while parsing statement", &token);
10373 statement = create_invalid_statement();
10378 rem_anchor_token(';');
10380 assert(statement != NULL
10381 && statement->base.source_position.input_name != NULL);
10387 * parse a statement and emits "statement has no effect" warning if needed
10388 * (This is really a wrapper around intern_parse_statement with check for 1
10389 * single warning. It is needed, because for statement expressions we have
10390 * to avoid the warning on the last statement)
10392 static statement_t *parse_statement(void)
10394 statement_t *statement = intern_parse_statement();
10396 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10397 expression_t *expression = statement->expression.expression;
10398 if (!expression_has_effect(expression)) {
10399 warningf(&expression->base.source_position,
10400 "statement has no effect");
10408 * Parse a compound statement.
10410 static statement_t *parse_compound_statement(bool inside_expression_statement)
10412 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10414 PUSH_PARENT(statement);
10417 add_anchor_token('}');
10418 /* tokens, which can start a statement */
10419 /* TODO MS, __builtin_FOO */
10420 add_anchor_token('!');
10421 add_anchor_token('&');
10422 add_anchor_token('(');
10423 add_anchor_token('*');
10424 add_anchor_token('+');
10425 add_anchor_token('-');
10426 add_anchor_token('{');
10427 add_anchor_token('~');
10428 add_anchor_token(T_CHARACTER_CONSTANT);
10429 add_anchor_token(T_COLONCOLON);
10430 add_anchor_token(T_FLOATINGPOINT);
10431 add_anchor_token(T_IDENTIFIER);
10432 add_anchor_token(T_INTEGER);
10433 add_anchor_token(T_MINUSMINUS);
10434 add_anchor_token(T_PLUSPLUS);
10435 add_anchor_token(T_STRING_LITERAL);
10436 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10437 add_anchor_token(T_WIDE_STRING_LITERAL);
10438 add_anchor_token(T__Bool);
10439 add_anchor_token(T__Complex);
10440 add_anchor_token(T__Imaginary);
10441 add_anchor_token(T___FUNCTION__);
10442 add_anchor_token(T___PRETTY_FUNCTION__);
10443 add_anchor_token(T___alignof__);
10444 add_anchor_token(T___attribute__);
10445 add_anchor_token(T___builtin_va_start);
10446 add_anchor_token(T___extension__);
10447 add_anchor_token(T___func__);
10448 add_anchor_token(T___imag__);
10449 add_anchor_token(T___label__);
10450 add_anchor_token(T___real__);
10451 add_anchor_token(T___thread);
10452 add_anchor_token(T_asm);
10453 add_anchor_token(T_auto);
10454 add_anchor_token(T_bool);
10455 add_anchor_token(T_break);
10456 add_anchor_token(T_case);
10457 add_anchor_token(T_char);
10458 add_anchor_token(T_class);
10459 add_anchor_token(T_const);
10460 add_anchor_token(T_const_cast);
10461 add_anchor_token(T_continue);
10462 add_anchor_token(T_default);
10463 add_anchor_token(T_delete);
10464 add_anchor_token(T_double);
10465 add_anchor_token(T_do);
10466 add_anchor_token(T_dynamic_cast);
10467 add_anchor_token(T_enum);
10468 add_anchor_token(T_extern);
10469 add_anchor_token(T_false);
10470 add_anchor_token(T_float);
10471 add_anchor_token(T_for);
10472 add_anchor_token(T_goto);
10473 add_anchor_token(T_if);
10474 add_anchor_token(T_inline);
10475 add_anchor_token(T_int);
10476 add_anchor_token(T_long);
10477 add_anchor_token(T_new);
10478 add_anchor_token(T_operator);
10479 add_anchor_token(T_register);
10480 add_anchor_token(T_reinterpret_cast);
10481 add_anchor_token(T_restrict);
10482 add_anchor_token(T_return);
10483 add_anchor_token(T_short);
10484 add_anchor_token(T_signed);
10485 add_anchor_token(T_sizeof);
10486 add_anchor_token(T_static);
10487 add_anchor_token(T_static_cast);
10488 add_anchor_token(T_struct);
10489 add_anchor_token(T_switch);
10490 add_anchor_token(T_template);
10491 add_anchor_token(T_this);
10492 add_anchor_token(T_throw);
10493 add_anchor_token(T_true);
10494 add_anchor_token(T_try);
10495 add_anchor_token(T_typedef);
10496 add_anchor_token(T_typeid);
10497 add_anchor_token(T_typename);
10498 add_anchor_token(T_typeof);
10499 add_anchor_token(T_union);
10500 add_anchor_token(T_unsigned);
10501 add_anchor_token(T_using);
10502 add_anchor_token(T_void);
10503 add_anchor_token(T_volatile);
10504 add_anchor_token(T_wchar_t);
10505 add_anchor_token(T_while);
10507 size_t const top = environment_top();
10508 scope_t *old_scope = scope_push(&statement->compound.scope);
10510 statement_t **anchor = &statement->compound.statements;
10511 bool only_decls_so_far = true;
10512 while (token.type != '}') {
10513 if (token.type == T_EOF) {
10514 errorf(&statement->base.source_position,
10515 "EOF while parsing compound statement");
10518 statement_t *sub_statement = intern_parse_statement();
10519 if (is_invalid_statement(sub_statement)) {
10520 /* an error occurred. if we are at an anchor, return */
10526 if (warning.declaration_after_statement) {
10527 if (sub_statement->kind != STATEMENT_DECLARATION) {
10528 only_decls_so_far = false;
10529 } else if (!only_decls_so_far) {
10530 warningf(&sub_statement->base.source_position,
10531 "ISO C90 forbids mixed declarations and code");
10535 *anchor = sub_statement;
10537 while (sub_statement->base.next != NULL)
10538 sub_statement = sub_statement->base.next;
10540 anchor = &sub_statement->base.next;
10544 /* look over all statements again to produce no effect warnings */
10545 if (warning.unused_value) {
10546 statement_t *sub_statement = statement->compound.statements;
10547 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10548 if (sub_statement->kind != STATEMENT_EXPRESSION)
10550 /* don't emit a warning for the last expression in an expression
10551 * statement as it has always an effect */
10552 if (inside_expression_statement && sub_statement->base.next == NULL)
10555 expression_t *expression = sub_statement->expression.expression;
10556 if (!expression_has_effect(expression)) {
10557 warningf(&expression->base.source_position,
10558 "statement has no effect");
10564 rem_anchor_token(T_while);
10565 rem_anchor_token(T_wchar_t);
10566 rem_anchor_token(T_volatile);
10567 rem_anchor_token(T_void);
10568 rem_anchor_token(T_using);
10569 rem_anchor_token(T_unsigned);
10570 rem_anchor_token(T_union);
10571 rem_anchor_token(T_typeof);
10572 rem_anchor_token(T_typename);
10573 rem_anchor_token(T_typeid);
10574 rem_anchor_token(T_typedef);
10575 rem_anchor_token(T_try);
10576 rem_anchor_token(T_true);
10577 rem_anchor_token(T_throw);
10578 rem_anchor_token(T_this);
10579 rem_anchor_token(T_template);
10580 rem_anchor_token(T_switch);
10581 rem_anchor_token(T_struct);
10582 rem_anchor_token(T_static_cast);
10583 rem_anchor_token(T_static);
10584 rem_anchor_token(T_sizeof);
10585 rem_anchor_token(T_signed);
10586 rem_anchor_token(T_short);
10587 rem_anchor_token(T_return);
10588 rem_anchor_token(T_restrict);
10589 rem_anchor_token(T_reinterpret_cast);
10590 rem_anchor_token(T_register);
10591 rem_anchor_token(T_operator);
10592 rem_anchor_token(T_new);
10593 rem_anchor_token(T_long);
10594 rem_anchor_token(T_int);
10595 rem_anchor_token(T_inline);
10596 rem_anchor_token(T_if);
10597 rem_anchor_token(T_goto);
10598 rem_anchor_token(T_for);
10599 rem_anchor_token(T_float);
10600 rem_anchor_token(T_false);
10601 rem_anchor_token(T_extern);
10602 rem_anchor_token(T_enum);
10603 rem_anchor_token(T_dynamic_cast);
10604 rem_anchor_token(T_do);
10605 rem_anchor_token(T_double);
10606 rem_anchor_token(T_delete);
10607 rem_anchor_token(T_default);
10608 rem_anchor_token(T_continue);
10609 rem_anchor_token(T_const_cast);
10610 rem_anchor_token(T_const);
10611 rem_anchor_token(T_class);
10612 rem_anchor_token(T_char);
10613 rem_anchor_token(T_case);
10614 rem_anchor_token(T_break);
10615 rem_anchor_token(T_bool);
10616 rem_anchor_token(T_auto);
10617 rem_anchor_token(T_asm);
10618 rem_anchor_token(T___thread);
10619 rem_anchor_token(T___real__);
10620 rem_anchor_token(T___label__);
10621 rem_anchor_token(T___imag__);
10622 rem_anchor_token(T___func__);
10623 rem_anchor_token(T___extension__);
10624 rem_anchor_token(T___builtin_va_start);
10625 rem_anchor_token(T___attribute__);
10626 rem_anchor_token(T___alignof__);
10627 rem_anchor_token(T___PRETTY_FUNCTION__);
10628 rem_anchor_token(T___FUNCTION__);
10629 rem_anchor_token(T__Imaginary);
10630 rem_anchor_token(T__Complex);
10631 rem_anchor_token(T__Bool);
10632 rem_anchor_token(T_WIDE_STRING_LITERAL);
10633 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10634 rem_anchor_token(T_STRING_LITERAL);
10635 rem_anchor_token(T_PLUSPLUS);
10636 rem_anchor_token(T_MINUSMINUS);
10637 rem_anchor_token(T_INTEGER);
10638 rem_anchor_token(T_IDENTIFIER);
10639 rem_anchor_token(T_FLOATINGPOINT);
10640 rem_anchor_token(T_COLONCOLON);
10641 rem_anchor_token(T_CHARACTER_CONSTANT);
10642 rem_anchor_token('~');
10643 rem_anchor_token('{');
10644 rem_anchor_token('-');
10645 rem_anchor_token('+');
10646 rem_anchor_token('*');
10647 rem_anchor_token('(');
10648 rem_anchor_token('&');
10649 rem_anchor_token('!');
10650 rem_anchor_token('}');
10651 assert(current_scope == &statement->compound.scope);
10652 scope_pop(old_scope);
10653 environment_pop_to(top);
10660 * Check for unused global static functions and variables
10662 static void check_unused_globals(void)
10664 if (!warning.unused_function && !warning.unused_variable)
10667 for (const entity_t *entity = file_scope->entities; entity != NULL;
10668 entity = entity->base.next) {
10669 if (!is_declaration(entity))
10672 const declaration_t *declaration = &entity->declaration;
10673 if (declaration->used ||
10674 declaration->modifiers & DM_UNUSED ||
10675 declaration->modifiers & DM_USED ||
10676 declaration->storage_class != STORAGE_CLASS_STATIC)
10679 type_t *const type = declaration->type;
10681 if (entity->kind == ENTITY_FUNCTION) {
10682 /* inhibit warning for static inline functions */
10683 if (entity->function.is_inline)
10686 s = entity->function.statement != NULL ? "defined" : "declared";
10691 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10692 type, declaration->base.symbol, s);
10696 static void parse_global_asm(void)
10698 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10701 expect('(', end_error);
10703 statement->asms.asm_text = parse_string_literals();
10704 statement->base.next = unit->global_asm;
10705 unit->global_asm = statement;
10707 expect(')', end_error);
10708 expect(';', end_error);
10713 static void parse_linkage_specification(void)
10716 assert(token.type == T_STRING_LITERAL);
10718 const char *linkage = parse_string_literals().begin;
10720 linkage_kind_t old_linkage = current_linkage;
10721 linkage_kind_t new_linkage;
10722 if (strcmp(linkage, "C") == 0) {
10723 new_linkage = LINKAGE_C;
10724 } else if (strcmp(linkage, "C++") == 0) {
10725 new_linkage = LINKAGE_CXX;
10727 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10728 new_linkage = LINKAGE_INVALID;
10730 current_linkage = new_linkage;
10732 if (next_if('{')) {
10734 expect('}', end_error);
10740 assert(current_linkage == new_linkage);
10741 current_linkage = old_linkage;
10744 static void parse_external(void)
10746 switch (token.type) {
10747 DECLARATION_START_NO_EXTERN
10749 case T___extension__:
10750 /* tokens below are for implicit int */
10751 case '&': /* & x; -> int& x; (and error later, because C++ has no
10753 case '*': /* * x; -> int* x; */
10754 case '(': /* (x); -> int (x); */
10755 parse_external_declaration();
10759 if (look_ahead(1)->type == T_STRING_LITERAL) {
10760 parse_linkage_specification();
10762 parse_external_declaration();
10767 parse_global_asm();
10771 parse_namespace_definition();
10775 if (!strict_mode) {
10777 warningf(HERE, "stray ';' outside of function");
10784 errorf(HERE, "stray %K outside of function", &token);
10785 if (token.type == '(' || token.type == '{' || token.type == '[')
10786 eat_until_matching_token(token.type);
10792 static void parse_externals(void)
10794 add_anchor_token('}');
10795 add_anchor_token(T_EOF);
10798 unsigned char token_anchor_copy[T_LAST_TOKEN];
10799 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10802 while (token.type != T_EOF && token.type != '}') {
10804 bool anchor_leak = false;
10805 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10806 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10808 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10809 anchor_leak = true;
10812 if (in_gcc_extension) {
10813 errorf(HERE, "Leaked __extension__");
10814 anchor_leak = true;
10824 rem_anchor_token(T_EOF);
10825 rem_anchor_token('}');
10829 * Parse a translation unit.
10831 static void parse_translation_unit(void)
10833 add_anchor_token(T_EOF);
10838 if (token.type == T_EOF)
10841 errorf(HERE, "stray %K outside of function", &token);
10842 if (token.type == '(' || token.type == '{' || token.type == '[')
10843 eat_until_matching_token(token.type);
10851 * @return the translation unit or NULL if errors occurred.
10853 void start_parsing(void)
10855 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10856 label_stack = NEW_ARR_F(stack_entry_t, 0);
10857 diagnostic_count = 0;
10861 type_set_output(stderr);
10862 ast_set_output(stderr);
10864 assert(unit == NULL);
10865 unit = allocate_ast_zero(sizeof(unit[0]));
10867 assert(file_scope == NULL);
10868 file_scope = &unit->scope;
10870 assert(current_scope == NULL);
10871 scope_push(&unit->scope);
10873 create_gnu_builtins();
10875 create_microsoft_intrinsics();
10878 translation_unit_t *finish_parsing(void)
10880 assert(current_scope == &unit->scope);
10883 assert(file_scope == &unit->scope);
10884 check_unused_globals();
10887 DEL_ARR_F(environment_stack);
10888 DEL_ARR_F(label_stack);
10890 translation_unit_t *result = unit;
10895 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10896 * are given length one. */
10897 static void complete_incomplete_arrays(void)
10899 size_t n = ARR_LEN(incomplete_arrays);
10900 for (size_t i = 0; i != n; ++i) {
10901 declaration_t *const decl = incomplete_arrays[i];
10902 type_t *const orig_type = decl->type;
10903 type_t *const type = skip_typeref(orig_type);
10905 if (!is_type_incomplete(type))
10908 if (warning.other) {
10909 warningf(&decl->base.source_position,
10910 "array '%#T' assumed to have one element",
10911 orig_type, decl->base.symbol);
10914 type_t *const new_type = duplicate_type(type);
10915 new_type->array.size_constant = true;
10916 new_type->array.has_implicit_size = true;
10917 new_type->array.size = 1;
10919 type_t *const result = identify_new_type(new_type);
10921 decl->type = result;
10925 void prepare_main_collect2(entity_t *entity)
10927 // create call to __main
10928 symbol_t *symbol = symbol_table_insert("__main");
10929 entity_t *subsubmain_ent
10930 = create_implicit_function(symbol, &builtin_source_position);
10932 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10933 type_t *ftype = subsubmain_ent->declaration.type;
10934 ref->base.source_position = builtin_source_position;
10935 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10936 ref->reference.entity = subsubmain_ent;
10938 expression_t *call = allocate_expression_zero(EXPR_CALL);
10939 call->base.source_position = builtin_source_position;
10940 call->base.type = type_void;
10941 call->call.function = ref;
10943 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10944 expr_statement->base.source_position = builtin_source_position;
10945 expr_statement->expression.expression = call;
10947 statement_t *statement = entity->function.statement;
10948 assert(statement->kind == STATEMENT_COMPOUND);
10949 compound_statement_t *compounds = &statement->compound;
10951 expr_statement->base.next = compounds->statements;
10952 compounds->statements = expr_statement;
10957 lookahead_bufpos = 0;
10958 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10961 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10962 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10963 parse_translation_unit();
10964 complete_incomplete_arrays();
10965 DEL_ARR_F(incomplete_arrays);
10966 incomplete_arrays = NULL;
10970 * create a builtin function.
10972 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10974 symbol_t *symbol = symbol_table_insert(name);
10975 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10976 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10977 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10978 entity->declaration.type = function_type;
10979 entity->declaration.implicit = true;
10980 entity->base.symbol = symbol;
10981 entity->base.source_position = builtin_source_position;
10983 entity->function.btk = kind;
10985 record_entity(entity, /*is_definition=*/false);
10991 * Create predefined gnu builtins.
10993 static void create_gnu_builtins(void)
10995 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10997 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10998 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10999 GNU_BUILTIN(inf, make_function_0_type(type_double));
11000 GNU_BUILTIN(inff, make_function_0_type(type_float));
11001 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
11002 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
11003 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
11004 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
11005 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
11006 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
11007 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11008 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
11009 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
11010 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
11011 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
11012 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
11013 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
11014 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
11015 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
11021 * Create predefined MS intrinsics.
11023 static void create_microsoft_intrinsics(void)
11025 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
11027 /* intrinsics for all architectures */
11028 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11029 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
11030 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11031 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
11032 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
11033 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
11034 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
11036 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
11037 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
11038 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
11039 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
11042 MS_BUILTIN(_enable, make_function_0_type(type_void));
11043 MS_BUILTIN(_disable, make_function_0_type(type_void));
11044 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11045 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11046 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11047 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11048 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11049 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11050 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11051 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11052 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11053 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11054 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11056 if (machine_size <= 32) {
11057 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11058 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11060 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11061 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11068 * Initialize the parser.
11070 void init_parser(void)
11072 sym_anonymous = symbol_table_insert("<anonymous>");
11074 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11076 init_expression_parsers();
11077 obstack_init(&temp_obst);
11079 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11080 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11084 * Terminate the parser.
11086 void exit_parser(void)
11088 obstack_free(&temp_obst, NULL);