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_entity = NULL;
91 static entity_t *current_init_decl = NULL;
92 static switch_statement_t *current_switch = NULL;
93 static statement_t *current_loop = NULL;
94 static statement_t *current_parent = NULL;
95 static ms_try_statement_t *current_try = NULL;
96 static linkage_kind_t current_linkage = LINKAGE_INVALID;
97 static goto_statement_t *goto_first = NULL;
98 static goto_statement_t **goto_anchor = NULL;
99 static label_statement_t *label_first = NULL;
100 static label_statement_t **label_anchor = NULL;
101 /** current translation unit. */
102 static translation_unit_t *unit = NULL;
103 /** true if we are in a type property context (evaluation only for type) */
104 static bool in_type_prop = false;
105 /** true if we are in an __extension__ context. */
106 static bool in_gcc_extension = false;
107 static struct obstack temp_obst;
108 static entity_t *anonymous_entity;
109 static declaration_t **incomplete_arrays;
112 #define PUSH_PARENT(stmt) \
113 statement_t *const prev_parent = current_parent; \
114 ((void)(current_parent = (stmt)))
115 #define POP_PARENT ((void)(current_parent = prev_parent))
117 /** special symbol used for anonymous entities. */
118 static symbol_t *sym_anonymous = NULL;
120 /** The token anchor set */
121 static unsigned char token_anchor_set[T_LAST_TOKEN];
123 /** The current source position. */
124 #define HERE (&token.source_position)
126 /** true if we are in GCC mode. */
127 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
129 static statement_t *parse_compound_statement(bool inside_expression_statement);
130 static statement_t *parse_statement(void);
132 static expression_t *parse_sub_expression(precedence_t);
133 static expression_t *parse_expression(void);
134 static type_t *parse_typename(void);
135 static void parse_externals(void);
136 static void parse_external(void);
138 static void parse_compound_type_entries(compound_t *compound_declaration);
140 static void check_call_argument(type_t *expected_type,
141 call_argument_t *argument, unsigned pos);
143 typedef enum declarator_flags_t {
145 DECL_MAY_BE_ABSTRACT = 1U << 0,
146 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
147 DECL_IS_PARAMETER = 1U << 2
148 } declarator_flags_t;
150 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
151 declarator_flags_t flags);
153 static entity_t *record_entity(entity_t *entity, bool is_definition);
155 static void semantic_comparison(binary_expression_t *expression);
157 static void create_gnu_builtins(void);
158 static void create_microsoft_intrinsics(void);
160 #define STORAGE_CLASSES \
161 STORAGE_CLASSES_NO_EXTERN \
164 #define STORAGE_CLASSES_NO_EXTERN \
171 #define TYPE_QUALIFIERS \
176 case T__forceinline: \
177 case T___attribute__:
179 #define COMPLEX_SPECIFIERS \
181 #define IMAGINARY_SPECIFIERS \
184 #define TYPE_SPECIFIERS \
186 case T___builtin_va_list: \
211 #define DECLARATION_START \
216 #define DECLARATION_START_NO_EXTERN \
217 STORAGE_CLASSES_NO_EXTERN \
221 #define TYPENAME_START \
225 #define EXPRESSION_START \
234 case T_CHARACTER_CONSTANT: \
235 case T_FLOATINGPOINT: \
239 case T_STRING_LITERAL: \
240 case T_WIDE_CHARACTER_CONSTANT: \
241 case T_WIDE_STRING_LITERAL: \
242 case T___FUNCDNAME__: \
243 case T___FUNCSIG__: \
244 case T___FUNCTION__: \
245 case T___PRETTY_FUNCTION__: \
246 case T___alignof__: \
247 case T___builtin_classify_type: \
248 case T___builtin_constant_p: \
249 case T___builtin_isgreater: \
250 case T___builtin_isgreaterequal: \
251 case T___builtin_isless: \
252 case T___builtin_islessequal: \
253 case T___builtin_islessgreater: \
254 case T___builtin_isunordered: \
255 case T___builtin_offsetof: \
256 case T___builtin_va_arg: \
257 case T___builtin_va_start: \
258 case T___builtin_va_copy: \
269 * Allocate an AST node with given size and
270 * initialize all fields with zero.
272 static void *allocate_ast_zero(size_t size)
274 void *res = allocate_ast(size);
275 memset(res, 0, size);
280 * Returns the size of an entity node.
282 * @param kind the entity kind
284 static size_t get_entity_struct_size(entity_kind_t kind)
286 static const size_t sizes[] = {
287 [ENTITY_VARIABLE] = sizeof(variable_t),
288 [ENTITY_PARAMETER] = sizeof(parameter_t),
289 [ENTITY_COMPOUND_MEMBER] = sizeof(compound_member_t),
290 [ENTITY_FUNCTION] = sizeof(function_t),
291 [ENTITY_TYPEDEF] = sizeof(typedef_t),
292 [ENTITY_STRUCT] = sizeof(compound_t),
293 [ENTITY_UNION] = sizeof(compound_t),
294 [ENTITY_ENUM] = sizeof(enum_t),
295 [ENTITY_ENUM_VALUE] = sizeof(enum_value_t),
296 [ENTITY_LABEL] = sizeof(label_t),
297 [ENTITY_LOCAL_LABEL] = sizeof(label_t),
298 [ENTITY_NAMESPACE] = sizeof(namespace_t)
300 assert(kind < lengthof(sizes));
301 assert(sizes[kind] != 0);
306 * Allocate an entity of given kind and initialize all
309 * @param kind the kind of the entity to allocate
311 static entity_t *allocate_entity_zero(entity_kind_t kind)
313 size_t size = get_entity_struct_size(kind);
314 entity_t *entity = allocate_ast_zero(size);
320 * Returns the size of a statement node.
322 * @param kind the statement kind
324 static size_t get_statement_struct_size(statement_kind_t kind)
326 static const size_t sizes[] = {
327 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
328 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
329 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
330 [STATEMENT_RETURN] = sizeof(return_statement_t),
331 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
332 [STATEMENT_IF] = sizeof(if_statement_t),
333 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
334 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
335 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
336 [STATEMENT_BREAK] = sizeof(statement_base_t),
337 [STATEMENT_GOTO] = sizeof(goto_statement_t),
338 [STATEMENT_LABEL] = sizeof(label_statement_t),
339 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
340 [STATEMENT_WHILE] = sizeof(while_statement_t),
341 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
342 [STATEMENT_FOR] = sizeof(for_statement_t),
343 [STATEMENT_ASM] = sizeof(asm_statement_t),
344 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
345 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
347 assert(kind < lengthof(sizes));
348 assert(sizes[kind] != 0);
353 * Returns the size of an expression node.
355 * @param kind the expression kind
357 static size_t get_expression_struct_size(expression_kind_t kind)
359 static const size_t sizes[] = {
360 [EXPR_INVALID] = sizeof(expression_base_t),
361 [EXPR_REFERENCE] = sizeof(reference_expression_t),
362 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
363 [EXPR_CONST] = sizeof(const_expression_t),
364 [EXPR_CHARACTER_CONSTANT] = sizeof(const_expression_t),
365 [EXPR_WIDE_CHARACTER_CONSTANT] = sizeof(const_expression_t),
366 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
367 [EXPR_WIDE_STRING_LITERAL] = sizeof(wide_string_literal_expression_t),
368 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
369 [EXPR_CALL] = sizeof(call_expression_t),
370 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
371 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
372 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
373 [EXPR_SELECT] = sizeof(select_expression_t),
374 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
375 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
376 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
377 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
378 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
379 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
380 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
381 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
382 [EXPR_VA_START] = sizeof(va_start_expression_t),
383 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
384 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
385 [EXPR_STATEMENT] = sizeof(statement_expression_t),
386 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
388 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
389 return sizes[EXPR_UNARY_FIRST];
391 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
392 return sizes[EXPR_BINARY_FIRST];
394 assert(kind < lengthof(sizes));
395 assert(sizes[kind] != 0);
400 * Allocate a statement node of given kind and initialize all
401 * fields with zero. Sets its source position to the position
402 * of the current token.
404 static statement_t *allocate_statement_zero(statement_kind_t kind)
406 size_t size = get_statement_struct_size(kind);
407 statement_t *res = allocate_ast_zero(size);
409 res->base.kind = kind;
410 res->base.parent = current_parent;
411 res->base.source_position = token.source_position;
416 * Allocate an expression node of given kind and initialize all
419 * @param kind the kind of the expression to allocate
421 static expression_t *allocate_expression_zero(expression_kind_t kind)
423 size_t size = get_expression_struct_size(kind);
424 expression_t *res = allocate_ast_zero(size);
426 res->base.kind = kind;
427 res->base.type = type_error_type;
428 res->base.source_position = token.source_position;
433 * Creates a new invalid expression at the source position
434 * of the current token.
436 static expression_t *create_invalid_expression(void)
438 return allocate_expression_zero(EXPR_INVALID);
442 * Creates a new invalid statement.
444 static statement_t *create_invalid_statement(void)
446 return allocate_statement_zero(STATEMENT_INVALID);
450 * Allocate a new empty statement.
452 static statement_t *create_empty_statement(void)
454 return allocate_statement_zero(STATEMENT_EMPTY);
458 * Returns the size of a type node.
460 * @param kind the type kind
462 static size_t get_type_struct_size(type_kind_t kind)
464 static const size_t sizes[] = {
465 [TYPE_ATOMIC] = sizeof(atomic_type_t),
466 [TYPE_COMPLEX] = sizeof(complex_type_t),
467 [TYPE_IMAGINARY] = sizeof(imaginary_type_t),
468 [TYPE_BITFIELD] = sizeof(bitfield_type_t),
469 [TYPE_COMPOUND_STRUCT] = sizeof(compound_type_t),
470 [TYPE_COMPOUND_UNION] = sizeof(compound_type_t),
471 [TYPE_ENUM] = sizeof(enum_type_t),
472 [TYPE_FUNCTION] = sizeof(function_type_t),
473 [TYPE_POINTER] = sizeof(pointer_type_t),
474 [TYPE_ARRAY] = sizeof(array_type_t),
475 [TYPE_BUILTIN] = sizeof(builtin_type_t),
476 [TYPE_TYPEDEF] = sizeof(typedef_type_t),
477 [TYPE_TYPEOF] = sizeof(typeof_type_t),
479 assert(lengthof(sizes) == (int)TYPE_TYPEOF + 1);
480 assert(kind <= TYPE_TYPEOF);
481 assert(sizes[kind] != 0);
486 * Allocate a type node of given kind and initialize all
489 * @param kind type kind to allocate
491 static type_t *allocate_type_zero(type_kind_t kind)
493 size_t size = get_type_struct_size(kind);
494 type_t *res = obstack_alloc(type_obst, size);
495 memset(res, 0, size);
496 res->base.kind = kind;
501 static function_parameter_t *allocate_parameter(type_t *const type)
503 function_parameter_t *const param = obstack_alloc(type_obst, sizeof(*param));
504 memset(param, 0, sizeof(*param));
510 * Returns the size of an initializer node.
512 * @param kind the initializer kind
514 static size_t get_initializer_size(initializer_kind_t kind)
516 static const size_t sizes[] = {
517 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
518 [INITIALIZER_STRING] = sizeof(initializer_string_t),
519 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
520 [INITIALIZER_LIST] = sizeof(initializer_list_t),
521 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
523 assert(kind < lengthof(sizes));
524 assert(sizes[kind] != 0);
529 * Allocate an initializer node of given kind and initialize all
532 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
534 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
541 * Returns the index of the top element of the environment stack.
543 static size_t environment_top(void)
545 return ARR_LEN(environment_stack);
549 * Returns the index of the top element of the global label stack.
551 static size_t label_top(void)
553 return ARR_LEN(label_stack);
557 * Return the next token.
559 static inline void next_token(void)
561 token = lookahead_buffer[lookahead_bufpos];
562 lookahead_buffer[lookahead_bufpos] = lexer_token;
565 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
568 print_token(stderr, &token);
569 fprintf(stderr, "\n");
573 static inline bool next_if(int const type)
575 if (token.type == type) {
584 * Return the next token with a given lookahead.
586 static inline const token_t *look_ahead(size_t num)
588 assert(0 < num && num <= MAX_LOOKAHEAD);
589 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
590 return &lookahead_buffer[pos];
594 * Adds a token type to the token type anchor set (a multi-set).
596 static void add_anchor_token(int token_type)
598 assert(0 <= token_type && token_type < T_LAST_TOKEN);
599 ++token_anchor_set[token_type];
603 * Set the number of tokens types of the given type
604 * to zero and return the old count.
606 static int save_and_reset_anchor_state(int token_type)
608 assert(0 <= token_type && token_type < T_LAST_TOKEN);
609 int count = token_anchor_set[token_type];
610 token_anchor_set[token_type] = 0;
615 * Restore the number of token types to the given count.
617 static void restore_anchor_state(int token_type, int count)
619 assert(0 <= token_type && token_type < T_LAST_TOKEN);
620 token_anchor_set[token_type] = count;
624 * Remove a token type from the token type anchor set (a multi-set).
626 static void rem_anchor_token(int token_type)
628 assert(0 <= token_type && token_type < T_LAST_TOKEN);
629 assert(token_anchor_set[token_type] != 0);
630 --token_anchor_set[token_type];
634 * Return true if the token type of the current token is
637 static bool at_anchor(void)
641 return token_anchor_set[token.type];
645 * Eat tokens until a matching token type is found.
647 static void eat_until_matching_token(int type)
651 case '(': end_token = ')'; break;
652 case '{': end_token = '}'; break;
653 case '[': end_token = ']'; break;
654 default: end_token = type; break;
657 unsigned parenthesis_count = 0;
658 unsigned brace_count = 0;
659 unsigned bracket_count = 0;
660 while (token.type != end_token ||
661 parenthesis_count != 0 ||
663 bracket_count != 0) {
664 switch (token.type) {
666 case '(': ++parenthesis_count; break;
667 case '{': ++brace_count; break;
668 case '[': ++bracket_count; break;
671 if (parenthesis_count > 0)
681 if (bracket_count > 0)
684 if (token.type == end_token &&
685 parenthesis_count == 0 &&
699 * Eat input tokens until an anchor is found.
701 static void eat_until_anchor(void)
703 while (token_anchor_set[token.type] == 0) {
704 if (token.type == '(' || token.type == '{' || token.type == '[')
705 eat_until_matching_token(token.type);
711 * Eat a whole block from input tokens.
713 static void eat_block(void)
715 eat_until_matching_token('{');
719 #define eat(token_type) (assert(token.type == (token_type)), next_token())
722 * Report a parse error because an expected token was not found.
725 #if defined __GNUC__ && __GNUC__ >= 4
726 __attribute__((sentinel))
728 void parse_error_expected(const char *message, ...)
730 if (message != NULL) {
731 errorf(HERE, "%s", message);
734 va_start(ap, message);
735 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
740 * Report an incompatible type.
742 static void type_error_incompatible(const char *msg,
743 const source_position_t *source_position, type_t *type1, type_t *type2)
745 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
750 * Expect the current token is the expected token.
751 * If not, generate an error, eat the current statement,
752 * and goto the end_error label.
754 #define expect(expected, error_label) \
756 if (UNLIKELY(token.type != (expected))) { \
757 parse_error_expected(NULL, (expected), NULL); \
758 add_anchor_token(expected); \
759 eat_until_anchor(); \
760 next_if((expected)); \
761 rem_anchor_token(expected); \
768 * Push a given scope on the scope stack and make it the
771 static scope_t *scope_push(scope_t *new_scope)
773 if (current_scope != NULL) {
774 new_scope->depth = current_scope->depth + 1;
777 scope_t *old_scope = current_scope;
778 current_scope = new_scope;
783 * Pop the current scope from the scope stack.
785 static void scope_pop(scope_t *old_scope)
787 current_scope = old_scope;
791 * Search an entity by its symbol in a given namespace.
793 static entity_t *get_entity(const symbol_t *const symbol,
794 namespace_tag_t namespc)
796 entity_t *entity = symbol->entity;
797 for (; entity != NULL; entity = entity->base.symbol_next) {
798 if (entity->base.namespc == namespc)
805 /* §6.2.3:1 24) There is only one name space for tags even though three are
807 static entity_t *get_tag(symbol_t const *const symbol,
808 entity_kind_tag_t const kind)
810 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
811 if (entity != NULL && entity->kind != kind) {
813 "'%Y' defined as wrong kind of tag (previous definition %P)",
814 symbol, &entity->base.source_position);
821 * pushs an entity on the environment stack and links the corresponding symbol
824 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
826 symbol_t *symbol = entity->base.symbol;
827 entity_namespace_t namespc = entity->base.namespc;
828 assert(namespc != NAMESPACE_INVALID);
830 /* replace/add entity into entity list of the symbol */
833 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
838 /* replace an entry? */
839 if (iter->base.namespc == namespc) {
840 entity->base.symbol_next = iter->base.symbol_next;
846 /* remember old declaration */
848 entry.symbol = symbol;
849 entry.old_entity = iter;
850 entry.namespc = namespc;
851 ARR_APP1(stack_entry_t, *stack_ptr, entry);
855 * Push an entity on the environment stack.
857 static void environment_push(entity_t *entity)
859 assert(entity->base.source_position.input_name != NULL);
860 assert(entity->base.parent_scope != NULL);
861 stack_push(&environment_stack, entity);
865 * Push a declaration on the global label stack.
867 * @param declaration the declaration
869 static void label_push(entity_t *label)
871 /* we abuse the parameters scope as parent for the labels */
872 label->base.parent_scope = ¤t_function->parameters;
873 stack_push(&label_stack, label);
877 * pops symbols from the environment stack until @p new_top is the top element
879 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
881 stack_entry_t *stack = *stack_ptr;
882 size_t top = ARR_LEN(stack);
885 assert(new_top <= top);
889 for (i = top; i > new_top; --i) {
890 stack_entry_t *entry = &stack[i - 1];
892 entity_t *old_entity = entry->old_entity;
893 symbol_t *symbol = entry->symbol;
894 entity_namespace_t namespc = entry->namespc;
896 /* replace with old_entity/remove */
899 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
901 assert(iter != NULL);
902 /* replace an entry? */
903 if (iter->base.namespc == namespc)
907 /* restore definition from outer scopes (if there was one) */
908 if (old_entity != NULL) {
909 old_entity->base.symbol_next = iter->base.symbol_next;
910 *anchor = old_entity;
912 /* remove entry from list */
913 *anchor = iter->base.symbol_next;
917 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
921 * Pop all entries from the environment stack until the new_top
924 * @param new_top the new stack top
926 static void environment_pop_to(size_t new_top)
928 stack_pop_to(&environment_stack, new_top);
932 * Pop all entries from the global label stack until the new_top
935 * @param new_top the new stack top
937 static void label_pop_to(size_t new_top)
939 stack_pop_to(&label_stack, new_top);
942 static int get_akind_rank(atomic_type_kind_t akind)
948 * Return the type rank for an atomic type.
950 static int get_rank(const type_t *type)
952 assert(!is_typeref(type));
953 if (type->kind == TYPE_ENUM)
954 return get_akind_rank(type->enumt.akind);
956 assert(type->kind == TYPE_ATOMIC);
957 return get_akind_rank(type->atomic.akind);
961 * §6.3.1.1:2 Do integer promotion for a given type.
963 * @param type the type to promote
964 * @return the promoted type
966 static type_t *promote_integer(type_t *type)
968 if (type->kind == TYPE_BITFIELD)
969 type = type->bitfield.base_type;
971 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
978 * Create a cast expression.
980 * @param expression the expression to cast
981 * @param dest_type the destination type
983 static expression_t *create_cast_expression(expression_t *expression,
986 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
988 cast->unary.value = expression;
989 cast->base.type = dest_type;
995 * Check if a given expression represents a null pointer constant.
997 * @param expression the expression to check
999 static bool is_null_pointer_constant(const expression_t *expression)
1001 /* skip void* cast */
1002 if (expression->kind == EXPR_UNARY_CAST ||
1003 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
1004 type_t *const type = skip_typeref(expression->base.type);
1005 if (types_compatible(type, type_void_ptr))
1006 expression = expression->unary.value;
1009 type_t *const type = skip_typeref(expression->base.type);
1011 is_type_integer(type) &&
1012 is_constant_expression(expression) &&
1013 !fold_constant_to_bool(expression);
1017 * Create an implicit cast expression.
1019 * @param expression the expression to cast
1020 * @param dest_type the destination type
1022 static expression_t *create_implicit_cast(expression_t *expression,
1025 type_t *const source_type = expression->base.type;
1027 if (source_type == dest_type)
1030 return create_cast_expression(expression, dest_type);
1033 typedef enum assign_error_t {
1035 ASSIGN_ERROR_INCOMPATIBLE,
1036 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
1037 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
1038 ASSIGN_WARNING_POINTER_FROM_INT,
1039 ASSIGN_WARNING_INT_FROM_POINTER
1042 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
1043 const expression_t *const right,
1044 const char *context,
1045 const source_position_t *source_position)
1047 type_t *const orig_type_right = right->base.type;
1048 type_t *const type_left = skip_typeref(orig_type_left);
1049 type_t *const type_right = skip_typeref(orig_type_right);
1052 case ASSIGN_SUCCESS:
1054 case ASSIGN_ERROR_INCOMPATIBLE:
1055 errorf(source_position,
1056 "destination type '%T' in %s is incompatible with type '%T'",
1057 orig_type_left, context, orig_type_right);
1060 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
1061 if (warning.other) {
1062 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
1063 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
1065 /* the left type has all qualifiers from the right type */
1066 unsigned missing_qualifiers
1067 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1068 warningf(source_position,
1069 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
1070 orig_type_left, context, orig_type_right, missing_qualifiers);
1075 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
1076 if (warning.other) {
1077 warningf(source_position,
1078 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
1079 orig_type_left, context, right, orig_type_right);
1083 case ASSIGN_WARNING_POINTER_FROM_INT:
1084 if (warning.other) {
1085 warningf(source_position,
1086 "%s makes pointer '%T' from integer '%T' without a cast",
1087 context, orig_type_left, orig_type_right);
1091 case ASSIGN_WARNING_INT_FROM_POINTER:
1092 if (warning.other) {
1093 warningf(source_position,
1094 "%s makes integer '%T' from pointer '%T' without a cast",
1095 context, orig_type_left, orig_type_right);
1100 panic("invalid error value");
1104 /** Implements the rules from §6.5.16.1 */
1105 static assign_error_t semantic_assign(type_t *orig_type_left,
1106 const expression_t *const right)
1108 type_t *const orig_type_right = right->base.type;
1109 type_t *const type_left = skip_typeref(orig_type_left);
1110 type_t *const type_right = skip_typeref(orig_type_right);
1112 if (is_type_pointer(type_left)) {
1113 if (is_null_pointer_constant(right)) {
1114 return ASSIGN_SUCCESS;
1115 } else if (is_type_pointer(type_right)) {
1116 type_t *points_to_left
1117 = skip_typeref(type_left->pointer.points_to);
1118 type_t *points_to_right
1119 = skip_typeref(type_right->pointer.points_to);
1120 assign_error_t res = ASSIGN_SUCCESS;
1122 /* the left type has all qualifiers from the right type */
1123 unsigned missing_qualifiers
1124 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1125 if (missing_qualifiers != 0) {
1126 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1129 points_to_left = get_unqualified_type(points_to_left);
1130 points_to_right = get_unqualified_type(points_to_right);
1132 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1135 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1136 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1137 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1140 if (!types_compatible(points_to_left, points_to_right)) {
1141 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1145 } else if (is_type_integer(type_right)) {
1146 return ASSIGN_WARNING_POINTER_FROM_INT;
1148 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1149 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1150 && is_type_pointer(type_right))) {
1151 return ASSIGN_SUCCESS;
1152 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1153 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1154 type_t *const unqual_type_left = get_unqualified_type(type_left);
1155 type_t *const unqual_type_right = get_unqualified_type(type_right);
1156 if (types_compatible(unqual_type_left, unqual_type_right)) {
1157 return ASSIGN_SUCCESS;
1159 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1160 return ASSIGN_WARNING_INT_FROM_POINTER;
1163 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1164 return ASSIGN_SUCCESS;
1166 return ASSIGN_ERROR_INCOMPATIBLE;
1169 static expression_t *parse_constant_expression(void)
1171 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1173 if (!is_constant_expression(result)) {
1174 errorf(&result->base.source_position,
1175 "expression '%E' is not constant", result);
1181 static expression_t *parse_assignment_expression(void)
1183 return parse_sub_expression(PREC_ASSIGNMENT);
1186 static string_t parse_string_literals(void)
1188 assert(token.type == T_STRING_LITERAL);
1189 string_t result = token.v.string;
1193 while (token.type == T_STRING_LITERAL) {
1194 result = concat_strings(&result, &token.v.string);
1202 * compare two string, ignoring double underscores on the second.
1204 static int strcmp_underscore(const char *s1, const char *s2)
1206 if (s2[0] == '_' && s2[1] == '_') {
1207 size_t len2 = strlen(s2);
1208 size_t len1 = strlen(s1);
1209 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1210 return strncmp(s1, s2+2, len2-4);
1214 return strcmp(s1, s2);
1217 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1219 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1220 attribute->kind = kind;
1225 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1228 * __attribute__ ( ( attribute-list ) )
1232 * attribute_list , attrib
1237 * any-word ( identifier )
1238 * any-word ( identifier , nonempty-expr-list )
1239 * any-word ( expr-list )
1241 * where the "identifier" must not be declared as a type, and
1242 * "any-word" may be any identifier (including one declared as a
1243 * type), a reserved word storage class specifier, type specifier or
1244 * type qualifier. ??? This still leaves out most reserved keywords
1245 * (following the old parser), shouldn't we include them, and why not
1246 * allow identifiers declared as types to start the arguments?
1248 * Matze: this all looks confusing and little systematic, so we're even less
1249 * strict and parse any list of things which are identifiers or
1250 * (assignment-)expressions.
1252 static attribute_argument_t *parse_attribute_arguments(void)
1254 attribute_argument_t *first = NULL;
1255 attribute_argument_t **anchor = &first;
1256 if (token.type != ')') do {
1257 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1259 /* is it an identifier */
1260 if (token.type == T_IDENTIFIER
1261 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1262 symbol_t *symbol = token.v.symbol;
1263 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1264 argument->v.symbol = symbol;
1267 /* must be an expression */
1268 expression_t *expression = parse_assignment_expression();
1270 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1271 argument->v.expression = expression;
1274 /* append argument */
1276 anchor = &argument->next;
1277 } while (next_if(','));
1278 expect(')', end_error);
1287 static attribute_t *parse_attribute_asm(void)
1291 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1293 expect('(', end_error);
1294 attribute->a.arguments = parse_attribute_arguments();
1301 static symbol_t *get_symbol_from_token(void)
1303 switch(token.type) {
1305 return token.v.symbol;
1334 /* maybe we need more tokens ... add them on demand */
1335 return get_token_symbol(&token);
1341 static attribute_t *parse_attribute_gnu_single(void)
1343 /* parse "any-word" */
1344 symbol_t *symbol = get_symbol_from_token();
1345 if (symbol == NULL) {
1346 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1350 const char *name = symbol->string;
1353 attribute_kind_t kind;
1354 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1355 const char *attribute_name = get_attribute_name(kind);
1356 if (attribute_name != NULL
1357 && strcmp_underscore(attribute_name, name) == 0)
1361 if (kind >= ATTRIBUTE_GNU_LAST) {
1362 if (warning.attribute) {
1363 warningf(HERE, "unknown attribute '%s' ignored", name);
1365 /* TODO: we should still save the attribute in the list... */
1366 kind = ATTRIBUTE_UNKNOWN;
1369 attribute_t *attribute = allocate_attribute_zero(kind);
1371 /* parse arguments */
1373 attribute->a.arguments = parse_attribute_arguments();
1381 static attribute_t *parse_attribute_gnu(void)
1383 attribute_t *first = NULL;
1384 attribute_t **anchor = &first;
1386 eat(T___attribute__);
1387 expect('(', end_error);
1388 expect('(', end_error);
1390 if (token.type != ')') do {
1391 attribute_t *attribute = parse_attribute_gnu_single();
1392 if (attribute == NULL)
1395 *anchor = attribute;
1396 anchor = &attribute->next;
1397 } while (next_if(','));
1398 expect(')', end_error);
1399 expect(')', end_error);
1405 /** Parse attributes. */
1406 static attribute_t *parse_attributes(attribute_t *first)
1408 attribute_t **anchor = &first;
1410 while (*anchor != NULL)
1411 anchor = &(*anchor)->next;
1413 attribute_t *attribute;
1414 switch (token.type) {
1415 case T___attribute__:
1416 attribute = parse_attribute_gnu();
1420 attribute = parse_attribute_asm();
1425 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1430 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1433 case T__forceinline:
1435 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1440 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1445 /* TODO record modifier */
1447 warningf(HERE, "Ignoring declaration modifier %K", &token);
1448 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1455 *anchor = attribute;
1456 anchor = &attribute->next;
1460 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1462 static entity_t *determine_lhs_ent(expression_t *const expr,
1465 switch (expr->kind) {
1466 case EXPR_REFERENCE: {
1467 entity_t *const entity = expr->reference.entity;
1468 /* we should only find variables as lvalues... */
1469 if (entity->base.kind != ENTITY_VARIABLE
1470 && entity->base.kind != ENTITY_PARAMETER)
1476 case EXPR_ARRAY_ACCESS: {
1477 expression_t *const ref = expr->array_access.array_ref;
1478 entity_t * ent = NULL;
1479 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1480 ent = determine_lhs_ent(ref, lhs_ent);
1483 mark_vars_read(expr->select.compound, lhs_ent);
1485 mark_vars_read(expr->array_access.index, lhs_ent);
1490 if (is_type_compound(skip_typeref(expr->base.type))) {
1491 return determine_lhs_ent(expr->select.compound, lhs_ent);
1493 mark_vars_read(expr->select.compound, lhs_ent);
1498 case EXPR_UNARY_DEREFERENCE: {
1499 expression_t *const val = expr->unary.value;
1500 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1502 return determine_lhs_ent(val->unary.value, lhs_ent);
1504 mark_vars_read(val, NULL);
1510 mark_vars_read(expr, NULL);
1515 #define ENT_ANY ((entity_t*)-1)
1518 * Mark declarations, which are read. This is used to detect variables, which
1522 * x is not marked as "read", because it is only read to calculate its own new
1526 * x and y are not detected as "not read", because multiple variables are
1529 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1531 switch (expr->kind) {
1532 case EXPR_REFERENCE: {
1533 entity_t *const entity = expr->reference.entity;
1534 if (entity->kind != ENTITY_VARIABLE
1535 && entity->kind != ENTITY_PARAMETER)
1538 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1539 if (entity->kind == ENTITY_VARIABLE) {
1540 entity->variable.read = true;
1542 entity->parameter.read = true;
1549 // TODO respect pure/const
1550 mark_vars_read(expr->call.function, NULL);
1551 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1552 mark_vars_read(arg->expression, NULL);
1556 case EXPR_CONDITIONAL:
1557 // TODO lhs_decl should depend on whether true/false have an effect
1558 mark_vars_read(expr->conditional.condition, NULL);
1559 if (expr->conditional.true_expression != NULL)
1560 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1561 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1565 if (lhs_ent == ENT_ANY
1566 && !is_type_compound(skip_typeref(expr->base.type)))
1568 mark_vars_read(expr->select.compound, lhs_ent);
1571 case EXPR_ARRAY_ACCESS: {
1572 expression_t *const ref = expr->array_access.array_ref;
1573 mark_vars_read(ref, lhs_ent);
1574 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1575 mark_vars_read(expr->array_access.index, lhs_ent);
1580 mark_vars_read(expr->va_arge.ap, lhs_ent);
1584 mark_vars_read(expr->va_copye.src, lhs_ent);
1587 case EXPR_UNARY_CAST:
1588 /* Special case: Use void cast to mark a variable as "read" */
1589 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1594 case EXPR_UNARY_THROW:
1595 if (expr->unary.value == NULL)
1598 case EXPR_UNARY_DEREFERENCE:
1599 case EXPR_UNARY_DELETE:
1600 case EXPR_UNARY_DELETE_ARRAY:
1601 if (lhs_ent == ENT_ANY)
1605 case EXPR_UNARY_NEGATE:
1606 case EXPR_UNARY_PLUS:
1607 case EXPR_UNARY_BITWISE_NEGATE:
1608 case EXPR_UNARY_NOT:
1609 case EXPR_UNARY_TAKE_ADDRESS:
1610 case EXPR_UNARY_POSTFIX_INCREMENT:
1611 case EXPR_UNARY_POSTFIX_DECREMENT:
1612 case EXPR_UNARY_PREFIX_INCREMENT:
1613 case EXPR_UNARY_PREFIX_DECREMENT:
1614 case EXPR_UNARY_CAST_IMPLICIT:
1615 case EXPR_UNARY_ASSUME:
1617 mark_vars_read(expr->unary.value, lhs_ent);
1620 case EXPR_BINARY_ADD:
1621 case EXPR_BINARY_SUB:
1622 case EXPR_BINARY_MUL:
1623 case EXPR_BINARY_DIV:
1624 case EXPR_BINARY_MOD:
1625 case EXPR_BINARY_EQUAL:
1626 case EXPR_BINARY_NOTEQUAL:
1627 case EXPR_BINARY_LESS:
1628 case EXPR_BINARY_LESSEQUAL:
1629 case EXPR_BINARY_GREATER:
1630 case EXPR_BINARY_GREATEREQUAL:
1631 case EXPR_BINARY_BITWISE_AND:
1632 case EXPR_BINARY_BITWISE_OR:
1633 case EXPR_BINARY_BITWISE_XOR:
1634 case EXPR_BINARY_LOGICAL_AND:
1635 case EXPR_BINARY_LOGICAL_OR:
1636 case EXPR_BINARY_SHIFTLEFT:
1637 case EXPR_BINARY_SHIFTRIGHT:
1638 case EXPR_BINARY_COMMA:
1639 case EXPR_BINARY_ISGREATER:
1640 case EXPR_BINARY_ISGREATEREQUAL:
1641 case EXPR_BINARY_ISLESS:
1642 case EXPR_BINARY_ISLESSEQUAL:
1643 case EXPR_BINARY_ISLESSGREATER:
1644 case EXPR_BINARY_ISUNORDERED:
1645 mark_vars_read(expr->binary.left, lhs_ent);
1646 mark_vars_read(expr->binary.right, lhs_ent);
1649 case EXPR_BINARY_ASSIGN:
1650 case EXPR_BINARY_MUL_ASSIGN:
1651 case EXPR_BINARY_DIV_ASSIGN:
1652 case EXPR_BINARY_MOD_ASSIGN:
1653 case EXPR_BINARY_ADD_ASSIGN:
1654 case EXPR_BINARY_SUB_ASSIGN:
1655 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1656 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1657 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1658 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1659 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1660 if (lhs_ent == ENT_ANY)
1662 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1663 mark_vars_read(expr->binary.right, lhs_ent);
1668 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1674 case EXPR_CHARACTER_CONSTANT:
1675 case EXPR_WIDE_CHARACTER_CONSTANT:
1676 case EXPR_STRING_LITERAL:
1677 case EXPR_WIDE_STRING_LITERAL:
1678 case EXPR_COMPOUND_LITERAL: // TODO init?
1680 case EXPR_CLASSIFY_TYPE:
1683 case EXPR_BUILTIN_CONSTANT_P:
1684 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1686 case EXPR_STATEMENT: // TODO
1687 case EXPR_LABEL_ADDRESS:
1688 case EXPR_REFERENCE_ENUM_VALUE:
1692 panic("unhandled expression");
1695 static designator_t *parse_designation(void)
1697 designator_t *result = NULL;
1698 designator_t **anchor = &result;
1701 designator_t *designator;
1702 switch (token.type) {
1704 designator = allocate_ast_zero(sizeof(designator[0]));
1705 designator->source_position = token.source_position;
1707 add_anchor_token(']');
1708 designator->array_index = parse_constant_expression();
1709 rem_anchor_token(']');
1710 expect(']', end_error);
1713 designator = allocate_ast_zero(sizeof(designator[0]));
1714 designator->source_position = token.source_position;
1716 if (token.type != T_IDENTIFIER) {
1717 parse_error_expected("while parsing designator",
1718 T_IDENTIFIER, NULL);
1721 designator->symbol = token.v.symbol;
1725 expect('=', end_error);
1729 assert(designator != NULL);
1730 *anchor = designator;
1731 anchor = &designator->next;
1737 static initializer_t *initializer_from_string(array_type_t *type,
1738 const string_t *const string)
1740 /* TODO: check len vs. size of array type */
1743 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1744 initializer->string.string = *string;
1749 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1750 wide_string_t *const string)
1752 /* TODO: check len vs. size of array type */
1755 initializer_t *const initializer =
1756 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1757 initializer->wide_string.string = *string;
1763 * Build an initializer from a given expression.
1765 static initializer_t *initializer_from_expression(type_t *orig_type,
1766 expression_t *expression)
1768 /* TODO check that expression is a constant expression */
1770 /* §6.7.8.14/15 char array may be initialized by string literals */
1771 type_t *type = skip_typeref(orig_type);
1772 type_t *expr_type_orig = expression->base.type;
1773 type_t *expr_type = skip_typeref(expr_type_orig);
1774 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1775 array_type_t *const array_type = &type->array;
1776 type_t *const element_type = skip_typeref(array_type->element_type);
1778 if (element_type->kind == TYPE_ATOMIC) {
1779 atomic_type_kind_t akind = element_type->atomic.akind;
1780 switch (expression->kind) {
1781 case EXPR_STRING_LITERAL:
1782 if (akind == ATOMIC_TYPE_CHAR
1783 || akind == ATOMIC_TYPE_SCHAR
1784 || akind == ATOMIC_TYPE_UCHAR) {
1785 return initializer_from_string(array_type,
1786 &expression->string.value);
1790 case EXPR_WIDE_STRING_LITERAL: {
1791 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1792 if (get_unqualified_type(element_type) == bare_wchar_type) {
1793 return initializer_from_wide_string(array_type,
1794 &expression->wide_string.value);
1805 assign_error_t error = semantic_assign(type, expression);
1806 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1808 report_assign_error(error, type, expression, "initializer",
1809 &expression->base.source_position);
1811 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1812 result->value.value = create_implicit_cast(expression, type);
1818 * Checks if a given expression can be used as an constant initializer.
1820 static bool is_initializer_constant(const expression_t *expression)
1822 return is_constant_expression(expression)
1823 || is_address_constant(expression);
1827 * Parses an scalar initializer.
1829 * §6.7.8.11; eat {} without warning
1831 static initializer_t *parse_scalar_initializer(type_t *type,
1832 bool must_be_constant)
1834 /* there might be extra {} hierarchies */
1838 warningf(HERE, "extra curly braces around scalar initializer");
1841 } while (next_if('{'));
1844 expression_t *expression = parse_assignment_expression();
1845 mark_vars_read(expression, NULL);
1846 if (must_be_constant && !is_initializer_constant(expression)) {
1847 errorf(&expression->base.source_position,
1848 "initialisation expression '%E' is not constant",
1852 initializer_t *initializer = initializer_from_expression(type, expression);
1854 if (initializer == NULL) {
1855 errorf(&expression->base.source_position,
1856 "expression '%E' (type '%T') doesn't match expected type '%T'",
1857 expression, expression->base.type, type);
1862 bool additional_warning_displayed = false;
1863 while (braces > 0) {
1865 if (token.type != '}') {
1866 if (!additional_warning_displayed && warning.other) {
1867 warningf(HERE, "additional elements in scalar initializer");
1868 additional_warning_displayed = true;
1879 * An entry in the type path.
1881 typedef struct type_path_entry_t type_path_entry_t;
1882 struct type_path_entry_t {
1883 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1885 size_t index; /**< For array types: the current index. */
1886 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1891 * A type path expression a position inside compound or array types.
1893 typedef struct type_path_t type_path_t;
1894 struct type_path_t {
1895 type_path_entry_t *path; /**< An flexible array containing the current path. */
1896 type_t *top_type; /**< type of the element the path points */
1897 size_t max_index; /**< largest index in outermost array */
1901 * Prints a type path for debugging.
1903 static __attribute__((unused)) void debug_print_type_path(
1904 const type_path_t *path)
1906 size_t len = ARR_LEN(path->path);
1908 for (size_t i = 0; i < len; ++i) {
1909 const type_path_entry_t *entry = & path->path[i];
1911 type_t *type = skip_typeref(entry->type);
1912 if (is_type_compound(type)) {
1913 /* in gcc mode structs can have no members */
1914 if (entry->v.compound_entry == NULL) {
1918 fprintf(stderr, ".%s",
1919 entry->v.compound_entry->base.symbol->string);
1920 } else if (is_type_array(type)) {
1921 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1923 fprintf(stderr, "-INVALID-");
1926 if (path->top_type != NULL) {
1927 fprintf(stderr, " (");
1928 print_type(path->top_type);
1929 fprintf(stderr, ")");
1934 * Return the top type path entry, ie. in a path
1935 * (type).a.b returns the b.
1937 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1939 size_t len = ARR_LEN(path->path);
1941 return &path->path[len-1];
1945 * Enlarge the type path by an (empty) element.
1947 static type_path_entry_t *append_to_type_path(type_path_t *path)
1949 size_t len = ARR_LEN(path->path);
1950 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1952 type_path_entry_t *result = & path->path[len];
1953 memset(result, 0, sizeof(result[0]));
1958 * Descending into a sub-type. Enter the scope of the current top_type.
1960 static void descend_into_subtype(type_path_t *path)
1962 type_t *orig_top_type = path->top_type;
1963 type_t *top_type = skip_typeref(orig_top_type);
1965 type_path_entry_t *top = append_to_type_path(path);
1966 top->type = top_type;
1968 if (is_type_compound(top_type)) {
1969 compound_t *compound = top_type->compound.compound;
1970 entity_t *entry = compound->members.entities;
1972 if (entry != NULL) {
1973 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1974 top->v.compound_entry = &entry->declaration;
1975 path->top_type = entry->declaration.type;
1977 path->top_type = NULL;
1979 } else if (is_type_array(top_type)) {
1981 path->top_type = top_type->array.element_type;
1983 assert(!is_type_valid(top_type));
1988 * Pop an entry from the given type path, ie. returning from
1989 * (type).a.b to (type).a
1991 static void ascend_from_subtype(type_path_t *path)
1993 type_path_entry_t *top = get_type_path_top(path);
1995 path->top_type = top->type;
1997 size_t len = ARR_LEN(path->path);
1998 ARR_RESIZE(type_path_entry_t, path->path, len-1);
2002 * Pop entries from the given type path until the given
2003 * path level is reached.
2005 static void ascend_to(type_path_t *path, size_t top_path_level)
2007 size_t len = ARR_LEN(path->path);
2009 while (len > top_path_level) {
2010 ascend_from_subtype(path);
2011 len = ARR_LEN(path->path);
2015 static bool walk_designator(type_path_t *path, const designator_t *designator,
2016 bool used_in_offsetof)
2018 for (; designator != NULL; designator = designator->next) {
2019 type_path_entry_t *top = get_type_path_top(path);
2020 type_t *orig_type = top->type;
2022 type_t *type = skip_typeref(orig_type);
2024 if (designator->symbol != NULL) {
2025 symbol_t *symbol = designator->symbol;
2026 if (!is_type_compound(type)) {
2027 if (is_type_valid(type)) {
2028 errorf(&designator->source_position,
2029 "'.%Y' designator used for non-compound type '%T'",
2033 top->type = type_error_type;
2034 top->v.compound_entry = NULL;
2035 orig_type = type_error_type;
2037 compound_t *compound = type->compound.compound;
2038 entity_t *iter = compound->members.entities;
2039 for (; iter != NULL; iter = iter->base.next) {
2040 if (iter->base.symbol == symbol) {
2045 errorf(&designator->source_position,
2046 "'%T' has no member named '%Y'", orig_type, symbol);
2049 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
2050 if (used_in_offsetof) {
2051 type_t *real_type = skip_typeref(iter->declaration.type);
2052 if (real_type->kind == TYPE_BITFIELD) {
2053 errorf(&designator->source_position,
2054 "offsetof designator '%Y' may not specify bitfield",
2060 top->type = orig_type;
2061 top->v.compound_entry = &iter->declaration;
2062 orig_type = iter->declaration.type;
2065 expression_t *array_index = designator->array_index;
2066 assert(designator->array_index != NULL);
2068 if (!is_type_array(type)) {
2069 if (is_type_valid(type)) {
2070 errorf(&designator->source_position,
2071 "[%E] designator used for non-array type '%T'",
2072 array_index, orig_type);
2077 long index = fold_constant_to_int(array_index);
2078 if (!used_in_offsetof) {
2080 errorf(&designator->source_position,
2081 "array index [%E] must be positive", array_index);
2082 } else if (type->array.size_constant) {
2083 long array_size = type->array.size;
2084 if (index >= array_size) {
2085 errorf(&designator->source_position,
2086 "designator [%E] (%d) exceeds array size %d",
2087 array_index, index, array_size);
2092 top->type = orig_type;
2093 top->v.index = (size_t) index;
2094 orig_type = type->array.element_type;
2096 path->top_type = orig_type;
2098 if (designator->next != NULL) {
2099 descend_into_subtype(path);
2108 static void advance_current_object(type_path_t *path, size_t top_path_level)
2110 type_path_entry_t *top = get_type_path_top(path);
2112 type_t *type = skip_typeref(top->type);
2113 if (is_type_union(type)) {
2114 /* in unions only the first element is initialized */
2115 top->v.compound_entry = NULL;
2116 } else if (is_type_struct(type)) {
2117 declaration_t *entry = top->v.compound_entry;
2119 entity_t *next_entity = entry->base.next;
2120 if (next_entity != NULL) {
2121 assert(is_declaration(next_entity));
2122 entry = &next_entity->declaration;
2127 top->v.compound_entry = entry;
2128 if (entry != NULL) {
2129 path->top_type = entry->type;
2132 } else if (is_type_array(type)) {
2133 assert(is_type_array(type));
2137 if (!type->array.size_constant || top->v.index < type->array.size) {
2141 assert(!is_type_valid(type));
2145 /* we're past the last member of the current sub-aggregate, try if we
2146 * can ascend in the type hierarchy and continue with another subobject */
2147 size_t len = ARR_LEN(path->path);
2149 if (len > top_path_level) {
2150 ascend_from_subtype(path);
2151 advance_current_object(path, top_path_level);
2153 path->top_type = NULL;
2158 * skip any {...} blocks until a closing bracket is reached.
2160 static void skip_initializers(void)
2164 while (token.type != '}') {
2165 if (token.type == T_EOF)
2167 if (token.type == '{') {
2175 static initializer_t *create_empty_initializer(void)
2177 static initializer_t empty_initializer
2178 = { .list = { { INITIALIZER_LIST }, 0 } };
2179 return &empty_initializer;
2183 * Parse a part of an initialiser for a struct or union,
2185 static initializer_t *parse_sub_initializer(type_path_t *path,
2186 type_t *outer_type, size_t top_path_level,
2187 parse_initializer_env_t *env)
2189 if (token.type == '}') {
2190 /* empty initializer */
2191 return create_empty_initializer();
2194 type_t *orig_type = path->top_type;
2195 type_t *type = NULL;
2197 if (orig_type == NULL) {
2198 /* We are initializing an empty compound. */
2200 type = skip_typeref(orig_type);
2203 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2206 designator_t *designator = NULL;
2207 if (token.type == '.' || token.type == '[') {
2208 designator = parse_designation();
2209 goto finish_designator;
2210 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2211 /* GNU-style designator ("identifier: value") */
2212 designator = allocate_ast_zero(sizeof(designator[0]));
2213 designator->source_position = token.source_position;
2214 designator->symbol = token.v.symbol;
2219 /* reset path to toplevel, evaluate designator from there */
2220 ascend_to(path, top_path_level);
2221 if (!walk_designator(path, designator, false)) {
2222 /* can't continue after designation error */
2226 initializer_t *designator_initializer
2227 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2228 designator_initializer->designator.designator = designator;
2229 ARR_APP1(initializer_t*, initializers, designator_initializer);
2231 orig_type = path->top_type;
2232 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2237 if (token.type == '{') {
2238 if (type != NULL && is_type_scalar(type)) {
2239 sub = parse_scalar_initializer(type, env->must_be_constant);
2243 if (env->entity != NULL) {
2245 "extra brace group at end of initializer for '%Y'",
2246 env->entity->base.symbol);
2248 errorf(HERE, "extra brace group at end of initializer");
2251 descend_into_subtype(path);
2253 add_anchor_token('}');
2254 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2256 rem_anchor_token('}');
2259 ascend_from_subtype(path);
2260 expect('}', end_error);
2262 expect('}', end_error);
2263 goto error_parse_next;
2267 /* must be an expression */
2268 expression_t *expression = parse_assignment_expression();
2269 mark_vars_read(expression, NULL);
2271 if (env->must_be_constant && !is_initializer_constant(expression)) {
2272 errorf(&expression->base.source_position,
2273 "Initialisation expression '%E' is not constant",
2278 /* we are already outside, ... */
2279 if (outer_type == NULL)
2280 goto error_parse_next;
2281 type_t *const outer_type_skip = skip_typeref(outer_type);
2282 if (is_type_compound(outer_type_skip) &&
2283 !outer_type_skip->compound.compound->complete) {
2284 goto error_parse_next;
2289 /* handle { "string" } special case */
2290 if ((expression->kind == EXPR_STRING_LITERAL
2291 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2292 && outer_type != NULL) {
2293 sub = initializer_from_expression(outer_type, expression);
2296 if (token.type != '}' && warning.other) {
2297 warningf(HERE, "excessive elements in initializer for type '%T'",
2300 /* TODO: eat , ... */
2305 /* descend into subtypes until expression matches type */
2307 orig_type = path->top_type;
2308 type = skip_typeref(orig_type);
2310 sub = initializer_from_expression(orig_type, expression);
2314 if (!is_type_valid(type)) {
2317 if (is_type_scalar(type)) {
2318 errorf(&expression->base.source_position,
2319 "expression '%E' doesn't match expected type '%T'",
2320 expression, orig_type);
2324 descend_into_subtype(path);
2328 /* update largest index of top array */
2329 const type_path_entry_t *first = &path->path[0];
2330 type_t *first_type = first->type;
2331 first_type = skip_typeref(first_type);
2332 if (is_type_array(first_type)) {
2333 size_t index = first->v.index;
2334 if (index > path->max_index)
2335 path->max_index = index;
2339 /* append to initializers list */
2340 ARR_APP1(initializer_t*, initializers, sub);
2343 if (warning.other) {
2344 if (env->entity != NULL) {
2345 warningf(HERE, "excess elements in initializer for '%Y'",
2346 env->entity->base.symbol);
2348 warningf(HERE, "excess elements in initializer");
2354 if (token.type == '}') {
2357 expect(',', end_error);
2358 if (token.type == '}') {
2363 /* advance to the next declaration if we are not at the end */
2364 advance_current_object(path, top_path_level);
2365 orig_type = path->top_type;
2366 if (orig_type != NULL)
2367 type = skip_typeref(orig_type);
2373 size_t len = ARR_LEN(initializers);
2374 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2375 initializer_t *result = allocate_ast_zero(size);
2376 result->kind = INITIALIZER_LIST;
2377 result->list.len = len;
2378 memcpy(&result->list.initializers, initializers,
2379 len * sizeof(initializers[0]));
2381 DEL_ARR_F(initializers);
2382 ascend_to(path, top_path_level+1);
2387 skip_initializers();
2388 DEL_ARR_F(initializers);
2389 ascend_to(path, top_path_level+1);
2394 * Parses an initializer. Parsers either a compound literal
2395 * (env->declaration == NULL) or an initializer of a declaration.
2397 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2399 type_t *type = skip_typeref(env->type);
2400 size_t max_index = 0xdeadbeaf; // TODO: Resolve this uninitialized variable problem
2401 initializer_t *result;
2403 if (is_type_scalar(type)) {
2404 result = parse_scalar_initializer(type, env->must_be_constant);
2405 } else if (token.type == '{') {
2409 memset(&path, 0, sizeof(path));
2410 path.top_type = env->type;
2411 path.path = NEW_ARR_F(type_path_entry_t, 0);
2413 descend_into_subtype(&path);
2415 add_anchor_token('}');
2416 result = parse_sub_initializer(&path, env->type, 1, env);
2417 rem_anchor_token('}');
2419 max_index = path.max_index;
2420 DEL_ARR_F(path.path);
2422 expect('}', end_error);
2424 /* parse_scalar_initializer() also works in this case: we simply
2425 * have an expression without {} around it */
2426 result = parse_scalar_initializer(type, env->must_be_constant);
2429 /* §6.7.8:22 array initializers for arrays with unknown size determine
2430 * the array type size */
2431 if (is_type_array(type) && type->array.size_expression == NULL
2432 && result != NULL) {
2434 switch (result->kind) {
2435 case INITIALIZER_LIST:
2436 assert(max_index != 0xdeadbeaf);
2437 size = max_index + 1;
2440 case INITIALIZER_STRING:
2441 size = result->string.string.size;
2444 case INITIALIZER_WIDE_STRING:
2445 size = result->wide_string.string.size;
2448 case INITIALIZER_DESIGNATOR:
2449 case INITIALIZER_VALUE:
2450 /* can happen for parse errors */
2455 internal_errorf(HERE, "invalid initializer type");
2458 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
2459 cnst->base.type = type_size_t;
2460 cnst->conste.v.int_value = size;
2462 type_t *new_type = duplicate_type(type);
2464 new_type->array.size_expression = cnst;
2465 new_type->array.size_constant = true;
2466 new_type->array.has_implicit_size = true;
2467 new_type->array.size = size;
2468 env->type = new_type;
2476 static void append_entity(scope_t *scope, entity_t *entity)
2478 if (scope->last_entity != NULL) {
2479 scope->last_entity->base.next = entity;
2481 scope->entities = entity;
2483 entity->base.parent_entity = current_entity;
2484 scope->last_entity = entity;
2488 static compound_t *parse_compound_type_specifier(bool is_struct)
2490 eat(is_struct ? T_struct : T_union);
2492 symbol_t *symbol = NULL;
2493 compound_t *compound = NULL;
2494 attribute_t *attributes = NULL;
2496 if (token.type == T___attribute__) {
2497 attributes = parse_attributes(NULL);
2500 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2501 if (token.type == T_IDENTIFIER) {
2502 /* the compound has a name, check if we have seen it already */
2503 symbol = token.v.symbol;
2506 entity_t *entity = get_tag(symbol, kind);
2507 if (entity != NULL) {
2508 compound = &entity->compound;
2509 if (compound->base.parent_scope != current_scope &&
2510 (token.type == '{' || token.type == ';')) {
2511 /* we're in an inner scope and have a definition. Shadow
2512 * existing definition in outer scope */
2514 } else if (compound->complete && token.type == '{') {
2515 assert(symbol != NULL);
2516 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2517 is_struct ? "struct" : "union", symbol,
2518 &compound->base.source_position);
2519 /* clear members in the hope to avoid further errors */
2520 compound->members.entities = NULL;
2523 } else if (token.type != '{') {
2525 parse_error_expected("while parsing struct type specifier",
2526 T_IDENTIFIER, '{', NULL);
2528 parse_error_expected("while parsing union type specifier",
2529 T_IDENTIFIER, '{', NULL);
2535 if (compound == NULL) {
2536 entity_t *entity = allocate_entity_zero(kind);
2537 compound = &entity->compound;
2539 compound->alignment = 1;
2540 compound->base.namespc = NAMESPACE_TAG;
2541 compound->base.source_position = token.source_position;
2542 compound->base.symbol = symbol;
2543 compound->base.parent_scope = current_scope;
2544 if (symbol != NULL) {
2545 environment_push(entity);
2547 append_entity(current_scope, entity);
2550 if (token.type == '{') {
2551 parse_compound_type_entries(compound);
2553 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2554 if (symbol == NULL) {
2555 assert(anonymous_entity == NULL);
2556 anonymous_entity = (entity_t*)compound;
2560 if (attributes != NULL) {
2561 handle_entity_attributes(attributes, (entity_t*) compound);
2567 static void parse_enum_entries(type_t *const enum_type)
2571 if (token.type == '}') {
2572 errorf(HERE, "empty enum not allowed");
2577 add_anchor_token('}');
2579 if (token.type != T_IDENTIFIER) {
2580 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2582 rem_anchor_token('}');
2586 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2587 entity->enum_value.enum_type = enum_type;
2588 entity->base.symbol = token.v.symbol;
2589 entity->base.source_position = token.source_position;
2593 expression_t *value = parse_constant_expression();
2595 value = create_implicit_cast(value, enum_type);
2596 entity->enum_value.value = value;
2601 record_entity(entity, false);
2602 } while (next_if(',') && token.type != '}');
2603 rem_anchor_token('}');
2605 expect('}', end_error);
2611 static type_t *parse_enum_specifier(void)
2617 switch (token.type) {
2619 symbol = token.v.symbol;
2622 entity = get_tag(symbol, ENTITY_ENUM);
2623 if (entity != NULL) {
2624 if (entity->base.parent_scope != current_scope &&
2625 (token.type == '{' || token.type == ';')) {
2626 /* we're in an inner scope and have a definition. Shadow
2627 * existing definition in outer scope */
2629 } else if (entity->enume.complete && token.type == '{') {
2630 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2631 symbol, &entity->base.source_position);
2642 parse_error_expected("while parsing enum type specifier",
2643 T_IDENTIFIER, '{', NULL);
2647 if (entity == NULL) {
2648 entity = allocate_entity_zero(ENTITY_ENUM);
2649 entity->base.namespc = NAMESPACE_TAG;
2650 entity->base.source_position = token.source_position;
2651 entity->base.symbol = symbol;
2652 entity->base.parent_scope = current_scope;
2655 type_t *const type = allocate_type_zero(TYPE_ENUM);
2656 type->enumt.enume = &entity->enume;
2657 type->enumt.akind = ATOMIC_TYPE_INT;
2659 if (token.type == '{') {
2660 if (symbol != NULL) {
2661 environment_push(entity);
2663 append_entity(current_scope, entity);
2664 entity->enume.complete = true;
2666 parse_enum_entries(type);
2667 parse_attributes(NULL);
2669 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2670 if (symbol == NULL) {
2671 assert(anonymous_entity == NULL);
2672 anonymous_entity = entity;
2674 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2675 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2683 * if a symbol is a typedef to another type, return true
2685 static bool is_typedef_symbol(symbol_t *symbol)
2687 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2688 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2691 static type_t *parse_typeof(void)
2697 expect('(', end_error);
2698 add_anchor_token(')');
2700 expression_t *expression = NULL;
2702 bool old_type_prop = in_type_prop;
2703 bool old_gcc_extension = in_gcc_extension;
2704 in_type_prop = true;
2706 while (next_if(T___extension__)) {
2707 /* This can be a prefix to a typename or an expression. */
2708 in_gcc_extension = true;
2710 switch (token.type) {
2712 if (is_typedef_symbol(token.v.symbol)) {
2713 type = parse_typename();
2715 expression = parse_expression();
2716 type = revert_automatic_type_conversion(expression);
2721 type = parse_typename();
2725 expression = parse_expression();
2726 type = expression->base.type;
2729 in_type_prop = old_type_prop;
2730 in_gcc_extension = old_gcc_extension;
2732 rem_anchor_token(')');
2733 expect(')', end_error);
2735 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2736 typeof_type->typeoft.expression = expression;
2737 typeof_type->typeoft.typeof_type = type;
2744 typedef enum specifiers_t {
2745 SPECIFIER_SIGNED = 1 << 0,
2746 SPECIFIER_UNSIGNED = 1 << 1,
2747 SPECIFIER_LONG = 1 << 2,
2748 SPECIFIER_INT = 1 << 3,
2749 SPECIFIER_DOUBLE = 1 << 4,
2750 SPECIFIER_CHAR = 1 << 5,
2751 SPECIFIER_WCHAR_T = 1 << 6,
2752 SPECIFIER_SHORT = 1 << 7,
2753 SPECIFIER_LONG_LONG = 1 << 8,
2754 SPECIFIER_FLOAT = 1 << 9,
2755 SPECIFIER_BOOL = 1 << 10,
2756 SPECIFIER_VOID = 1 << 11,
2757 SPECIFIER_INT8 = 1 << 12,
2758 SPECIFIER_INT16 = 1 << 13,
2759 SPECIFIER_INT32 = 1 << 14,
2760 SPECIFIER_INT64 = 1 << 15,
2761 SPECIFIER_INT128 = 1 << 16,
2762 SPECIFIER_COMPLEX = 1 << 17,
2763 SPECIFIER_IMAGINARY = 1 << 18,
2766 static type_t *create_builtin_type(symbol_t *const symbol,
2767 type_t *const real_type)
2769 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2770 type->builtin.symbol = symbol;
2771 type->builtin.real_type = real_type;
2772 return identify_new_type(type);
2775 static type_t *get_typedef_type(symbol_t *symbol)
2777 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2778 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2781 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2782 type->typedeft.typedefe = &entity->typedefe;
2787 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2789 expect('(', end_error);
2791 attribute_property_argument_t *property
2792 = allocate_ast_zero(sizeof(*property));
2795 if (token.type != T_IDENTIFIER) {
2796 parse_error_expected("while parsing property declspec",
2797 T_IDENTIFIER, NULL);
2802 symbol_t *symbol = token.v.symbol;
2804 if (strcmp(symbol->string, "put") == 0) {
2806 } else if (strcmp(symbol->string, "get") == 0) {
2809 errorf(HERE, "expected put or get in property declspec");
2812 expect('=', end_error);
2813 if (token.type != T_IDENTIFIER) {
2814 parse_error_expected("while parsing property declspec",
2815 T_IDENTIFIER, NULL);
2819 property->put_symbol = token.v.symbol;
2821 property->get_symbol = token.v.symbol;
2824 } while (next_if(','));
2826 attribute->a.property = property;
2828 expect(')', end_error);
2834 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2836 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2837 if (next_if(T_restrict)) {
2838 kind = ATTRIBUTE_MS_RESTRICT;
2839 } else if (token.type == T_IDENTIFIER) {
2840 const char *name = token.v.symbol->string;
2842 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2844 const char *attribute_name = get_attribute_name(k);
2845 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2851 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2852 warningf(HERE, "unknown __declspec '%s' ignored", name);
2855 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2859 attribute_t *attribute = allocate_attribute_zero(kind);
2861 if (kind == ATTRIBUTE_MS_PROPERTY) {
2862 return parse_attribute_ms_property(attribute);
2865 /* parse arguments */
2867 attribute->a.arguments = parse_attribute_arguments();
2872 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2876 expect('(', end_error);
2881 add_anchor_token(')');
2883 attribute_t **anchor = &first;
2885 while (*anchor != NULL)
2886 anchor = &(*anchor)->next;
2888 attribute_t *attribute
2889 = parse_microsoft_extended_decl_modifier_single();
2890 if (attribute == NULL)
2893 *anchor = attribute;
2894 anchor = &attribute->next;
2895 } while (next_if(','));
2897 rem_anchor_token(')');
2898 expect(')', end_error);
2902 rem_anchor_token(')');
2906 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2908 entity_t *entity = allocate_entity_zero(kind);
2909 entity->base.source_position = *HERE;
2910 entity->base.symbol = symbol;
2911 if (is_declaration(entity)) {
2912 entity->declaration.type = type_error_type;
2913 entity->declaration.implicit = true;
2914 } else if (kind == ENTITY_TYPEDEF) {
2915 entity->typedefe.type = type_error_type;
2916 entity->typedefe.builtin = true;
2918 if (kind != ENTITY_COMPOUND_MEMBER)
2919 record_entity(entity, false);
2923 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2925 type_t *type = NULL;
2926 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2927 unsigned type_specifiers = 0;
2928 bool newtype = false;
2929 bool saw_error = false;
2930 bool old_gcc_extension = in_gcc_extension;
2932 specifiers->source_position = token.source_position;
2935 specifiers->attributes = parse_attributes(specifiers->attributes);
2937 switch (token.type) {
2939 #define MATCH_STORAGE_CLASS(token, class) \
2941 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2942 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2944 specifiers->storage_class = class; \
2945 if (specifiers->thread_local) \
2946 goto check_thread_storage_class; \
2950 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2951 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2952 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2953 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2954 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2957 specifiers->attributes
2958 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2962 if (specifiers->thread_local) {
2963 errorf(HERE, "duplicate '__thread'");
2965 specifiers->thread_local = true;
2966 check_thread_storage_class:
2967 switch (specifiers->storage_class) {
2968 case STORAGE_CLASS_EXTERN:
2969 case STORAGE_CLASS_NONE:
2970 case STORAGE_CLASS_STATIC:
2974 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2975 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2976 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2977 wrong_thread_stoarge_class:
2978 errorf(HERE, "'__thread' used with '%s'", wrong);
2985 /* type qualifiers */
2986 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2988 qualifiers |= qualifier; \
2992 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2993 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2994 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2995 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2996 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2997 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2998 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2999 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3001 case T___extension__:
3003 in_gcc_extension = true;
3006 /* type specifiers */
3007 #define MATCH_SPECIFIER(token, specifier, name) \
3009 if (type_specifiers & specifier) { \
3010 errorf(HERE, "multiple " name " type specifiers given"); \
3012 type_specifiers |= specifier; \
3017 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
3018 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
3019 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
3020 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
3021 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
3022 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
3023 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
3024 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
3025 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
3026 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
3027 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
3028 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
3029 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
3030 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
3031 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
3032 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
3033 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
3034 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
3038 specifiers->is_inline = true;
3042 case T__forceinline:
3044 specifiers->modifiers |= DM_FORCEINLINE;
3049 if (type_specifiers & SPECIFIER_LONG_LONG) {
3050 errorf(HERE, "multiple type specifiers given");
3051 } else if (type_specifiers & SPECIFIER_LONG) {
3052 type_specifiers |= SPECIFIER_LONG_LONG;
3054 type_specifiers |= SPECIFIER_LONG;
3059 #define CHECK_DOUBLE_TYPE() \
3060 if ( type != NULL) \
3061 errorf(HERE, "multiple data types in declaration specifiers");
3064 CHECK_DOUBLE_TYPE();
3065 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
3067 type->compound.compound = parse_compound_type_specifier(true);
3070 CHECK_DOUBLE_TYPE();
3071 type = allocate_type_zero(TYPE_COMPOUND_UNION);
3072 type->compound.compound = parse_compound_type_specifier(false);
3075 CHECK_DOUBLE_TYPE();
3076 type = parse_enum_specifier();
3079 CHECK_DOUBLE_TYPE();
3080 type = parse_typeof();
3082 case T___builtin_va_list:
3083 CHECK_DOUBLE_TYPE();
3084 type = duplicate_type(type_valist);
3088 case T_IDENTIFIER: {
3089 /* only parse identifier if we haven't found a type yet */
3090 if (type != NULL || type_specifiers != 0) {
3091 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3092 * declaration, so it doesn't generate errors about expecting '(' or
3094 switch (look_ahead(1)->type) {
3101 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3105 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3110 goto finish_specifiers;
3114 type_t *const typedef_type = get_typedef_type(token.v.symbol);
3115 if (typedef_type == NULL) {
3116 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3117 * declaration, so it doesn't generate 'implicit int' followed by more
3118 * errors later on. */
3119 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3125 errorf(HERE, "%K does not name a type", &token);
3128 create_error_entity(token.v.symbol, ENTITY_TYPEDEF);
3130 type = allocate_type_zero(TYPE_TYPEDEF);
3131 type->typedeft.typedefe = &entity->typedefe;
3135 if (la1_type == '&' || la1_type == '*')
3136 goto finish_specifiers;
3141 goto finish_specifiers;
3146 type = typedef_type;
3150 /* function specifier */
3152 goto finish_specifiers;
3157 specifiers->attributes = parse_attributes(specifiers->attributes);
3159 in_gcc_extension = old_gcc_extension;
3161 if (type == NULL || (saw_error && type_specifiers != 0)) {
3162 atomic_type_kind_t atomic_type;
3164 /* match valid basic types */
3165 switch (type_specifiers) {
3166 case SPECIFIER_VOID:
3167 atomic_type = ATOMIC_TYPE_VOID;
3169 case SPECIFIER_WCHAR_T:
3170 atomic_type = ATOMIC_TYPE_WCHAR_T;
3172 case SPECIFIER_CHAR:
3173 atomic_type = ATOMIC_TYPE_CHAR;
3175 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3176 atomic_type = ATOMIC_TYPE_SCHAR;
3178 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3179 atomic_type = ATOMIC_TYPE_UCHAR;
3181 case SPECIFIER_SHORT:
3182 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3183 case SPECIFIER_SHORT | SPECIFIER_INT:
3184 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3185 atomic_type = ATOMIC_TYPE_SHORT;
3187 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3188 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3189 atomic_type = ATOMIC_TYPE_USHORT;
3192 case SPECIFIER_SIGNED:
3193 case SPECIFIER_SIGNED | SPECIFIER_INT:
3194 atomic_type = ATOMIC_TYPE_INT;
3196 case SPECIFIER_UNSIGNED:
3197 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3198 atomic_type = ATOMIC_TYPE_UINT;
3200 case SPECIFIER_LONG:
3201 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3202 case SPECIFIER_LONG | SPECIFIER_INT:
3203 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3204 atomic_type = ATOMIC_TYPE_LONG;
3206 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3207 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3208 atomic_type = ATOMIC_TYPE_ULONG;
3211 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3212 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3213 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3214 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3216 atomic_type = ATOMIC_TYPE_LONGLONG;
3217 goto warn_about_long_long;
3219 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3220 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3222 atomic_type = ATOMIC_TYPE_ULONGLONG;
3223 warn_about_long_long:
3224 if (warning.long_long) {
3225 warningf(&specifiers->source_position,
3226 "ISO C90 does not support 'long long'");
3230 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3231 atomic_type = unsigned_int8_type_kind;
3234 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3235 atomic_type = unsigned_int16_type_kind;
3238 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3239 atomic_type = unsigned_int32_type_kind;
3242 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3243 atomic_type = unsigned_int64_type_kind;
3246 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3247 atomic_type = unsigned_int128_type_kind;
3250 case SPECIFIER_INT8:
3251 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3252 atomic_type = int8_type_kind;
3255 case SPECIFIER_INT16:
3256 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3257 atomic_type = int16_type_kind;
3260 case SPECIFIER_INT32:
3261 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3262 atomic_type = int32_type_kind;
3265 case SPECIFIER_INT64:
3266 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3267 atomic_type = int64_type_kind;
3270 case SPECIFIER_INT128:
3271 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3272 atomic_type = int128_type_kind;
3275 case SPECIFIER_FLOAT:
3276 atomic_type = ATOMIC_TYPE_FLOAT;
3278 case SPECIFIER_DOUBLE:
3279 atomic_type = ATOMIC_TYPE_DOUBLE;
3281 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3282 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3284 case SPECIFIER_BOOL:
3285 atomic_type = ATOMIC_TYPE_BOOL;
3287 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3288 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3289 atomic_type = ATOMIC_TYPE_FLOAT;
3291 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3292 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3293 atomic_type = ATOMIC_TYPE_DOUBLE;
3295 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3296 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3297 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3300 /* invalid specifier combination, give an error message */
3301 if (type_specifiers == 0) {
3305 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3306 if (!(c_mode & _CXX) && !strict_mode) {
3307 if (warning.implicit_int) {
3308 warningf(HERE, "no type specifiers in declaration, using 'int'");
3310 atomic_type = ATOMIC_TYPE_INT;
3313 errorf(HERE, "no type specifiers given in declaration");
3315 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3316 (type_specifiers & SPECIFIER_UNSIGNED)) {
3317 errorf(HERE, "signed and unsigned specifiers given");
3318 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3319 errorf(HERE, "only integer types can be signed or unsigned");
3321 errorf(HERE, "multiple datatypes in declaration");
3326 if (type_specifiers & SPECIFIER_COMPLEX) {
3327 type = allocate_type_zero(TYPE_COMPLEX);
3328 type->complex.akind = atomic_type;
3329 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3330 type = allocate_type_zero(TYPE_IMAGINARY);
3331 type->imaginary.akind = atomic_type;
3333 type = allocate_type_zero(TYPE_ATOMIC);
3334 type->atomic.akind = atomic_type;
3337 } else if (type_specifiers != 0) {
3338 errorf(HERE, "multiple datatypes in declaration");
3341 /* FIXME: check type qualifiers here */
3342 type->base.qualifiers = qualifiers;
3345 type = identify_new_type(type);
3347 type = typehash_insert(type);
3350 if (specifiers->attributes != NULL)
3351 type = handle_type_attributes(specifiers->attributes, type);
3352 specifiers->type = type;
3356 specifiers->type = type_error_type;
3359 static type_qualifiers_t parse_type_qualifiers(void)
3361 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3364 switch (token.type) {
3365 /* type qualifiers */
3366 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3367 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3368 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3369 /* microsoft extended type modifiers */
3370 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3371 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3372 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3373 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3374 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3383 * Parses an K&R identifier list
3385 static void parse_identifier_list(scope_t *scope)
3388 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3389 entity->base.source_position = token.source_position;
3390 entity->base.namespc = NAMESPACE_NORMAL;
3391 entity->base.symbol = token.v.symbol;
3392 /* a K&R parameter has no type, yet */
3396 append_entity(scope, entity);
3397 } while (next_if(',') && token.type == T_IDENTIFIER);
3400 static entity_t *parse_parameter(void)
3402 declaration_specifiers_t specifiers;
3403 memset(&specifiers, 0, sizeof(specifiers));
3405 parse_declaration_specifiers(&specifiers);
3407 entity_t *entity = parse_declarator(&specifiers,
3408 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3409 anonymous_entity = NULL;
3413 static void semantic_parameter_incomplete(const entity_t *entity)
3415 assert(entity->kind == ENTITY_PARAMETER);
3417 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3418 * list in a function declarator that is part of a
3419 * definition of that function shall not have
3420 * incomplete type. */
3421 type_t *type = skip_typeref(entity->declaration.type);
3422 if (is_type_incomplete(type)) {
3423 errorf(&entity->base.source_position,
3424 "parameter '%#T' has incomplete type",
3425 entity->declaration.type, entity->base.symbol);
3429 static bool has_parameters(void)
3431 /* func(void) is not a parameter */
3432 if (token.type == T_IDENTIFIER) {
3433 entity_t const *const entity = get_entity(token.v.symbol, NAMESPACE_NORMAL);
3436 if (entity->kind != ENTITY_TYPEDEF)
3438 if (skip_typeref(entity->typedefe.type) != type_void)
3440 } else if (token.type != T_void) {
3443 if (look_ahead(1)->type != ')')
3450 * Parses function type parameters (and optionally creates variable_t entities
3451 * for them in a scope)
3453 static void parse_parameters(function_type_t *type, scope_t *scope)
3456 add_anchor_token(')');
3457 int saved_comma_state = save_and_reset_anchor_state(',');
3459 if (token.type == T_IDENTIFIER &&
3460 !is_typedef_symbol(token.v.symbol)) {
3461 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3462 if (la1_type == ',' || la1_type == ')') {
3463 type->kr_style_parameters = true;
3464 parse_identifier_list(scope);
3465 goto parameters_finished;
3469 if (token.type == ')') {
3470 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3471 if (!(c_mode & _CXX))
3472 type->unspecified_parameters = true;
3473 goto parameters_finished;
3476 if (has_parameters()) {
3477 function_parameter_t **anchor = &type->parameters;
3479 switch (token.type) {
3482 type->variadic = true;
3483 goto parameters_finished;
3486 case T___extension__:
3489 entity_t *entity = parse_parameter();
3490 if (entity->kind == ENTITY_TYPEDEF) {
3491 errorf(&entity->base.source_position,
3492 "typedef not allowed as function parameter");
3495 assert(is_declaration(entity));
3497 semantic_parameter_incomplete(entity);
3499 function_parameter_t *const parameter =
3500 allocate_parameter(entity->declaration.type);
3502 if (scope != NULL) {
3503 append_entity(scope, entity);
3506 *anchor = parameter;
3507 anchor = ¶meter->next;
3512 goto parameters_finished;
3514 } while (next_if(','));
3518 parameters_finished:
3519 rem_anchor_token(')');
3520 expect(')', end_error);
3523 restore_anchor_state(',', saved_comma_state);
3526 typedef enum construct_type_kind_t {
3529 CONSTRUCT_REFERENCE,
3532 } construct_type_kind_t;
3534 typedef union construct_type_t construct_type_t;
3536 typedef struct construct_type_base_t {
3537 construct_type_kind_t kind;
3538 construct_type_t *next;
3539 } construct_type_base_t;
3541 typedef struct parsed_pointer_t {
3542 construct_type_base_t base;
3543 type_qualifiers_t type_qualifiers;
3544 variable_t *base_variable; /**< MS __based extension. */
3547 typedef struct parsed_reference_t {
3548 construct_type_base_t base;
3549 } parsed_reference_t;
3551 typedef struct construct_function_type_t {
3552 construct_type_base_t base;
3553 type_t *function_type;
3554 } construct_function_type_t;
3556 typedef struct parsed_array_t {
3557 construct_type_base_t base;
3558 type_qualifiers_t type_qualifiers;
3564 union construct_type_t {
3565 construct_type_kind_t kind;
3566 construct_type_base_t base;
3567 parsed_pointer_t pointer;
3568 parsed_reference_t reference;
3569 construct_function_type_t function;
3570 parsed_array_t array;
3573 static construct_type_t *parse_pointer_declarator(void)
3577 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3578 memset(pointer, 0, sizeof(pointer[0]));
3579 pointer->base.kind = CONSTRUCT_POINTER;
3580 pointer->type_qualifiers = parse_type_qualifiers();
3581 //pointer->base_variable = base_variable;
3583 return (construct_type_t*) pointer;
3586 static construct_type_t *parse_reference_declarator(void)
3590 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3591 parsed_reference_t *reference = &cons->reference;
3592 memset(reference, 0, sizeof(*reference));
3593 cons->kind = CONSTRUCT_REFERENCE;
3598 static construct_type_t *parse_array_declarator(void)
3601 add_anchor_token(']');
3603 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3604 parsed_array_t *array = &cons->array;
3605 memset(array, 0, sizeof(*array));
3606 cons->kind = CONSTRUCT_ARRAY;
3608 if (next_if(T_static))
3609 array->is_static = true;
3611 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3612 if (type_qualifiers != 0 && next_if(T_static))
3613 array->is_static = true;
3614 array->type_qualifiers = type_qualifiers;
3616 if (token.type == '*' && look_ahead(1)->type == ']') {
3617 array->is_variable = true;
3619 } else if (token.type != ']') {
3620 expression_t *const size = parse_assignment_expression();
3622 /* §6.7.5.2:1 Array size must have integer type */
3623 type_t *const orig_type = size->base.type;
3624 type_t *const type = skip_typeref(orig_type);
3625 if (!is_type_integer(type) && is_type_valid(type)) {
3626 errorf(&size->base.source_position,
3627 "array size '%E' must have integer type but has type '%T'",
3632 mark_vars_read(size, NULL);
3635 rem_anchor_token(']');
3636 expect(']', end_error);
3642 static construct_type_t *parse_function_declarator(scope_t *scope)
3644 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3645 function_type_t *ftype = &type->function;
3647 ftype->linkage = current_linkage;
3648 ftype->calling_convention = CC_DEFAULT;
3650 parse_parameters(ftype, scope);
3652 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3653 construct_function_type_t *function = &cons->function;
3654 memset(function, 0, sizeof(*function));
3655 cons->kind = CONSTRUCT_FUNCTION;
3656 function->function_type = type;
3661 typedef struct parse_declarator_env_t {
3662 bool may_be_abstract : 1;
3663 bool must_be_abstract : 1;
3664 decl_modifiers_t modifiers;
3666 source_position_t source_position;
3668 attribute_t *attributes;
3669 } parse_declarator_env_t;
3671 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3673 /* construct a single linked list of construct_type_t's which describe
3674 * how to construct the final declarator type */
3675 construct_type_t *first = NULL;
3676 construct_type_t **anchor = &first;
3678 env->attributes = parse_attributes(env->attributes);
3681 construct_type_t *type;
3682 //variable_t *based = NULL; /* MS __based extension */
3683 switch (token.type) {
3685 if (!(c_mode & _CXX))
3686 errorf(HERE, "references are only available for C++");
3687 type = parse_reference_declarator();
3691 panic("based not supported anymore");
3696 type = parse_pointer_declarator();
3700 goto ptr_operator_end;
3704 anchor = &type->base.next;
3706 /* TODO: find out if this is correct */
3707 env->attributes = parse_attributes(env->attributes);
3711 construct_type_t *inner_types = NULL;
3713 switch (token.type) {
3715 if (env->must_be_abstract) {
3716 errorf(HERE, "no identifier expected in typename");
3718 env->symbol = token.v.symbol;
3719 env->source_position = token.source_position;
3724 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3725 * interpreted as ``function with no parameter specification'', rather
3726 * than redundant parentheses around the omitted identifier. */
3727 if (look_ahead(1)->type != ')') {
3729 add_anchor_token(')');
3730 inner_types = parse_inner_declarator(env);
3731 if (inner_types != NULL) {
3732 /* All later declarators only modify the return type */
3733 env->must_be_abstract = true;
3735 rem_anchor_token(')');
3736 expect(')', end_error);
3740 if (env->may_be_abstract)
3742 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3747 construct_type_t **const p = anchor;
3750 construct_type_t *type;
3751 switch (token.type) {
3753 scope_t *scope = NULL;
3754 if (!env->must_be_abstract) {
3755 scope = &env->parameters;
3758 type = parse_function_declarator(scope);
3762 type = parse_array_declarator();
3765 goto declarator_finished;
3768 /* insert in the middle of the list (at p) */
3769 type->base.next = *p;
3772 anchor = &type->base.next;
3775 declarator_finished:
3776 /* append inner_types at the end of the list, we don't to set anchor anymore
3777 * as it's not needed anymore */
3778 *anchor = inner_types;
3785 static type_t *construct_declarator_type(construct_type_t *construct_list,
3788 construct_type_t *iter = construct_list;
3789 for (; iter != NULL; iter = iter->base.next) {
3790 switch (iter->kind) {
3791 case CONSTRUCT_INVALID:
3793 case CONSTRUCT_FUNCTION: {
3794 construct_function_type_t *function = &iter->function;
3795 type_t *function_type = function->function_type;
3797 function_type->function.return_type = type;
3799 type_t *skipped_return_type = skip_typeref(type);
3801 if (is_type_function(skipped_return_type)) {
3802 errorf(HERE, "function returning function is not allowed");
3803 } else if (is_type_array(skipped_return_type)) {
3804 errorf(HERE, "function returning array is not allowed");
3806 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3808 "type qualifiers in return type of function type are meaningless");
3812 /* The function type was constructed earlier. Freeing it here will
3813 * destroy other types. */
3814 type = typehash_insert(function_type);
3818 case CONSTRUCT_POINTER: {
3819 if (is_type_reference(skip_typeref(type)))
3820 errorf(HERE, "cannot declare a pointer to reference");
3822 parsed_pointer_t *pointer = &iter->pointer;
3823 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3827 case CONSTRUCT_REFERENCE:
3828 if (is_type_reference(skip_typeref(type)))
3829 errorf(HERE, "cannot declare a reference to reference");
3831 type = make_reference_type(type);
3834 case CONSTRUCT_ARRAY: {
3835 if (is_type_reference(skip_typeref(type)))
3836 errorf(HERE, "cannot declare an array of references");
3838 parsed_array_t *array = &iter->array;
3839 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3841 expression_t *size_expression = array->size;
3842 if (size_expression != NULL) {
3844 = create_implicit_cast(size_expression, type_size_t);
3847 array_type->base.qualifiers = array->type_qualifiers;
3848 array_type->array.element_type = type;
3849 array_type->array.is_static = array->is_static;
3850 array_type->array.is_variable = array->is_variable;
3851 array_type->array.size_expression = size_expression;
3853 if (size_expression != NULL) {
3854 if (is_constant_expression(size_expression)) {
3856 = fold_constant_to_int(size_expression);
3857 array_type->array.size = size;
3858 array_type->array.size_constant = true;
3859 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3860 * have a value greater than zero. */
3862 if (size < 0 || !GNU_MODE) {
3863 errorf(&size_expression->base.source_position,
3864 "size of array must be greater than zero");
3865 } else if (warning.other) {
3866 warningf(&size_expression->base.source_position,
3867 "zero length arrays are a GCC extension");
3871 array_type->array.is_vla = true;
3875 type_t *skipped_type = skip_typeref(type);
3877 if (is_type_incomplete(skipped_type)) {
3878 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3879 } else if (is_type_function(skipped_type)) {
3880 errorf(HERE, "array of functions is not allowed");
3882 type = identify_new_type(array_type);
3886 internal_errorf(HERE, "invalid type construction found");
3892 static type_t *automatic_type_conversion(type_t *orig_type);
3894 static type_t *semantic_parameter(const source_position_t *pos,
3896 const declaration_specifiers_t *specifiers,
3899 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3900 * shall be adjusted to ``qualified pointer to type'',
3902 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3903 * type'' shall be adjusted to ``pointer to function
3904 * returning type'', as in 6.3.2.1. */
3905 type = automatic_type_conversion(type);
3907 if (specifiers->is_inline && is_type_valid(type)) {
3908 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3911 /* §6.9.1:6 The declarations in the declaration list shall contain
3912 * no storage-class specifier other than register and no
3913 * initializations. */
3914 if (specifiers->thread_local || (
3915 specifiers->storage_class != STORAGE_CLASS_NONE &&
3916 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3918 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3921 /* delay test for incomplete type, because we might have (void)
3922 * which is legal but incomplete... */
3927 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3928 declarator_flags_t flags)
3930 parse_declarator_env_t env;
3931 memset(&env, 0, sizeof(env));
3932 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3934 construct_type_t *construct_type = parse_inner_declarator(&env);
3936 construct_declarator_type(construct_type, specifiers->type);
3937 type_t *type = skip_typeref(orig_type);
3939 if (construct_type != NULL) {
3940 obstack_free(&temp_obst, construct_type);
3943 attribute_t *attributes = parse_attributes(env.attributes);
3944 /* append (shared) specifier attribute behind attributes of this
3946 attribute_t **anchor = &attributes;
3947 while (*anchor != NULL)
3948 anchor = &(*anchor)->next;
3949 *anchor = specifiers->attributes;
3952 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3953 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3954 entity->base.symbol = env.symbol;
3955 entity->base.source_position = env.source_position;
3956 entity->typedefe.type = orig_type;
3958 if (anonymous_entity != NULL) {
3959 if (is_type_compound(type)) {
3960 assert(anonymous_entity->compound.alias == NULL);
3961 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3962 anonymous_entity->kind == ENTITY_UNION);
3963 anonymous_entity->compound.alias = entity;
3964 anonymous_entity = NULL;
3965 } else if (is_type_enum(type)) {
3966 assert(anonymous_entity->enume.alias == NULL);
3967 assert(anonymous_entity->kind == ENTITY_ENUM);
3968 anonymous_entity->enume.alias = entity;
3969 anonymous_entity = NULL;
3973 /* create a declaration type entity */
3974 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3975 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3977 if (env.symbol != NULL) {
3978 if (specifiers->is_inline && is_type_valid(type)) {
3979 errorf(&env.source_position,
3980 "compound member '%Y' declared 'inline'", env.symbol);
3983 if (specifiers->thread_local ||
3984 specifiers->storage_class != STORAGE_CLASS_NONE) {
3985 errorf(&env.source_position,
3986 "compound member '%Y' must have no storage class",
3990 } else if (flags & DECL_IS_PARAMETER) {
3991 orig_type = semantic_parameter(&env.source_position, orig_type,
3992 specifiers, env.symbol);
3994 entity = allocate_entity_zero(ENTITY_PARAMETER);
3995 } else if (is_type_function(type)) {
3996 entity = allocate_entity_zero(ENTITY_FUNCTION);
3998 entity->function.is_inline = specifiers->is_inline;
3999 entity->function.parameters = env.parameters;
4001 if (env.symbol != NULL) {
4002 /* this needs fixes for C++ */
4003 bool in_function_scope = current_function != NULL;
4005 if (specifiers->thread_local || (
4006 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4007 specifiers->storage_class != STORAGE_CLASS_NONE &&
4008 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
4010 errorf(&env.source_position,
4011 "invalid storage class for function '%Y'", env.symbol);
4015 entity = allocate_entity_zero(ENTITY_VARIABLE);
4017 entity->variable.thread_local = specifiers->thread_local;
4019 if (env.symbol != NULL) {
4020 if (specifiers->is_inline && is_type_valid(type)) {
4021 errorf(&env.source_position,
4022 "variable '%Y' declared 'inline'", env.symbol);
4025 bool invalid_storage_class = false;
4026 if (current_scope == file_scope) {
4027 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
4028 specifiers->storage_class != STORAGE_CLASS_NONE &&
4029 specifiers->storage_class != STORAGE_CLASS_STATIC) {
4030 invalid_storage_class = true;
4033 if (specifiers->thread_local &&
4034 specifiers->storage_class == STORAGE_CLASS_NONE) {
4035 invalid_storage_class = true;
4038 if (invalid_storage_class) {
4039 errorf(&env.source_position,
4040 "invalid storage class for variable '%Y'", env.symbol);
4045 if (env.symbol != NULL) {
4046 entity->base.symbol = env.symbol;
4047 entity->base.source_position = env.source_position;
4049 entity->base.source_position = specifiers->source_position;
4051 entity->base.namespc = NAMESPACE_NORMAL;
4052 entity->declaration.type = orig_type;
4053 entity->declaration.alignment = get_type_alignment(orig_type);
4054 entity->declaration.modifiers = env.modifiers;
4055 entity->declaration.attributes = attributes;
4057 storage_class_t storage_class = specifiers->storage_class;
4058 entity->declaration.declared_storage_class = storage_class;
4060 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4061 storage_class = STORAGE_CLASS_AUTO;
4062 entity->declaration.storage_class = storage_class;
4065 if (attributes != NULL) {
4066 handle_entity_attributes(attributes, entity);
4072 static type_t *parse_abstract_declarator(type_t *base_type)
4074 parse_declarator_env_t env;
4075 memset(&env, 0, sizeof(env));
4076 env.may_be_abstract = true;
4077 env.must_be_abstract = true;
4079 construct_type_t *construct_type = parse_inner_declarator(&env);
4081 type_t *result = construct_declarator_type(construct_type, base_type);
4082 if (construct_type != NULL) {
4083 obstack_free(&temp_obst, construct_type);
4085 result = handle_type_attributes(env.attributes, result);
4091 * Check if the declaration of main is suspicious. main should be a
4092 * function with external linkage, returning int, taking either zero
4093 * arguments, two, or three arguments of appropriate types, ie.
4095 * int main([ int argc, char **argv [, char **env ] ]).
4097 * @param decl the declaration to check
4098 * @param type the function type of the declaration
4100 static void check_main(const entity_t *entity)
4102 const source_position_t *pos = &entity->base.source_position;
4103 if (entity->kind != ENTITY_FUNCTION) {
4104 warningf(pos, "'main' is not a function");
4108 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4109 warningf(pos, "'main' is normally a non-static function");
4112 type_t *type = skip_typeref(entity->declaration.type);
4113 assert(is_type_function(type));
4115 function_type_t *func_type = &type->function;
4116 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4117 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4118 func_type->return_type);
4120 const function_parameter_t *parm = func_type->parameters;
4122 type_t *const first_type = parm->type;
4123 if (!types_compatible(skip_typeref(first_type), type_int)) {
4125 "first argument of 'main' should be 'int', but is '%T'",
4130 type_t *const second_type = parm->type;
4131 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4132 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4136 type_t *const third_type = parm->type;
4137 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4138 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4142 goto warn_arg_count;
4146 warningf(pos, "'main' takes only zero, two or three arguments");
4152 * Check if a symbol is the equal to "main".
4154 static bool is_sym_main(const symbol_t *const sym)
4156 return strcmp(sym->string, "main") == 0;
4159 static void error_redefined_as_different_kind(const source_position_t *pos,
4160 const entity_t *old, entity_kind_t new_kind)
4162 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4163 get_entity_kind_name(old->kind), old->base.symbol,
4164 get_entity_kind_name(new_kind), &old->base.source_position);
4167 static bool is_error_entity(entity_t *const ent)
4169 if (is_declaration(ent)) {
4170 return is_type_valid(skip_typeref(ent->declaration.type));
4171 } else if (ent->kind == ENTITY_TYPEDEF) {
4172 return is_type_valid(skip_typeref(ent->typedefe.type));
4177 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4179 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4180 if (attributes_equal(tattr, attr))
4187 * test wether new_list contains any attributes not included in old_list
4189 static bool has_new_attributes(const attribute_t *old_list,
4190 const attribute_t *new_list)
4192 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4193 if (!contains_attribute(old_list, attr))
4200 * Merge in attributes from an attribute list (probably from a previous
4201 * declaration with the same name). Warning: destroys the old structure
4202 * of the attribute list - don't reuse attributes after this call.
4204 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4207 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4209 if (contains_attribute(decl->attributes, attr))
4212 /* move attribute to new declarations attributes list */
4213 attr->next = decl->attributes;
4214 decl->attributes = attr;
4219 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4220 * for various problems that occur for multiple definitions
4222 static entity_t *record_entity(entity_t *entity, const bool is_definition)
4224 const symbol_t *const symbol = entity->base.symbol;
4225 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4226 const source_position_t *pos = &entity->base.source_position;
4228 /* can happen in error cases */
4232 entity_t *const previous_entity = get_entity(symbol, namespc);
4233 /* pushing the same entity twice will break the stack structure */
4234 assert(previous_entity != entity);
4236 if (entity->kind == ENTITY_FUNCTION) {
4237 type_t *const orig_type = entity->declaration.type;
4238 type_t *const type = skip_typeref(orig_type);
4240 assert(is_type_function(type));
4241 if (type->function.unspecified_parameters &&
4242 warning.strict_prototypes &&
4243 previous_entity == NULL) {
4244 warningf(pos, "function declaration '%#T' is not a prototype",
4248 if (warning.main && current_scope == file_scope
4249 && is_sym_main(symbol)) {
4254 if (is_declaration(entity) &&
4255 warning.nested_externs &&
4256 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4257 current_scope != file_scope) {
4258 warningf(pos, "nested extern declaration of '%#T'",
4259 entity->declaration.type, symbol);
4262 if (previous_entity != NULL) {
4263 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4264 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4265 assert(previous_entity->kind == ENTITY_PARAMETER);
4267 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4268 entity->declaration.type, symbol,
4269 previous_entity->declaration.type, symbol,
4270 &previous_entity->base.source_position);
4274 if (previous_entity->base.parent_scope == current_scope) {
4275 if (previous_entity->kind != entity->kind) {
4276 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4277 error_redefined_as_different_kind(pos, previous_entity,
4282 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4283 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4284 symbol, &previous_entity->base.source_position);
4287 if (previous_entity->kind == ENTITY_TYPEDEF) {
4288 /* TODO: C++ allows this for exactly the same type */
4289 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4290 symbol, &previous_entity->base.source_position);
4294 /* at this point we should have only VARIABLES or FUNCTIONS */
4295 assert(is_declaration(previous_entity) && is_declaration(entity));
4297 declaration_t *const prev_decl = &previous_entity->declaration;
4298 declaration_t *const decl = &entity->declaration;
4300 /* can happen for K&R style declarations */
4301 if (prev_decl->type == NULL &&
4302 previous_entity->kind == ENTITY_PARAMETER &&
4303 entity->kind == ENTITY_PARAMETER) {
4304 prev_decl->type = decl->type;
4305 prev_decl->storage_class = decl->storage_class;
4306 prev_decl->declared_storage_class = decl->declared_storage_class;
4307 prev_decl->modifiers = decl->modifiers;
4308 return previous_entity;
4311 type_t *const orig_type = decl->type;
4312 assert(orig_type != NULL);
4313 type_t *const type = skip_typeref(orig_type);
4314 type_t *const prev_type = skip_typeref(prev_decl->type);
4316 if (!types_compatible(type, prev_type)) {
4318 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4319 orig_type, symbol, prev_decl->type, symbol,
4320 &previous_entity->base.source_position);
4322 unsigned old_storage_class = prev_decl->storage_class;
4324 if (warning.redundant_decls &&
4327 !(prev_decl->modifiers & DM_USED) &&
4328 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4329 warningf(&previous_entity->base.source_position,
4330 "unnecessary static forward declaration for '%#T'",
4331 prev_decl->type, symbol);
4334 storage_class_t new_storage_class = decl->storage_class;
4336 /* pretend no storage class means extern for function
4337 * declarations (except if the previous declaration is neither
4338 * none nor extern) */
4339 if (entity->kind == ENTITY_FUNCTION) {
4340 /* the previous declaration could have unspecified parameters or
4341 * be a typedef, so use the new type */
4342 if (prev_type->function.unspecified_parameters || is_definition)
4343 prev_decl->type = type;
4345 switch (old_storage_class) {
4346 case STORAGE_CLASS_NONE:
4347 old_storage_class = STORAGE_CLASS_EXTERN;
4350 case STORAGE_CLASS_EXTERN:
4351 if (is_definition) {
4352 if (warning.missing_prototypes &&
4353 prev_type->function.unspecified_parameters &&
4354 !is_sym_main(symbol)) {
4355 warningf(pos, "no previous prototype for '%#T'",
4358 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4359 new_storage_class = STORAGE_CLASS_EXTERN;
4366 } else if (is_type_incomplete(prev_type)) {
4367 prev_decl->type = type;
4370 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4371 new_storage_class == STORAGE_CLASS_EXTERN) {
4373 warn_redundant_declaration: ;
4375 = has_new_attributes(prev_decl->attributes,
4377 if (has_new_attrs) {
4378 merge_in_attributes(decl, prev_decl->attributes);
4379 } else if (!is_definition &&
4380 warning.redundant_decls &&
4381 is_type_valid(prev_type) &&
4382 strcmp(previous_entity->base.source_position.input_name,
4383 "<builtin>") != 0) {
4385 "redundant declaration for '%Y' (declared %P)",
4386 symbol, &previous_entity->base.source_position);
4388 } else if (current_function == NULL) {
4389 if (old_storage_class != STORAGE_CLASS_STATIC &&
4390 new_storage_class == STORAGE_CLASS_STATIC) {
4392 "static declaration of '%Y' follows non-static declaration (declared %P)",
4393 symbol, &previous_entity->base.source_position);
4394 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4395 prev_decl->storage_class = STORAGE_CLASS_NONE;
4396 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4398 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4400 goto error_redeclaration;
4401 goto warn_redundant_declaration;
4403 } else if (is_type_valid(prev_type)) {
4404 if (old_storage_class == new_storage_class) {
4405 error_redeclaration:
4406 errorf(pos, "redeclaration of '%Y' (declared %P)",
4407 symbol, &previous_entity->base.source_position);
4410 "redeclaration of '%Y' with different linkage (declared %P)",
4411 symbol, &previous_entity->base.source_position);
4416 prev_decl->modifiers |= decl->modifiers;
4417 if (entity->kind == ENTITY_FUNCTION) {
4418 previous_entity->function.is_inline |= entity->function.is_inline;
4420 return previous_entity;
4423 if (warning.shadow) {
4424 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4425 get_entity_kind_name(entity->kind), symbol,
4426 get_entity_kind_name(previous_entity->kind),
4427 &previous_entity->base.source_position);
4431 if (entity->kind == ENTITY_FUNCTION) {
4432 if (is_definition &&
4433 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4434 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4435 warningf(pos, "no previous prototype for '%#T'",
4436 entity->declaration.type, symbol);
4437 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4438 warningf(pos, "no previous declaration for '%#T'",
4439 entity->declaration.type, symbol);
4442 } else if (warning.missing_declarations &&
4443 entity->kind == ENTITY_VARIABLE &&
4444 current_scope == file_scope) {
4445 declaration_t *declaration = &entity->declaration;
4446 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4447 warningf(pos, "no previous declaration for '%#T'",
4448 declaration->type, symbol);
4453 assert(entity->base.parent_scope == NULL);
4454 assert(current_scope != NULL);
4456 entity->base.parent_scope = current_scope;
4457 entity->base.namespc = NAMESPACE_NORMAL;
4458 environment_push(entity);
4459 append_entity(current_scope, entity);
4464 static void parser_error_multiple_definition(entity_t *entity,
4465 const source_position_t *source_position)
4467 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4468 entity->base.symbol, &entity->base.source_position);
4471 static bool is_declaration_specifier(const token_t *token,
4472 bool only_specifiers_qualifiers)
4474 switch (token->type) {
4479 return is_typedef_symbol(token->v.symbol);
4481 case T___extension__:
4483 return !only_specifiers_qualifiers;
4490 static void parse_init_declarator_rest(entity_t *entity)
4492 assert(is_declaration(entity));
4493 declaration_t *const declaration = &entity->declaration;
4497 type_t *orig_type = declaration->type;
4498 type_t *type = skip_typeref(orig_type);
4500 if (entity->kind == ENTITY_VARIABLE
4501 && entity->variable.initializer != NULL) {
4502 parser_error_multiple_definition(entity, HERE);
4505 bool must_be_constant = false;
4506 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4507 entity->base.parent_scope == file_scope) {
4508 must_be_constant = true;
4511 if (is_type_function(type)) {
4512 errorf(&entity->base.source_position,
4513 "function '%#T' is initialized like a variable",
4514 orig_type, entity->base.symbol);
4515 orig_type = type_error_type;
4518 parse_initializer_env_t env;
4519 env.type = orig_type;
4520 env.must_be_constant = must_be_constant;
4521 env.entity = entity;
4522 current_init_decl = entity;
4524 initializer_t *initializer = parse_initializer(&env);
4525 current_init_decl = NULL;
4527 if (entity->kind == ENTITY_VARIABLE) {
4528 /* §6.7.5:22 array initializers for arrays with unknown size
4529 * determine the array type size */
4530 declaration->type = env.type;
4531 entity->variable.initializer = initializer;
4535 /* parse rest of a declaration without any declarator */
4536 static void parse_anonymous_declaration_rest(
4537 const declaration_specifiers_t *specifiers)
4540 anonymous_entity = NULL;
4542 if (warning.other) {
4543 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4544 specifiers->thread_local) {
4545 warningf(&specifiers->source_position,
4546 "useless storage class in empty declaration");
4549 type_t *type = specifiers->type;
4550 switch (type->kind) {
4551 case TYPE_COMPOUND_STRUCT:
4552 case TYPE_COMPOUND_UNION: {
4553 if (type->compound.compound->base.symbol == NULL) {
4554 warningf(&specifiers->source_position,
4555 "unnamed struct/union that defines no instances");
4564 warningf(&specifiers->source_position, "empty declaration");
4570 static void check_variable_type_complete(entity_t *ent)
4572 if (ent->kind != ENTITY_VARIABLE)
4575 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4576 * type for the object shall be complete [...] */
4577 declaration_t *decl = &ent->declaration;
4578 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4579 decl->storage_class == STORAGE_CLASS_STATIC)
4582 type_t *const orig_type = decl->type;
4583 type_t *const type = skip_typeref(orig_type);
4584 if (!is_type_incomplete(type))
4587 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4588 * are given length one. */
4589 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4590 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4594 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4595 orig_type, ent->base.symbol);
4599 static void parse_declaration_rest(entity_t *ndeclaration,
4600 const declaration_specifiers_t *specifiers,
4601 parsed_declaration_func finished_declaration,
4602 declarator_flags_t flags)
4604 add_anchor_token(';');
4605 add_anchor_token(',');
4607 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4609 if (token.type == '=') {
4610 parse_init_declarator_rest(entity);
4611 } else if (entity->kind == ENTITY_VARIABLE) {
4612 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4613 * [...] where the extern specifier is explicitly used. */
4614 declaration_t *decl = &entity->declaration;
4615 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4616 type_t *type = decl->type;
4617 if (is_type_reference(skip_typeref(type))) {
4618 errorf(&entity->base.source_position,
4619 "reference '%#T' must be initialized",
4620 type, entity->base.symbol);
4625 check_variable_type_complete(entity);
4630 add_anchor_token('=');
4631 ndeclaration = parse_declarator(specifiers, flags);
4632 rem_anchor_token('=');
4634 expect(';', end_error);
4637 anonymous_entity = NULL;
4638 rem_anchor_token(';');
4639 rem_anchor_token(',');
4642 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4644 symbol_t *symbol = entity->base.symbol;
4645 if (symbol == NULL) {
4646 errorf(HERE, "anonymous declaration not valid as function parameter");
4650 assert(entity->base.namespc == NAMESPACE_NORMAL);
4651 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4652 if (previous_entity == NULL
4653 || previous_entity->base.parent_scope != current_scope) {
4654 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4659 if (is_definition) {
4660 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4663 return record_entity(entity, false);
4666 static void parse_declaration(parsed_declaration_func finished_declaration,
4667 declarator_flags_t flags)
4669 declaration_specifiers_t specifiers;
4670 memset(&specifiers, 0, sizeof(specifiers));
4672 add_anchor_token(';');
4673 parse_declaration_specifiers(&specifiers);
4674 rem_anchor_token(';');
4676 if (token.type == ';') {
4677 parse_anonymous_declaration_rest(&specifiers);
4679 entity_t *entity = parse_declarator(&specifiers, flags);
4680 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4685 static type_t *get_default_promoted_type(type_t *orig_type)
4687 type_t *result = orig_type;
4689 type_t *type = skip_typeref(orig_type);
4690 if (is_type_integer(type)) {
4691 result = promote_integer(type);
4692 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4693 result = type_double;
4699 static void parse_kr_declaration_list(entity_t *entity)
4701 if (entity->kind != ENTITY_FUNCTION)
4704 type_t *type = skip_typeref(entity->declaration.type);
4705 assert(is_type_function(type));
4706 if (!type->function.kr_style_parameters)
4709 add_anchor_token('{');
4711 /* push function parameters */
4712 size_t const top = environment_top();
4713 scope_t *old_scope = scope_push(&entity->function.parameters);
4715 entity_t *parameter = entity->function.parameters.entities;
4716 for ( ; parameter != NULL; parameter = parameter->base.next) {
4717 assert(parameter->base.parent_scope == NULL);
4718 parameter->base.parent_scope = current_scope;
4719 environment_push(parameter);
4722 /* parse declaration list */
4724 switch (token.type) {
4726 case T___extension__:
4727 /* This covers symbols, which are no type, too, and results in
4728 * better error messages. The typical cases are misspelled type
4729 * names and missing includes. */
4731 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4739 /* pop function parameters */
4740 assert(current_scope == &entity->function.parameters);
4741 scope_pop(old_scope);
4742 environment_pop_to(top);
4744 /* update function type */
4745 type_t *new_type = duplicate_type(type);
4747 function_parameter_t *parameters = NULL;
4748 function_parameter_t **anchor = ¶meters;
4750 /* did we have an earlier prototype? */
4751 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4752 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4755 function_parameter_t *proto_parameter = NULL;
4756 if (proto_type != NULL) {
4757 type_t *proto_type_type = proto_type->declaration.type;
4758 proto_parameter = proto_type_type->function.parameters;
4759 /* If a K&R function definition has a variadic prototype earlier, then
4760 * make the function definition variadic, too. This should conform to
4761 * §6.7.5.3:15 and §6.9.1:8. */
4762 new_type->function.variadic = proto_type_type->function.variadic;
4764 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4766 new_type->function.unspecified_parameters = true;
4769 bool need_incompatible_warning = false;
4770 parameter = entity->function.parameters.entities;
4771 for (; parameter != NULL; parameter = parameter->base.next,
4773 proto_parameter == NULL ? NULL : proto_parameter->next) {
4774 if (parameter->kind != ENTITY_PARAMETER)
4777 type_t *parameter_type = parameter->declaration.type;
4778 if (parameter_type == NULL) {
4780 errorf(HERE, "no type specified for function parameter '%Y'",
4781 parameter->base.symbol);
4782 parameter_type = type_error_type;
4784 if (warning.implicit_int) {
4785 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4786 parameter->base.symbol);
4788 parameter_type = type_int;
4790 parameter->declaration.type = parameter_type;
4793 semantic_parameter_incomplete(parameter);
4795 /* we need the default promoted types for the function type */
4796 type_t *not_promoted = parameter_type;
4797 parameter_type = get_default_promoted_type(parameter_type);
4799 /* gcc special: if the type of the prototype matches the unpromoted
4800 * type don't promote */
4801 if (!strict_mode && proto_parameter != NULL) {
4802 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4803 type_t *promo_skip = skip_typeref(parameter_type);
4804 type_t *param_skip = skip_typeref(not_promoted);
4805 if (!types_compatible(proto_p_type, promo_skip)
4806 && types_compatible(proto_p_type, param_skip)) {
4808 need_incompatible_warning = true;
4809 parameter_type = not_promoted;
4812 function_parameter_t *const parameter
4813 = allocate_parameter(parameter_type);
4815 *anchor = parameter;
4816 anchor = ¶meter->next;
4819 new_type->function.parameters = parameters;
4820 new_type = identify_new_type(new_type);
4822 if (warning.other && need_incompatible_warning) {
4823 type_t *proto_type_type = proto_type->declaration.type;
4825 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4826 proto_type_type, proto_type->base.symbol,
4827 new_type, entity->base.symbol,
4828 &proto_type->base.source_position);
4831 entity->declaration.type = new_type;
4833 rem_anchor_token('{');
4836 static bool first_err = true;
4839 * When called with first_err set, prints the name of the current function,
4842 static void print_in_function(void)
4846 diagnosticf("%s: In function '%Y':\n",
4847 current_function->base.base.source_position.input_name,
4848 current_function->base.base.symbol);
4853 * Check if all labels are defined in the current function.
4854 * Check if all labels are used in the current function.
4856 static void check_labels(void)
4858 for (const goto_statement_t *goto_statement = goto_first;
4859 goto_statement != NULL;
4860 goto_statement = goto_statement->next) {
4861 /* skip computed gotos */
4862 if (goto_statement->expression != NULL)
4865 label_t *label = goto_statement->label;
4868 if (label->base.source_position.input_name == NULL) {
4869 print_in_function();
4870 errorf(&goto_statement->base.source_position,
4871 "label '%Y' used but not defined", label->base.symbol);
4875 if (warning.unused_label) {
4876 for (const label_statement_t *label_statement = label_first;
4877 label_statement != NULL;
4878 label_statement = label_statement->next) {
4879 label_t *label = label_statement->label;
4881 if (! label->used) {
4882 print_in_function();
4883 warningf(&label_statement->base.source_position,
4884 "label '%Y' defined but not used", label->base.symbol);
4890 static void warn_unused_entity(entity_t *entity, entity_t *last)
4892 entity_t const *const end = last != NULL ? last->base.next : NULL;
4893 for (; entity != end; entity = entity->base.next) {
4894 if (!is_declaration(entity))
4897 declaration_t *declaration = &entity->declaration;
4898 if (declaration->implicit)
4901 if (!declaration->used) {
4902 print_in_function();
4903 const char *what = get_entity_kind_name(entity->kind);
4904 warningf(&entity->base.source_position, "%s '%Y' is unused",
4905 what, entity->base.symbol);
4906 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4907 print_in_function();
4908 const char *what = get_entity_kind_name(entity->kind);
4909 warningf(&entity->base.source_position, "%s '%Y' is never read",
4910 what, entity->base.symbol);
4915 static void check_unused_variables(statement_t *const stmt, void *const env)
4919 switch (stmt->kind) {
4920 case STATEMENT_DECLARATION: {
4921 declaration_statement_t const *const decls = &stmt->declaration;
4922 warn_unused_entity(decls->declarations_begin,
4923 decls->declarations_end);
4928 warn_unused_entity(stmt->fors.scope.entities, NULL);
4937 * Check declarations of current_function for unused entities.
4939 static void check_declarations(void)
4941 if (warning.unused_parameter) {
4942 const scope_t *scope = ¤t_function->parameters;
4944 /* do not issue unused warnings for main */
4945 if (!is_sym_main(current_function->base.base.symbol)) {
4946 warn_unused_entity(scope->entities, NULL);
4949 if (warning.unused_variable) {
4950 walk_statements(current_function->statement, check_unused_variables,
4955 static int determine_truth(expression_t const* const cond)
4958 !is_constant_expression(cond) ? 0 :
4959 fold_constant_to_bool(cond) ? 1 :
4963 static void check_reachable(statement_t *);
4964 static bool reaches_end;
4966 static bool expression_returns(expression_t const *const expr)
4968 switch (expr->kind) {
4970 expression_t const *const func = expr->call.function;
4971 if (func->kind == EXPR_REFERENCE) {
4972 entity_t *entity = func->reference.entity;
4973 if (entity->kind == ENTITY_FUNCTION
4974 && entity->declaration.modifiers & DM_NORETURN)
4978 if (!expression_returns(func))
4981 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4982 if (!expression_returns(arg->expression))
4989 case EXPR_REFERENCE:
4990 case EXPR_REFERENCE_ENUM_VALUE:
4992 case EXPR_CHARACTER_CONSTANT:
4993 case EXPR_WIDE_CHARACTER_CONSTANT:
4994 case EXPR_STRING_LITERAL:
4995 case EXPR_WIDE_STRING_LITERAL:
4996 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4997 case EXPR_LABEL_ADDRESS:
4998 case EXPR_CLASSIFY_TYPE:
4999 case EXPR_SIZEOF: // TODO handle obscure VLA case
5002 case EXPR_BUILTIN_CONSTANT_P:
5003 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
5008 case EXPR_STATEMENT: {
5009 bool old_reaches_end = reaches_end;
5010 reaches_end = false;
5011 check_reachable(expr->statement.statement);
5012 bool returns = reaches_end;
5013 reaches_end = old_reaches_end;
5017 case EXPR_CONDITIONAL:
5018 // TODO handle constant expression
5020 if (!expression_returns(expr->conditional.condition))
5023 if (expr->conditional.true_expression != NULL
5024 && expression_returns(expr->conditional.true_expression))
5027 return expression_returns(expr->conditional.false_expression);
5030 return expression_returns(expr->select.compound);
5032 case EXPR_ARRAY_ACCESS:
5034 expression_returns(expr->array_access.array_ref) &&
5035 expression_returns(expr->array_access.index);
5038 return expression_returns(expr->va_starte.ap);
5041 return expression_returns(expr->va_arge.ap);
5044 return expression_returns(expr->va_copye.src);
5046 EXPR_UNARY_CASES_MANDATORY
5047 return expression_returns(expr->unary.value);
5049 case EXPR_UNARY_THROW:
5053 // TODO handle constant lhs of && and ||
5055 expression_returns(expr->binary.left) &&
5056 expression_returns(expr->binary.right);
5062 panic("unhandled expression");
5065 static bool initializer_returns(initializer_t const *const init)
5067 switch (init->kind) {
5068 case INITIALIZER_VALUE:
5069 return expression_returns(init->value.value);
5071 case INITIALIZER_LIST: {
5072 initializer_t * const* i = init->list.initializers;
5073 initializer_t * const* const end = i + init->list.len;
5074 bool returns = true;
5075 for (; i != end; ++i) {
5076 if (!initializer_returns(*i))
5082 case INITIALIZER_STRING:
5083 case INITIALIZER_WIDE_STRING:
5084 case INITIALIZER_DESIGNATOR: // designators have no payload
5087 panic("unhandled initializer");
5090 static bool noreturn_candidate;
5092 static void check_reachable(statement_t *const stmt)
5094 if (stmt->base.reachable)
5096 if (stmt->kind != STATEMENT_DO_WHILE)
5097 stmt->base.reachable = true;
5099 statement_t *last = stmt;
5101 switch (stmt->kind) {
5102 case STATEMENT_INVALID:
5103 case STATEMENT_EMPTY:
5105 next = stmt->base.next;
5108 case STATEMENT_DECLARATION: {
5109 declaration_statement_t const *const decl = &stmt->declaration;
5110 entity_t const * ent = decl->declarations_begin;
5111 entity_t const *const last = decl->declarations_end;
5113 for (;; ent = ent->base.next) {
5114 if (ent->kind == ENTITY_VARIABLE &&
5115 ent->variable.initializer != NULL &&
5116 !initializer_returns(ent->variable.initializer)) {
5123 next = stmt->base.next;
5127 case STATEMENT_COMPOUND:
5128 next = stmt->compound.statements;
5130 next = stmt->base.next;
5133 case STATEMENT_RETURN: {
5134 expression_t const *const val = stmt->returns.value;
5135 if (val == NULL || expression_returns(val))
5136 noreturn_candidate = false;
5140 case STATEMENT_IF: {
5141 if_statement_t const *const ifs = &stmt->ifs;
5142 expression_t const *const cond = ifs->condition;
5144 if (!expression_returns(cond))
5147 int const val = determine_truth(cond);
5150 check_reachable(ifs->true_statement);
5155 if (ifs->false_statement != NULL) {
5156 check_reachable(ifs->false_statement);
5160 next = stmt->base.next;
5164 case STATEMENT_SWITCH: {
5165 switch_statement_t const *const switchs = &stmt->switchs;
5166 expression_t const *const expr = switchs->expression;
5168 if (!expression_returns(expr))
5171 if (is_constant_expression(expr)) {
5172 long const val = fold_constant_to_int(expr);
5173 case_label_statement_t * defaults = NULL;
5174 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5175 if (i->expression == NULL) {
5180 if (i->first_case <= val && val <= i->last_case) {
5181 check_reachable((statement_t*)i);
5186 if (defaults != NULL) {
5187 check_reachable((statement_t*)defaults);
5191 bool has_default = false;
5192 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5193 if (i->expression == NULL)
5196 check_reachable((statement_t*)i);
5203 next = stmt->base.next;
5207 case STATEMENT_EXPRESSION: {
5208 /* Check for noreturn function call */
5209 expression_t const *const expr = stmt->expression.expression;
5210 if (!expression_returns(expr))
5213 next = stmt->base.next;
5217 case STATEMENT_CONTINUE:
5218 for (statement_t *parent = stmt;;) {
5219 parent = parent->base.parent;
5220 if (parent == NULL) /* continue not within loop */
5224 switch (parent->kind) {
5225 case STATEMENT_WHILE: goto continue_while;
5226 case STATEMENT_DO_WHILE: goto continue_do_while;
5227 case STATEMENT_FOR: goto continue_for;
5233 case STATEMENT_BREAK:
5234 for (statement_t *parent = stmt;;) {
5235 parent = parent->base.parent;
5236 if (parent == NULL) /* break not within loop/switch */
5239 switch (parent->kind) {
5240 case STATEMENT_SWITCH:
5241 case STATEMENT_WHILE:
5242 case STATEMENT_DO_WHILE:
5245 next = parent->base.next;
5246 goto found_break_parent;
5254 case STATEMENT_GOTO:
5255 if (stmt->gotos.expression) {
5256 if (!expression_returns(stmt->gotos.expression))
5259 statement_t *parent = stmt->base.parent;
5260 if (parent == NULL) /* top level goto */
5264 next = stmt->gotos.label->statement;
5265 if (next == NULL) /* missing label */
5270 case STATEMENT_LABEL:
5271 next = stmt->label.statement;
5274 case STATEMENT_CASE_LABEL:
5275 next = stmt->case_label.statement;
5278 case STATEMENT_WHILE: {
5279 while_statement_t const *const whiles = &stmt->whiles;
5280 expression_t const *const cond = whiles->condition;
5282 if (!expression_returns(cond))
5285 int const val = determine_truth(cond);
5288 check_reachable(whiles->body);
5293 next = stmt->base.next;
5297 case STATEMENT_DO_WHILE:
5298 next = stmt->do_while.body;
5301 case STATEMENT_FOR: {
5302 for_statement_t *const fors = &stmt->fors;
5304 if (fors->condition_reachable)
5306 fors->condition_reachable = true;
5308 expression_t const *const cond = fors->condition;
5313 } else if (expression_returns(cond)) {
5314 val = determine_truth(cond);
5320 check_reachable(fors->body);
5325 next = stmt->base.next;
5329 case STATEMENT_MS_TRY: {
5330 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5331 check_reachable(ms_try->try_statement);
5332 next = ms_try->final_statement;
5336 case STATEMENT_LEAVE: {
5337 statement_t *parent = stmt;
5339 parent = parent->base.parent;
5340 if (parent == NULL) /* __leave not within __try */
5343 if (parent->kind == STATEMENT_MS_TRY) {
5345 next = parent->ms_try.final_statement;
5353 panic("invalid statement kind");
5356 while (next == NULL) {
5357 next = last->base.parent;
5359 noreturn_candidate = false;
5361 type_t *const type = skip_typeref(current_function->base.type);
5362 assert(is_type_function(type));
5363 type_t *const ret = skip_typeref(type->function.return_type);
5364 if (warning.return_type &&
5365 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5366 is_type_valid(ret) &&
5367 !is_sym_main(current_function->base.base.symbol)) {
5368 warningf(&stmt->base.source_position,
5369 "control reaches end of non-void function");
5374 switch (next->kind) {
5375 case STATEMENT_INVALID:
5376 case STATEMENT_EMPTY:
5377 case STATEMENT_DECLARATION:
5378 case STATEMENT_EXPRESSION:
5380 case STATEMENT_RETURN:
5381 case STATEMENT_CONTINUE:
5382 case STATEMENT_BREAK:
5383 case STATEMENT_GOTO:
5384 case STATEMENT_LEAVE:
5385 panic("invalid control flow in function");
5387 case STATEMENT_COMPOUND:
5388 if (next->compound.stmt_expr) {
5394 case STATEMENT_SWITCH:
5395 case STATEMENT_LABEL:
5396 case STATEMENT_CASE_LABEL:
5398 next = next->base.next;
5401 case STATEMENT_WHILE: {
5403 if (next->base.reachable)
5405 next->base.reachable = true;
5407 while_statement_t const *const whiles = &next->whiles;
5408 expression_t const *const cond = whiles->condition;
5410 if (!expression_returns(cond))
5413 int const val = determine_truth(cond);
5416 check_reachable(whiles->body);
5422 next = next->base.next;
5426 case STATEMENT_DO_WHILE: {
5428 if (next->base.reachable)
5430 next->base.reachable = true;
5432 do_while_statement_t const *const dw = &next->do_while;
5433 expression_t const *const cond = dw->condition;
5435 if (!expression_returns(cond))
5438 int const val = determine_truth(cond);
5441 check_reachable(dw->body);
5447 next = next->base.next;
5451 case STATEMENT_FOR: {
5453 for_statement_t *const fors = &next->fors;
5455 fors->step_reachable = true;
5457 if (fors->condition_reachable)
5459 fors->condition_reachable = true;
5461 expression_t const *const cond = fors->condition;
5466 } else if (expression_returns(cond)) {
5467 val = determine_truth(cond);
5473 check_reachable(fors->body);
5479 next = next->base.next;
5483 case STATEMENT_MS_TRY:
5485 next = next->ms_try.final_statement;
5490 check_reachable(next);
5493 static void check_unreachable(statement_t* const stmt, void *const env)
5497 switch (stmt->kind) {
5498 case STATEMENT_DO_WHILE:
5499 if (!stmt->base.reachable) {
5500 expression_t const *const cond = stmt->do_while.condition;
5501 if (determine_truth(cond) >= 0) {
5502 warningf(&cond->base.source_position,
5503 "condition of do-while-loop is unreachable");
5508 case STATEMENT_FOR: {
5509 for_statement_t const* const fors = &stmt->fors;
5511 // if init and step are unreachable, cond is unreachable, too
5512 if (!stmt->base.reachable && !fors->step_reachable) {
5513 warningf(&stmt->base.source_position, "statement is unreachable");
5515 if (!stmt->base.reachable && fors->initialisation != NULL) {
5516 warningf(&fors->initialisation->base.source_position,
5517 "initialisation of for-statement is unreachable");
5520 if (!fors->condition_reachable && fors->condition != NULL) {
5521 warningf(&fors->condition->base.source_position,
5522 "condition of for-statement is unreachable");
5525 if (!fors->step_reachable && fors->step != NULL) {
5526 warningf(&fors->step->base.source_position,
5527 "step of for-statement is unreachable");
5533 case STATEMENT_COMPOUND:
5534 if (stmt->compound.statements != NULL)
5536 goto warn_unreachable;
5538 case STATEMENT_DECLARATION: {
5539 /* Only warn if there is at least one declarator with an initializer.
5540 * This typically occurs in switch statements. */
5541 declaration_statement_t const *const decl = &stmt->declaration;
5542 entity_t const * ent = decl->declarations_begin;
5543 entity_t const *const last = decl->declarations_end;
5545 for (;; ent = ent->base.next) {
5546 if (ent->kind == ENTITY_VARIABLE &&
5547 ent->variable.initializer != NULL) {
5548 goto warn_unreachable;
5558 if (!stmt->base.reachable)
5559 warningf(&stmt->base.source_position, "statement is unreachable");
5564 static void parse_external_declaration(void)
5566 /* function-definitions and declarations both start with declaration
5568 declaration_specifiers_t specifiers;
5569 memset(&specifiers, 0, sizeof(specifiers));
5571 add_anchor_token(';');
5572 parse_declaration_specifiers(&specifiers);
5573 rem_anchor_token(';');
5575 /* must be a declaration */
5576 if (token.type == ';') {
5577 parse_anonymous_declaration_rest(&specifiers);
5581 add_anchor_token(',');
5582 add_anchor_token('=');
5583 add_anchor_token(';');
5584 add_anchor_token('{');
5586 /* declarator is common to both function-definitions and declarations */
5587 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5589 rem_anchor_token('{');
5590 rem_anchor_token(';');
5591 rem_anchor_token('=');
5592 rem_anchor_token(',');
5594 /* must be a declaration */
5595 switch (token.type) {
5599 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5604 /* must be a function definition */
5605 parse_kr_declaration_list(ndeclaration);
5607 if (token.type != '{') {
5608 parse_error_expected("while parsing function definition", '{', NULL);
5609 eat_until_matching_token(';');
5613 assert(is_declaration(ndeclaration));
5614 type_t *const orig_type = ndeclaration->declaration.type;
5615 type_t * type = skip_typeref(orig_type);
5617 if (!is_type_function(type)) {
5618 if (is_type_valid(type)) {
5619 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5620 type, ndeclaration->base.symbol);
5624 } else if (is_typeref(orig_type)) {
5626 errorf(&ndeclaration->base.source_position,
5627 "type of function definition '%#T' is a typedef",
5628 orig_type, ndeclaration->base.symbol);
5631 if (warning.aggregate_return &&
5632 is_type_compound(skip_typeref(type->function.return_type))) {
5633 warningf(HERE, "function '%Y' returns an aggregate",
5634 ndeclaration->base.symbol);
5636 if (warning.traditional && !type->function.unspecified_parameters) {
5637 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5638 ndeclaration->base.symbol);
5640 if (warning.old_style_definition && type->function.unspecified_parameters) {
5641 warningf(HERE, "old-style function definition '%Y'",
5642 ndeclaration->base.symbol);
5645 /* §6.7.5.3:14 a function definition with () means no
5646 * parameters (and not unspecified parameters) */
5647 if (type->function.unspecified_parameters &&
5648 type->function.parameters == NULL) {
5649 type_t *copy = duplicate_type(type);
5650 copy->function.unspecified_parameters = false;
5651 type = identify_new_type(copy);
5653 ndeclaration->declaration.type = type;
5656 entity_t *const entity = record_entity(ndeclaration, true);
5657 assert(entity->kind == ENTITY_FUNCTION);
5658 assert(ndeclaration->kind == ENTITY_FUNCTION);
5660 function_t *function = &entity->function;
5661 if (ndeclaration != entity) {
5662 function->parameters = ndeclaration->function.parameters;
5664 assert(is_declaration(entity));
5665 type = skip_typeref(entity->declaration.type);
5667 /* push function parameters and switch scope */
5668 size_t const top = environment_top();
5669 scope_t *old_scope = scope_push(&function->parameters);
5671 entity_t *parameter = function->parameters.entities;
5672 for (; parameter != NULL; parameter = parameter->base.next) {
5673 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5674 parameter->base.parent_scope = current_scope;
5676 assert(parameter->base.parent_scope == NULL
5677 || parameter->base.parent_scope == current_scope);
5678 parameter->base.parent_scope = current_scope;
5679 if (parameter->base.symbol == NULL) {
5680 errorf(¶meter->base.source_position, "parameter name omitted");
5683 environment_push(parameter);
5686 if (function->statement != NULL) {
5687 parser_error_multiple_definition(entity, HERE);
5690 /* parse function body */
5691 int label_stack_top = label_top();
5692 function_t *old_current_function = current_function;
5693 entity_t *old_current_entity = current_entity;
5694 current_function = function;
5695 current_entity = (entity_t*) function;
5696 current_parent = NULL;
5699 goto_anchor = &goto_first;
5701 label_anchor = &label_first;
5703 statement_t *const body = parse_compound_statement(false);
5704 function->statement = body;
5707 check_declarations();
5708 if (warning.return_type ||
5709 warning.unreachable_code ||
5710 (warning.missing_noreturn
5711 && !(function->base.modifiers & DM_NORETURN))) {
5712 noreturn_candidate = true;
5713 check_reachable(body);
5714 if (warning.unreachable_code)
5715 walk_statements(body, check_unreachable, NULL);
5716 if (warning.missing_noreturn &&
5717 noreturn_candidate &&
5718 !(function->base.modifiers & DM_NORETURN)) {
5719 warningf(&body->base.source_position,
5720 "function '%#T' is candidate for attribute 'noreturn'",
5721 type, entity->base.symbol);
5725 assert(current_parent == NULL);
5726 assert(current_function == function);
5727 assert(current_entity == (entity_t*) function);
5728 current_entity = old_current_entity;
5729 current_function = old_current_function;
5730 label_pop_to(label_stack_top);
5733 assert(current_scope == &function->parameters);
5734 scope_pop(old_scope);
5735 environment_pop_to(top);
5738 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5739 source_position_t *source_position,
5740 const symbol_t *symbol)
5742 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5744 type->bitfield.base_type = base_type;
5745 type->bitfield.size_expression = size;
5748 type_t *skipped_type = skip_typeref(base_type);
5749 if (!is_type_integer(skipped_type)) {
5750 errorf(HERE, "bitfield base type '%T' is not an integer type",
5754 bit_size = get_type_size(base_type) * 8;
5757 if (is_constant_expression(size)) {
5758 long v = fold_constant_to_int(size);
5759 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5762 errorf(source_position, "negative width in bit-field '%Y'",
5764 } else if (v == 0 && symbol != NULL) {
5765 errorf(source_position, "zero width for bit-field '%Y'",
5767 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5768 errorf(source_position, "width of '%Y' exceeds its type",
5771 type->bitfield.bit_size = v;
5778 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5780 entity_t *iter = compound->members.entities;
5781 for (; iter != NULL; iter = iter->base.next) {
5782 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5785 if (iter->base.symbol == symbol) {
5787 } else if (iter->base.symbol == NULL) {
5788 /* search in anonymous structs and unions */
5789 type_t *type = skip_typeref(iter->declaration.type);
5790 if (is_type_compound(type)) {
5791 if (find_compound_entry(type->compound.compound, symbol)
5802 static void check_deprecated(const source_position_t *source_position,
5803 const entity_t *entity)
5805 if (!warning.deprecated_declarations)
5807 if (!is_declaration(entity))
5809 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5812 char const *const prefix = get_entity_kind_name(entity->kind);
5813 const char *deprecated_string
5814 = get_deprecated_string(entity->declaration.attributes);
5815 if (deprecated_string != NULL) {
5816 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5817 prefix, entity->base.symbol, &entity->base.source_position,
5820 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5821 entity->base.symbol, &entity->base.source_position);
5826 static expression_t *create_select(const source_position_t *pos,
5828 type_qualifiers_t qualifiers,
5831 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5833 check_deprecated(pos, entry);
5835 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5836 select->select.compound = addr;
5837 select->select.compound_entry = entry;
5839 type_t *entry_type = entry->declaration.type;
5840 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5842 /* we always do the auto-type conversions; the & and sizeof parser contains
5843 * code to revert this! */
5844 select->base.type = automatic_type_conversion(res_type);
5845 if (res_type->kind == TYPE_BITFIELD) {
5846 select->base.type = res_type->bitfield.base_type;
5853 * Find entry with symbol in compound. Search anonymous structs and unions and
5854 * creates implicit select expressions for them.
5855 * Returns the adress for the innermost compound.
5857 static expression_t *find_create_select(const source_position_t *pos,
5859 type_qualifiers_t qualifiers,
5860 compound_t *compound, symbol_t *symbol)
5862 entity_t *iter = compound->members.entities;
5863 for (; iter != NULL; iter = iter->base.next) {
5864 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5867 symbol_t *iter_symbol = iter->base.symbol;
5868 if (iter_symbol == NULL) {
5869 type_t *type = iter->declaration.type;
5870 if (type->kind != TYPE_COMPOUND_STRUCT
5871 && type->kind != TYPE_COMPOUND_UNION)
5874 compound_t *sub_compound = type->compound.compound;
5876 if (find_compound_entry(sub_compound, symbol) == NULL)
5879 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5880 sub_addr->base.source_position = *pos;
5881 sub_addr->select.implicit = true;
5882 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5886 if (iter_symbol == symbol) {
5887 return create_select(pos, addr, qualifiers, iter);
5894 static void parse_compound_declarators(compound_t *compound,
5895 const declaration_specifiers_t *specifiers)
5900 if (token.type == ':') {
5901 source_position_t source_position = *HERE;
5904 type_t *base_type = specifiers->type;
5905 expression_t *size = parse_constant_expression();
5907 type_t *type = make_bitfield_type(base_type, size,
5908 &source_position, NULL);
5910 attribute_t *attributes = parse_attributes(NULL);
5911 attribute_t **anchor = &attributes;
5912 while (*anchor != NULL)
5913 anchor = &(*anchor)->next;
5914 *anchor = specifiers->attributes;
5916 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5917 entity->base.namespc = NAMESPACE_NORMAL;
5918 entity->base.source_position = source_position;
5919 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5920 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5921 entity->declaration.type = type;
5922 entity->declaration.attributes = attributes;
5924 if (attributes != NULL) {
5925 handle_entity_attributes(attributes, entity);
5927 append_entity(&compound->members, entity);
5929 entity = parse_declarator(specifiers,
5930 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5931 if (entity->kind == ENTITY_TYPEDEF) {
5932 errorf(&entity->base.source_position,
5933 "typedef not allowed as compound member");
5935 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5937 /* make sure we don't define a symbol multiple times */
5938 symbol_t *symbol = entity->base.symbol;
5939 if (symbol != NULL) {
5940 entity_t *prev = find_compound_entry(compound, symbol);
5942 errorf(&entity->base.source_position,
5943 "multiple declarations of symbol '%Y' (declared %P)",
5944 symbol, &prev->base.source_position);
5948 if (token.type == ':') {
5949 source_position_t source_position = *HERE;
5951 expression_t *size = parse_constant_expression();
5953 type_t *type = entity->declaration.type;
5954 type_t *bitfield_type = make_bitfield_type(type, size,
5955 &source_position, entity->base.symbol);
5957 attribute_t *attributes = parse_attributes(NULL);
5958 entity->declaration.type = bitfield_type;
5959 handle_entity_attributes(attributes, entity);
5961 type_t *orig_type = entity->declaration.type;
5962 type_t *type = skip_typeref(orig_type);
5963 if (is_type_function(type)) {
5964 errorf(&entity->base.source_position,
5965 "compound member '%Y' must not have function type '%T'",
5966 entity->base.symbol, orig_type);
5967 } else if (is_type_incomplete(type)) {
5968 /* §6.7.2.1:16 flexible array member */
5969 if (!is_type_array(type) ||
5970 token.type != ';' ||
5971 look_ahead(1)->type != '}') {
5972 errorf(&entity->base.source_position,
5973 "compound member '%Y' has incomplete type '%T'",
5974 entity->base.symbol, orig_type);
5979 append_entity(&compound->members, entity);
5982 } while (next_if(','));
5983 expect(';', end_error);
5986 anonymous_entity = NULL;
5989 static void parse_compound_type_entries(compound_t *compound)
5992 add_anchor_token('}');
5994 while (token.type != '}') {
5995 if (token.type == T_EOF) {
5996 errorf(HERE, "EOF while parsing struct");
5999 declaration_specifiers_t specifiers;
6000 memset(&specifiers, 0, sizeof(specifiers));
6001 parse_declaration_specifiers(&specifiers);
6003 parse_compound_declarators(compound, &specifiers);
6005 rem_anchor_token('}');
6009 compound->complete = true;
6012 static type_t *parse_typename(void)
6014 declaration_specifiers_t specifiers;
6015 memset(&specifiers, 0, sizeof(specifiers));
6016 parse_declaration_specifiers(&specifiers);
6017 if (specifiers.storage_class != STORAGE_CLASS_NONE
6018 || specifiers.thread_local) {
6019 /* TODO: improve error message, user does probably not know what a
6020 * storage class is...
6022 errorf(HERE, "typename may not have a storage class");
6025 type_t *result = parse_abstract_declarator(specifiers.type);
6033 typedef expression_t* (*parse_expression_function)(void);
6034 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
6036 typedef struct expression_parser_function_t expression_parser_function_t;
6037 struct expression_parser_function_t {
6038 parse_expression_function parser;
6039 precedence_t infix_precedence;
6040 parse_expression_infix_function infix_parser;
6043 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6046 * Prints an error message if an expression was expected but not read
6048 static expression_t *expected_expression_error(void)
6050 /* skip the error message if the error token was read */
6051 if (token.type != T_ERROR) {
6052 errorf(HERE, "expected expression, got token %K", &token);
6056 return create_invalid_expression();
6060 * Parse a string constant.
6062 static expression_t *parse_string_const(void)
6065 if (token.type == T_STRING_LITERAL) {
6066 string_t res = token.v.string;
6068 while (token.type == T_STRING_LITERAL) {
6069 res = concat_strings(&res, &token.v.string);
6072 if (token.type != T_WIDE_STRING_LITERAL) {
6073 expression_t *const cnst = allocate_expression_zero(EXPR_STRING_LITERAL);
6074 /* note: that we use type_char_ptr here, which is already the
6075 * automatic converted type. revert_automatic_type_conversion
6076 * will construct the array type */
6077 cnst->base.type = warning.write_strings ? type_const_char_ptr : type_char_ptr;
6078 cnst->string.value = res;
6082 wres = concat_string_wide_string(&res, &token.v.wide_string);
6084 wres = token.v.wide_string;
6089 switch (token.type) {
6090 case T_WIDE_STRING_LITERAL:
6091 wres = concat_wide_strings(&wres, &token.v.wide_string);
6094 case T_STRING_LITERAL:
6095 wres = concat_wide_string_string(&wres, &token.v.string);
6099 expression_t *const cnst = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6100 cnst->base.type = warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6101 cnst->wide_string.value = wres;
6110 * Parse a boolean constant.
6112 static expression_t *parse_bool_const(bool value)
6114 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6115 cnst->base.type = type_bool;
6116 cnst->conste.v.int_value = value;
6124 * Parse an integer constant.
6126 static expression_t *parse_int_const(void)
6128 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6129 cnst->base.type = token.datatype;
6130 cnst->conste.v.int_value = token.v.intvalue;
6138 * Parse a character constant.
6140 static expression_t *parse_character_constant(void)
6142 expression_t *cnst = allocate_expression_zero(EXPR_CHARACTER_CONSTANT);
6143 cnst->base.type = token.datatype;
6144 cnst->conste.v.character = token.v.string;
6146 if (cnst->conste.v.character.size != 1) {
6148 errorf(HERE, "more than 1 character in character constant");
6149 } else if (warning.multichar) {
6150 warningf(HERE, "multi-character character constant");
6159 * Parse a wide character constant.
6161 static expression_t *parse_wide_character_constant(void)
6163 expression_t *cnst = allocate_expression_zero(EXPR_WIDE_CHARACTER_CONSTANT);
6164 cnst->base.type = token.datatype;
6165 cnst->conste.v.wide_character = token.v.wide_string;
6167 if (cnst->conste.v.wide_character.size != 1) {
6169 errorf(HERE, "more than 1 character in character constant");
6170 } else if (warning.multichar) {
6171 warningf(HERE, "multi-character character constant");
6180 * Parse a float constant.
6182 static expression_t *parse_float_const(void)
6184 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
6185 cnst->base.type = token.datatype;
6186 cnst->conste.v.float_value = token.v.floatvalue;
6193 static entity_t *create_implicit_function(symbol_t *symbol,
6194 const source_position_t *source_position)
6196 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6197 ntype->function.return_type = type_int;
6198 ntype->function.unspecified_parameters = true;
6199 ntype->function.linkage = LINKAGE_C;
6200 type_t *type = identify_new_type(ntype);
6202 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6203 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6204 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6205 entity->declaration.type = type;
6206 entity->declaration.implicit = true;
6207 entity->base.symbol = symbol;
6208 entity->base.source_position = *source_position;
6210 if (current_scope != NULL) {
6211 bool strict_prototypes_old = warning.strict_prototypes;
6212 warning.strict_prototypes = false;
6213 record_entity(entity, false);
6214 warning.strict_prototypes = strict_prototypes_old;
6221 * Creates a return_type (func)(argument_type) function type if not
6224 static type_t *make_function_2_type(type_t *return_type, type_t *argument_type1,
6225 type_t *argument_type2)
6227 function_parameter_t *const parameter2 = allocate_parameter(argument_type2);
6228 function_parameter_t *const parameter1 = allocate_parameter(argument_type1);
6229 parameter1->next = parameter2;
6231 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6232 type->function.return_type = return_type;
6233 type->function.parameters = parameter1;
6235 return identify_new_type(type);
6239 * Creates a return_type (func)(argument_type) function type if not
6242 * @param return_type the return type
6243 * @param argument_type the argument type
6245 static type_t *make_function_1_type(type_t *return_type, type_t *argument_type)
6247 function_parameter_t *const parameter = allocate_parameter(argument_type);
6249 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6250 type->function.return_type = return_type;
6251 type->function.parameters = parameter;
6253 return identify_new_type(type);
6257 * Creates a return_type (func)(argument_type, ...) function type if not
6260 * @param return_type the return type
6261 * @param argument_type the argument type
6263 static type_t *make_function_1_type_variadic(type_t *return_type, type_t *argument_type)
6265 function_parameter_t *const parameter = allocate_parameter(argument_type);
6267 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6268 type->function.return_type = return_type;
6269 type->function.parameters = parameter;
6270 type->function.variadic = true;
6272 return identify_new_type(type);
6276 * Creates a return_type (func)(void) function type if not
6279 * @param return_type the return type
6281 static type_t *make_function_0_type(type_t *return_type)
6283 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6284 type->function.return_type = return_type;
6285 type->function.parameters = NULL;
6287 return identify_new_type(type);
6291 * Creates a NO_RETURN return_type (func)(void) function type if not
6294 * @param return_type the return type
6296 static type_t *make_function_0_type_noreturn(type_t *return_type)
6298 type_t *type = allocate_type_zero(TYPE_FUNCTION);
6299 type->function.return_type = return_type;
6300 type->function.parameters = NULL;
6301 type->function.modifiers |= DM_NORETURN;
6302 return identify_new_type(type);
6306 * Performs automatic type cast as described in §6.3.2.1.
6308 * @param orig_type the original type
6310 static type_t *automatic_type_conversion(type_t *orig_type)
6312 type_t *type = skip_typeref(orig_type);
6313 if (is_type_array(type)) {
6314 array_type_t *array_type = &type->array;
6315 type_t *element_type = array_type->element_type;
6316 unsigned qualifiers = array_type->base.qualifiers;
6318 return make_pointer_type(element_type, qualifiers);
6321 if (is_type_function(type)) {
6322 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6329 * reverts the automatic casts of array to pointer types and function
6330 * to function-pointer types as defined §6.3.2.1
6332 type_t *revert_automatic_type_conversion(const expression_t *expression)
6334 switch (expression->kind) {
6335 case EXPR_REFERENCE: {
6336 entity_t *entity = expression->reference.entity;
6337 if (is_declaration(entity)) {
6338 return entity->declaration.type;
6339 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6340 return entity->enum_value.enum_type;
6342 panic("no declaration or enum in reference");
6347 entity_t *entity = expression->select.compound_entry;
6348 assert(is_declaration(entity));
6349 type_t *type = entity->declaration.type;
6350 return get_qualified_type(type,
6351 expression->base.type->base.qualifiers);
6354 case EXPR_UNARY_DEREFERENCE: {
6355 const expression_t *const value = expression->unary.value;
6356 type_t *const type = skip_typeref(value->base.type);
6357 if (!is_type_pointer(type))
6358 return type_error_type;
6359 return type->pointer.points_to;
6362 case EXPR_ARRAY_ACCESS: {
6363 const expression_t *array_ref = expression->array_access.array_ref;
6364 type_t *type_left = skip_typeref(array_ref->base.type);
6365 if (!is_type_pointer(type_left))
6366 return type_error_type;
6367 return type_left->pointer.points_to;
6370 case EXPR_STRING_LITERAL: {
6371 size_t size = expression->string.value.size;
6372 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6375 case EXPR_WIDE_STRING_LITERAL: {
6376 size_t size = expression->wide_string.value.size;
6377 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6380 case EXPR_COMPOUND_LITERAL:
6381 return expression->compound_literal.type;
6384 return expression->base.type;
6389 * Find an entity matching a symbol in a scope.
6390 * Uses current scope if scope is NULL
6392 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6393 namespace_tag_t namespc)
6395 if (scope == NULL) {
6396 return get_entity(symbol, namespc);
6399 /* we should optimize here, if scope grows above a certain size we should
6400 construct a hashmap here... */
6401 entity_t *entity = scope->entities;
6402 for ( ; entity != NULL; entity = entity->base.next) {
6403 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6410 static entity_t *parse_qualified_identifier(void)
6412 /* namespace containing the symbol */
6414 source_position_t pos;
6415 const scope_t *lookup_scope = NULL;
6417 if (next_if(T_COLONCOLON))
6418 lookup_scope = &unit->scope;
6422 if (token.type != T_IDENTIFIER) {
6423 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6424 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6426 symbol = token.v.symbol;
6431 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6433 if (!next_if(T_COLONCOLON))
6436 switch (entity->kind) {
6437 case ENTITY_NAMESPACE:
6438 lookup_scope = &entity->namespacee.members;
6443 lookup_scope = &entity->compound.members;
6446 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6447 symbol, get_entity_kind_name(entity->kind));
6452 if (entity == NULL) {
6453 if (!strict_mode && token.type == '(') {
6454 /* an implicitly declared function */
6455 if (warning.error_implicit_function_declaration) {
6456 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6457 } else if (warning.implicit_function_declaration) {
6458 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6461 entity = create_implicit_function(symbol, &pos);
6463 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6464 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6471 /* skip further qualifications */
6472 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6474 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6477 static expression_t *parse_reference(void)
6479 entity_t *entity = parse_qualified_identifier();
6482 if (is_declaration(entity)) {
6483 orig_type = entity->declaration.type;
6484 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6485 orig_type = entity->enum_value.enum_type;
6487 panic("expected declaration or enum value in reference");
6490 /* we always do the auto-type conversions; the & and sizeof parser contains
6491 * code to revert this! */
6492 type_t *type = automatic_type_conversion(orig_type);
6494 expression_kind_t kind = EXPR_REFERENCE;
6495 if (entity->kind == ENTITY_ENUM_VALUE)
6496 kind = EXPR_REFERENCE_ENUM_VALUE;
6498 expression_t *expression = allocate_expression_zero(kind);
6499 expression->reference.entity = entity;
6500 expression->base.type = type;
6502 /* this declaration is used */
6503 if (is_declaration(entity)) {
6504 entity->declaration.used = true;
6507 if (entity->base.parent_scope != file_scope
6508 && (current_function != NULL
6509 && entity->base.parent_scope->depth < current_function->parameters.depth)
6510 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6511 if (entity->kind == ENTITY_VARIABLE) {
6512 /* access of a variable from an outer function */
6513 entity->variable.address_taken = true;
6514 } else if (entity->kind == ENTITY_PARAMETER) {
6515 entity->parameter.address_taken = true;
6517 current_function->need_closure = true;
6520 check_deprecated(HERE, entity);
6522 if (warning.init_self && entity == current_init_decl && !in_type_prop
6523 && entity->kind == ENTITY_VARIABLE) {
6524 current_init_decl = NULL;
6525 warningf(HERE, "variable '%#T' is initialized by itself",
6526 entity->declaration.type, entity->base.symbol);
6532 static bool semantic_cast(expression_t *cast)
6534 expression_t *expression = cast->unary.value;
6535 type_t *orig_dest_type = cast->base.type;
6536 type_t *orig_type_right = expression->base.type;
6537 type_t const *dst_type = skip_typeref(orig_dest_type);
6538 type_t const *src_type = skip_typeref(orig_type_right);
6539 source_position_t const *pos = &cast->base.source_position;
6541 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6542 if (dst_type == type_void)
6545 /* only integer and pointer can be casted to pointer */
6546 if (is_type_pointer(dst_type) &&
6547 !is_type_pointer(src_type) &&
6548 !is_type_integer(src_type) &&
6549 is_type_valid(src_type)) {
6550 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6554 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6555 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6559 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6560 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6564 if (warning.cast_qual &&
6565 is_type_pointer(src_type) &&
6566 is_type_pointer(dst_type)) {
6567 type_t *src = skip_typeref(src_type->pointer.points_to);
6568 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6569 unsigned missing_qualifiers =
6570 src->base.qualifiers & ~dst->base.qualifiers;
6571 if (missing_qualifiers != 0) {
6573 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6574 missing_qualifiers, orig_type_right);
6580 static expression_t *parse_compound_literal(type_t *type)
6582 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6584 parse_initializer_env_t env;
6587 env.must_be_constant = false;
6588 initializer_t *initializer = parse_initializer(&env);
6591 expression->compound_literal.initializer = initializer;
6592 expression->compound_literal.type = type;
6593 expression->base.type = automatic_type_conversion(type);
6599 * Parse a cast expression.
6601 static expression_t *parse_cast(void)
6603 add_anchor_token(')');
6605 source_position_t source_position = token.source_position;
6607 type_t *type = parse_typename();
6609 rem_anchor_token(')');
6610 expect(')', end_error);
6612 if (token.type == '{') {
6613 return parse_compound_literal(type);
6616 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6617 cast->base.source_position = source_position;
6619 expression_t *value = parse_sub_expression(PREC_CAST);
6620 cast->base.type = type;
6621 cast->unary.value = value;
6623 if (! semantic_cast(cast)) {
6624 /* TODO: record the error in the AST. else it is impossible to detect it */
6629 return create_invalid_expression();
6633 * Parse a statement expression.
6635 static expression_t *parse_statement_expression(void)
6637 add_anchor_token(')');
6639 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6641 statement_t *statement = parse_compound_statement(true);
6642 statement->compound.stmt_expr = true;
6643 expression->statement.statement = statement;
6645 /* find last statement and use its type */
6646 type_t *type = type_void;
6647 const statement_t *stmt = statement->compound.statements;
6649 while (stmt->base.next != NULL)
6650 stmt = stmt->base.next;
6652 if (stmt->kind == STATEMENT_EXPRESSION) {
6653 type = stmt->expression.expression->base.type;
6655 } else if (warning.other) {
6656 warningf(&expression->base.source_position, "empty statement expression ({})");
6658 expression->base.type = type;
6660 rem_anchor_token(')');
6661 expect(')', end_error);
6668 * Parse a parenthesized expression.
6670 static expression_t *parse_parenthesized_expression(void)
6674 switch (token.type) {
6676 /* gcc extension: a statement expression */
6677 return parse_statement_expression();
6681 return parse_cast();
6683 if (is_typedef_symbol(token.v.symbol)) {
6684 return parse_cast();
6688 add_anchor_token(')');
6689 expression_t *result = parse_expression();
6690 result->base.parenthesized = true;
6691 rem_anchor_token(')');
6692 expect(')', end_error);
6698 static expression_t *parse_function_keyword(void)
6702 if (current_function == NULL) {
6703 errorf(HERE, "'__func__' used outside of a function");
6706 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6707 expression->base.type = type_char_ptr;
6708 expression->funcname.kind = FUNCNAME_FUNCTION;
6715 static expression_t *parse_pretty_function_keyword(void)
6717 if (current_function == NULL) {
6718 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6721 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6722 expression->base.type = type_char_ptr;
6723 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6725 eat(T___PRETTY_FUNCTION__);
6730 static expression_t *parse_funcsig_keyword(void)
6732 if (current_function == NULL) {
6733 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6736 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6737 expression->base.type = type_char_ptr;
6738 expression->funcname.kind = FUNCNAME_FUNCSIG;
6745 static expression_t *parse_funcdname_keyword(void)
6747 if (current_function == NULL) {
6748 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6751 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6752 expression->base.type = type_char_ptr;
6753 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6755 eat(T___FUNCDNAME__);
6760 static designator_t *parse_designator(void)
6762 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6763 result->source_position = *HERE;
6765 if (token.type != T_IDENTIFIER) {
6766 parse_error_expected("while parsing member designator",
6767 T_IDENTIFIER, NULL);
6770 result->symbol = token.v.symbol;
6773 designator_t *last_designator = result;
6776 if (token.type != T_IDENTIFIER) {
6777 parse_error_expected("while parsing member designator",
6778 T_IDENTIFIER, NULL);
6781 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6782 designator->source_position = *HERE;
6783 designator->symbol = token.v.symbol;
6786 last_designator->next = designator;
6787 last_designator = designator;
6791 add_anchor_token(']');
6792 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6793 designator->source_position = *HERE;
6794 designator->array_index = parse_expression();
6795 rem_anchor_token(']');
6796 expect(']', end_error);
6797 if (designator->array_index == NULL) {
6801 last_designator->next = designator;
6802 last_designator = designator;
6814 * Parse the __builtin_offsetof() expression.
6816 static expression_t *parse_offsetof(void)
6818 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6819 expression->base.type = type_size_t;
6821 eat(T___builtin_offsetof);
6823 expect('(', end_error);
6824 add_anchor_token(',');
6825 type_t *type = parse_typename();
6826 rem_anchor_token(',');
6827 expect(',', end_error);
6828 add_anchor_token(')');
6829 designator_t *designator = parse_designator();
6830 rem_anchor_token(')');
6831 expect(')', end_error);
6833 expression->offsetofe.type = type;
6834 expression->offsetofe.designator = designator;
6837 memset(&path, 0, sizeof(path));
6838 path.top_type = type;
6839 path.path = NEW_ARR_F(type_path_entry_t, 0);
6841 descend_into_subtype(&path);
6843 if (!walk_designator(&path, designator, true)) {
6844 return create_invalid_expression();
6847 DEL_ARR_F(path.path);
6851 return create_invalid_expression();
6855 * Parses a _builtin_va_start() expression.
6857 static expression_t *parse_va_start(void)
6859 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6861 eat(T___builtin_va_start);
6863 expect('(', end_error);
6864 add_anchor_token(',');
6865 expression->va_starte.ap = parse_assignment_expression();
6866 rem_anchor_token(',');
6867 expect(',', end_error);
6868 expression_t *const expr = parse_assignment_expression();
6869 if (expr->kind == EXPR_REFERENCE) {
6870 entity_t *const entity = expr->reference.entity;
6871 if (!current_function->base.type->function.variadic) {
6872 errorf(&expr->base.source_position,
6873 "'va_start' used in non-variadic function");
6874 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6875 entity->base.next != NULL ||
6876 entity->kind != ENTITY_PARAMETER) {
6877 errorf(&expr->base.source_position,
6878 "second argument of 'va_start' must be last parameter of the current function");
6880 expression->va_starte.parameter = &entity->variable;
6882 expect(')', end_error);
6885 expect(')', end_error);
6887 return create_invalid_expression();
6891 * Parses a __builtin_va_arg() expression.
6893 static expression_t *parse_va_arg(void)
6895 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6897 eat(T___builtin_va_arg);
6899 expect('(', end_error);
6901 ap.expression = parse_assignment_expression();
6902 expression->va_arge.ap = ap.expression;
6903 check_call_argument(type_valist, &ap, 1);
6905 expect(',', end_error);
6906 expression->base.type = parse_typename();
6907 expect(')', end_error);
6911 return create_invalid_expression();
6915 * Parses a __builtin_va_copy() expression.
6917 static expression_t *parse_va_copy(void)
6919 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6921 eat(T___builtin_va_copy);
6923 expect('(', end_error);
6924 expression_t *dst = parse_assignment_expression();
6925 assign_error_t error = semantic_assign(type_valist, dst);
6926 report_assign_error(error, type_valist, dst, "call argument 1",
6927 &dst->base.source_position);
6928 expression->va_copye.dst = dst;
6930 expect(',', end_error);
6932 call_argument_t src;
6933 src.expression = parse_assignment_expression();
6934 check_call_argument(type_valist, &src, 2);
6935 expression->va_copye.src = src.expression;
6936 expect(')', end_error);
6940 return create_invalid_expression();
6944 * Parses a __builtin_constant_p() expression.
6946 static expression_t *parse_builtin_constant(void)
6948 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6950 eat(T___builtin_constant_p);
6952 expect('(', end_error);
6953 add_anchor_token(')');
6954 expression->builtin_constant.value = parse_assignment_expression();
6955 rem_anchor_token(')');
6956 expect(')', end_error);
6957 expression->base.type = type_int;
6961 return create_invalid_expression();
6965 * Parses a __builtin_types_compatible_p() expression.
6967 static expression_t *parse_builtin_types_compatible(void)
6969 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6971 eat(T___builtin_types_compatible_p);
6973 expect('(', end_error);
6974 add_anchor_token(')');
6975 add_anchor_token(',');
6976 expression->builtin_types_compatible.left = parse_typename();
6977 rem_anchor_token(',');
6978 expect(',', end_error);
6979 expression->builtin_types_compatible.right = parse_typename();
6980 rem_anchor_token(')');
6981 expect(')', end_error);
6982 expression->base.type = type_int;
6986 return create_invalid_expression();
6990 * Parses a __builtin_is_*() compare expression.
6992 static expression_t *parse_compare_builtin(void)
6994 expression_t *expression;
6996 switch (token.type) {
6997 case T___builtin_isgreater:
6998 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
7000 case T___builtin_isgreaterequal:
7001 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
7003 case T___builtin_isless:
7004 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
7006 case T___builtin_islessequal:
7007 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
7009 case T___builtin_islessgreater:
7010 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
7012 case T___builtin_isunordered:
7013 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
7016 internal_errorf(HERE, "invalid compare builtin found");
7018 expression->base.source_position = *HERE;
7021 expect('(', end_error);
7022 expression->binary.left = parse_assignment_expression();
7023 expect(',', end_error);
7024 expression->binary.right = parse_assignment_expression();
7025 expect(')', end_error);
7027 type_t *const orig_type_left = expression->binary.left->base.type;
7028 type_t *const orig_type_right = expression->binary.right->base.type;
7030 type_t *const type_left = skip_typeref(orig_type_left);
7031 type_t *const type_right = skip_typeref(orig_type_right);
7032 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7033 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7034 type_error_incompatible("invalid operands in comparison",
7035 &expression->base.source_position, orig_type_left, orig_type_right);
7038 semantic_comparison(&expression->binary);
7043 return create_invalid_expression();
7047 * Parses a MS assume() expression.
7049 static expression_t *parse_assume(void)
7051 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7055 expect('(', end_error);
7056 add_anchor_token(')');
7057 expression->unary.value = parse_assignment_expression();
7058 rem_anchor_token(')');
7059 expect(')', end_error);
7061 expression->base.type = type_void;
7064 return create_invalid_expression();
7068 * Return the declaration for a given label symbol or create a new one.
7070 * @param symbol the symbol of the label
7072 static label_t *get_label(symbol_t *symbol)
7075 assert(current_function != NULL);
7077 label = get_entity(symbol, NAMESPACE_LABEL);
7078 /* if we found a local label, we already created the declaration */
7079 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7080 if (label->base.parent_scope != current_scope) {
7081 assert(label->base.parent_scope->depth < current_scope->depth);
7082 current_function->goto_to_outer = true;
7084 return &label->label;
7087 label = get_entity(symbol, NAMESPACE_LABEL);
7088 /* if we found a label in the same function, then we already created the
7091 && label->base.parent_scope == ¤t_function->parameters) {
7092 return &label->label;
7095 /* otherwise we need to create a new one */
7096 label = allocate_entity_zero(ENTITY_LABEL);
7097 label->base.namespc = NAMESPACE_LABEL;
7098 label->base.symbol = symbol;
7102 return &label->label;
7106 * Parses a GNU && label address expression.
7108 static expression_t *parse_label_address(void)
7110 source_position_t source_position = token.source_position;
7112 if (token.type != T_IDENTIFIER) {
7113 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7116 symbol_t *symbol = token.v.symbol;
7119 label_t *label = get_label(symbol);
7121 label->address_taken = true;
7123 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7124 expression->base.source_position = source_position;
7126 /* label address is threaten as a void pointer */
7127 expression->base.type = type_void_ptr;
7128 expression->label_address.label = label;
7131 return create_invalid_expression();
7135 * Parse a microsoft __noop expression.
7137 static expression_t *parse_noop_expression(void)
7139 /* the result is a (int)0 */
7140 expression_t *cnst = allocate_expression_zero(EXPR_CONST);
7141 cnst->base.type = type_int;
7142 cnst->conste.v.int_value = 0;
7143 cnst->conste.is_ms_noop = true;
7147 if (token.type == '(') {
7148 /* parse arguments */
7150 add_anchor_token(')');
7151 add_anchor_token(',');
7153 if (token.type != ')') do {
7154 (void)parse_assignment_expression();
7155 } while (next_if(','));
7157 rem_anchor_token(',');
7158 rem_anchor_token(')');
7159 expect(')', end_error);
7166 * Parses a primary expression.
7168 static expression_t *parse_primary_expression(void)
7170 switch (token.type) {
7171 case T_false: return parse_bool_const(false);
7172 case T_true: return parse_bool_const(true);
7173 case T_INTEGER: return parse_int_const();
7174 case T_CHARACTER_CONSTANT: return parse_character_constant();
7175 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7176 case T_FLOATINGPOINT: return parse_float_const();
7177 case T_STRING_LITERAL:
7178 case T_WIDE_STRING_LITERAL: return parse_string_const();
7179 case T___FUNCTION__:
7180 case T___func__: return parse_function_keyword();
7181 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7182 case T___FUNCSIG__: return parse_funcsig_keyword();
7183 case T___FUNCDNAME__: return parse_funcdname_keyword();
7184 case T___builtin_offsetof: return parse_offsetof();
7185 case T___builtin_va_start: return parse_va_start();
7186 case T___builtin_va_arg: return parse_va_arg();
7187 case T___builtin_va_copy: return parse_va_copy();
7188 case T___builtin_isgreater:
7189 case T___builtin_isgreaterequal:
7190 case T___builtin_isless:
7191 case T___builtin_islessequal:
7192 case T___builtin_islessgreater:
7193 case T___builtin_isunordered: return parse_compare_builtin();
7194 case T___builtin_constant_p: return parse_builtin_constant();
7195 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7196 case T__assume: return parse_assume();
7199 return parse_label_address();
7202 case '(': return parse_parenthesized_expression();
7203 case T___noop: return parse_noop_expression();
7205 /* Gracefully handle type names while parsing expressions. */
7207 return parse_reference();
7209 if (!is_typedef_symbol(token.v.symbol)) {
7210 return parse_reference();
7214 source_position_t const pos = *HERE;
7215 type_t const *const type = parse_typename();
7216 errorf(&pos, "encountered type '%T' while parsing expression", type);
7217 return create_invalid_expression();
7221 errorf(HERE, "unexpected token %K, expected an expression", &token);
7222 return create_invalid_expression();
7226 * Check if the expression has the character type and issue a warning then.
7228 static void check_for_char_index_type(const expression_t *expression)
7230 type_t *const type = expression->base.type;
7231 const type_t *const base_type = skip_typeref(type);
7233 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7234 warning.char_subscripts) {
7235 warningf(&expression->base.source_position,
7236 "array subscript has type '%T'", type);
7240 static expression_t *parse_array_expression(expression_t *left)
7242 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7245 add_anchor_token(']');
7247 expression_t *inside = parse_expression();
7249 type_t *const orig_type_left = left->base.type;
7250 type_t *const orig_type_inside = inside->base.type;
7252 type_t *const type_left = skip_typeref(orig_type_left);
7253 type_t *const type_inside = skip_typeref(orig_type_inside);
7255 type_t *return_type;
7256 array_access_expression_t *array_access = &expression->array_access;
7257 if (is_type_pointer(type_left)) {
7258 return_type = type_left->pointer.points_to;
7259 array_access->array_ref = left;
7260 array_access->index = inside;
7261 check_for_char_index_type(inside);
7262 } else if (is_type_pointer(type_inside)) {
7263 return_type = type_inside->pointer.points_to;
7264 array_access->array_ref = inside;
7265 array_access->index = left;
7266 array_access->flipped = true;
7267 check_for_char_index_type(left);
7269 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7271 "array access on object with non-pointer types '%T', '%T'",
7272 orig_type_left, orig_type_inside);
7274 return_type = type_error_type;
7275 array_access->array_ref = left;
7276 array_access->index = inside;
7279 expression->base.type = automatic_type_conversion(return_type);
7281 rem_anchor_token(']');
7282 expect(']', end_error);
7287 static expression_t *parse_typeprop(expression_kind_t const kind)
7289 expression_t *tp_expression = allocate_expression_zero(kind);
7290 tp_expression->base.type = type_size_t;
7292 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7294 /* we only refer to a type property, mark this case */
7295 bool old = in_type_prop;
7296 in_type_prop = true;
7299 expression_t *expression;
7300 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7302 add_anchor_token(')');
7303 orig_type = parse_typename();
7304 rem_anchor_token(')');
7305 expect(')', end_error);
7307 if (token.type == '{') {
7308 /* It was not sizeof(type) after all. It is sizeof of an expression
7309 * starting with a compound literal */
7310 expression = parse_compound_literal(orig_type);
7311 goto typeprop_expression;
7314 expression = parse_sub_expression(PREC_UNARY);
7316 typeprop_expression:
7317 tp_expression->typeprop.tp_expression = expression;
7319 orig_type = revert_automatic_type_conversion(expression);
7320 expression->base.type = orig_type;
7323 tp_expression->typeprop.type = orig_type;
7324 type_t const* const type = skip_typeref(orig_type);
7325 char const* const wrong_type =
7326 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7327 is_type_incomplete(type) ? "incomplete" :
7328 type->kind == TYPE_FUNCTION ? "function designator" :
7329 type->kind == TYPE_BITFIELD ? "bitfield" :
7331 if (wrong_type != NULL) {
7332 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7333 errorf(&tp_expression->base.source_position,
7334 "operand of %s expression must not be of %s type '%T'",
7335 what, wrong_type, orig_type);
7340 return tp_expression;
7343 static expression_t *parse_sizeof(void)
7345 return parse_typeprop(EXPR_SIZEOF);
7348 static expression_t *parse_alignof(void)
7350 return parse_typeprop(EXPR_ALIGNOF);
7353 static expression_t *parse_select_expression(expression_t *addr)
7355 assert(token.type == '.' || token.type == T_MINUSGREATER);
7356 bool select_left_arrow = (token.type == T_MINUSGREATER);
7359 if (token.type != T_IDENTIFIER) {
7360 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7361 return create_invalid_expression();
7363 symbol_t *symbol = token.v.symbol;
7366 type_t *const orig_type = addr->base.type;
7367 type_t *const type = skip_typeref(orig_type);
7370 bool saw_error = false;
7371 if (is_type_pointer(type)) {
7372 if (!select_left_arrow) {
7374 "request for member '%Y' in something not a struct or union, but '%T'",
7378 type_left = skip_typeref(type->pointer.points_to);
7380 if (select_left_arrow && is_type_valid(type)) {
7381 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7387 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7388 type_left->kind != TYPE_COMPOUND_UNION) {
7390 if (is_type_valid(type_left) && !saw_error) {
7392 "request for member '%Y' in something not a struct or union, but '%T'",
7395 return create_invalid_expression();
7398 compound_t *compound = type_left->compound.compound;
7399 if (!compound->complete) {
7400 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7402 return create_invalid_expression();
7405 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7406 expression_t *result
7407 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7409 if (result == NULL) {
7410 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7411 return create_invalid_expression();
7417 static void check_call_argument(type_t *expected_type,
7418 call_argument_t *argument, unsigned pos)
7420 type_t *expected_type_skip = skip_typeref(expected_type);
7421 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7422 expression_t *arg_expr = argument->expression;
7423 type_t *arg_type = skip_typeref(arg_expr->base.type);
7425 /* handle transparent union gnu extension */
7426 if (is_type_union(expected_type_skip)
7427 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7428 compound_t *union_decl = expected_type_skip->compound.compound;
7429 type_t *best_type = NULL;
7430 entity_t *entry = union_decl->members.entities;
7431 for ( ; entry != NULL; entry = entry->base.next) {
7432 assert(is_declaration(entry));
7433 type_t *decl_type = entry->declaration.type;
7434 error = semantic_assign(decl_type, arg_expr);
7435 if (error == ASSIGN_ERROR_INCOMPATIBLE
7436 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7439 if (error == ASSIGN_SUCCESS) {
7440 best_type = decl_type;
7441 } else if (best_type == NULL) {
7442 best_type = decl_type;
7446 if (best_type != NULL) {
7447 expected_type = best_type;
7451 error = semantic_assign(expected_type, arg_expr);
7452 argument->expression = create_implicit_cast(arg_expr, expected_type);
7454 if (error != ASSIGN_SUCCESS) {
7455 /* report exact scope in error messages (like "in argument 3") */
7457 snprintf(buf, sizeof(buf), "call argument %u", pos);
7458 report_assign_error(error, expected_type, arg_expr, buf,
7459 &arg_expr->base.source_position);
7460 } else if (warning.traditional || warning.conversion) {
7461 type_t *const promoted_type = get_default_promoted_type(arg_type);
7462 if (!types_compatible(expected_type_skip, promoted_type) &&
7463 !types_compatible(expected_type_skip, type_void_ptr) &&
7464 !types_compatible(type_void_ptr, promoted_type)) {
7465 /* Deliberately show the skipped types in this warning */
7466 warningf(&arg_expr->base.source_position,
7467 "passing call argument %u as '%T' rather than '%T' due to prototype",
7468 pos, expected_type_skip, promoted_type);
7474 * Handle the semantic restrictions of builtin calls
7476 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7477 switch (call->function->reference.entity->function.btk) {
7478 case bk_gnu_builtin_return_address:
7479 case bk_gnu_builtin_frame_address: {
7480 /* argument must be constant */
7481 call_argument_t *argument = call->arguments;
7483 if (! is_constant_expression(argument->expression)) {
7484 errorf(&call->base.source_position,
7485 "argument of '%Y' must be a constant expression",
7486 call->function->reference.entity->base.symbol);
7490 case bk_gnu_builtin_prefetch: {
7491 /* second and third argument must be constant if existent */
7492 call_argument_t *rw = call->arguments->next;
7493 call_argument_t *locality = NULL;
7496 if (! is_constant_expression(rw->expression)) {
7497 errorf(&call->base.source_position,
7498 "second argument of '%Y' must be a constant expression",
7499 call->function->reference.entity->base.symbol);
7501 locality = rw->next;
7503 if (locality != NULL) {
7504 if (! is_constant_expression(locality->expression)) {
7505 errorf(&call->base.source_position,
7506 "third argument of '%Y' must be a constant expression",
7507 call->function->reference.entity->base.symbol);
7509 locality = rw->next;
7519 * Parse a call expression, ie. expression '( ... )'.
7521 * @param expression the function address
7523 static expression_t *parse_call_expression(expression_t *expression)
7525 expression_t *result = allocate_expression_zero(EXPR_CALL);
7526 call_expression_t *call = &result->call;
7527 call->function = expression;
7529 type_t *const orig_type = expression->base.type;
7530 type_t *const type = skip_typeref(orig_type);
7532 function_type_t *function_type = NULL;
7533 if (is_type_pointer(type)) {
7534 type_t *const to_type = skip_typeref(type->pointer.points_to);
7536 if (is_type_function(to_type)) {
7537 function_type = &to_type->function;
7538 call->base.type = function_type->return_type;
7542 if (function_type == NULL && is_type_valid(type)) {
7544 "called object '%E' (type '%T') is not a pointer to a function",
7545 expression, orig_type);
7548 /* parse arguments */
7550 add_anchor_token(')');
7551 add_anchor_token(',');
7553 if (token.type != ')') {
7554 call_argument_t **anchor = &call->arguments;
7556 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7557 argument->expression = parse_assignment_expression();
7560 anchor = &argument->next;
7561 } while (next_if(','));
7563 rem_anchor_token(',');
7564 rem_anchor_token(')');
7565 expect(')', end_error);
7567 if (function_type == NULL)
7570 /* check type and count of call arguments */
7571 function_parameter_t *parameter = function_type->parameters;
7572 call_argument_t *argument = call->arguments;
7573 if (!function_type->unspecified_parameters) {
7574 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7575 parameter = parameter->next, argument = argument->next) {
7576 check_call_argument(parameter->type, argument, ++pos);
7579 if (parameter != NULL) {
7580 errorf(HERE, "too few arguments to function '%E'", expression);
7581 } else if (argument != NULL && !function_type->variadic) {
7582 errorf(HERE, "too many arguments to function '%E'", expression);
7586 /* do default promotion for other arguments */
7587 for (; argument != NULL; argument = argument->next) {
7588 type_t *type = argument->expression->base.type;
7590 type = get_default_promoted_type(type);
7592 argument->expression
7593 = create_implicit_cast(argument->expression, type);
7596 check_format(&result->call);
7598 if (warning.aggregate_return &&
7599 is_type_compound(skip_typeref(function_type->return_type))) {
7600 warningf(&result->base.source_position,
7601 "function call has aggregate value");
7604 if (call->function->kind == EXPR_REFERENCE) {
7605 reference_expression_t *reference = &call->function->reference;
7606 if (reference->entity->kind == ENTITY_FUNCTION &&
7607 reference->entity->function.btk != bk_none)
7608 handle_builtin_argument_restrictions(call);
7615 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7617 static bool same_compound_type(const type_t *type1, const type_t *type2)
7620 is_type_compound(type1) &&
7621 type1->kind == type2->kind &&
7622 type1->compound.compound == type2->compound.compound;
7625 static expression_t const *get_reference_address(expression_t const *expr)
7627 bool regular_take_address = true;
7629 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7630 expr = expr->unary.value;
7632 regular_take_address = false;
7635 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7638 expr = expr->unary.value;
7641 if (expr->kind != EXPR_REFERENCE)
7644 /* special case for functions which are automatically converted to a
7645 * pointer to function without an extra TAKE_ADDRESS operation */
7646 if (!regular_take_address &&
7647 expr->reference.entity->kind != ENTITY_FUNCTION) {
7654 static void warn_reference_address_as_bool(expression_t const* expr)
7656 if (!warning.address)
7659 expr = get_reference_address(expr);
7661 warningf(&expr->base.source_position,
7662 "the address of '%Y' will always evaluate as 'true'",
7663 expr->reference.entity->base.symbol);
7667 static void warn_assignment_in_condition(const expression_t *const expr)
7669 if (!warning.parentheses)
7671 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7673 if (expr->base.parenthesized)
7675 warningf(&expr->base.source_position,
7676 "suggest parentheses around assignment used as truth value");
7679 static void semantic_condition(expression_t const *const expr,
7680 char const *const context)
7682 type_t *const type = skip_typeref(expr->base.type);
7683 if (is_type_scalar(type)) {
7684 warn_reference_address_as_bool(expr);
7685 warn_assignment_in_condition(expr);
7686 } else if (is_type_valid(type)) {
7687 errorf(&expr->base.source_position,
7688 "%s must have scalar type", context);
7693 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7695 * @param expression the conditional expression
7697 static expression_t *parse_conditional_expression(expression_t *expression)
7699 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7701 conditional_expression_t *conditional = &result->conditional;
7702 conditional->condition = expression;
7705 add_anchor_token(':');
7707 /* §6.5.15:2 The first operand shall have scalar type. */
7708 semantic_condition(expression, "condition of conditional operator");
7710 expression_t *true_expression = expression;
7711 bool gnu_cond = false;
7712 if (GNU_MODE && token.type == ':') {
7715 true_expression = parse_expression();
7717 rem_anchor_token(':');
7718 expect(':', end_error);
7720 expression_t *false_expression =
7721 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7723 type_t *const orig_true_type = true_expression->base.type;
7724 type_t *const orig_false_type = false_expression->base.type;
7725 type_t *const true_type = skip_typeref(orig_true_type);
7726 type_t *const false_type = skip_typeref(orig_false_type);
7729 type_t *result_type;
7730 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7731 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7732 /* ISO/IEC 14882:1998(E) §5.16:2 */
7733 if (true_expression->kind == EXPR_UNARY_THROW) {
7734 result_type = false_type;
7735 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7736 result_type = true_type;
7738 if (warning.other && (
7739 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7740 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7742 warningf(&conditional->base.source_position,
7743 "ISO C forbids conditional expression with only one void side");
7745 result_type = type_void;
7747 } else if (is_type_arithmetic(true_type)
7748 && is_type_arithmetic(false_type)) {
7749 result_type = semantic_arithmetic(true_type, false_type);
7751 true_expression = create_implicit_cast(true_expression, result_type);
7752 false_expression = create_implicit_cast(false_expression, result_type);
7754 conditional->true_expression = true_expression;
7755 conditional->false_expression = false_expression;
7756 conditional->base.type = result_type;
7757 } else if (same_compound_type(true_type, false_type)) {
7758 /* just take 1 of the 2 types */
7759 result_type = true_type;
7760 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7761 type_t *pointer_type;
7763 expression_t *other_expression;
7764 if (is_type_pointer(true_type) &&
7765 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7766 pointer_type = true_type;
7767 other_type = false_type;
7768 other_expression = false_expression;
7770 pointer_type = false_type;
7771 other_type = true_type;
7772 other_expression = true_expression;
7775 if (is_null_pointer_constant(other_expression)) {
7776 result_type = pointer_type;
7777 } else if (is_type_pointer(other_type)) {
7778 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7779 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7782 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7783 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7785 } else if (types_compatible(get_unqualified_type(to1),
7786 get_unqualified_type(to2))) {
7789 if (warning.other) {
7790 warningf(&conditional->base.source_position,
7791 "pointer types '%T' and '%T' in conditional expression are incompatible",
7792 true_type, false_type);
7797 type_t *const type =
7798 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7799 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7800 } else if (is_type_integer(other_type)) {
7801 if (warning.other) {
7802 warningf(&conditional->base.source_position,
7803 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7805 result_type = pointer_type;
7807 if (is_type_valid(other_type)) {
7808 type_error_incompatible("while parsing conditional",
7809 &expression->base.source_position, true_type, false_type);
7811 result_type = type_error_type;
7814 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7815 type_error_incompatible("while parsing conditional",
7816 &conditional->base.source_position, true_type,
7819 result_type = type_error_type;
7822 conditional->true_expression
7823 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7824 conditional->false_expression
7825 = create_implicit_cast(false_expression, result_type);
7826 conditional->base.type = result_type;
7831 * Parse an extension expression.
7833 static expression_t *parse_extension(void)
7835 eat(T___extension__);
7837 bool old_gcc_extension = in_gcc_extension;
7838 in_gcc_extension = true;
7839 expression_t *expression = parse_sub_expression(PREC_UNARY);
7840 in_gcc_extension = old_gcc_extension;
7845 * Parse a __builtin_classify_type() expression.
7847 static expression_t *parse_builtin_classify_type(void)
7849 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7850 result->base.type = type_int;
7852 eat(T___builtin_classify_type);
7854 expect('(', end_error);
7855 add_anchor_token(')');
7856 expression_t *expression = parse_expression();
7857 rem_anchor_token(')');
7858 expect(')', end_error);
7859 result->classify_type.type_expression = expression;
7863 return create_invalid_expression();
7867 * Parse a delete expression
7868 * ISO/IEC 14882:1998(E) §5.3.5
7870 static expression_t *parse_delete(void)
7872 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7873 result->base.type = type_void;
7878 result->kind = EXPR_UNARY_DELETE_ARRAY;
7879 expect(']', end_error);
7883 expression_t *const value = parse_sub_expression(PREC_CAST);
7884 result->unary.value = value;
7886 type_t *const type = skip_typeref(value->base.type);
7887 if (!is_type_pointer(type)) {
7888 if (is_type_valid(type)) {
7889 errorf(&value->base.source_position,
7890 "operand of delete must have pointer type");
7892 } else if (warning.other &&
7893 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7894 warningf(&value->base.source_position,
7895 "deleting 'void*' is undefined");
7902 * Parse a throw expression
7903 * ISO/IEC 14882:1998(E) §15:1
7905 static expression_t *parse_throw(void)
7907 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7908 result->base.type = type_void;
7912 expression_t *value = NULL;
7913 switch (token.type) {
7915 value = parse_assignment_expression();
7916 /* ISO/IEC 14882:1998(E) §15.1:3 */
7917 type_t *const orig_type = value->base.type;
7918 type_t *const type = skip_typeref(orig_type);
7919 if (is_type_incomplete(type)) {
7920 errorf(&value->base.source_position,
7921 "cannot throw object of incomplete type '%T'", orig_type);
7922 } else if (is_type_pointer(type)) {
7923 type_t *const points_to = skip_typeref(type->pointer.points_to);
7924 if (is_type_incomplete(points_to) &&
7925 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7926 errorf(&value->base.source_position,
7927 "cannot throw pointer to incomplete type '%T'", orig_type);
7935 result->unary.value = value;
7940 static bool check_pointer_arithmetic(const source_position_t *source_position,
7941 type_t *pointer_type,
7942 type_t *orig_pointer_type)
7944 type_t *points_to = pointer_type->pointer.points_to;
7945 points_to = skip_typeref(points_to);
7947 if (is_type_incomplete(points_to)) {
7948 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7949 errorf(source_position,
7950 "arithmetic with pointer to incomplete type '%T' not allowed",
7953 } else if (warning.pointer_arith) {
7954 warningf(source_position,
7955 "pointer of type '%T' used in arithmetic",
7958 } else if (is_type_function(points_to)) {
7960 errorf(source_position,
7961 "arithmetic with pointer to function type '%T' not allowed",
7964 } else if (warning.pointer_arith) {
7965 warningf(source_position,
7966 "pointer to a function '%T' used in arithmetic",
7973 static bool is_lvalue(const expression_t *expression)
7975 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7976 switch (expression->kind) {
7977 case EXPR_ARRAY_ACCESS:
7978 case EXPR_COMPOUND_LITERAL:
7979 case EXPR_REFERENCE:
7981 case EXPR_UNARY_DEREFERENCE:
7985 type_t *type = skip_typeref(expression->base.type);
7987 /* ISO/IEC 14882:1998(E) §3.10:3 */
7988 is_type_reference(type) ||
7989 /* Claim it is an lvalue, if the type is invalid. There was a parse
7990 * error before, which maybe prevented properly recognizing it as
7992 !is_type_valid(type);
7997 static void semantic_incdec(unary_expression_t *expression)
7999 type_t *const orig_type = expression->value->base.type;
8000 type_t *const type = skip_typeref(orig_type);
8001 if (is_type_pointer(type)) {
8002 if (!check_pointer_arithmetic(&expression->base.source_position,
8006 } else if (!is_type_real(type) && is_type_valid(type)) {
8007 /* TODO: improve error message */
8008 errorf(&expression->base.source_position,
8009 "operation needs an arithmetic or pointer type");
8012 if (!is_lvalue(expression->value)) {
8013 /* TODO: improve error message */
8014 errorf(&expression->base.source_position, "lvalue required as operand");
8016 expression->base.type = orig_type;
8019 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8021 type_t *const orig_type = expression->value->base.type;
8022 type_t *const type = skip_typeref(orig_type);
8023 if (!is_type_arithmetic(type)) {
8024 if (is_type_valid(type)) {
8025 /* TODO: improve error message */
8026 errorf(&expression->base.source_position,
8027 "operation needs an arithmetic type");
8032 expression->base.type = orig_type;
8035 static void semantic_unexpr_plus(unary_expression_t *expression)
8037 semantic_unexpr_arithmetic(expression);
8038 if (warning.traditional)
8039 warningf(&expression->base.source_position,
8040 "traditional C rejects the unary plus operator");
8043 static void semantic_not(unary_expression_t *expression)
8045 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8046 semantic_condition(expression->value, "operand of !");
8047 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8050 static void semantic_unexpr_integer(unary_expression_t *expression)
8052 type_t *const orig_type = expression->value->base.type;
8053 type_t *const type = skip_typeref(orig_type);
8054 if (!is_type_integer(type)) {
8055 if (is_type_valid(type)) {
8056 errorf(&expression->base.source_position,
8057 "operand of ~ must be of integer type");
8062 expression->base.type = orig_type;
8065 static void semantic_dereference(unary_expression_t *expression)
8067 type_t *const orig_type = expression->value->base.type;
8068 type_t *const type = skip_typeref(orig_type);
8069 if (!is_type_pointer(type)) {
8070 if (is_type_valid(type)) {
8071 errorf(&expression->base.source_position,
8072 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8077 type_t *result_type = type->pointer.points_to;
8078 result_type = automatic_type_conversion(result_type);
8079 expression->base.type = result_type;
8083 * Record that an address is taken (expression represents an lvalue).
8085 * @param expression the expression
8086 * @param may_be_register if true, the expression might be an register
8088 static void set_address_taken(expression_t *expression, bool may_be_register)
8090 if (expression->kind != EXPR_REFERENCE)
8093 entity_t *const entity = expression->reference.entity;
8095 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8098 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8099 && !may_be_register) {
8100 errorf(&expression->base.source_position,
8101 "address of register %s '%Y' requested",
8102 get_entity_kind_name(entity->kind), entity->base.symbol);
8105 if (entity->kind == ENTITY_VARIABLE) {
8106 entity->variable.address_taken = true;
8108 assert(entity->kind == ENTITY_PARAMETER);
8109 entity->parameter.address_taken = true;
8114 * Check the semantic of the address taken expression.
8116 static void semantic_take_addr(unary_expression_t *expression)
8118 expression_t *value = expression->value;
8119 value->base.type = revert_automatic_type_conversion(value);
8121 type_t *orig_type = value->base.type;
8122 type_t *type = skip_typeref(orig_type);
8123 if (!is_type_valid(type))
8127 if (!is_lvalue(value)) {
8128 errorf(&expression->base.source_position, "'&' requires an lvalue");
8130 if (type->kind == TYPE_BITFIELD) {
8131 errorf(&expression->base.source_position,
8132 "'&' not allowed on object with bitfield type '%T'",
8136 set_address_taken(value, false);
8138 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8141 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8142 static expression_t *parse_##unexpression_type(void) \
8144 expression_t *unary_expression \
8145 = allocate_expression_zero(unexpression_type); \
8147 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8149 sfunc(&unary_expression->unary); \
8151 return unary_expression; \
8154 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8155 semantic_unexpr_arithmetic)
8156 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8157 semantic_unexpr_plus)
8158 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8160 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8161 semantic_dereference)
8162 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8164 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8165 semantic_unexpr_integer)
8166 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8168 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8171 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8173 static expression_t *parse_##unexpression_type(expression_t *left) \
8175 expression_t *unary_expression \
8176 = allocate_expression_zero(unexpression_type); \
8178 unary_expression->unary.value = left; \
8180 sfunc(&unary_expression->unary); \
8182 return unary_expression; \
8185 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8186 EXPR_UNARY_POSTFIX_INCREMENT,
8188 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8189 EXPR_UNARY_POSTFIX_DECREMENT,
8192 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8194 /* TODO: handle complex + imaginary types */
8196 type_left = get_unqualified_type(type_left);
8197 type_right = get_unqualified_type(type_right);
8199 /* §6.3.1.8 Usual arithmetic conversions */
8200 if (type_left == type_long_double || type_right == type_long_double) {
8201 return type_long_double;
8202 } else if (type_left == type_double || type_right == type_double) {
8204 } else if (type_left == type_float || type_right == type_float) {
8208 type_left = promote_integer(type_left);
8209 type_right = promote_integer(type_right);
8211 if (type_left == type_right)
8214 bool const signed_left = is_type_signed(type_left);
8215 bool const signed_right = is_type_signed(type_right);
8216 int const rank_left = get_rank(type_left);
8217 int const rank_right = get_rank(type_right);
8219 if (signed_left == signed_right)
8220 return rank_left >= rank_right ? type_left : type_right;
8229 u_rank = rank_right;
8230 u_type = type_right;
8232 s_rank = rank_right;
8233 s_type = type_right;
8238 if (u_rank >= s_rank)
8241 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8243 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8244 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8248 case ATOMIC_TYPE_INT: return type_unsigned_int;
8249 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8250 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8252 default: panic("invalid atomic type");
8257 * Check the semantic restrictions for a binary expression.
8259 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8261 expression_t *const left = expression->left;
8262 expression_t *const right = expression->right;
8263 type_t *const orig_type_left = left->base.type;
8264 type_t *const orig_type_right = right->base.type;
8265 type_t *const type_left = skip_typeref(orig_type_left);
8266 type_t *const type_right = skip_typeref(orig_type_right);
8268 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8269 /* TODO: improve error message */
8270 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8271 errorf(&expression->base.source_position,
8272 "operation needs arithmetic types");
8277 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8278 expression->left = create_implicit_cast(left, arithmetic_type);
8279 expression->right = create_implicit_cast(right, arithmetic_type);
8280 expression->base.type = arithmetic_type;
8283 static void warn_div_by_zero(binary_expression_t const *const expression)
8285 if (!warning.div_by_zero ||
8286 !is_type_integer(expression->base.type))
8289 expression_t const *const right = expression->right;
8290 /* The type of the right operand can be different for /= */
8291 if (is_type_integer(right->base.type) &&
8292 is_constant_expression(right) &&
8293 !fold_constant_to_bool(right)) {
8294 warningf(&expression->base.source_position, "division by zero");
8299 * Check the semantic restrictions for a div/mod expression.
8301 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8303 semantic_binexpr_arithmetic(expression);
8304 warn_div_by_zero(expression);
8307 static void warn_addsub_in_shift(const expression_t *const expr)
8309 if (expr->base.parenthesized)
8313 switch (expr->kind) {
8314 case EXPR_BINARY_ADD: op = '+'; break;
8315 case EXPR_BINARY_SUB: op = '-'; break;
8319 warningf(&expr->base.source_position,
8320 "suggest parentheses around '%c' inside shift", op);
8323 static bool semantic_shift(binary_expression_t *expression)
8325 expression_t *const left = expression->left;
8326 expression_t *const right = expression->right;
8327 type_t *const orig_type_left = left->base.type;
8328 type_t *const orig_type_right = right->base.type;
8329 type_t * type_left = skip_typeref(orig_type_left);
8330 type_t * type_right = skip_typeref(orig_type_right);
8332 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8333 /* TODO: improve error message */
8334 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8335 errorf(&expression->base.source_position,
8336 "operands of shift operation must have integer types");
8341 type_left = promote_integer(type_left);
8343 if (is_constant_expression(right)) {
8344 long count = fold_constant_to_int(right);
8346 warningf(&right->base.source_position,
8347 "shift count must be non-negative");
8348 } else if ((unsigned long)count >=
8349 get_atomic_type_size(type_left->atomic.akind) * 8) {
8350 warningf(&right->base.source_position,
8351 "shift count must be less than type width");
8355 type_right = promote_integer(type_right);
8356 expression->right = create_implicit_cast(right, type_right);
8361 static void semantic_shift_op(binary_expression_t *expression)
8363 expression_t *const left = expression->left;
8364 expression_t *const right = expression->right;
8366 if (!semantic_shift(expression))
8369 if (warning.parentheses) {
8370 warn_addsub_in_shift(left);
8371 warn_addsub_in_shift(right);
8374 type_t *const orig_type_left = left->base.type;
8375 type_t * type_left = skip_typeref(orig_type_left);
8377 type_left = promote_integer(type_left);
8378 expression->left = create_implicit_cast(left, type_left);
8379 expression->base.type = type_left;
8382 static void semantic_add(binary_expression_t *expression)
8384 expression_t *const left = expression->left;
8385 expression_t *const right = expression->right;
8386 type_t *const orig_type_left = left->base.type;
8387 type_t *const orig_type_right = right->base.type;
8388 type_t *const type_left = skip_typeref(orig_type_left);
8389 type_t *const type_right = skip_typeref(orig_type_right);
8392 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8393 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8394 expression->left = create_implicit_cast(left, arithmetic_type);
8395 expression->right = create_implicit_cast(right, arithmetic_type);
8396 expression->base.type = arithmetic_type;
8397 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8398 check_pointer_arithmetic(&expression->base.source_position,
8399 type_left, orig_type_left);
8400 expression->base.type = type_left;
8401 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8402 check_pointer_arithmetic(&expression->base.source_position,
8403 type_right, orig_type_right);
8404 expression->base.type = type_right;
8405 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8406 errorf(&expression->base.source_position,
8407 "invalid operands to binary + ('%T', '%T')",
8408 orig_type_left, orig_type_right);
8412 static void semantic_sub(binary_expression_t *expression)
8414 expression_t *const left = expression->left;
8415 expression_t *const right = expression->right;
8416 type_t *const orig_type_left = left->base.type;
8417 type_t *const orig_type_right = right->base.type;
8418 type_t *const type_left = skip_typeref(orig_type_left);
8419 type_t *const type_right = skip_typeref(orig_type_right);
8420 source_position_t const *const pos = &expression->base.source_position;
8423 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8424 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8425 expression->left = create_implicit_cast(left, arithmetic_type);
8426 expression->right = create_implicit_cast(right, arithmetic_type);
8427 expression->base.type = arithmetic_type;
8428 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8429 check_pointer_arithmetic(&expression->base.source_position,
8430 type_left, orig_type_left);
8431 expression->base.type = type_left;
8432 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8433 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8434 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8435 if (!types_compatible(unqual_left, unqual_right)) {
8437 "subtracting pointers to incompatible types '%T' and '%T'",
8438 orig_type_left, orig_type_right);
8439 } else if (!is_type_object(unqual_left)) {
8440 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8441 errorf(pos, "subtracting pointers to non-object types '%T'",
8443 } else if (warning.other) {
8444 warningf(pos, "subtracting pointers to void");
8447 expression->base.type = type_ptrdiff_t;
8448 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8449 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8450 orig_type_left, orig_type_right);
8454 static void warn_string_literal_address(expression_t const* expr)
8456 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8457 expr = expr->unary.value;
8458 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8460 expr = expr->unary.value;
8463 if (expr->kind == EXPR_STRING_LITERAL ||
8464 expr->kind == EXPR_WIDE_STRING_LITERAL) {
8465 warningf(&expr->base.source_position,
8466 "comparison with string literal results in unspecified behaviour");
8470 static void warn_comparison_in_comparison(const expression_t *const expr)
8472 if (expr->base.parenthesized)
8474 switch (expr->base.kind) {
8475 case EXPR_BINARY_LESS:
8476 case EXPR_BINARY_GREATER:
8477 case EXPR_BINARY_LESSEQUAL:
8478 case EXPR_BINARY_GREATEREQUAL:
8479 case EXPR_BINARY_NOTEQUAL:
8480 case EXPR_BINARY_EQUAL:
8481 warningf(&expr->base.source_position,
8482 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8489 static bool maybe_negative(expression_t const *const expr)
8492 !is_constant_expression(expr) ||
8493 fold_constant_to_int(expr) < 0;
8497 * Check the semantics of comparison expressions.
8499 * @param expression The expression to check.
8501 static void semantic_comparison(binary_expression_t *expression)
8503 expression_t *left = expression->left;
8504 expression_t *right = expression->right;
8506 if (warning.address) {
8507 warn_string_literal_address(left);
8508 warn_string_literal_address(right);
8510 expression_t const* const func_left = get_reference_address(left);
8511 if (func_left != NULL && is_null_pointer_constant(right)) {
8512 warningf(&expression->base.source_position,
8513 "the address of '%Y' will never be NULL",
8514 func_left->reference.entity->base.symbol);
8517 expression_t const* const func_right = get_reference_address(right);
8518 if (func_right != NULL && is_null_pointer_constant(right)) {
8519 warningf(&expression->base.source_position,
8520 "the address of '%Y' will never be NULL",
8521 func_right->reference.entity->base.symbol);
8525 if (warning.parentheses) {
8526 warn_comparison_in_comparison(left);
8527 warn_comparison_in_comparison(right);
8530 type_t *orig_type_left = left->base.type;
8531 type_t *orig_type_right = right->base.type;
8532 type_t *type_left = skip_typeref(orig_type_left);
8533 type_t *type_right = skip_typeref(orig_type_right);
8535 /* TODO non-arithmetic types */
8536 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8537 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8539 /* test for signed vs unsigned compares */
8540 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8541 bool const signed_left = is_type_signed(type_left);
8542 bool const signed_right = is_type_signed(type_right);
8543 if (signed_left != signed_right) {
8544 /* FIXME long long needs better const folding magic */
8545 /* TODO check whether constant value can be represented by other type */
8546 if ((signed_left && maybe_negative(left)) ||
8547 (signed_right && maybe_negative(right))) {
8548 warningf(&expression->base.source_position,
8549 "comparison between signed and unsigned");
8554 expression->left = create_implicit_cast(left, arithmetic_type);
8555 expression->right = create_implicit_cast(right, arithmetic_type);
8556 expression->base.type = arithmetic_type;
8557 if (warning.float_equal &&
8558 (expression->base.kind == EXPR_BINARY_EQUAL ||
8559 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8560 is_type_float(arithmetic_type)) {
8561 warningf(&expression->base.source_position,
8562 "comparing floating point with == or != is unsafe");
8564 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8565 /* TODO check compatibility */
8566 } else if (is_type_pointer(type_left)) {
8567 expression->right = create_implicit_cast(right, type_left);
8568 } else if (is_type_pointer(type_right)) {
8569 expression->left = create_implicit_cast(left, type_right);
8570 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8571 type_error_incompatible("invalid operands in comparison",
8572 &expression->base.source_position,
8573 type_left, type_right);
8575 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8579 * Checks if a compound type has constant fields.
8581 static bool has_const_fields(const compound_type_t *type)
8583 compound_t *compound = type->compound;
8584 entity_t *entry = compound->members.entities;
8586 for (; entry != NULL; entry = entry->base.next) {
8587 if (!is_declaration(entry))
8590 const type_t *decl_type = skip_typeref(entry->declaration.type);
8591 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8598 static bool is_valid_assignment_lhs(expression_t const* const left)
8600 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8601 type_t *const type_left = skip_typeref(orig_type_left);
8603 if (!is_lvalue(left)) {
8604 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8609 if (left->kind == EXPR_REFERENCE
8610 && left->reference.entity->kind == ENTITY_FUNCTION) {
8611 errorf(HERE, "cannot assign to function '%E'", left);
8615 if (is_type_array(type_left)) {
8616 errorf(HERE, "cannot assign to array '%E'", left);
8619 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8620 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8624 if (is_type_incomplete(type_left)) {
8625 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8626 left, orig_type_left);
8629 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8630 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8631 left, orig_type_left);
8638 static void semantic_arithmetic_assign(binary_expression_t *expression)
8640 expression_t *left = expression->left;
8641 expression_t *right = expression->right;
8642 type_t *orig_type_left = left->base.type;
8643 type_t *orig_type_right = right->base.type;
8645 if (!is_valid_assignment_lhs(left))
8648 type_t *type_left = skip_typeref(orig_type_left);
8649 type_t *type_right = skip_typeref(orig_type_right);
8651 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8652 /* TODO: improve error message */
8653 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8654 errorf(&expression->base.source_position,
8655 "operation needs arithmetic types");
8660 /* combined instructions are tricky. We can't create an implicit cast on
8661 * the left side, because we need the uncasted form for the store.
8662 * The ast2firm pass has to know that left_type must be right_type
8663 * for the arithmetic operation and create a cast by itself */
8664 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8665 expression->right = create_implicit_cast(right, arithmetic_type);
8666 expression->base.type = type_left;
8669 static void semantic_divmod_assign(binary_expression_t *expression)
8671 semantic_arithmetic_assign(expression);
8672 warn_div_by_zero(expression);
8675 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8677 expression_t *const left = expression->left;
8678 expression_t *const right = expression->right;
8679 type_t *const orig_type_left = left->base.type;
8680 type_t *const orig_type_right = right->base.type;
8681 type_t *const type_left = skip_typeref(orig_type_left);
8682 type_t *const type_right = skip_typeref(orig_type_right);
8684 if (!is_valid_assignment_lhs(left))
8687 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8688 /* combined instructions are tricky. We can't create an implicit cast on
8689 * the left side, because we need the uncasted form for the store.
8690 * The ast2firm pass has to know that left_type must be right_type
8691 * for the arithmetic operation and create a cast by itself */
8692 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8693 expression->right = create_implicit_cast(right, arithmetic_type);
8694 expression->base.type = type_left;
8695 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8696 check_pointer_arithmetic(&expression->base.source_position,
8697 type_left, orig_type_left);
8698 expression->base.type = type_left;
8699 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8700 errorf(&expression->base.source_position,
8701 "incompatible types '%T' and '%T' in assignment",
8702 orig_type_left, orig_type_right);
8706 static void semantic_integer_assign(binary_expression_t *expression)
8708 expression_t *left = expression->left;
8709 expression_t *right = expression->right;
8710 type_t *orig_type_left = left->base.type;
8711 type_t *orig_type_right = right->base.type;
8713 if (!is_valid_assignment_lhs(left))
8716 type_t *type_left = skip_typeref(orig_type_left);
8717 type_t *type_right = skip_typeref(orig_type_right);
8719 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8720 /* TODO: improve error message */
8721 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8722 errorf(&expression->base.source_position,
8723 "operation needs integer types");
8728 /* combined instructions are tricky. We can't create an implicit cast on
8729 * the left side, because we need the uncasted form for the store.
8730 * The ast2firm pass has to know that left_type must be right_type
8731 * for the arithmetic operation and create a cast by itself */
8732 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8733 expression->right = create_implicit_cast(right, arithmetic_type);
8734 expression->base.type = type_left;
8737 static void semantic_shift_assign(binary_expression_t *expression)
8739 expression_t *left = expression->left;
8741 if (!is_valid_assignment_lhs(left))
8744 if (!semantic_shift(expression))
8747 expression->base.type = skip_typeref(left->base.type);
8750 static void warn_logical_and_within_or(const expression_t *const expr)
8752 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8754 if (expr->base.parenthesized)
8756 warningf(&expr->base.source_position,
8757 "suggest parentheses around && within ||");
8761 * Check the semantic restrictions of a logical expression.
8763 static void semantic_logical_op(binary_expression_t *expression)
8765 /* §6.5.13:2 Each of the operands shall have scalar type.
8766 * §6.5.14:2 Each of the operands shall have scalar type. */
8767 semantic_condition(expression->left, "left operand of logical operator");
8768 semantic_condition(expression->right, "right operand of logical operator");
8769 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8770 warning.parentheses) {
8771 warn_logical_and_within_or(expression->left);
8772 warn_logical_and_within_or(expression->right);
8774 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8778 * Check the semantic restrictions of a binary assign expression.
8780 static void semantic_binexpr_assign(binary_expression_t *expression)
8782 expression_t *left = expression->left;
8783 type_t *orig_type_left = left->base.type;
8785 if (!is_valid_assignment_lhs(left))
8788 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8789 report_assign_error(error, orig_type_left, expression->right,
8790 "assignment", &left->base.source_position);
8791 expression->right = create_implicit_cast(expression->right, orig_type_left);
8792 expression->base.type = orig_type_left;
8796 * Determine if the outermost operation (or parts thereof) of the given
8797 * expression has no effect in order to generate a warning about this fact.
8798 * Therefore in some cases this only examines some of the operands of the
8799 * expression (see comments in the function and examples below).
8801 * f() + 23; // warning, because + has no effect
8802 * x || f(); // no warning, because x controls execution of f()
8803 * x ? y : f(); // warning, because y has no effect
8804 * (void)x; // no warning to be able to suppress the warning
8805 * This function can NOT be used for an "expression has definitely no effect"-
8807 static bool expression_has_effect(const expression_t *const expr)
8809 switch (expr->kind) {
8810 case EXPR_UNKNOWN: break;
8811 case EXPR_INVALID: return true; /* do NOT warn */
8812 case EXPR_REFERENCE: return false;
8813 case EXPR_REFERENCE_ENUM_VALUE: return false;
8814 /* suppress the warning for microsoft __noop operations */
8815 case EXPR_CONST: return expr->conste.is_ms_noop;
8816 case EXPR_CHARACTER_CONSTANT: return false;
8817 case EXPR_WIDE_CHARACTER_CONSTANT: return false;
8818 case EXPR_STRING_LITERAL: return false;
8819 case EXPR_WIDE_STRING_LITERAL: return false;
8820 case EXPR_LABEL_ADDRESS: return false;
8823 const call_expression_t *const call = &expr->call;
8824 if (call->function->kind != EXPR_REFERENCE)
8827 switch (call->function->reference.entity->function.btk) {
8828 /* FIXME: which builtins have no effect? */
8829 default: return true;
8833 /* Generate the warning if either the left or right hand side of a
8834 * conditional expression has no effect */
8835 case EXPR_CONDITIONAL: {
8836 conditional_expression_t const *const cond = &expr->conditional;
8837 expression_t const *const t = cond->true_expression;
8839 (t == NULL || expression_has_effect(t)) &&
8840 expression_has_effect(cond->false_expression);
8843 case EXPR_SELECT: return false;
8844 case EXPR_ARRAY_ACCESS: return false;
8845 case EXPR_SIZEOF: return false;
8846 case EXPR_CLASSIFY_TYPE: return false;
8847 case EXPR_ALIGNOF: return false;
8849 case EXPR_FUNCNAME: return false;
8850 case EXPR_BUILTIN_CONSTANT_P: return false;
8851 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8852 case EXPR_OFFSETOF: return false;
8853 case EXPR_VA_START: return true;
8854 case EXPR_VA_ARG: return true;
8855 case EXPR_VA_COPY: return true;
8856 case EXPR_STATEMENT: return true; // TODO
8857 case EXPR_COMPOUND_LITERAL: return false;
8859 case EXPR_UNARY_NEGATE: return false;
8860 case EXPR_UNARY_PLUS: return false;
8861 case EXPR_UNARY_BITWISE_NEGATE: return false;
8862 case EXPR_UNARY_NOT: return false;
8863 case EXPR_UNARY_DEREFERENCE: return false;
8864 case EXPR_UNARY_TAKE_ADDRESS: return false;
8865 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8866 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8867 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8868 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8870 /* Treat void casts as if they have an effect in order to being able to
8871 * suppress the warning */
8872 case EXPR_UNARY_CAST: {
8873 type_t *const type = skip_typeref(expr->base.type);
8874 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8877 case EXPR_UNARY_CAST_IMPLICIT: return true;
8878 case EXPR_UNARY_ASSUME: return true;
8879 case EXPR_UNARY_DELETE: return true;
8880 case EXPR_UNARY_DELETE_ARRAY: return true;
8881 case EXPR_UNARY_THROW: return true;
8883 case EXPR_BINARY_ADD: return false;
8884 case EXPR_BINARY_SUB: return false;
8885 case EXPR_BINARY_MUL: return false;
8886 case EXPR_BINARY_DIV: return false;
8887 case EXPR_BINARY_MOD: return false;
8888 case EXPR_BINARY_EQUAL: return false;
8889 case EXPR_BINARY_NOTEQUAL: return false;
8890 case EXPR_BINARY_LESS: return false;
8891 case EXPR_BINARY_LESSEQUAL: return false;
8892 case EXPR_BINARY_GREATER: return false;
8893 case EXPR_BINARY_GREATEREQUAL: return false;
8894 case EXPR_BINARY_BITWISE_AND: return false;
8895 case EXPR_BINARY_BITWISE_OR: return false;
8896 case EXPR_BINARY_BITWISE_XOR: return false;
8897 case EXPR_BINARY_SHIFTLEFT: return false;
8898 case EXPR_BINARY_SHIFTRIGHT: return false;
8899 case EXPR_BINARY_ASSIGN: return true;
8900 case EXPR_BINARY_MUL_ASSIGN: return true;
8901 case EXPR_BINARY_DIV_ASSIGN: return true;
8902 case EXPR_BINARY_MOD_ASSIGN: return true;
8903 case EXPR_BINARY_ADD_ASSIGN: return true;
8904 case EXPR_BINARY_SUB_ASSIGN: return true;
8905 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8906 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8907 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8908 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8909 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8911 /* Only examine the right hand side of && and ||, because the left hand
8912 * side already has the effect of controlling the execution of the right
8914 case EXPR_BINARY_LOGICAL_AND:
8915 case EXPR_BINARY_LOGICAL_OR:
8916 /* Only examine the right hand side of a comma expression, because the left
8917 * hand side has a separate warning */
8918 case EXPR_BINARY_COMMA:
8919 return expression_has_effect(expr->binary.right);
8921 case EXPR_BINARY_ISGREATER: return false;
8922 case EXPR_BINARY_ISGREATEREQUAL: return false;
8923 case EXPR_BINARY_ISLESS: return false;
8924 case EXPR_BINARY_ISLESSEQUAL: return false;
8925 case EXPR_BINARY_ISLESSGREATER: return false;
8926 case EXPR_BINARY_ISUNORDERED: return false;
8929 internal_errorf(HERE, "unexpected expression");
8932 static void semantic_comma(binary_expression_t *expression)
8934 if (warning.unused_value) {
8935 const expression_t *const left = expression->left;
8936 if (!expression_has_effect(left)) {
8937 warningf(&left->base.source_position,
8938 "left-hand operand of comma expression has no effect");
8941 expression->base.type = expression->right->base.type;
8945 * @param prec_r precedence of the right operand
8947 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8948 static expression_t *parse_##binexpression_type(expression_t *left) \
8950 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8951 binexpr->binary.left = left; \
8954 expression_t *right = parse_sub_expression(prec_r); \
8956 binexpr->binary.right = right; \
8957 sfunc(&binexpr->binary); \
8962 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8963 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8964 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8965 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8966 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8967 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8968 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8969 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8970 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8971 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8972 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8973 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8974 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8975 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8976 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8977 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8978 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8979 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8980 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8981 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8982 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8983 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8984 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8985 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8986 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8987 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8988 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8989 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8990 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8991 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8994 static expression_t *parse_sub_expression(precedence_t precedence)
8996 if (token.type < 0) {
8997 return expected_expression_error();
9000 expression_parser_function_t *parser
9001 = &expression_parsers[token.type];
9002 source_position_t source_position = token.source_position;
9005 if (parser->parser != NULL) {
9006 left = parser->parser();
9008 left = parse_primary_expression();
9010 assert(left != NULL);
9011 left->base.source_position = source_position;
9014 if (token.type < 0) {
9015 return expected_expression_error();
9018 parser = &expression_parsers[token.type];
9019 if (parser->infix_parser == NULL)
9021 if (parser->infix_precedence < precedence)
9024 left = parser->infix_parser(left);
9026 assert(left != NULL);
9027 assert(left->kind != EXPR_UNKNOWN);
9028 left->base.source_position = source_position;
9035 * Parse an expression.
9037 static expression_t *parse_expression(void)
9039 return parse_sub_expression(PREC_EXPRESSION);
9043 * Register a parser for a prefix-like operator.
9045 * @param parser the parser function
9046 * @param token_type the token type of the prefix token
9048 static void register_expression_parser(parse_expression_function parser,
9051 expression_parser_function_t *entry = &expression_parsers[token_type];
9053 if (entry->parser != NULL) {
9054 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9055 panic("trying to register multiple expression parsers for a token");
9057 entry->parser = parser;
9061 * Register a parser for an infix operator with given precedence.
9063 * @param parser the parser function
9064 * @param token_type the token type of the infix operator
9065 * @param precedence the precedence of the operator
9067 static void register_infix_parser(parse_expression_infix_function parser,
9068 int token_type, precedence_t precedence)
9070 expression_parser_function_t *entry = &expression_parsers[token_type];
9072 if (entry->infix_parser != NULL) {
9073 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9074 panic("trying to register multiple infix expression parsers for a "
9077 entry->infix_parser = parser;
9078 entry->infix_precedence = precedence;
9082 * Initialize the expression parsers.
9084 static void init_expression_parsers(void)
9086 memset(&expression_parsers, 0, sizeof(expression_parsers));
9088 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9089 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9090 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9091 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9092 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9093 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9094 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9095 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9096 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9097 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9098 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9099 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9100 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9101 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9102 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9103 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9104 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9105 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9106 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9107 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9108 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9109 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9110 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9111 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9112 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9113 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9114 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9115 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9116 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9117 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9118 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9119 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9120 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9121 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9122 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9123 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9124 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9126 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9127 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9128 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9129 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9130 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9131 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9132 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9133 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9134 register_expression_parser(parse_sizeof, T_sizeof);
9135 register_expression_parser(parse_alignof, T___alignof__);
9136 register_expression_parser(parse_extension, T___extension__);
9137 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9138 register_expression_parser(parse_delete, T_delete);
9139 register_expression_parser(parse_throw, T_throw);
9143 * Parse a asm statement arguments specification.
9145 static asm_argument_t *parse_asm_arguments(bool is_out)
9147 asm_argument_t *result = NULL;
9148 asm_argument_t **anchor = &result;
9150 while (token.type == T_STRING_LITERAL || token.type == '[') {
9151 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9152 memset(argument, 0, sizeof(argument[0]));
9155 if (token.type != T_IDENTIFIER) {
9156 parse_error_expected("while parsing asm argument",
9157 T_IDENTIFIER, NULL);
9160 argument->symbol = token.v.symbol;
9162 expect(']', end_error);
9165 argument->constraints = parse_string_literals();
9166 expect('(', end_error);
9167 add_anchor_token(')');
9168 expression_t *expression = parse_expression();
9169 rem_anchor_token(')');
9171 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9172 * change size or type representation (e.g. int -> long is ok, but
9173 * int -> float is not) */
9174 if (expression->kind == EXPR_UNARY_CAST) {
9175 type_t *const type = expression->base.type;
9176 type_kind_t const kind = type->kind;
9177 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9180 if (kind == TYPE_ATOMIC) {
9181 atomic_type_kind_t const akind = type->atomic.akind;
9182 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9183 size = get_atomic_type_size(akind);
9185 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9186 size = get_atomic_type_size(get_intptr_kind());
9190 expression_t *const value = expression->unary.value;
9191 type_t *const value_type = value->base.type;
9192 type_kind_t const value_kind = value_type->kind;
9194 unsigned value_flags;
9195 unsigned value_size;
9196 if (value_kind == TYPE_ATOMIC) {
9197 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9198 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9199 value_size = get_atomic_type_size(value_akind);
9200 } else if (value_kind == TYPE_POINTER) {
9201 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9202 value_size = get_atomic_type_size(get_intptr_kind());
9207 if (value_flags != flags || value_size != size)
9211 } while (expression->kind == EXPR_UNARY_CAST);
9215 if (!is_lvalue(expression)) {
9216 errorf(&expression->base.source_position,
9217 "asm output argument is not an lvalue");
9220 if (argument->constraints.begin[0] == '+')
9221 mark_vars_read(expression, NULL);
9223 mark_vars_read(expression, NULL);
9225 argument->expression = expression;
9226 expect(')', end_error);
9228 set_address_taken(expression, true);
9231 anchor = &argument->next;
9243 * Parse a asm statement clobber specification.
9245 static asm_clobber_t *parse_asm_clobbers(void)
9247 asm_clobber_t *result = NULL;
9248 asm_clobber_t **anchor = &result;
9250 while (token.type == T_STRING_LITERAL) {
9251 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9252 clobber->clobber = parse_string_literals();
9255 anchor = &clobber->next;
9265 * Parse an asm statement.
9267 static statement_t *parse_asm_statement(void)
9269 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9270 asm_statement_t *asm_statement = &statement->asms;
9274 if (next_if(T_volatile))
9275 asm_statement->is_volatile = true;
9277 expect('(', end_error);
9278 add_anchor_token(')');
9279 add_anchor_token(':');
9280 asm_statement->asm_text = parse_string_literals();
9282 if (!next_if(':')) {
9283 rem_anchor_token(':');
9287 asm_statement->outputs = parse_asm_arguments(true);
9288 if (!next_if(':')) {
9289 rem_anchor_token(':');
9293 asm_statement->inputs = parse_asm_arguments(false);
9294 if (!next_if(':')) {
9295 rem_anchor_token(':');
9298 rem_anchor_token(':');
9300 asm_statement->clobbers = parse_asm_clobbers();
9303 rem_anchor_token(')');
9304 expect(')', end_error);
9305 expect(';', end_error);
9307 if (asm_statement->outputs == NULL) {
9308 /* GCC: An 'asm' instruction without any output operands will be treated
9309 * identically to a volatile 'asm' instruction. */
9310 asm_statement->is_volatile = true;
9315 return create_invalid_statement();
9319 * Parse a case statement.
9321 static statement_t *parse_case_statement(void)
9323 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9324 source_position_t *const pos = &statement->base.source_position;
9328 expression_t *const expression = parse_expression();
9329 statement->case_label.expression = expression;
9330 if (!is_constant_expression(expression)) {
9331 /* This check does not prevent the error message in all cases of an
9332 * prior error while parsing the expression. At least it catches the
9333 * common case of a mistyped enum entry. */
9334 if (is_type_valid(skip_typeref(expression->base.type))) {
9335 errorf(pos, "case label does not reduce to an integer constant");
9337 statement->case_label.is_bad = true;
9339 long const val = fold_constant_to_int(expression);
9340 statement->case_label.first_case = val;
9341 statement->case_label.last_case = val;
9345 if (next_if(T_DOTDOTDOT)) {
9346 expression_t *const end_range = parse_expression();
9347 statement->case_label.end_range = end_range;
9348 if (!is_constant_expression(end_range)) {
9349 /* This check does not prevent the error message in all cases of an
9350 * prior error while parsing the expression. At least it catches the
9351 * common case of a mistyped enum entry. */
9352 if (is_type_valid(skip_typeref(end_range->base.type))) {
9353 errorf(pos, "case range does not reduce to an integer constant");
9355 statement->case_label.is_bad = true;
9357 long const val = fold_constant_to_int(end_range);
9358 statement->case_label.last_case = val;
9360 if (warning.other && val < statement->case_label.first_case) {
9361 statement->case_label.is_empty_range = true;
9362 warningf(pos, "empty range specified");
9368 PUSH_PARENT(statement);
9370 expect(':', end_error);
9373 if (current_switch != NULL) {
9374 if (! statement->case_label.is_bad) {
9375 /* Check for duplicate case values */
9376 case_label_statement_t *c = &statement->case_label;
9377 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9378 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9381 if (c->last_case < l->first_case || c->first_case > l->last_case)
9384 errorf(pos, "duplicate case value (previously used %P)",
9385 &l->base.source_position);
9389 /* link all cases into the switch statement */
9390 if (current_switch->last_case == NULL) {
9391 current_switch->first_case = &statement->case_label;
9393 current_switch->last_case->next = &statement->case_label;
9395 current_switch->last_case = &statement->case_label;
9397 errorf(pos, "case label not within a switch statement");
9400 statement_t *const inner_stmt = parse_statement();
9401 statement->case_label.statement = inner_stmt;
9402 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9403 errorf(&inner_stmt->base.source_position, "declaration after case label");
9411 * Parse a default statement.
9413 static statement_t *parse_default_statement(void)
9415 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9419 PUSH_PARENT(statement);
9421 expect(':', end_error);
9422 if (current_switch != NULL) {
9423 const case_label_statement_t *def_label = current_switch->default_label;
9424 if (def_label != NULL) {
9425 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9426 &def_label->base.source_position);
9428 current_switch->default_label = &statement->case_label;
9430 /* link all cases into the switch statement */
9431 if (current_switch->last_case == NULL) {
9432 current_switch->first_case = &statement->case_label;
9434 current_switch->last_case->next = &statement->case_label;
9436 current_switch->last_case = &statement->case_label;
9439 errorf(&statement->base.source_position,
9440 "'default' label not within a switch statement");
9443 statement_t *const inner_stmt = parse_statement();
9444 statement->case_label.statement = inner_stmt;
9445 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9446 errorf(&inner_stmt->base.source_position, "declaration after default label");
9453 return create_invalid_statement();
9457 * Parse a label statement.
9459 static statement_t *parse_label_statement(void)
9461 assert(token.type == T_IDENTIFIER);
9462 symbol_t *symbol = token.v.symbol;
9463 label_t *label = get_label(symbol);
9465 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9466 statement->label.label = label;
9470 PUSH_PARENT(statement);
9472 /* if statement is already set then the label is defined twice,
9473 * otherwise it was just mentioned in a goto/local label declaration so far
9475 if (label->statement != NULL) {
9476 errorf(HERE, "duplicate label '%Y' (declared %P)",
9477 symbol, &label->base.source_position);
9479 label->base.source_position = token.source_position;
9480 label->statement = statement;
9485 if (token.type == '}') {
9486 /* TODO only warn? */
9487 if (warning.other && false) {
9488 warningf(HERE, "label at end of compound statement");
9489 statement->label.statement = create_empty_statement();
9491 errorf(HERE, "label at end of compound statement");
9492 statement->label.statement = create_invalid_statement();
9494 } else if (token.type == ';') {
9495 /* Eat an empty statement here, to avoid the warning about an empty
9496 * statement after a label. label:; is commonly used to have a label
9497 * before a closing brace. */
9498 statement->label.statement = create_empty_statement();
9501 statement_t *const inner_stmt = parse_statement();
9502 statement->label.statement = inner_stmt;
9503 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9504 errorf(&inner_stmt->base.source_position, "declaration after label");
9508 /* remember the labels in a list for later checking */
9509 *label_anchor = &statement->label;
9510 label_anchor = &statement->label.next;
9517 * Parse an if statement.
9519 static statement_t *parse_if(void)
9521 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9525 PUSH_PARENT(statement);
9527 add_anchor_token('{');
9529 expect('(', end_error);
9530 add_anchor_token(')');
9531 expression_t *const expr = parse_expression();
9532 statement->ifs.condition = expr;
9533 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9535 semantic_condition(expr, "condition of 'if'-statment");
9536 mark_vars_read(expr, NULL);
9537 rem_anchor_token(')');
9538 expect(')', end_error);
9541 rem_anchor_token('{');
9543 add_anchor_token(T_else);
9544 statement_t *const true_stmt = parse_statement();
9545 statement->ifs.true_statement = true_stmt;
9546 rem_anchor_token(T_else);
9548 if (next_if(T_else)) {
9549 statement->ifs.false_statement = parse_statement();
9550 } else if (warning.parentheses &&
9551 true_stmt->kind == STATEMENT_IF &&
9552 true_stmt->ifs.false_statement != NULL) {
9553 warningf(&true_stmt->base.source_position,
9554 "suggest explicit braces to avoid ambiguous 'else'");
9562 * Check that all enums are handled in a switch.
9564 * @param statement the switch statement to check
9566 static void check_enum_cases(const switch_statement_t *statement)
9568 const type_t *type = skip_typeref(statement->expression->base.type);
9569 if (! is_type_enum(type))
9571 const enum_type_t *enumt = &type->enumt;
9573 /* if we have a default, no warnings */
9574 if (statement->default_label != NULL)
9577 /* FIXME: calculation of value should be done while parsing */
9578 /* TODO: quadratic algorithm here. Change to an n log n one */
9579 long last_value = -1;
9580 const entity_t *entry = enumt->enume->base.next;
9581 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9582 entry = entry->base.next) {
9583 const expression_t *expression = entry->enum_value.value;
9584 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9586 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9587 if (l->expression == NULL)
9589 if (l->first_case <= value && value <= l->last_case) {
9595 warningf(&statement->base.source_position,
9596 "enumeration value '%Y' not handled in switch",
9597 entry->base.symbol);
9604 * Parse a switch statement.
9606 static statement_t *parse_switch(void)
9608 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9612 PUSH_PARENT(statement);
9614 expect('(', end_error);
9615 add_anchor_token(')');
9616 expression_t *const expr = parse_expression();
9617 mark_vars_read(expr, NULL);
9618 type_t * type = skip_typeref(expr->base.type);
9619 if (is_type_integer(type)) {
9620 type = promote_integer(type);
9621 if (warning.traditional) {
9622 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9623 warningf(&expr->base.source_position,
9624 "'%T' switch expression not converted to '%T' in ISO C",
9628 } else if (is_type_valid(type)) {
9629 errorf(&expr->base.source_position,
9630 "switch quantity is not an integer, but '%T'", type);
9631 type = type_error_type;
9633 statement->switchs.expression = create_implicit_cast(expr, type);
9634 expect(')', end_error);
9635 rem_anchor_token(')');
9637 switch_statement_t *rem = current_switch;
9638 current_switch = &statement->switchs;
9639 statement->switchs.body = parse_statement();
9640 current_switch = rem;
9642 if (warning.switch_default &&
9643 statement->switchs.default_label == NULL) {
9644 warningf(&statement->base.source_position, "switch has no default case");
9646 if (warning.switch_enum)
9647 check_enum_cases(&statement->switchs);
9653 return create_invalid_statement();
9656 static statement_t *parse_loop_body(statement_t *const loop)
9658 statement_t *const rem = current_loop;
9659 current_loop = loop;
9661 statement_t *const body = parse_statement();
9668 * Parse a while statement.
9670 static statement_t *parse_while(void)
9672 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9676 PUSH_PARENT(statement);
9678 expect('(', end_error);
9679 add_anchor_token(')');
9680 expression_t *const cond = parse_expression();
9681 statement->whiles.condition = cond;
9682 /* §6.8.5:2 The controlling expression of an iteration statement shall
9683 * have scalar type. */
9684 semantic_condition(cond, "condition of 'while'-statement");
9685 mark_vars_read(cond, NULL);
9686 rem_anchor_token(')');
9687 expect(')', end_error);
9689 statement->whiles.body = parse_loop_body(statement);
9695 return create_invalid_statement();
9699 * Parse a do statement.
9701 static statement_t *parse_do(void)
9703 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9707 PUSH_PARENT(statement);
9709 add_anchor_token(T_while);
9710 statement->do_while.body = parse_loop_body(statement);
9711 rem_anchor_token(T_while);
9713 expect(T_while, end_error);
9714 expect('(', end_error);
9715 add_anchor_token(')');
9716 expression_t *const cond = parse_expression();
9717 statement->do_while.condition = cond;
9718 /* §6.8.5:2 The controlling expression of an iteration statement shall
9719 * have scalar type. */
9720 semantic_condition(cond, "condition of 'do-while'-statement");
9721 mark_vars_read(cond, NULL);
9722 rem_anchor_token(')');
9723 expect(')', end_error);
9724 expect(';', end_error);
9730 return create_invalid_statement();
9734 * Parse a for statement.
9736 static statement_t *parse_for(void)
9738 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9742 expect('(', end_error1);
9743 add_anchor_token(')');
9745 PUSH_PARENT(statement);
9747 size_t const top = environment_top();
9748 scope_t *old_scope = scope_push(&statement->fors.scope);
9750 bool old_gcc_extension = in_gcc_extension;
9751 while (next_if(T___extension__)) {
9752 in_gcc_extension = true;
9756 } else if (is_declaration_specifier(&token, false)) {
9757 parse_declaration(record_entity, DECL_FLAGS_NONE);
9759 add_anchor_token(';');
9760 expression_t *const init = parse_expression();
9761 statement->fors.initialisation = init;
9762 mark_vars_read(init, ENT_ANY);
9763 if (warning.unused_value && !expression_has_effect(init)) {
9764 warningf(&init->base.source_position,
9765 "initialisation of 'for'-statement has no effect");
9767 rem_anchor_token(';');
9768 expect(';', end_error2);
9770 in_gcc_extension = old_gcc_extension;
9772 if (token.type != ';') {
9773 add_anchor_token(';');
9774 expression_t *const cond = parse_expression();
9775 statement->fors.condition = cond;
9776 /* §6.8.5:2 The controlling expression of an iteration statement
9777 * shall have scalar type. */
9778 semantic_condition(cond, "condition of 'for'-statement");
9779 mark_vars_read(cond, NULL);
9780 rem_anchor_token(';');
9782 expect(';', end_error2);
9783 if (token.type != ')') {
9784 expression_t *const step = parse_expression();
9785 statement->fors.step = step;
9786 mark_vars_read(step, ENT_ANY);
9787 if (warning.unused_value && !expression_has_effect(step)) {
9788 warningf(&step->base.source_position,
9789 "step of 'for'-statement has no effect");
9792 expect(')', end_error2);
9793 rem_anchor_token(')');
9794 statement->fors.body = parse_loop_body(statement);
9796 assert(current_scope == &statement->fors.scope);
9797 scope_pop(old_scope);
9798 environment_pop_to(top);
9805 rem_anchor_token(')');
9806 assert(current_scope == &statement->fors.scope);
9807 scope_pop(old_scope);
9808 environment_pop_to(top);
9812 return create_invalid_statement();
9816 * Parse a goto statement.
9818 static statement_t *parse_goto(void)
9820 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9823 if (GNU_MODE && next_if('*')) {
9824 expression_t *expression = parse_expression();
9825 mark_vars_read(expression, NULL);
9827 /* Argh: although documentation says the expression must be of type void*,
9828 * gcc accepts anything that can be casted into void* without error */
9829 type_t *type = expression->base.type;
9831 if (type != type_error_type) {
9832 if (!is_type_pointer(type) && !is_type_integer(type)) {
9833 errorf(&expression->base.source_position,
9834 "cannot convert to a pointer type");
9835 } else if (warning.other && type != type_void_ptr) {
9836 warningf(&expression->base.source_position,
9837 "type of computed goto expression should be 'void*' not '%T'", type);
9839 expression = create_implicit_cast(expression, type_void_ptr);
9842 statement->gotos.expression = expression;
9843 } else if (token.type == T_IDENTIFIER) {
9844 symbol_t *symbol = token.v.symbol;
9846 statement->gotos.label = get_label(symbol);
9849 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9851 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9856 /* remember the goto's in a list for later checking */
9857 *goto_anchor = &statement->gotos;
9858 goto_anchor = &statement->gotos.next;
9860 expect(';', end_error);
9864 return create_invalid_statement();
9868 * Parse a continue statement.
9870 static statement_t *parse_continue(void)
9872 if (current_loop == NULL) {
9873 errorf(HERE, "continue statement not within loop");
9876 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9879 expect(';', end_error);
9886 * Parse a break statement.
9888 static statement_t *parse_break(void)
9890 if (current_switch == NULL && current_loop == NULL) {
9891 errorf(HERE, "break statement not within loop or switch");
9894 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9897 expect(';', end_error);
9904 * Parse a __leave statement.
9906 static statement_t *parse_leave_statement(void)
9908 if (current_try == NULL) {
9909 errorf(HERE, "__leave statement not within __try");
9912 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9915 expect(';', end_error);
9922 * Check if a given entity represents a local variable.
9924 static bool is_local_variable(const entity_t *entity)
9926 if (entity->kind != ENTITY_VARIABLE)
9929 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9930 case STORAGE_CLASS_AUTO:
9931 case STORAGE_CLASS_REGISTER: {
9932 const type_t *type = skip_typeref(entity->declaration.type);
9933 if (is_type_function(type)) {
9945 * Check if a given expression represents a local variable.
9947 static bool expression_is_local_variable(const expression_t *expression)
9949 if (expression->base.kind != EXPR_REFERENCE) {
9952 const entity_t *entity = expression->reference.entity;
9953 return is_local_variable(entity);
9957 * Check if a given expression represents a local variable and
9958 * return its declaration then, else return NULL.
9960 entity_t *expression_is_variable(const expression_t *expression)
9962 if (expression->base.kind != EXPR_REFERENCE) {
9965 entity_t *entity = expression->reference.entity;
9966 if (entity->kind != ENTITY_VARIABLE)
9973 * Parse a return statement.
9975 static statement_t *parse_return(void)
9979 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9981 expression_t *return_value = NULL;
9982 if (token.type != ';') {
9983 return_value = parse_expression();
9984 mark_vars_read(return_value, NULL);
9987 const type_t *const func_type = skip_typeref(current_function->base.type);
9988 assert(is_type_function(func_type));
9989 type_t *const return_type = skip_typeref(func_type->function.return_type);
9991 source_position_t const *const pos = &statement->base.source_position;
9992 if (return_value != NULL) {
9993 type_t *return_value_type = skip_typeref(return_value->base.type);
9995 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9996 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9997 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9998 /* Only warn in C mode, because GCC does the same */
9999 if (c_mode & _CXX || strict_mode) {
10001 "'return' with a value, in function returning 'void'");
10002 } else if (warning.other) {
10004 "'return' with a value, in function returning 'void'");
10006 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10007 /* Only warn in C mode, because GCC does the same */
10010 "'return' with expression in function returning 'void'");
10011 } else if (warning.other) {
10013 "'return' with expression in function returning 'void'");
10017 assign_error_t error = semantic_assign(return_type, return_value);
10018 report_assign_error(error, return_type, return_value, "'return'",
10021 return_value = create_implicit_cast(return_value, return_type);
10022 /* check for returning address of a local var */
10023 if (warning.other && return_value != NULL
10024 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10025 const expression_t *expression = return_value->unary.value;
10026 if (expression_is_local_variable(expression)) {
10027 warningf(pos, "function returns address of local variable");
10030 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10031 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10032 if (c_mode & _CXX || strict_mode) {
10034 "'return' without value, in function returning non-void");
10037 "'return' without value, in function returning non-void");
10040 statement->returns.value = return_value;
10042 expect(';', end_error);
10049 * Parse a declaration statement.
10051 static statement_t *parse_declaration_statement(void)
10053 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10055 entity_t *before = current_scope->last_entity;
10057 parse_external_declaration();
10059 parse_declaration(record_entity, DECL_FLAGS_NONE);
10062 declaration_statement_t *const decl = &statement->declaration;
10063 entity_t *const begin =
10064 before != NULL ? before->base.next : current_scope->entities;
10065 decl->declarations_begin = begin;
10066 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10072 * Parse an expression statement, ie. expr ';'.
10074 static statement_t *parse_expression_statement(void)
10076 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10078 expression_t *const expr = parse_expression();
10079 statement->expression.expression = expr;
10080 mark_vars_read(expr, ENT_ANY);
10082 expect(';', end_error);
10089 * Parse a microsoft __try { } __finally { } or
10090 * __try{ } __except() { }
10092 static statement_t *parse_ms_try_statment(void)
10094 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10097 PUSH_PARENT(statement);
10099 ms_try_statement_t *rem = current_try;
10100 current_try = &statement->ms_try;
10101 statement->ms_try.try_statement = parse_compound_statement(false);
10106 if (next_if(T___except)) {
10107 expect('(', end_error);
10108 add_anchor_token(')');
10109 expression_t *const expr = parse_expression();
10110 mark_vars_read(expr, NULL);
10111 type_t * type = skip_typeref(expr->base.type);
10112 if (is_type_integer(type)) {
10113 type = promote_integer(type);
10114 } else if (is_type_valid(type)) {
10115 errorf(&expr->base.source_position,
10116 "__expect expression is not an integer, but '%T'", type);
10117 type = type_error_type;
10119 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10120 rem_anchor_token(')');
10121 expect(')', end_error);
10122 statement->ms_try.final_statement = parse_compound_statement(false);
10123 } else if (next_if(T__finally)) {
10124 statement->ms_try.final_statement = parse_compound_statement(false);
10126 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10127 return create_invalid_statement();
10131 return create_invalid_statement();
10134 static statement_t *parse_empty_statement(void)
10136 if (warning.empty_statement) {
10137 warningf(HERE, "statement is empty");
10139 statement_t *const statement = create_empty_statement();
10144 static statement_t *parse_local_label_declaration(void)
10146 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10150 entity_t *begin = NULL, *end = NULL;
10153 if (token.type != T_IDENTIFIER) {
10154 parse_error_expected("while parsing local label declaration",
10155 T_IDENTIFIER, NULL);
10158 symbol_t *symbol = token.v.symbol;
10159 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10160 if (entity != NULL && entity->base.parent_scope == current_scope) {
10161 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10162 symbol, &entity->base.source_position);
10164 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10166 entity->base.parent_scope = current_scope;
10167 entity->base.namespc = NAMESPACE_LABEL;
10168 entity->base.source_position = token.source_position;
10169 entity->base.symbol = symbol;
10172 end->base.next = entity;
10177 environment_push(entity);
10180 } while (next_if(','));
10183 statement->declaration.declarations_begin = begin;
10184 statement->declaration.declarations_end = end;
10188 static void parse_namespace_definition(void)
10192 entity_t *entity = NULL;
10193 symbol_t *symbol = NULL;
10195 if (token.type == T_IDENTIFIER) {
10196 symbol = token.v.symbol;
10199 entity = get_entity(symbol, NAMESPACE_NORMAL);
10201 && entity->kind != ENTITY_NAMESPACE
10202 && entity->base.parent_scope == current_scope) {
10203 if (!is_error_entity(entity)) {
10204 error_redefined_as_different_kind(&token.source_position,
10205 entity, ENTITY_NAMESPACE);
10211 if (entity == NULL) {
10212 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10213 entity->base.symbol = symbol;
10214 entity->base.source_position = token.source_position;
10215 entity->base.namespc = NAMESPACE_NORMAL;
10216 entity->base.parent_scope = current_scope;
10219 if (token.type == '=') {
10220 /* TODO: parse namespace alias */
10221 panic("namespace alias definition not supported yet");
10224 environment_push(entity);
10225 append_entity(current_scope, entity);
10227 size_t const top = environment_top();
10228 scope_t *old_scope = scope_push(&entity->namespacee.members);
10230 entity_t *old_current_entity = current_entity;
10231 current_entity = entity;
10233 expect('{', end_error);
10235 expect('}', end_error);
10238 assert(current_scope == &entity->namespacee.members);
10239 assert(current_entity == entity);
10240 current_entity = old_current_entity;
10241 scope_pop(old_scope);
10242 environment_pop_to(top);
10246 * Parse a statement.
10247 * There's also parse_statement() which additionally checks for
10248 * "statement has no effect" warnings
10250 static statement_t *intern_parse_statement(void)
10252 statement_t *statement = NULL;
10254 /* declaration or statement */
10255 add_anchor_token(';');
10256 switch (token.type) {
10257 case T_IDENTIFIER: {
10258 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10259 if (la1_type == ':') {
10260 statement = parse_label_statement();
10261 } else if (is_typedef_symbol(token.v.symbol)) {
10262 statement = parse_declaration_statement();
10264 /* it's an identifier, the grammar says this must be an
10265 * expression statement. However it is common that users mistype
10266 * declaration types, so we guess a bit here to improve robustness
10267 * for incorrect programs */
10268 switch (la1_type) {
10271 if (get_entity(token.v.symbol, NAMESPACE_NORMAL) != NULL)
10272 goto expression_statment;
10277 statement = parse_declaration_statement();
10281 expression_statment:
10282 statement = parse_expression_statement();
10289 case T___extension__:
10290 /* This can be a prefix to a declaration or an expression statement.
10291 * We simply eat it now and parse the rest with tail recursion. */
10292 while (next_if(T___extension__)) {}
10293 bool old_gcc_extension = in_gcc_extension;
10294 in_gcc_extension = true;
10295 statement = intern_parse_statement();
10296 in_gcc_extension = old_gcc_extension;
10300 statement = parse_declaration_statement();
10304 statement = parse_local_label_declaration();
10307 case ';': statement = parse_empty_statement(); break;
10308 case '{': statement = parse_compound_statement(false); break;
10309 case T___leave: statement = parse_leave_statement(); break;
10310 case T___try: statement = parse_ms_try_statment(); break;
10311 case T_asm: statement = parse_asm_statement(); break;
10312 case T_break: statement = parse_break(); break;
10313 case T_case: statement = parse_case_statement(); break;
10314 case T_continue: statement = parse_continue(); break;
10315 case T_default: statement = parse_default_statement(); break;
10316 case T_do: statement = parse_do(); break;
10317 case T_for: statement = parse_for(); break;
10318 case T_goto: statement = parse_goto(); break;
10319 case T_if: statement = parse_if(); break;
10320 case T_return: statement = parse_return(); break;
10321 case T_switch: statement = parse_switch(); break;
10322 case T_while: statement = parse_while(); break;
10325 statement = parse_expression_statement();
10329 errorf(HERE, "unexpected token %K while parsing statement", &token);
10330 statement = create_invalid_statement();
10335 rem_anchor_token(';');
10337 assert(statement != NULL
10338 && statement->base.source_position.input_name != NULL);
10344 * parse a statement and emits "statement has no effect" warning if needed
10345 * (This is really a wrapper around intern_parse_statement with check for 1
10346 * single warning. It is needed, because for statement expressions we have
10347 * to avoid the warning on the last statement)
10349 static statement_t *parse_statement(void)
10351 statement_t *statement = intern_parse_statement();
10353 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10354 expression_t *expression = statement->expression.expression;
10355 if (!expression_has_effect(expression)) {
10356 warningf(&expression->base.source_position,
10357 "statement has no effect");
10365 * Parse a compound statement.
10367 static statement_t *parse_compound_statement(bool inside_expression_statement)
10369 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10371 PUSH_PARENT(statement);
10374 add_anchor_token('}');
10375 /* tokens, which can start a statement */
10376 /* TODO MS, __builtin_FOO */
10377 add_anchor_token('!');
10378 add_anchor_token('&');
10379 add_anchor_token('(');
10380 add_anchor_token('*');
10381 add_anchor_token('+');
10382 add_anchor_token('-');
10383 add_anchor_token('{');
10384 add_anchor_token('~');
10385 add_anchor_token(T_CHARACTER_CONSTANT);
10386 add_anchor_token(T_COLONCOLON);
10387 add_anchor_token(T_FLOATINGPOINT);
10388 add_anchor_token(T_IDENTIFIER);
10389 add_anchor_token(T_INTEGER);
10390 add_anchor_token(T_MINUSMINUS);
10391 add_anchor_token(T_PLUSPLUS);
10392 add_anchor_token(T_STRING_LITERAL);
10393 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10394 add_anchor_token(T_WIDE_STRING_LITERAL);
10395 add_anchor_token(T__Bool);
10396 add_anchor_token(T__Complex);
10397 add_anchor_token(T__Imaginary);
10398 add_anchor_token(T___FUNCTION__);
10399 add_anchor_token(T___PRETTY_FUNCTION__);
10400 add_anchor_token(T___alignof__);
10401 add_anchor_token(T___attribute__);
10402 add_anchor_token(T___builtin_va_start);
10403 add_anchor_token(T___extension__);
10404 add_anchor_token(T___func__);
10405 add_anchor_token(T___imag__);
10406 add_anchor_token(T___label__);
10407 add_anchor_token(T___real__);
10408 add_anchor_token(T___thread);
10409 add_anchor_token(T_asm);
10410 add_anchor_token(T_auto);
10411 add_anchor_token(T_bool);
10412 add_anchor_token(T_break);
10413 add_anchor_token(T_case);
10414 add_anchor_token(T_char);
10415 add_anchor_token(T_class);
10416 add_anchor_token(T_const);
10417 add_anchor_token(T_const_cast);
10418 add_anchor_token(T_continue);
10419 add_anchor_token(T_default);
10420 add_anchor_token(T_delete);
10421 add_anchor_token(T_double);
10422 add_anchor_token(T_do);
10423 add_anchor_token(T_dynamic_cast);
10424 add_anchor_token(T_enum);
10425 add_anchor_token(T_extern);
10426 add_anchor_token(T_false);
10427 add_anchor_token(T_float);
10428 add_anchor_token(T_for);
10429 add_anchor_token(T_goto);
10430 add_anchor_token(T_if);
10431 add_anchor_token(T_inline);
10432 add_anchor_token(T_int);
10433 add_anchor_token(T_long);
10434 add_anchor_token(T_new);
10435 add_anchor_token(T_operator);
10436 add_anchor_token(T_register);
10437 add_anchor_token(T_reinterpret_cast);
10438 add_anchor_token(T_restrict);
10439 add_anchor_token(T_return);
10440 add_anchor_token(T_short);
10441 add_anchor_token(T_signed);
10442 add_anchor_token(T_sizeof);
10443 add_anchor_token(T_static);
10444 add_anchor_token(T_static_cast);
10445 add_anchor_token(T_struct);
10446 add_anchor_token(T_switch);
10447 add_anchor_token(T_template);
10448 add_anchor_token(T_this);
10449 add_anchor_token(T_throw);
10450 add_anchor_token(T_true);
10451 add_anchor_token(T_try);
10452 add_anchor_token(T_typedef);
10453 add_anchor_token(T_typeid);
10454 add_anchor_token(T_typename);
10455 add_anchor_token(T_typeof);
10456 add_anchor_token(T_union);
10457 add_anchor_token(T_unsigned);
10458 add_anchor_token(T_using);
10459 add_anchor_token(T_void);
10460 add_anchor_token(T_volatile);
10461 add_anchor_token(T_wchar_t);
10462 add_anchor_token(T_while);
10464 size_t const top = environment_top();
10465 scope_t *old_scope = scope_push(&statement->compound.scope);
10467 statement_t **anchor = &statement->compound.statements;
10468 bool only_decls_so_far = true;
10469 while (token.type != '}') {
10470 if (token.type == T_EOF) {
10471 errorf(&statement->base.source_position,
10472 "EOF while parsing compound statement");
10475 statement_t *sub_statement = intern_parse_statement();
10476 if (is_invalid_statement(sub_statement)) {
10477 /* an error occurred. if we are at an anchor, return */
10483 if (warning.declaration_after_statement) {
10484 if (sub_statement->kind != STATEMENT_DECLARATION) {
10485 only_decls_so_far = false;
10486 } else if (!only_decls_so_far) {
10487 warningf(&sub_statement->base.source_position,
10488 "ISO C90 forbids mixed declarations and code");
10492 *anchor = sub_statement;
10494 while (sub_statement->base.next != NULL)
10495 sub_statement = sub_statement->base.next;
10497 anchor = &sub_statement->base.next;
10501 /* look over all statements again to produce no effect warnings */
10502 if (warning.unused_value) {
10503 statement_t *sub_statement = statement->compound.statements;
10504 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10505 if (sub_statement->kind != STATEMENT_EXPRESSION)
10507 /* don't emit a warning for the last expression in an expression
10508 * statement as it has always an effect */
10509 if (inside_expression_statement && sub_statement->base.next == NULL)
10512 expression_t *expression = sub_statement->expression.expression;
10513 if (!expression_has_effect(expression)) {
10514 warningf(&expression->base.source_position,
10515 "statement has no effect");
10521 rem_anchor_token(T_while);
10522 rem_anchor_token(T_wchar_t);
10523 rem_anchor_token(T_volatile);
10524 rem_anchor_token(T_void);
10525 rem_anchor_token(T_using);
10526 rem_anchor_token(T_unsigned);
10527 rem_anchor_token(T_union);
10528 rem_anchor_token(T_typeof);
10529 rem_anchor_token(T_typename);
10530 rem_anchor_token(T_typeid);
10531 rem_anchor_token(T_typedef);
10532 rem_anchor_token(T_try);
10533 rem_anchor_token(T_true);
10534 rem_anchor_token(T_throw);
10535 rem_anchor_token(T_this);
10536 rem_anchor_token(T_template);
10537 rem_anchor_token(T_switch);
10538 rem_anchor_token(T_struct);
10539 rem_anchor_token(T_static_cast);
10540 rem_anchor_token(T_static);
10541 rem_anchor_token(T_sizeof);
10542 rem_anchor_token(T_signed);
10543 rem_anchor_token(T_short);
10544 rem_anchor_token(T_return);
10545 rem_anchor_token(T_restrict);
10546 rem_anchor_token(T_reinterpret_cast);
10547 rem_anchor_token(T_register);
10548 rem_anchor_token(T_operator);
10549 rem_anchor_token(T_new);
10550 rem_anchor_token(T_long);
10551 rem_anchor_token(T_int);
10552 rem_anchor_token(T_inline);
10553 rem_anchor_token(T_if);
10554 rem_anchor_token(T_goto);
10555 rem_anchor_token(T_for);
10556 rem_anchor_token(T_float);
10557 rem_anchor_token(T_false);
10558 rem_anchor_token(T_extern);
10559 rem_anchor_token(T_enum);
10560 rem_anchor_token(T_dynamic_cast);
10561 rem_anchor_token(T_do);
10562 rem_anchor_token(T_double);
10563 rem_anchor_token(T_delete);
10564 rem_anchor_token(T_default);
10565 rem_anchor_token(T_continue);
10566 rem_anchor_token(T_const_cast);
10567 rem_anchor_token(T_const);
10568 rem_anchor_token(T_class);
10569 rem_anchor_token(T_char);
10570 rem_anchor_token(T_case);
10571 rem_anchor_token(T_break);
10572 rem_anchor_token(T_bool);
10573 rem_anchor_token(T_auto);
10574 rem_anchor_token(T_asm);
10575 rem_anchor_token(T___thread);
10576 rem_anchor_token(T___real__);
10577 rem_anchor_token(T___label__);
10578 rem_anchor_token(T___imag__);
10579 rem_anchor_token(T___func__);
10580 rem_anchor_token(T___extension__);
10581 rem_anchor_token(T___builtin_va_start);
10582 rem_anchor_token(T___attribute__);
10583 rem_anchor_token(T___alignof__);
10584 rem_anchor_token(T___PRETTY_FUNCTION__);
10585 rem_anchor_token(T___FUNCTION__);
10586 rem_anchor_token(T__Imaginary);
10587 rem_anchor_token(T__Complex);
10588 rem_anchor_token(T__Bool);
10589 rem_anchor_token(T_WIDE_STRING_LITERAL);
10590 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10591 rem_anchor_token(T_STRING_LITERAL);
10592 rem_anchor_token(T_PLUSPLUS);
10593 rem_anchor_token(T_MINUSMINUS);
10594 rem_anchor_token(T_INTEGER);
10595 rem_anchor_token(T_IDENTIFIER);
10596 rem_anchor_token(T_FLOATINGPOINT);
10597 rem_anchor_token(T_COLONCOLON);
10598 rem_anchor_token(T_CHARACTER_CONSTANT);
10599 rem_anchor_token('~');
10600 rem_anchor_token('{');
10601 rem_anchor_token('-');
10602 rem_anchor_token('+');
10603 rem_anchor_token('*');
10604 rem_anchor_token('(');
10605 rem_anchor_token('&');
10606 rem_anchor_token('!');
10607 rem_anchor_token('}');
10608 assert(current_scope == &statement->compound.scope);
10609 scope_pop(old_scope);
10610 environment_pop_to(top);
10617 * Check for unused global static functions and variables
10619 static void check_unused_globals(void)
10621 if (!warning.unused_function && !warning.unused_variable)
10624 for (const entity_t *entity = file_scope->entities; entity != NULL;
10625 entity = entity->base.next) {
10626 if (!is_declaration(entity))
10629 const declaration_t *declaration = &entity->declaration;
10630 if (declaration->used ||
10631 declaration->modifiers & DM_UNUSED ||
10632 declaration->modifiers & DM_USED ||
10633 declaration->storage_class != STORAGE_CLASS_STATIC)
10636 type_t *const type = declaration->type;
10638 if (entity->kind == ENTITY_FUNCTION) {
10639 /* inhibit warning for static inline functions */
10640 if (entity->function.is_inline)
10643 s = entity->function.statement != NULL ? "defined" : "declared";
10648 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10649 type, declaration->base.symbol, s);
10653 static void parse_global_asm(void)
10655 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10658 expect('(', end_error);
10660 statement->asms.asm_text = parse_string_literals();
10661 statement->base.next = unit->global_asm;
10662 unit->global_asm = statement;
10664 expect(')', end_error);
10665 expect(';', end_error);
10670 static void parse_linkage_specification(void)
10673 assert(token.type == T_STRING_LITERAL);
10675 const char *linkage = parse_string_literals().begin;
10677 linkage_kind_t old_linkage = current_linkage;
10678 linkage_kind_t new_linkage;
10679 if (strcmp(linkage, "C") == 0) {
10680 new_linkage = LINKAGE_C;
10681 } else if (strcmp(linkage, "C++") == 0) {
10682 new_linkage = LINKAGE_CXX;
10684 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10685 new_linkage = LINKAGE_INVALID;
10687 current_linkage = new_linkage;
10689 if (next_if('{')) {
10691 expect('}', end_error);
10697 assert(current_linkage == new_linkage);
10698 current_linkage = old_linkage;
10701 static void parse_external(void)
10703 switch (token.type) {
10704 DECLARATION_START_NO_EXTERN
10706 case T___extension__:
10707 /* tokens below are for implicit int */
10708 case '&': /* & x; -> int& x; (and error later, because C++ has no
10710 case '*': /* * x; -> int* x; */
10711 case '(': /* (x); -> int (x); */
10712 parse_external_declaration();
10716 if (look_ahead(1)->type == T_STRING_LITERAL) {
10717 parse_linkage_specification();
10719 parse_external_declaration();
10724 parse_global_asm();
10728 parse_namespace_definition();
10732 if (!strict_mode) {
10734 warningf(HERE, "stray ';' outside of function");
10741 errorf(HERE, "stray %K outside of function", &token);
10742 if (token.type == '(' || token.type == '{' || token.type == '[')
10743 eat_until_matching_token(token.type);
10749 static void parse_externals(void)
10751 add_anchor_token('}');
10752 add_anchor_token(T_EOF);
10755 unsigned char token_anchor_copy[T_LAST_TOKEN];
10756 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10759 while (token.type != T_EOF && token.type != '}') {
10761 bool anchor_leak = false;
10762 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10763 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10765 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10766 anchor_leak = true;
10769 if (in_gcc_extension) {
10770 errorf(HERE, "Leaked __extension__");
10771 anchor_leak = true;
10781 rem_anchor_token(T_EOF);
10782 rem_anchor_token('}');
10786 * Parse a translation unit.
10788 static void parse_translation_unit(void)
10790 add_anchor_token(T_EOF);
10795 if (token.type == T_EOF)
10798 errorf(HERE, "stray %K outside of function", &token);
10799 if (token.type == '(' || token.type == '{' || token.type == '[')
10800 eat_until_matching_token(token.type);
10808 * @return the translation unit or NULL if errors occurred.
10810 void start_parsing(void)
10812 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10813 label_stack = NEW_ARR_F(stack_entry_t, 0);
10814 diagnostic_count = 0;
10818 type_set_output(stderr);
10819 ast_set_output(stderr);
10821 assert(unit == NULL);
10822 unit = allocate_ast_zero(sizeof(unit[0]));
10824 assert(file_scope == NULL);
10825 file_scope = &unit->scope;
10827 assert(current_scope == NULL);
10828 scope_push(&unit->scope);
10830 create_gnu_builtins();
10832 create_microsoft_intrinsics();
10835 translation_unit_t *finish_parsing(void)
10837 assert(current_scope == &unit->scope);
10840 assert(file_scope == &unit->scope);
10841 check_unused_globals();
10844 DEL_ARR_F(environment_stack);
10845 DEL_ARR_F(label_stack);
10847 translation_unit_t *result = unit;
10852 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10853 * are given length one. */
10854 static void complete_incomplete_arrays(void)
10856 size_t n = ARR_LEN(incomplete_arrays);
10857 for (size_t i = 0; i != n; ++i) {
10858 declaration_t *const decl = incomplete_arrays[i];
10859 type_t *const orig_type = decl->type;
10860 type_t *const type = skip_typeref(orig_type);
10862 if (!is_type_incomplete(type))
10865 if (warning.other) {
10866 warningf(&decl->base.source_position,
10867 "array '%#T' assumed to have one element",
10868 orig_type, decl->base.symbol);
10871 type_t *const new_type = duplicate_type(type);
10872 new_type->array.size_constant = true;
10873 new_type->array.has_implicit_size = true;
10874 new_type->array.size = 1;
10876 type_t *const result = identify_new_type(new_type);
10878 decl->type = result;
10882 void prepare_main_collect2(entity_t *entity)
10884 // create call to __main
10885 symbol_t *symbol = symbol_table_insert("__main");
10886 entity_t *subsubmain_ent
10887 = create_implicit_function(symbol, &builtin_source_position);
10889 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10890 type_t *ftype = subsubmain_ent->declaration.type;
10891 ref->base.source_position = builtin_source_position;
10892 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10893 ref->reference.entity = subsubmain_ent;
10895 expression_t *call = allocate_expression_zero(EXPR_CALL);
10896 call->base.source_position = builtin_source_position;
10897 call->base.type = type_void;
10898 call->call.function = ref;
10900 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10901 expr_statement->base.source_position = builtin_source_position;
10902 expr_statement->expression.expression = call;
10904 statement_t *statement = entity->function.statement;
10905 assert(statement->kind == STATEMENT_COMPOUND);
10906 compound_statement_t *compounds = &statement->compound;
10908 expr_statement->base.next = compounds->statements;
10909 compounds->statements = expr_statement;
10914 lookahead_bufpos = 0;
10915 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10918 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10919 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10920 parse_translation_unit();
10921 complete_incomplete_arrays();
10922 DEL_ARR_F(incomplete_arrays);
10923 incomplete_arrays = NULL;
10927 * create a builtin function.
10929 static entity_t *create_builtin_function(builtin_kind_t kind, const char *name, type_t *function_type)
10931 symbol_t *symbol = symbol_table_insert(name);
10932 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
10933 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
10934 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
10935 entity->declaration.type = function_type;
10936 entity->declaration.implicit = true;
10937 entity->base.symbol = symbol;
10938 entity->base.source_position = builtin_source_position;
10940 entity->function.btk = kind;
10942 record_entity(entity, /*is_definition=*/false);
10948 * Create predefined gnu builtins.
10950 static void create_gnu_builtins(void)
10952 #define GNU_BUILTIN(a, b) create_builtin_function(bk_gnu_builtin_##a, "__builtin_" #a, b)
10954 GNU_BUILTIN(alloca, make_function_1_type(type_void_ptr, type_size_t));
10955 GNU_BUILTIN(huge_val, make_function_0_type(type_double));
10956 GNU_BUILTIN(inf, make_function_0_type(type_double));
10957 GNU_BUILTIN(inff, make_function_0_type(type_float));
10958 GNU_BUILTIN(infl, make_function_0_type(type_long_double));
10959 GNU_BUILTIN(nan, make_function_1_type(type_double, type_char_ptr));
10960 GNU_BUILTIN(nanf, make_function_1_type(type_float, type_char_ptr));
10961 GNU_BUILTIN(nanl, make_function_1_type(type_long_double, type_char_ptr));
10962 GNU_BUILTIN(va_end, make_function_1_type(type_void, type_valist));
10963 GNU_BUILTIN(expect, make_function_2_type(type_long, type_long, type_long));
10964 GNU_BUILTIN(return_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10965 GNU_BUILTIN(frame_address, make_function_1_type(type_void_ptr, type_unsigned_int));
10966 GNU_BUILTIN(ffs, make_function_1_type(type_int, type_unsigned_int));
10967 GNU_BUILTIN(clz, make_function_1_type(type_int, type_unsigned_int));
10968 GNU_BUILTIN(ctz, make_function_1_type(type_int, type_unsigned_int));
10969 GNU_BUILTIN(popcount, make_function_1_type(type_int, type_unsigned_int));
10970 GNU_BUILTIN(parity, make_function_1_type(type_int, type_unsigned_int));
10971 GNU_BUILTIN(prefetch, make_function_1_type_variadic(type_float, type_void_ptr));
10972 GNU_BUILTIN(trap, make_function_0_type_noreturn(type_void));
10978 * Create predefined MS intrinsics.
10980 static void create_microsoft_intrinsics(void)
10982 #define MS_BUILTIN(a, b) create_builtin_function(bk_ms##a, #a, b)
10984 /* intrinsics for all architectures */
10985 MS_BUILTIN(_rotl, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10986 MS_BUILTIN(_rotr, make_function_2_type(type_unsigned_int, type_unsigned_int, type_int));
10987 MS_BUILTIN(_rotl64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
10988 MS_BUILTIN(_rotr64, make_function_2_type(type_unsigned_int64, type_unsigned_int64, type_int));
10989 MS_BUILTIN(_byteswap_ushort, make_function_1_type(type_unsigned_short, type_unsigned_short));
10990 MS_BUILTIN(_byteswap_ulong, make_function_1_type(type_unsigned_long, type_unsigned_long));
10991 MS_BUILTIN(_byteswap_uint64, make_function_1_type(type_unsigned_int64, type_unsigned_int64));
10993 MS_BUILTIN(__debugbreak, make_function_0_type(type_void));
10994 MS_BUILTIN(_ReturnAddress, make_function_0_type(type_void_ptr));
10995 MS_BUILTIN(_AddressOfReturnAddress, make_function_0_type(type_void_ptr));
10996 MS_BUILTIN(__popcount, make_function_1_type(type_unsigned_int, type_unsigned_int));
10999 MS_BUILTIN(_enable, make_function_0_type(type_void));
11000 MS_BUILTIN(_disable, make_function_0_type(type_void));
11001 MS_BUILTIN(__inbyte, make_function_1_type(type_unsigned_char, type_unsigned_short));
11002 MS_BUILTIN(__inword, make_function_1_type(type_unsigned_short, type_unsigned_short));
11003 MS_BUILTIN(__indword, make_function_1_type(type_unsigned_long, type_unsigned_short));
11004 MS_BUILTIN(__outbyte, make_function_2_type(type_void, type_unsigned_short, type_unsigned_char));
11005 MS_BUILTIN(__outword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_short));
11006 MS_BUILTIN(__outdword, make_function_2_type(type_void, type_unsigned_short, type_unsigned_long));
11007 MS_BUILTIN(__ud2, make_function_0_type_noreturn(type_void));
11008 MS_BUILTIN(_BitScanForward, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11009 MS_BUILTIN(_BitScanReverse, make_function_2_type(type_unsigned_char, type_unsigned_long_ptr, type_unsigned_long));
11010 MS_BUILTIN(_InterlockedExchange, make_function_2_type(type_long, type_long_ptr, type_long));
11011 MS_BUILTIN(_InterlockedExchange64, make_function_2_type(type_int64, type_int64_ptr, type_int64));
11013 if (machine_size <= 32) {
11014 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int));
11015 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int));
11017 MS_BUILTIN(__readeflags, make_function_0_type(type_unsigned_int64));
11018 MS_BUILTIN(__writeeflags, make_function_1_type(type_void, type_unsigned_int64));
11025 * Initialize the parser.
11027 void init_parser(void)
11029 sym_anonymous = symbol_table_insert("<anonymous>");
11031 memset(token_anchor_set, 0, sizeof(token_anchor_set));
11033 init_expression_parsers();
11034 obstack_init(&temp_obst);
11036 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
11037 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
11041 * Terminate the parser.
11043 void exit_parser(void)
11045 obstack_free(&temp_obst, NULL);