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"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
113 #define PUSH_PARENT(stmt) \
114 statement_t *const prev_parent = current_parent; \
115 ((void)(current_parent = (stmt)))
116 #define POP_PARENT ((void)(current_parent = prev_parent))
118 /** special symbol used for anonymous entities. */
119 static symbol_t *sym_anonymous = NULL;
121 /** The token anchor set */
122 static unsigned char token_anchor_set[T_LAST_TOKEN];
124 /** The current source position. */
125 #define HERE (&token.source_position)
127 /** true if we are in GCC mode. */
128 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
130 static statement_t *parse_compound_statement(bool inside_expression_statement);
131 static statement_t *parse_statement(void);
133 static expression_t *parse_subexpression(precedence_t);
134 static expression_t *parse_expression(void);
135 static type_t *parse_typename(void);
136 static void parse_externals(void);
137 static void parse_external(void);
139 static void parse_compound_type_entries(compound_t *compound_declaration);
141 static void check_call_argument(type_t *expected_type,
142 call_argument_t *argument, unsigned pos);
144 typedef enum declarator_flags_t {
146 DECL_MAY_BE_ABSTRACT = 1U << 0,
147 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
148 DECL_IS_PARAMETER = 1U << 2
149 } declarator_flags_t;
151 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
152 declarator_flags_t flags);
154 static void semantic_comparison(binary_expression_t *expression);
156 #define STORAGE_CLASSES \
157 STORAGE_CLASSES_NO_EXTERN \
160 #define STORAGE_CLASSES_NO_EXTERN \
167 #define TYPE_QUALIFIERS \
172 case T__forceinline: \
173 case T___attribute__:
175 #define COMPLEX_SPECIFIERS \
177 #define IMAGINARY_SPECIFIERS \
180 #define TYPE_SPECIFIERS \
182 case T___builtin_va_list: \
207 #define DECLARATION_START \
212 #define DECLARATION_START_NO_EXTERN \
213 STORAGE_CLASSES_NO_EXTERN \
217 #define TYPENAME_START \
221 #define EXPRESSION_START \
230 case T_CHARACTER_CONSTANT: \
231 case T_FLOATINGPOINT: \
232 case T_FLOATINGPOINT_HEXADECIMAL: \
234 case T_INTEGER_HEXADECIMAL: \
235 case T_INTEGER_OCTAL: \
238 case T_STRING_LITERAL: \
239 case T_WIDE_CHARACTER_CONSTANT: \
240 case T_WIDE_STRING_LITERAL: \
241 case T___FUNCDNAME__: \
242 case T___FUNCSIG__: \
243 case T___FUNCTION__: \
244 case T___PRETTY_FUNCTION__: \
245 case T___alignof__: \
246 case T___builtin_classify_type: \
247 case T___builtin_constant_p: \
248 case T___builtin_isgreater: \
249 case T___builtin_isgreaterequal: \
250 case T___builtin_isless: \
251 case T___builtin_islessequal: \
252 case T___builtin_islessgreater: \
253 case T___builtin_isunordered: \
254 case T___builtin_offsetof: \
255 case T___builtin_va_arg: \
256 case T___builtin_va_copy: \
257 case T___builtin_va_start: \
268 * Returns the size of a statement node.
270 * @param kind the statement kind
272 static size_t get_statement_struct_size(statement_kind_t kind)
274 static const size_t sizes[] = {
275 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
276 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
277 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
278 [STATEMENT_RETURN] = sizeof(return_statement_t),
279 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
280 [STATEMENT_IF] = sizeof(if_statement_t),
281 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
282 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
283 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
284 [STATEMENT_BREAK] = sizeof(statement_base_t),
285 [STATEMENT_GOTO] = sizeof(goto_statement_t),
286 [STATEMENT_LABEL] = sizeof(label_statement_t),
287 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
288 [STATEMENT_WHILE] = sizeof(while_statement_t),
289 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
290 [STATEMENT_FOR] = sizeof(for_statement_t),
291 [STATEMENT_ASM] = sizeof(asm_statement_t),
292 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
293 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
295 assert(kind < lengthof(sizes));
296 assert(sizes[kind] != 0);
301 * Returns the size of an expression node.
303 * @param kind the expression kind
305 static size_t get_expression_struct_size(expression_kind_t kind)
307 static const size_t sizes[] = {
308 [EXPR_INVALID] = sizeof(expression_base_t),
309 [EXPR_REFERENCE] = sizeof(reference_expression_t),
310 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
311 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
312 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
314 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
316 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
317 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
318 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
319 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
320 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
321 [EXPR_CALL] = sizeof(call_expression_t),
322 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
323 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
324 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
325 [EXPR_SELECT] = sizeof(select_expression_t),
326 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
327 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
328 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
329 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
330 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
331 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
332 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
333 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
334 [EXPR_VA_START] = sizeof(va_start_expression_t),
335 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
336 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
337 [EXPR_STATEMENT] = sizeof(statement_expression_t),
338 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
340 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
341 return sizes[EXPR_UNARY_FIRST];
343 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
344 return sizes[EXPR_BINARY_FIRST];
346 assert(kind < lengthof(sizes));
347 assert(sizes[kind] != 0);
352 * Allocate a statement node of given kind and initialize all
353 * fields with zero. Sets its source position to the position
354 * of the current token.
356 static statement_t *allocate_statement_zero(statement_kind_t kind)
358 size_t size = get_statement_struct_size(kind);
359 statement_t *res = allocate_ast_zero(size);
361 res->base.kind = kind;
362 res->base.parent = current_parent;
363 res->base.source_position = token.source_position;
368 * Allocate an expression node of given kind and initialize all
371 * @param kind the kind of the expression to allocate
373 static expression_t *allocate_expression_zero(expression_kind_t kind)
375 size_t size = get_expression_struct_size(kind);
376 expression_t *res = allocate_ast_zero(size);
378 res->base.kind = kind;
379 res->base.type = type_error_type;
380 res->base.source_position = token.source_position;
385 * Creates a new invalid expression at the source position
386 * of the current token.
388 static expression_t *create_invalid_expression(void)
390 return allocate_expression_zero(EXPR_INVALID);
394 * Creates a new invalid statement.
396 static statement_t *create_invalid_statement(void)
398 return allocate_statement_zero(STATEMENT_INVALID);
402 * Allocate a new empty statement.
404 static statement_t *create_empty_statement(void)
406 return allocate_statement_zero(STATEMENT_EMPTY);
409 static function_parameter_t *allocate_parameter(type_t *const type)
411 function_parameter_t *const param
412 = obstack_alloc(type_obst, sizeof(*param));
413 memset(param, 0, sizeof(*param));
419 * Returns the size of an initializer node.
421 * @param kind the initializer kind
423 static size_t get_initializer_size(initializer_kind_t kind)
425 static const size_t sizes[] = {
426 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
427 [INITIALIZER_STRING] = sizeof(initializer_string_t),
428 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
429 [INITIALIZER_LIST] = sizeof(initializer_list_t),
430 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
432 assert(kind < lengthof(sizes));
433 assert(sizes[kind] != 0);
438 * Allocate an initializer node of given kind and initialize all
441 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
443 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
450 * Returns the index of the top element of the environment stack.
452 static size_t environment_top(void)
454 return ARR_LEN(environment_stack);
458 * Returns the index of the top element of the global label stack.
460 static size_t label_top(void)
462 return ARR_LEN(label_stack);
466 * Return the next token.
468 static inline void next_token(void)
470 token = lookahead_buffer[lookahead_bufpos];
471 lookahead_buffer[lookahead_bufpos] = lexer_token;
474 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
477 print_token(stderr, &token);
478 fprintf(stderr, "\n");
482 static inline bool next_if(int const type)
484 if (token.type == type) {
493 * Return the next token with a given lookahead.
495 static inline const token_t *look_ahead(size_t num)
497 assert(0 < num && num <= MAX_LOOKAHEAD);
498 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
499 return &lookahead_buffer[pos];
503 * Adds a token type to the token type anchor set (a multi-set).
505 static void add_anchor_token(int token_type)
507 assert(0 <= token_type && token_type < T_LAST_TOKEN);
508 ++token_anchor_set[token_type];
512 * Set the number of tokens types of the given type
513 * to zero and return the old count.
515 static int save_and_reset_anchor_state(int token_type)
517 assert(0 <= token_type && token_type < T_LAST_TOKEN);
518 int count = token_anchor_set[token_type];
519 token_anchor_set[token_type] = 0;
524 * Restore the number of token types to the given count.
526 static void restore_anchor_state(int token_type, int count)
528 assert(0 <= token_type && token_type < T_LAST_TOKEN);
529 token_anchor_set[token_type] = count;
533 * Remove a token type from the token type anchor set (a multi-set).
535 static void rem_anchor_token(int token_type)
537 assert(0 <= token_type && token_type < T_LAST_TOKEN);
538 assert(token_anchor_set[token_type] != 0);
539 --token_anchor_set[token_type];
543 * Return true if the token type of the current token is
546 static bool at_anchor(void)
550 return token_anchor_set[token.type];
554 * Eat tokens until a matching token type is found.
556 static void eat_until_matching_token(int type)
560 case '(': end_token = ')'; break;
561 case '{': end_token = '}'; break;
562 case '[': end_token = ']'; break;
563 default: end_token = type; break;
566 unsigned parenthesis_count = 0;
567 unsigned brace_count = 0;
568 unsigned bracket_count = 0;
569 while (token.type != end_token ||
570 parenthesis_count != 0 ||
572 bracket_count != 0) {
573 switch (token.type) {
575 case '(': ++parenthesis_count; break;
576 case '{': ++brace_count; break;
577 case '[': ++bracket_count; break;
580 if (parenthesis_count > 0)
590 if (bracket_count > 0)
593 if (token.type == end_token &&
594 parenthesis_count == 0 &&
608 * Eat input tokens until an anchor is found.
610 static void eat_until_anchor(void)
612 while (token_anchor_set[token.type] == 0) {
613 if (token.type == '(' || token.type == '{' || token.type == '[')
614 eat_until_matching_token(token.type);
620 * Eat a whole block from input tokens.
622 static void eat_block(void)
624 eat_until_matching_token('{');
628 #define eat(token_type) (assert(token.type == (token_type)), next_token())
631 * Report a parse error because an expected token was not found.
634 #if defined __GNUC__ && __GNUC__ >= 4
635 __attribute__((sentinel))
637 void parse_error_expected(const char *message, ...)
639 if (message != NULL) {
640 errorf(HERE, "%s", message);
643 va_start(ap, message);
644 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
649 * Report an incompatible type.
651 static void type_error_incompatible(const char *msg,
652 const source_position_t *source_position, type_t *type1, type_t *type2)
654 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
659 * Expect the current token is the expected token.
660 * If not, generate an error, eat the current statement,
661 * and goto the error_label label.
663 #define expect(expected, error_label) \
665 if (UNLIKELY(token.type != (expected))) { \
666 parse_error_expected(NULL, (expected), NULL); \
667 add_anchor_token(expected); \
668 eat_until_anchor(); \
669 next_if((expected)); \
670 rem_anchor_token(expected); \
677 * Push a given scope on the scope stack and make it the
680 static scope_t *scope_push(scope_t *new_scope)
682 if (current_scope != NULL) {
683 new_scope->depth = current_scope->depth + 1;
686 scope_t *old_scope = current_scope;
687 current_scope = new_scope;
692 * Pop the current scope from the scope stack.
694 static void scope_pop(scope_t *old_scope)
696 current_scope = old_scope;
700 * Search an entity by its symbol in a given namespace.
702 static entity_t *get_entity(const symbol_t *const symbol,
703 namespace_tag_t namespc)
705 assert(namespc != NAMESPACE_INVALID);
706 entity_t *entity = symbol->entity;
707 for (; entity != NULL; entity = entity->base.symbol_next) {
708 if (entity->base.namespc == namespc)
715 /* §6.2.3:1 24) There is only one name space for tags even though three are
717 static entity_t *get_tag(symbol_t const *const symbol,
718 entity_kind_tag_t const kind)
720 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
721 if (entity != NULL && entity->kind != kind) {
723 "'%Y' defined as wrong kind of tag (previous definition %P)",
724 symbol, &entity->base.source_position);
731 * pushs an entity on the environment stack and links the corresponding symbol
734 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
736 symbol_t *symbol = entity->base.symbol;
737 entity_namespace_t namespc = entity->base.namespc;
738 assert(namespc != NAMESPACE_INVALID);
740 /* replace/add entity into entity list of the symbol */
743 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
748 /* replace an entry? */
749 if (iter->base.namespc == namespc) {
750 entity->base.symbol_next = iter->base.symbol_next;
756 /* remember old declaration */
758 entry.symbol = symbol;
759 entry.old_entity = iter;
760 entry.namespc = namespc;
761 ARR_APP1(stack_entry_t, *stack_ptr, entry);
765 * Push an entity on the environment stack.
767 static void environment_push(entity_t *entity)
769 assert(entity->base.source_position.input_name != NULL);
770 assert(entity->base.parent_scope != NULL);
771 stack_push(&environment_stack, entity);
775 * Push a declaration on the global label stack.
777 * @param declaration the declaration
779 static void label_push(entity_t *label)
781 /* we abuse the parameters scope as parent for the labels */
782 label->base.parent_scope = ¤t_function->parameters;
783 stack_push(&label_stack, label);
787 * pops symbols from the environment stack until @p new_top is the top element
789 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
791 stack_entry_t *stack = *stack_ptr;
792 size_t top = ARR_LEN(stack);
795 assert(new_top <= top);
799 for (i = top; i > new_top; --i) {
800 stack_entry_t *entry = &stack[i - 1];
802 entity_t *old_entity = entry->old_entity;
803 symbol_t *symbol = entry->symbol;
804 entity_namespace_t namespc = entry->namespc;
806 /* replace with old_entity/remove */
809 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
811 assert(iter != NULL);
812 /* replace an entry? */
813 if (iter->base.namespc == namespc)
817 /* restore definition from outer scopes (if there was one) */
818 if (old_entity != NULL) {
819 old_entity->base.symbol_next = iter->base.symbol_next;
820 *anchor = old_entity;
822 /* remove entry from list */
823 *anchor = iter->base.symbol_next;
827 ARR_SHRINKLEN(*stack_ptr, new_top);
831 * Pop all entries from the environment stack until the new_top
834 * @param new_top the new stack top
836 static void environment_pop_to(size_t new_top)
838 stack_pop_to(&environment_stack, new_top);
842 * Pop all entries from the global label stack until the new_top
845 * @param new_top the new stack top
847 static void label_pop_to(size_t new_top)
849 stack_pop_to(&label_stack, new_top);
852 static int get_akind_rank(atomic_type_kind_t akind)
858 * Return the type rank for an atomic type.
860 static int get_rank(const type_t *type)
862 assert(!is_typeref(type));
863 if (type->kind == TYPE_ENUM)
864 return get_akind_rank(type->enumt.akind);
866 assert(type->kind == TYPE_ATOMIC);
867 return get_akind_rank(type->atomic.akind);
871 * §6.3.1.1:2 Do integer promotion for a given type.
873 * @param type the type to promote
874 * @return the promoted type
876 static type_t *promote_integer(type_t *type)
878 if (type->kind == TYPE_BITFIELD)
879 type = type->bitfield.base_type;
881 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
888 * Create a cast expression.
890 * @param expression the expression to cast
891 * @param dest_type the destination type
893 static expression_t *create_cast_expression(expression_t *expression,
896 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
898 cast->unary.value = expression;
899 cast->base.type = dest_type;
905 * Check if a given expression represents a null pointer constant.
907 * @param expression the expression to check
909 static bool is_null_pointer_constant(const expression_t *expression)
911 /* skip void* cast */
912 if (expression->kind == EXPR_UNARY_CAST ||
913 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
914 type_t *const type = skip_typeref(expression->base.type);
915 if (types_compatible(type, type_void_ptr))
916 expression = expression->unary.value;
919 type_t *const type = skip_typeref(expression->base.type);
920 if (!is_type_integer(type))
922 switch (is_constant_expression(expression)) {
923 case EXPR_CLASS_ERROR: return true;
924 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
925 default: return false;
930 * Create an implicit cast expression.
932 * @param expression the expression to cast
933 * @param dest_type the destination type
935 static expression_t *create_implicit_cast(expression_t *expression,
938 type_t *const source_type = expression->base.type;
940 if (source_type == dest_type)
943 return create_cast_expression(expression, dest_type);
946 typedef enum assign_error_t {
948 ASSIGN_ERROR_INCOMPATIBLE,
949 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
950 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
951 ASSIGN_WARNING_POINTER_FROM_INT,
952 ASSIGN_WARNING_INT_FROM_POINTER
955 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
956 const expression_t *const right,
958 const source_position_t *source_position)
960 type_t *const orig_type_right = right->base.type;
961 type_t *const type_left = skip_typeref(orig_type_left);
962 type_t *const type_right = skip_typeref(orig_type_right);
967 case ASSIGN_ERROR_INCOMPATIBLE:
968 errorf(source_position,
969 "destination type '%T' in %s is incompatible with type '%T'",
970 orig_type_left, context, orig_type_right);
973 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
975 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
976 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
978 /* the left type has all qualifiers from the right type */
979 unsigned missing_qualifiers
980 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
981 warningf(source_position,
982 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
983 orig_type_left, context, orig_type_right, missing_qualifiers);
988 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
990 warningf(source_position,
991 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
992 orig_type_left, context, right, orig_type_right);
996 case ASSIGN_WARNING_POINTER_FROM_INT:
998 warningf(source_position,
999 "%s makes pointer '%T' from integer '%T' without a cast",
1000 context, orig_type_left, orig_type_right);
1004 case ASSIGN_WARNING_INT_FROM_POINTER:
1005 if (warning.other) {
1006 warningf(source_position,
1007 "%s makes integer '%T' from pointer '%T' without a cast",
1008 context, orig_type_left, orig_type_right);
1013 panic("invalid error value");
1017 /** Implements the rules from §6.5.16.1 */
1018 static assign_error_t semantic_assign(type_t *orig_type_left,
1019 const expression_t *const right)
1021 type_t *const orig_type_right = right->base.type;
1022 type_t *const type_left = skip_typeref(orig_type_left);
1023 type_t *const type_right = skip_typeref(orig_type_right);
1025 if (is_type_pointer(type_left)) {
1026 if (is_null_pointer_constant(right)) {
1027 return ASSIGN_SUCCESS;
1028 } else if (is_type_pointer(type_right)) {
1029 type_t *points_to_left
1030 = skip_typeref(type_left->pointer.points_to);
1031 type_t *points_to_right
1032 = skip_typeref(type_right->pointer.points_to);
1033 assign_error_t res = ASSIGN_SUCCESS;
1035 /* the left type has all qualifiers from the right type */
1036 unsigned missing_qualifiers
1037 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1038 if (missing_qualifiers != 0) {
1039 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1042 points_to_left = get_unqualified_type(points_to_left);
1043 points_to_right = get_unqualified_type(points_to_right);
1045 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1048 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1049 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1050 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1053 if (!types_compatible(points_to_left, points_to_right)) {
1054 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1058 } else if (is_type_integer(type_right)) {
1059 return ASSIGN_WARNING_POINTER_FROM_INT;
1061 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1062 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1063 && is_type_pointer(type_right))) {
1064 return ASSIGN_SUCCESS;
1065 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1066 type_t *const unqual_type_left = get_unqualified_type(type_left);
1067 type_t *const unqual_type_right = get_unqualified_type(type_right);
1068 if (types_compatible(unqual_type_left, unqual_type_right)) {
1069 return ASSIGN_SUCCESS;
1071 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1072 return ASSIGN_WARNING_INT_FROM_POINTER;
1075 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1076 return ASSIGN_SUCCESS;
1078 return ASSIGN_ERROR_INCOMPATIBLE;
1081 static expression_t *parse_constant_expression(void)
1083 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1085 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1086 errorf(&result->base.source_position,
1087 "expression '%E' is not constant", result);
1093 static expression_t *parse_assignment_expression(void)
1095 return parse_subexpression(PREC_ASSIGNMENT);
1098 static void warn_string_concat(const source_position_t *pos)
1100 if (warning.traditional) {
1101 warningf(pos, "traditional C rejects string constant concatenation");
1105 static string_t parse_string_literals(void)
1107 assert(token.type == T_STRING_LITERAL);
1108 string_t result = token.literal;
1112 while (token.type == T_STRING_LITERAL) {
1113 warn_string_concat(&token.source_position);
1114 result = concat_strings(&result, &token.literal);
1122 * compare two string, ignoring double underscores on the second.
1124 static int strcmp_underscore(const char *s1, const char *s2)
1126 if (s2[0] == '_' && s2[1] == '_') {
1127 size_t len2 = strlen(s2);
1128 size_t len1 = strlen(s1);
1129 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1130 return strncmp(s1, s2+2, len2-4);
1134 return strcmp(s1, s2);
1137 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1139 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1140 attribute->kind = kind;
1145 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1148 * __attribute__ ( ( attribute-list ) )
1152 * attribute_list , attrib
1157 * any-word ( identifier )
1158 * any-word ( identifier , nonempty-expr-list )
1159 * any-word ( expr-list )
1161 * where the "identifier" must not be declared as a type, and
1162 * "any-word" may be any identifier (including one declared as a
1163 * type), a reserved word storage class specifier, type specifier or
1164 * type qualifier. ??? This still leaves out most reserved keywords
1165 * (following the old parser), shouldn't we include them, and why not
1166 * allow identifiers declared as types to start the arguments?
1168 * Matze: this all looks confusing and little systematic, so we're even less
1169 * strict and parse any list of things which are identifiers or
1170 * (assignment-)expressions.
1172 static attribute_argument_t *parse_attribute_arguments(void)
1174 attribute_argument_t *first = NULL;
1175 attribute_argument_t **anchor = &first;
1176 if (token.type != ')') do {
1177 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1179 /* is it an identifier */
1180 if (token.type == T_IDENTIFIER
1181 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1182 symbol_t *symbol = token.symbol;
1183 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1184 argument->v.symbol = symbol;
1187 /* must be an expression */
1188 expression_t *expression = parse_assignment_expression();
1190 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1191 argument->v.expression = expression;
1194 /* append argument */
1196 anchor = &argument->next;
1197 } while (next_if(','));
1198 expect(')', end_error);
1207 static attribute_t *parse_attribute_asm(void)
1211 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1213 expect('(', end_error);
1214 attribute->a.arguments = parse_attribute_arguments();
1221 static symbol_t *get_symbol_from_token(void)
1223 switch(token.type) {
1225 return token.symbol;
1254 /* maybe we need more tokens ... add them on demand */
1255 return get_token_symbol(&token);
1261 static attribute_t *parse_attribute_gnu_single(void)
1263 /* parse "any-word" */
1264 symbol_t *symbol = get_symbol_from_token();
1265 if (symbol == NULL) {
1266 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1270 const char *name = symbol->string;
1273 attribute_kind_t kind;
1274 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1275 const char *attribute_name = get_attribute_name(kind);
1276 if (attribute_name != NULL
1277 && strcmp_underscore(attribute_name, name) == 0)
1281 if (kind >= ATTRIBUTE_GNU_LAST) {
1282 if (warning.attribute) {
1283 warningf(HERE, "unknown attribute '%s' ignored", name);
1285 /* TODO: we should still save the attribute in the list... */
1286 kind = ATTRIBUTE_UNKNOWN;
1289 attribute_t *attribute = allocate_attribute_zero(kind);
1291 /* parse arguments */
1293 attribute->a.arguments = parse_attribute_arguments();
1298 static attribute_t *parse_attribute_gnu(void)
1300 attribute_t *first = NULL;
1301 attribute_t **anchor = &first;
1303 eat(T___attribute__);
1304 expect('(', end_error);
1305 expect('(', end_error);
1307 if (token.type != ')') do {
1308 attribute_t *attribute = parse_attribute_gnu_single();
1309 if (attribute == NULL)
1312 *anchor = attribute;
1313 anchor = &attribute->next;
1314 } while (next_if(','));
1315 expect(')', end_error);
1316 expect(')', end_error);
1322 /** Parse attributes. */
1323 static attribute_t *parse_attributes(attribute_t *first)
1325 attribute_t **anchor = &first;
1327 while (*anchor != NULL)
1328 anchor = &(*anchor)->next;
1330 attribute_t *attribute;
1331 switch (token.type) {
1332 case T___attribute__:
1333 attribute = parse_attribute_gnu();
1334 if (attribute == NULL)
1339 attribute = parse_attribute_asm();
1344 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1349 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1352 case T__forceinline:
1354 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1359 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1364 /* TODO record modifier */
1366 warningf(HERE, "Ignoring declaration modifier %K", &token);
1367 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1374 *anchor = attribute;
1375 anchor = &attribute->next;
1379 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1381 static entity_t *determine_lhs_ent(expression_t *const expr,
1384 switch (expr->kind) {
1385 case EXPR_REFERENCE: {
1386 entity_t *const entity = expr->reference.entity;
1387 /* we should only find variables as lvalues... */
1388 if (entity->base.kind != ENTITY_VARIABLE
1389 && entity->base.kind != ENTITY_PARAMETER)
1395 case EXPR_ARRAY_ACCESS: {
1396 expression_t *const ref = expr->array_access.array_ref;
1397 entity_t * ent = NULL;
1398 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1399 ent = determine_lhs_ent(ref, lhs_ent);
1402 mark_vars_read(expr->select.compound, lhs_ent);
1404 mark_vars_read(expr->array_access.index, lhs_ent);
1409 if (is_type_compound(skip_typeref(expr->base.type))) {
1410 return determine_lhs_ent(expr->select.compound, lhs_ent);
1412 mark_vars_read(expr->select.compound, lhs_ent);
1417 case EXPR_UNARY_DEREFERENCE: {
1418 expression_t *const val = expr->unary.value;
1419 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1421 return determine_lhs_ent(val->unary.value, lhs_ent);
1423 mark_vars_read(val, NULL);
1429 mark_vars_read(expr, NULL);
1434 #define ENT_ANY ((entity_t*)-1)
1437 * Mark declarations, which are read. This is used to detect variables, which
1441 * x is not marked as "read", because it is only read to calculate its own new
1445 * x and y are not detected as "not read", because multiple variables are
1448 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1450 switch (expr->kind) {
1451 case EXPR_REFERENCE: {
1452 entity_t *const entity = expr->reference.entity;
1453 if (entity->kind != ENTITY_VARIABLE
1454 && entity->kind != ENTITY_PARAMETER)
1457 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1458 if (entity->kind == ENTITY_VARIABLE) {
1459 entity->variable.read = true;
1461 entity->parameter.read = true;
1468 // TODO respect pure/const
1469 mark_vars_read(expr->call.function, NULL);
1470 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1471 mark_vars_read(arg->expression, NULL);
1475 case EXPR_CONDITIONAL:
1476 // TODO lhs_decl should depend on whether true/false have an effect
1477 mark_vars_read(expr->conditional.condition, NULL);
1478 if (expr->conditional.true_expression != NULL)
1479 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1480 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1484 if (lhs_ent == ENT_ANY
1485 && !is_type_compound(skip_typeref(expr->base.type)))
1487 mark_vars_read(expr->select.compound, lhs_ent);
1490 case EXPR_ARRAY_ACCESS: {
1491 expression_t *const ref = expr->array_access.array_ref;
1492 mark_vars_read(ref, lhs_ent);
1493 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1494 mark_vars_read(expr->array_access.index, lhs_ent);
1499 mark_vars_read(expr->va_arge.ap, lhs_ent);
1503 mark_vars_read(expr->va_copye.src, lhs_ent);
1506 case EXPR_UNARY_CAST:
1507 /* Special case: Use void cast to mark a variable as "read" */
1508 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1513 case EXPR_UNARY_THROW:
1514 if (expr->unary.value == NULL)
1517 case EXPR_UNARY_DEREFERENCE:
1518 case EXPR_UNARY_DELETE:
1519 case EXPR_UNARY_DELETE_ARRAY:
1520 if (lhs_ent == ENT_ANY)
1524 case EXPR_UNARY_NEGATE:
1525 case EXPR_UNARY_PLUS:
1526 case EXPR_UNARY_BITWISE_NEGATE:
1527 case EXPR_UNARY_NOT:
1528 case EXPR_UNARY_TAKE_ADDRESS:
1529 case EXPR_UNARY_POSTFIX_INCREMENT:
1530 case EXPR_UNARY_POSTFIX_DECREMENT:
1531 case EXPR_UNARY_PREFIX_INCREMENT:
1532 case EXPR_UNARY_PREFIX_DECREMENT:
1533 case EXPR_UNARY_CAST_IMPLICIT:
1534 case EXPR_UNARY_ASSUME:
1536 mark_vars_read(expr->unary.value, lhs_ent);
1539 case EXPR_BINARY_ADD:
1540 case EXPR_BINARY_SUB:
1541 case EXPR_BINARY_MUL:
1542 case EXPR_BINARY_DIV:
1543 case EXPR_BINARY_MOD:
1544 case EXPR_BINARY_EQUAL:
1545 case EXPR_BINARY_NOTEQUAL:
1546 case EXPR_BINARY_LESS:
1547 case EXPR_BINARY_LESSEQUAL:
1548 case EXPR_BINARY_GREATER:
1549 case EXPR_BINARY_GREATEREQUAL:
1550 case EXPR_BINARY_BITWISE_AND:
1551 case EXPR_BINARY_BITWISE_OR:
1552 case EXPR_BINARY_BITWISE_XOR:
1553 case EXPR_BINARY_LOGICAL_AND:
1554 case EXPR_BINARY_LOGICAL_OR:
1555 case EXPR_BINARY_SHIFTLEFT:
1556 case EXPR_BINARY_SHIFTRIGHT:
1557 case EXPR_BINARY_COMMA:
1558 case EXPR_BINARY_ISGREATER:
1559 case EXPR_BINARY_ISGREATEREQUAL:
1560 case EXPR_BINARY_ISLESS:
1561 case EXPR_BINARY_ISLESSEQUAL:
1562 case EXPR_BINARY_ISLESSGREATER:
1563 case EXPR_BINARY_ISUNORDERED:
1564 mark_vars_read(expr->binary.left, lhs_ent);
1565 mark_vars_read(expr->binary.right, lhs_ent);
1568 case EXPR_BINARY_ASSIGN:
1569 case EXPR_BINARY_MUL_ASSIGN:
1570 case EXPR_BINARY_DIV_ASSIGN:
1571 case EXPR_BINARY_MOD_ASSIGN:
1572 case EXPR_BINARY_ADD_ASSIGN:
1573 case EXPR_BINARY_SUB_ASSIGN:
1574 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1575 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1576 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1577 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1578 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1579 if (lhs_ent == ENT_ANY)
1581 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1582 mark_vars_read(expr->binary.right, lhs_ent);
1587 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1593 case EXPR_STRING_LITERAL:
1594 case EXPR_WIDE_STRING_LITERAL:
1595 case EXPR_COMPOUND_LITERAL: // TODO init?
1597 case EXPR_CLASSIFY_TYPE:
1600 case EXPR_BUILTIN_CONSTANT_P:
1601 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1603 case EXPR_STATEMENT: // TODO
1604 case EXPR_LABEL_ADDRESS:
1605 case EXPR_REFERENCE_ENUM_VALUE:
1609 panic("unhandled expression");
1612 static designator_t *parse_designation(void)
1614 designator_t *result = NULL;
1615 designator_t **anchor = &result;
1618 designator_t *designator;
1619 switch (token.type) {
1621 designator = allocate_ast_zero(sizeof(designator[0]));
1622 designator->source_position = token.source_position;
1624 add_anchor_token(']');
1625 designator->array_index = parse_constant_expression();
1626 rem_anchor_token(']');
1627 expect(']', end_error);
1630 designator = allocate_ast_zero(sizeof(designator[0]));
1631 designator->source_position = token.source_position;
1633 if (token.type != T_IDENTIFIER) {
1634 parse_error_expected("while parsing designator",
1635 T_IDENTIFIER, NULL);
1638 designator->symbol = token.symbol;
1642 expect('=', end_error);
1646 assert(designator != NULL);
1647 *anchor = designator;
1648 anchor = &designator->next;
1654 static initializer_t *initializer_from_string(array_type_t *const type,
1655 const string_t *const string)
1657 /* TODO: check len vs. size of array type */
1660 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1661 initializer->string.string = *string;
1666 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1667 const string_t *const string)
1669 /* TODO: check len vs. size of array type */
1672 initializer_t *const initializer =
1673 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1674 initializer->wide_string.string = *string;
1680 * Build an initializer from a given expression.
1682 static initializer_t *initializer_from_expression(type_t *orig_type,
1683 expression_t *expression)
1685 /* TODO check that expression is a constant expression */
1687 /* §6.7.8.14/15 char array may be initialized by string literals */
1688 type_t *type = skip_typeref(orig_type);
1689 type_t *expr_type_orig = expression->base.type;
1690 type_t *expr_type = skip_typeref(expr_type_orig);
1692 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1693 array_type_t *const array_type = &type->array;
1694 type_t *const element_type = skip_typeref(array_type->element_type);
1696 if (element_type->kind == TYPE_ATOMIC) {
1697 atomic_type_kind_t akind = element_type->atomic.akind;
1698 switch (expression->kind) {
1699 case EXPR_STRING_LITERAL:
1700 if (akind == ATOMIC_TYPE_CHAR
1701 || akind == ATOMIC_TYPE_SCHAR
1702 || akind == ATOMIC_TYPE_UCHAR) {
1703 return initializer_from_string(array_type,
1704 &expression->string_literal.value);
1708 case EXPR_WIDE_STRING_LITERAL: {
1709 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1710 if (get_unqualified_type(element_type) == bare_wchar_type) {
1711 return initializer_from_wide_string(array_type,
1712 &expression->string_literal.value);
1723 assign_error_t error = semantic_assign(type, expression);
1724 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1726 report_assign_error(error, type, expression, "initializer",
1727 &expression->base.source_position);
1729 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1730 result->value.value = create_implicit_cast(expression, type);
1736 * Checks if a given expression can be used as an constant initializer.
1738 static bool is_initializer_constant(const expression_t *expression)
1741 is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1742 is_address_constant(expression) != EXPR_CLASS_VARIABLE;
1746 * Parses an scalar initializer.
1748 * §6.7.8.11; eat {} without warning
1750 static initializer_t *parse_scalar_initializer(type_t *type,
1751 bool must_be_constant)
1753 /* there might be extra {} hierarchies */
1757 warningf(HERE, "extra curly braces around scalar initializer");
1760 } while (next_if('{'));
1763 expression_t *expression = parse_assignment_expression();
1764 mark_vars_read(expression, NULL);
1765 if (must_be_constant && !is_initializer_constant(expression)) {
1766 errorf(&expression->base.source_position,
1767 "initialisation expression '%E' is not constant",
1771 initializer_t *initializer = initializer_from_expression(type, expression);
1773 if (initializer == NULL) {
1774 errorf(&expression->base.source_position,
1775 "expression '%E' (type '%T') doesn't match expected type '%T'",
1776 expression, expression->base.type, type);
1781 bool additional_warning_displayed = false;
1782 while (braces > 0) {
1784 if (token.type != '}') {
1785 if (!additional_warning_displayed && warning.other) {
1786 warningf(HERE, "additional elements in scalar initializer");
1787 additional_warning_displayed = true;
1798 * An entry in the type path.
1800 typedef struct type_path_entry_t type_path_entry_t;
1801 struct type_path_entry_t {
1802 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1804 size_t index; /**< For array types: the current index. */
1805 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1810 * A type path expression a position inside compound or array types.
1812 typedef struct type_path_t type_path_t;
1813 struct type_path_t {
1814 type_path_entry_t *path; /**< An flexible array containing the current path. */
1815 type_t *top_type; /**< type of the element the path points */
1816 size_t max_index; /**< largest index in outermost array */
1820 * Prints a type path for debugging.
1822 static __attribute__((unused)) void debug_print_type_path(
1823 const type_path_t *path)
1825 size_t len = ARR_LEN(path->path);
1827 for (size_t i = 0; i < len; ++i) {
1828 const type_path_entry_t *entry = & path->path[i];
1830 type_t *type = skip_typeref(entry->type);
1831 if (is_type_compound(type)) {
1832 /* in gcc mode structs can have no members */
1833 if (entry->v.compound_entry == NULL) {
1837 fprintf(stderr, ".%s",
1838 entry->v.compound_entry->base.symbol->string);
1839 } else if (is_type_array(type)) {
1840 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1842 fprintf(stderr, "-INVALID-");
1845 if (path->top_type != NULL) {
1846 fprintf(stderr, " (");
1847 print_type(path->top_type);
1848 fprintf(stderr, ")");
1853 * Return the top type path entry, ie. in a path
1854 * (type).a.b returns the b.
1856 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1858 size_t len = ARR_LEN(path->path);
1860 return &path->path[len-1];
1864 * Enlarge the type path by an (empty) element.
1866 static type_path_entry_t *append_to_type_path(type_path_t *path)
1868 size_t len = ARR_LEN(path->path);
1869 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1871 type_path_entry_t *result = & path->path[len];
1872 memset(result, 0, sizeof(result[0]));
1877 * Descending into a sub-type. Enter the scope of the current top_type.
1879 static void descend_into_subtype(type_path_t *path)
1881 type_t *orig_top_type = path->top_type;
1882 type_t *top_type = skip_typeref(orig_top_type);
1884 type_path_entry_t *top = append_to_type_path(path);
1885 top->type = top_type;
1887 if (is_type_compound(top_type)) {
1888 compound_t *compound = top_type->compound.compound;
1889 entity_t *entry = compound->members.entities;
1891 if (entry != NULL) {
1892 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1893 top->v.compound_entry = &entry->declaration;
1894 path->top_type = entry->declaration.type;
1896 path->top_type = NULL;
1898 } else if (is_type_array(top_type)) {
1900 path->top_type = top_type->array.element_type;
1902 assert(!is_type_valid(top_type));
1907 * Pop an entry from the given type path, ie. returning from
1908 * (type).a.b to (type).a
1910 static void ascend_from_subtype(type_path_t *path)
1912 type_path_entry_t *top = get_type_path_top(path);
1914 path->top_type = top->type;
1916 size_t len = ARR_LEN(path->path);
1917 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1921 * Pop entries from the given type path until the given
1922 * path level is reached.
1924 static void ascend_to(type_path_t *path, size_t top_path_level)
1926 size_t len = ARR_LEN(path->path);
1928 while (len > top_path_level) {
1929 ascend_from_subtype(path);
1930 len = ARR_LEN(path->path);
1934 static bool walk_designator(type_path_t *path, const designator_t *designator,
1935 bool used_in_offsetof)
1937 for (; designator != NULL; designator = designator->next) {
1938 type_path_entry_t *top = get_type_path_top(path);
1939 type_t *orig_type = top->type;
1941 type_t *type = skip_typeref(orig_type);
1943 if (designator->symbol != NULL) {
1944 symbol_t *symbol = designator->symbol;
1945 if (!is_type_compound(type)) {
1946 if (is_type_valid(type)) {
1947 errorf(&designator->source_position,
1948 "'.%Y' designator used for non-compound type '%T'",
1952 top->type = type_error_type;
1953 top->v.compound_entry = NULL;
1954 orig_type = type_error_type;
1956 compound_t *compound = type->compound.compound;
1957 entity_t *iter = compound->members.entities;
1958 for (; iter != NULL; iter = iter->base.next) {
1959 if (iter->base.symbol == symbol) {
1964 errorf(&designator->source_position,
1965 "'%T' has no member named '%Y'", orig_type, symbol);
1968 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1969 if (used_in_offsetof) {
1970 type_t *real_type = skip_typeref(iter->declaration.type);
1971 if (real_type->kind == TYPE_BITFIELD) {
1972 errorf(&designator->source_position,
1973 "offsetof designator '%Y' must not specify bitfield",
1979 top->type = orig_type;
1980 top->v.compound_entry = &iter->declaration;
1981 orig_type = iter->declaration.type;
1984 expression_t *array_index = designator->array_index;
1985 assert(designator->array_index != NULL);
1987 if (!is_type_array(type)) {
1988 if (is_type_valid(type)) {
1989 errorf(&designator->source_position,
1990 "[%E] designator used for non-array type '%T'",
1991 array_index, orig_type);
1996 long index = fold_constant_to_int(array_index);
1997 if (!used_in_offsetof) {
1999 errorf(&designator->source_position,
2000 "array index [%E] must be positive", array_index);
2001 } else if (type->array.size_constant) {
2002 long array_size = type->array.size;
2003 if (index >= array_size) {
2004 errorf(&designator->source_position,
2005 "designator [%E] (%d) exceeds array size %d",
2006 array_index, index, array_size);
2011 top->type = orig_type;
2012 top->v.index = (size_t) index;
2013 orig_type = type->array.element_type;
2015 path->top_type = orig_type;
2017 if (designator->next != NULL) {
2018 descend_into_subtype(path);
2024 static void advance_current_object(type_path_t *path, size_t top_path_level)
2026 type_path_entry_t *top = get_type_path_top(path);
2028 type_t *type = skip_typeref(top->type);
2029 if (is_type_union(type)) {
2030 /* in unions only the first element is initialized */
2031 top->v.compound_entry = NULL;
2032 } else if (is_type_struct(type)) {
2033 declaration_t *entry = top->v.compound_entry;
2035 entity_t *next_entity = entry->base.next;
2036 if (next_entity != NULL) {
2037 assert(is_declaration(next_entity));
2038 entry = &next_entity->declaration;
2043 top->v.compound_entry = entry;
2044 if (entry != NULL) {
2045 path->top_type = entry->type;
2048 } else if (is_type_array(type)) {
2049 assert(is_type_array(type));
2053 if (!type->array.size_constant || top->v.index < type->array.size) {
2057 assert(!is_type_valid(type));
2061 /* we're past the last member of the current sub-aggregate, try if we
2062 * can ascend in the type hierarchy and continue with another subobject */
2063 size_t len = ARR_LEN(path->path);
2065 if (len > top_path_level) {
2066 ascend_from_subtype(path);
2067 advance_current_object(path, top_path_level);
2069 path->top_type = NULL;
2074 * skip any {...} blocks until a closing bracket is reached.
2076 static void skip_initializers(void)
2080 while (token.type != '}') {
2081 if (token.type == T_EOF)
2083 if (token.type == '{') {
2091 static initializer_t *create_empty_initializer(void)
2093 static initializer_t empty_initializer
2094 = { .list = { { INITIALIZER_LIST }, 0 } };
2095 return &empty_initializer;
2099 * Parse a part of an initialiser for a struct or union,
2101 static initializer_t *parse_sub_initializer(type_path_t *path,
2102 type_t *outer_type, size_t top_path_level,
2103 parse_initializer_env_t *env)
2105 if (token.type == '}') {
2106 /* empty initializer */
2107 return create_empty_initializer();
2110 type_t *orig_type = path->top_type;
2111 type_t *type = NULL;
2113 if (orig_type == NULL) {
2114 /* We are initializing an empty compound. */
2116 type = skip_typeref(orig_type);
2119 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2122 designator_t *designator = NULL;
2123 if (token.type == '.' || token.type == '[') {
2124 designator = parse_designation();
2125 goto finish_designator;
2126 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2127 /* GNU-style designator ("identifier: value") */
2128 designator = allocate_ast_zero(sizeof(designator[0]));
2129 designator->source_position = token.source_position;
2130 designator->symbol = token.symbol;
2135 /* reset path to toplevel, evaluate designator from there */
2136 ascend_to(path, top_path_level);
2137 if (!walk_designator(path, designator, false)) {
2138 /* can't continue after designation error */
2142 initializer_t *designator_initializer
2143 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2144 designator_initializer->designator.designator = designator;
2145 ARR_APP1(initializer_t*, initializers, designator_initializer);
2147 orig_type = path->top_type;
2148 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2153 if (token.type == '{') {
2154 if (type != NULL && is_type_scalar(type)) {
2155 sub = parse_scalar_initializer(type, env->must_be_constant);
2159 if (env->entity != NULL) {
2161 "extra brace group at end of initializer for '%Y'",
2162 env->entity->base.symbol);
2164 errorf(HERE, "extra brace group at end of initializer");
2167 descend_into_subtype(path);
2169 add_anchor_token('}');
2170 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2172 rem_anchor_token('}');
2175 ascend_from_subtype(path);
2176 expect('}', end_error);
2178 expect('}', end_error);
2179 goto error_parse_next;
2183 /* must be an expression */
2184 expression_t *expression = parse_assignment_expression();
2185 mark_vars_read(expression, NULL);
2187 if (env->must_be_constant && !is_initializer_constant(expression)) {
2188 errorf(&expression->base.source_position,
2189 "Initialisation expression '%E' is not constant",
2194 /* we are already outside, ... */
2195 if (outer_type == NULL)
2196 goto error_parse_next;
2197 type_t *const outer_type_skip = skip_typeref(outer_type);
2198 if (is_type_compound(outer_type_skip) &&
2199 !outer_type_skip->compound.compound->complete) {
2200 goto error_parse_next;
2205 /* handle { "string" } special case */
2206 if ((expression->kind == EXPR_STRING_LITERAL
2207 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2208 && outer_type != NULL) {
2209 sub = initializer_from_expression(outer_type, expression);
2212 if (token.type != '}' && warning.other) {
2213 warningf(HERE, "excessive elements in initializer for type '%T'",
2216 /* TODO: eat , ... */
2221 /* descend into subtypes until expression matches type */
2223 orig_type = path->top_type;
2224 type = skip_typeref(orig_type);
2226 sub = initializer_from_expression(orig_type, expression);
2230 if (!is_type_valid(type)) {
2233 if (is_type_scalar(type)) {
2234 errorf(&expression->base.source_position,
2235 "expression '%E' doesn't match expected type '%T'",
2236 expression, orig_type);
2240 descend_into_subtype(path);
2244 /* update largest index of top array */
2245 const type_path_entry_t *first = &path->path[0];
2246 type_t *first_type = first->type;
2247 first_type = skip_typeref(first_type);
2248 if (is_type_array(first_type)) {
2249 size_t index = first->v.index;
2250 if (index > path->max_index)
2251 path->max_index = index;
2255 /* append to initializers list */
2256 ARR_APP1(initializer_t*, initializers, sub);
2259 if (warning.other) {
2260 if (env->entity != NULL) {
2261 warningf(HERE, "excess elements in initializer for '%Y'",
2262 env->entity->base.symbol);
2264 warningf(HERE, "excess elements in initializer");
2270 if (token.type == '}') {
2273 expect(',', end_error);
2274 if (token.type == '}') {
2279 /* advance to the next declaration if we are not at the end */
2280 advance_current_object(path, top_path_level);
2281 orig_type = path->top_type;
2282 if (orig_type != NULL)
2283 type = skip_typeref(orig_type);
2289 size_t len = ARR_LEN(initializers);
2290 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2291 initializer_t *result = allocate_ast_zero(size);
2292 result->kind = INITIALIZER_LIST;
2293 result->list.len = len;
2294 memcpy(&result->list.initializers, initializers,
2295 len * sizeof(initializers[0]));
2297 DEL_ARR_F(initializers);
2298 ascend_to(path, top_path_level+1);
2303 skip_initializers();
2304 DEL_ARR_F(initializers);
2305 ascend_to(path, top_path_level+1);
2309 static expression_t *make_size_literal(size_t value)
2311 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2312 literal->base.type = type_size_t;
2315 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2316 literal->literal.value = make_string(buf);
2322 * Parses an initializer. Parsers either a compound literal
2323 * (env->declaration == NULL) or an initializer of a declaration.
2325 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2327 type_t *type = skip_typeref(env->type);
2328 size_t max_index = 0;
2329 initializer_t *result;
2331 if (is_type_scalar(type)) {
2332 result = parse_scalar_initializer(type, env->must_be_constant);
2333 } else if (token.type == '{') {
2337 memset(&path, 0, sizeof(path));
2338 path.top_type = env->type;
2339 path.path = NEW_ARR_F(type_path_entry_t, 0);
2341 descend_into_subtype(&path);
2343 add_anchor_token('}');
2344 result = parse_sub_initializer(&path, env->type, 1, env);
2345 rem_anchor_token('}');
2347 max_index = path.max_index;
2348 DEL_ARR_F(path.path);
2350 expect('}', end_error);
2352 /* parse_scalar_initializer() also works in this case: we simply
2353 * have an expression without {} around it */
2354 result = parse_scalar_initializer(type, env->must_be_constant);
2357 /* §6.7.8:22 array initializers for arrays with unknown size determine
2358 * the array type size */
2359 if (is_type_array(type) && type->array.size_expression == NULL
2360 && result != NULL) {
2362 switch (result->kind) {
2363 case INITIALIZER_LIST:
2364 assert(max_index != 0xdeadbeaf);
2365 size = max_index + 1;
2368 case INITIALIZER_STRING:
2369 size = result->string.string.size;
2372 case INITIALIZER_WIDE_STRING:
2373 size = result->wide_string.string.size;
2376 case INITIALIZER_DESIGNATOR:
2377 case INITIALIZER_VALUE:
2378 /* can happen for parse errors */
2383 internal_errorf(HERE, "invalid initializer type");
2386 type_t *new_type = duplicate_type(type);
2388 new_type->array.size_expression = make_size_literal(size);
2389 new_type->array.size_constant = true;
2390 new_type->array.has_implicit_size = true;
2391 new_type->array.size = size;
2392 env->type = new_type;
2400 static void append_entity(scope_t *scope, entity_t *entity)
2402 if (scope->last_entity != NULL) {
2403 scope->last_entity->base.next = entity;
2405 scope->entities = entity;
2407 entity->base.parent_entity = current_entity;
2408 scope->last_entity = entity;
2412 static compound_t *parse_compound_type_specifier(bool is_struct)
2414 eat(is_struct ? T_struct : T_union);
2416 symbol_t *symbol = NULL;
2417 entity_t *entity = NULL;
2418 attribute_t *attributes = NULL;
2420 if (token.type == T___attribute__) {
2421 attributes = parse_attributes(NULL);
2424 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2425 if (token.type == T_IDENTIFIER) {
2426 /* the compound has a name, check if we have seen it already */
2427 symbol = token.symbol;
2430 entity = get_tag(symbol, kind);
2431 if (entity != NULL) {
2432 if (entity->base.parent_scope != current_scope &&
2433 (token.type == '{' || token.type == ';')) {
2434 /* we're in an inner scope and have a definition. Shadow
2435 * existing definition in outer scope */
2437 } else if (entity->compound.complete && token.type == '{') {
2438 assert(symbol != NULL);
2439 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2440 is_struct ? "struct" : "union", symbol,
2441 &entity->base.source_position);
2442 /* clear members in the hope to avoid further errors */
2443 entity->compound.members.entities = NULL;
2446 } else if (token.type != '{') {
2448 parse_error_expected("while parsing struct type specifier",
2449 T_IDENTIFIER, '{', NULL);
2451 parse_error_expected("while parsing union type specifier",
2452 T_IDENTIFIER, '{', NULL);
2458 if (entity == NULL) {
2459 entity = allocate_entity_zero(kind);
2461 entity->compound.alignment = 1;
2462 entity->base.namespc = NAMESPACE_TAG;
2463 entity->base.source_position = token.source_position;
2464 entity->base.symbol = symbol;
2465 entity->base.parent_scope = current_scope;
2466 if (symbol != NULL) {
2467 environment_push(entity);
2469 append_entity(current_scope, entity);
2472 if (token.type == '{') {
2473 parse_compound_type_entries(&entity->compound);
2475 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2476 if (symbol == NULL) {
2477 assert(anonymous_entity == NULL);
2478 anonymous_entity = entity;
2482 if (attributes != NULL) {
2483 handle_entity_attributes(attributes, entity);
2486 return &entity->compound;
2489 static void parse_enum_entries(type_t *const enum_type)
2493 if (token.type == '}') {
2494 errorf(HERE, "empty enum not allowed");
2499 add_anchor_token('}');
2501 if (token.type != T_IDENTIFIER) {
2502 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2504 rem_anchor_token('}');
2508 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2509 entity->enum_value.enum_type = enum_type;
2510 entity->base.namespc = NAMESPACE_NORMAL;
2511 entity->base.symbol = token.symbol;
2512 entity->base.source_position = token.source_position;
2516 expression_t *value = parse_constant_expression();
2518 value = create_implicit_cast(value, enum_type);
2519 entity->enum_value.value = value;
2524 record_entity(entity, false);
2525 } while (next_if(',') && token.type != '}');
2526 rem_anchor_token('}');
2528 expect('}', end_error);
2534 static type_t *parse_enum_specifier(void)
2540 switch (token.type) {
2542 symbol = token.symbol;
2545 entity = get_tag(symbol, ENTITY_ENUM);
2546 if (entity != NULL) {
2547 if (entity->base.parent_scope != current_scope &&
2548 (token.type == '{' || token.type == ';')) {
2549 /* we're in an inner scope and have a definition. Shadow
2550 * existing definition in outer scope */
2552 } else if (entity->enume.complete && token.type == '{') {
2553 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2554 symbol, &entity->base.source_position);
2565 parse_error_expected("while parsing enum type specifier",
2566 T_IDENTIFIER, '{', NULL);
2570 if (entity == NULL) {
2571 entity = allocate_entity_zero(ENTITY_ENUM);
2572 entity->base.namespc = NAMESPACE_TAG;
2573 entity->base.source_position = token.source_position;
2574 entity->base.symbol = symbol;
2575 entity->base.parent_scope = current_scope;
2578 type_t *const type = allocate_type_zero(TYPE_ENUM);
2579 type->enumt.enume = &entity->enume;
2580 type->enumt.akind = ATOMIC_TYPE_INT;
2582 if (token.type == '{') {
2583 if (symbol != NULL) {
2584 environment_push(entity);
2586 append_entity(current_scope, entity);
2587 entity->enume.complete = true;
2589 parse_enum_entries(type);
2590 parse_attributes(NULL);
2592 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2593 if (symbol == NULL) {
2594 assert(anonymous_entity == NULL);
2595 anonymous_entity = entity;
2597 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2598 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2606 * if a symbol is a typedef to another type, return true
2608 static bool is_typedef_symbol(symbol_t *symbol)
2610 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2611 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2614 static type_t *parse_typeof(void)
2620 expect('(', end_error);
2621 add_anchor_token(')');
2623 expression_t *expression = NULL;
2625 bool old_type_prop = in_type_prop;
2626 bool old_gcc_extension = in_gcc_extension;
2627 in_type_prop = true;
2629 while (next_if(T___extension__)) {
2630 /* This can be a prefix to a typename or an expression. */
2631 in_gcc_extension = true;
2633 switch (token.type) {
2635 if (is_typedef_symbol(token.symbol)) {
2637 type = parse_typename();
2640 expression = parse_expression();
2641 type = revert_automatic_type_conversion(expression);
2645 in_type_prop = old_type_prop;
2646 in_gcc_extension = old_gcc_extension;
2648 rem_anchor_token(')');
2649 expect(')', end_error);
2651 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2652 typeof_type->typeoft.expression = expression;
2653 typeof_type->typeoft.typeof_type = type;
2660 typedef enum specifiers_t {
2661 SPECIFIER_SIGNED = 1 << 0,
2662 SPECIFIER_UNSIGNED = 1 << 1,
2663 SPECIFIER_LONG = 1 << 2,
2664 SPECIFIER_INT = 1 << 3,
2665 SPECIFIER_DOUBLE = 1 << 4,
2666 SPECIFIER_CHAR = 1 << 5,
2667 SPECIFIER_WCHAR_T = 1 << 6,
2668 SPECIFIER_SHORT = 1 << 7,
2669 SPECIFIER_LONG_LONG = 1 << 8,
2670 SPECIFIER_FLOAT = 1 << 9,
2671 SPECIFIER_BOOL = 1 << 10,
2672 SPECIFIER_VOID = 1 << 11,
2673 SPECIFIER_INT8 = 1 << 12,
2674 SPECIFIER_INT16 = 1 << 13,
2675 SPECIFIER_INT32 = 1 << 14,
2676 SPECIFIER_INT64 = 1 << 15,
2677 SPECIFIER_INT128 = 1 << 16,
2678 SPECIFIER_COMPLEX = 1 << 17,
2679 SPECIFIER_IMAGINARY = 1 << 18,
2682 static type_t *get_typedef_type(symbol_t *symbol)
2684 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2685 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2688 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2689 type->typedeft.typedefe = &entity->typedefe;
2694 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2696 expect('(', end_error);
2698 attribute_property_argument_t *property
2699 = allocate_ast_zero(sizeof(*property));
2702 if (token.type != T_IDENTIFIER) {
2703 parse_error_expected("while parsing property declspec",
2704 T_IDENTIFIER, NULL);
2709 symbol_t *symbol = token.symbol;
2711 if (strcmp(symbol->string, "put") == 0) {
2713 } else if (strcmp(symbol->string, "get") == 0) {
2716 errorf(HERE, "expected put or get in property declspec");
2719 expect('=', end_error);
2720 if (token.type != T_IDENTIFIER) {
2721 parse_error_expected("while parsing property declspec",
2722 T_IDENTIFIER, NULL);
2726 property->put_symbol = token.symbol;
2728 property->get_symbol = token.symbol;
2731 } while (next_if(','));
2733 attribute->a.property = property;
2735 expect(')', end_error);
2741 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2743 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2744 if (next_if(T_restrict)) {
2745 kind = ATTRIBUTE_MS_RESTRICT;
2746 } else if (token.type == T_IDENTIFIER) {
2747 const char *name = token.symbol->string;
2749 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2751 const char *attribute_name = get_attribute_name(k);
2752 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2758 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2759 warningf(HERE, "unknown __declspec '%s' ignored", name);
2762 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2766 attribute_t *attribute = allocate_attribute_zero(kind);
2768 if (kind == ATTRIBUTE_MS_PROPERTY) {
2769 return parse_attribute_ms_property(attribute);
2772 /* parse arguments */
2774 attribute->a.arguments = parse_attribute_arguments();
2779 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2783 expect('(', end_error);
2788 add_anchor_token(')');
2790 attribute_t **anchor = &first;
2792 while (*anchor != NULL)
2793 anchor = &(*anchor)->next;
2795 attribute_t *attribute
2796 = parse_microsoft_extended_decl_modifier_single();
2797 if (attribute == NULL)
2800 *anchor = attribute;
2801 anchor = &attribute->next;
2802 } while (next_if(','));
2804 rem_anchor_token(')');
2805 expect(')', end_error);
2809 rem_anchor_token(')');
2813 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2815 entity_t *entity = allocate_entity_zero(kind);
2816 entity->base.namespc = NAMESPACE_NORMAL;
2817 entity->base.source_position = *HERE;
2818 entity->base.symbol = symbol;
2819 if (is_declaration(entity)) {
2820 entity->declaration.type = type_error_type;
2821 entity->declaration.implicit = true;
2822 } else if (kind == ENTITY_TYPEDEF) {
2823 entity->typedefe.type = type_error_type;
2824 entity->typedefe.builtin = true;
2826 if (kind != ENTITY_COMPOUND_MEMBER)
2827 record_entity(entity, false);
2831 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2833 type_t *type = NULL;
2834 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2835 unsigned type_specifiers = 0;
2836 bool newtype = false;
2837 bool saw_error = false;
2838 bool old_gcc_extension = in_gcc_extension;
2840 specifiers->source_position = token.source_position;
2843 specifiers->attributes = parse_attributes(specifiers->attributes);
2845 switch (token.type) {
2847 #define MATCH_STORAGE_CLASS(token, class) \
2849 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2850 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2852 specifiers->storage_class = class; \
2853 if (specifiers->thread_local) \
2854 goto check_thread_storage_class; \
2858 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2859 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2860 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2861 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2862 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2865 specifiers->attributes
2866 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2870 if (specifiers->thread_local) {
2871 errorf(HERE, "duplicate '__thread'");
2873 specifiers->thread_local = true;
2874 check_thread_storage_class:
2875 switch (specifiers->storage_class) {
2876 case STORAGE_CLASS_EXTERN:
2877 case STORAGE_CLASS_NONE:
2878 case STORAGE_CLASS_STATIC:
2882 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2883 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2884 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2885 wrong_thread_storage_class:
2886 errorf(HERE, "'__thread' used with '%s'", wrong);
2893 /* type qualifiers */
2894 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2896 qualifiers |= qualifier; \
2900 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2901 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2902 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2903 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2904 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2905 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2906 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2907 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2909 case T___extension__:
2911 in_gcc_extension = true;
2914 /* type specifiers */
2915 #define MATCH_SPECIFIER(token, specifier, name) \
2917 if (type_specifiers & specifier) { \
2918 errorf(HERE, "multiple " name " type specifiers given"); \
2920 type_specifiers |= specifier; \
2925 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2926 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2927 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2928 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2929 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2930 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2931 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2932 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2933 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2934 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2935 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2936 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2937 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2938 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2939 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2940 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2941 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2942 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2946 specifiers->is_inline = true;
2950 case T__forceinline:
2952 specifiers->modifiers |= DM_FORCEINLINE;
2957 if (type_specifiers & SPECIFIER_LONG_LONG) {
2958 errorf(HERE, "too many long type specifiers given");
2959 } else if (type_specifiers & SPECIFIER_LONG) {
2960 type_specifiers |= SPECIFIER_LONG_LONG;
2962 type_specifiers |= SPECIFIER_LONG;
2967 #define CHECK_DOUBLE_TYPE() \
2968 if ( type != NULL) \
2969 errorf(HERE, "multiple data types in declaration specifiers");
2972 CHECK_DOUBLE_TYPE();
2973 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2975 type->compound.compound = parse_compound_type_specifier(true);
2978 CHECK_DOUBLE_TYPE();
2979 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2980 type->compound.compound = parse_compound_type_specifier(false);
2983 CHECK_DOUBLE_TYPE();
2984 type = parse_enum_specifier();
2987 CHECK_DOUBLE_TYPE();
2988 type = parse_typeof();
2990 case T___builtin_va_list:
2991 CHECK_DOUBLE_TYPE();
2992 type = duplicate_type(type_valist);
2996 case T_IDENTIFIER: {
2997 /* only parse identifier if we haven't found a type yet */
2998 if (type != NULL || type_specifiers != 0) {
2999 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3000 * declaration, so it doesn't generate errors about expecting '(' or
3002 switch (look_ahead(1)->type) {
3009 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3013 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3018 goto finish_specifiers;
3022 type_t *const typedef_type = get_typedef_type(token.symbol);
3023 if (typedef_type == NULL) {
3024 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3025 * declaration, so it doesn't generate 'implicit int' followed by more
3026 * errors later on. */
3027 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3033 errorf(HERE, "%K does not name a type", &token);
3036 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3038 type = allocate_type_zero(TYPE_TYPEDEF);
3039 type->typedeft.typedefe = &entity->typedefe;
3047 goto finish_specifiers;
3052 type = typedef_type;
3056 /* function specifier */
3058 goto finish_specifiers;
3063 specifiers->attributes = parse_attributes(specifiers->attributes);
3065 in_gcc_extension = old_gcc_extension;
3067 if (type == NULL || (saw_error && type_specifiers != 0)) {
3068 atomic_type_kind_t atomic_type;
3070 /* match valid basic types */
3071 switch (type_specifiers) {
3072 case SPECIFIER_VOID:
3073 atomic_type = ATOMIC_TYPE_VOID;
3075 case SPECIFIER_WCHAR_T:
3076 atomic_type = ATOMIC_TYPE_WCHAR_T;
3078 case SPECIFIER_CHAR:
3079 atomic_type = ATOMIC_TYPE_CHAR;
3081 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3082 atomic_type = ATOMIC_TYPE_SCHAR;
3084 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3085 atomic_type = ATOMIC_TYPE_UCHAR;
3087 case SPECIFIER_SHORT:
3088 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3089 case SPECIFIER_SHORT | SPECIFIER_INT:
3090 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3091 atomic_type = ATOMIC_TYPE_SHORT;
3093 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3094 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3095 atomic_type = ATOMIC_TYPE_USHORT;
3098 case SPECIFIER_SIGNED:
3099 case SPECIFIER_SIGNED | SPECIFIER_INT:
3100 atomic_type = ATOMIC_TYPE_INT;
3102 case SPECIFIER_UNSIGNED:
3103 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3104 atomic_type = ATOMIC_TYPE_UINT;
3106 case SPECIFIER_LONG:
3107 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3108 case SPECIFIER_LONG | SPECIFIER_INT:
3109 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3110 atomic_type = ATOMIC_TYPE_LONG;
3112 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3113 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3114 atomic_type = ATOMIC_TYPE_ULONG;
3117 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3118 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3119 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3120 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3122 atomic_type = ATOMIC_TYPE_LONGLONG;
3123 goto warn_about_long_long;
3125 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3126 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3128 atomic_type = ATOMIC_TYPE_ULONGLONG;
3129 warn_about_long_long:
3130 if (warning.long_long) {
3131 warningf(&specifiers->source_position,
3132 "ISO C90 does not support 'long long'");
3136 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3137 atomic_type = unsigned_int8_type_kind;
3140 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3141 atomic_type = unsigned_int16_type_kind;
3144 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3145 atomic_type = unsigned_int32_type_kind;
3148 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3149 atomic_type = unsigned_int64_type_kind;
3152 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3153 atomic_type = unsigned_int128_type_kind;
3156 case SPECIFIER_INT8:
3157 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3158 atomic_type = int8_type_kind;
3161 case SPECIFIER_INT16:
3162 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3163 atomic_type = int16_type_kind;
3166 case SPECIFIER_INT32:
3167 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3168 atomic_type = int32_type_kind;
3171 case SPECIFIER_INT64:
3172 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3173 atomic_type = int64_type_kind;
3176 case SPECIFIER_INT128:
3177 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3178 atomic_type = int128_type_kind;
3181 case SPECIFIER_FLOAT:
3182 atomic_type = ATOMIC_TYPE_FLOAT;
3184 case SPECIFIER_DOUBLE:
3185 atomic_type = ATOMIC_TYPE_DOUBLE;
3187 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3188 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3190 case SPECIFIER_BOOL:
3191 atomic_type = ATOMIC_TYPE_BOOL;
3193 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3194 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3195 atomic_type = ATOMIC_TYPE_FLOAT;
3197 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3198 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3199 atomic_type = ATOMIC_TYPE_DOUBLE;
3201 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3202 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3203 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3206 /* invalid specifier combination, give an error message */
3207 if (type_specifiers == 0) {
3211 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3212 if (!(c_mode & _CXX) && !strict_mode) {
3213 if (warning.implicit_int) {
3214 warningf(HERE, "no type specifiers in declaration, using 'int'");
3216 atomic_type = ATOMIC_TYPE_INT;
3219 errorf(HERE, "no type specifiers given in declaration");
3221 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3222 (type_specifiers & SPECIFIER_UNSIGNED)) {
3223 errorf(HERE, "signed and unsigned specifiers given");
3224 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3225 errorf(HERE, "only integer types can be signed or unsigned");
3227 errorf(HERE, "multiple datatypes in declaration");
3232 if (type_specifiers & SPECIFIER_COMPLEX) {
3233 type = allocate_type_zero(TYPE_COMPLEX);
3234 type->complex.akind = atomic_type;
3235 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3236 type = allocate_type_zero(TYPE_IMAGINARY);
3237 type->imaginary.akind = atomic_type;
3239 type = allocate_type_zero(TYPE_ATOMIC);
3240 type->atomic.akind = atomic_type;
3243 } else if (type_specifiers != 0) {
3244 errorf(HERE, "multiple datatypes in declaration");
3247 /* FIXME: check type qualifiers here */
3248 type->base.qualifiers = qualifiers;
3251 type = identify_new_type(type);
3253 type = typehash_insert(type);
3256 if (specifiers->attributes != NULL)
3257 type = handle_type_attributes(specifiers->attributes, type);
3258 specifiers->type = type;
3262 specifiers->type = type_error_type;
3265 static type_qualifiers_t parse_type_qualifiers(void)
3267 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3270 switch (token.type) {
3271 /* type qualifiers */
3272 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3273 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3274 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3275 /* microsoft extended type modifiers */
3276 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3277 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3278 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3279 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3280 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3289 * Parses an K&R identifier list
3291 static void parse_identifier_list(scope_t *scope)
3294 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3295 entity->base.source_position = token.source_position;
3296 entity->base.namespc = NAMESPACE_NORMAL;
3297 entity->base.symbol = token.symbol;
3298 /* a K&R parameter has no type, yet */
3302 append_entity(scope, entity);
3303 } while (next_if(',') && token.type == T_IDENTIFIER);
3306 static entity_t *parse_parameter(void)
3308 declaration_specifiers_t specifiers;
3309 memset(&specifiers, 0, sizeof(specifiers));
3311 parse_declaration_specifiers(&specifiers);
3313 entity_t *entity = parse_declarator(&specifiers,
3314 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3315 anonymous_entity = NULL;
3319 static void semantic_parameter_incomplete(const entity_t *entity)
3321 assert(entity->kind == ENTITY_PARAMETER);
3323 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3324 * list in a function declarator that is part of a
3325 * definition of that function shall not have
3326 * incomplete type. */
3327 type_t *type = skip_typeref(entity->declaration.type);
3328 if (is_type_incomplete(type)) {
3329 errorf(&entity->base.source_position,
3330 "parameter '%#T' has incomplete type",
3331 entity->declaration.type, entity->base.symbol);
3335 static bool has_parameters(void)
3337 /* func(void) is not a parameter */
3338 if (token.type == T_IDENTIFIER) {
3339 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3342 if (entity->kind != ENTITY_TYPEDEF)
3344 if (skip_typeref(entity->typedefe.type) != type_void)
3346 } else if (token.type != T_void) {
3349 if (look_ahead(1)->type != ')')
3356 * Parses function type parameters (and optionally creates variable_t entities
3357 * for them in a scope)
3359 static void parse_parameters(function_type_t *type, scope_t *scope)
3362 add_anchor_token(')');
3363 int saved_comma_state = save_and_reset_anchor_state(',');
3365 if (token.type == T_IDENTIFIER &&
3366 !is_typedef_symbol(token.symbol)) {
3367 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3368 if (la1_type == ',' || la1_type == ')') {
3369 type->kr_style_parameters = true;
3370 parse_identifier_list(scope);
3371 goto parameters_finished;
3375 if (token.type == ')') {
3376 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3377 if (!(c_mode & _CXX))
3378 type->unspecified_parameters = true;
3379 } else if (has_parameters()) {
3380 function_parameter_t **anchor = &type->parameters;
3382 switch (token.type) {
3385 type->variadic = true;
3386 goto parameters_finished;
3389 case T___extension__:
3392 entity_t *entity = parse_parameter();
3393 if (entity->kind == ENTITY_TYPEDEF) {
3394 errorf(&entity->base.source_position,
3395 "typedef not allowed as function parameter");
3398 assert(is_declaration(entity));
3400 semantic_parameter_incomplete(entity);
3402 function_parameter_t *const parameter =
3403 allocate_parameter(entity->declaration.type);
3405 if (scope != NULL) {
3406 append_entity(scope, entity);
3409 *anchor = parameter;
3410 anchor = ¶meter->next;
3415 goto parameters_finished;
3417 } while (next_if(','));
3420 parameters_finished:
3421 rem_anchor_token(')');
3422 expect(')', end_error);
3425 restore_anchor_state(',', saved_comma_state);
3428 typedef enum construct_type_kind_t {
3431 CONSTRUCT_REFERENCE,
3434 } construct_type_kind_t;
3436 typedef union construct_type_t construct_type_t;
3438 typedef struct construct_type_base_t {
3439 construct_type_kind_t kind;
3440 source_position_t pos;
3441 construct_type_t *next;
3442 } construct_type_base_t;
3444 typedef struct parsed_pointer_t {
3445 construct_type_base_t base;
3446 type_qualifiers_t type_qualifiers;
3447 variable_t *base_variable; /**< MS __based extension. */
3450 typedef struct parsed_reference_t {
3451 construct_type_base_t base;
3452 } parsed_reference_t;
3454 typedef struct construct_function_type_t {
3455 construct_type_base_t base;
3456 type_t *function_type;
3457 } construct_function_type_t;
3459 typedef struct parsed_array_t {
3460 construct_type_base_t base;
3461 type_qualifiers_t type_qualifiers;
3467 union construct_type_t {
3468 construct_type_kind_t kind;
3469 construct_type_base_t base;
3470 parsed_pointer_t pointer;
3471 parsed_reference_t reference;
3472 construct_function_type_t function;
3473 parsed_array_t array;
3476 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3478 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3479 memset(cons, 0, size);
3481 cons->base.pos = *HERE;
3486 static construct_type_t *parse_pointer_declarator(void)
3488 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3490 cons->pointer.type_qualifiers = parse_type_qualifiers();
3491 //cons->pointer.base_variable = base_variable;
3496 /* ISO/IEC 14882:1998(E) §8.3.2 */
3497 static construct_type_t *parse_reference_declarator(void)
3499 if (!(c_mode & _CXX))
3500 errorf(HERE, "references are only available for C++");
3502 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3509 static construct_type_t *parse_array_declarator(void)
3511 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3512 parsed_array_t *const array = &cons->array;
3515 add_anchor_token(']');
3517 bool is_static = next_if(T_static);
3519 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3522 is_static = next_if(T_static);
3524 array->type_qualifiers = type_qualifiers;
3525 array->is_static = is_static;
3527 expression_t *size = NULL;
3528 if (token.type == '*' && look_ahead(1)->type == ']') {
3529 array->is_variable = true;
3531 } else if (token.type != ']') {
3532 size = parse_assignment_expression();
3534 /* §6.7.5.2:1 Array size must have integer type */
3535 type_t *const orig_type = size->base.type;
3536 type_t *const type = skip_typeref(orig_type);
3537 if (!is_type_integer(type) && is_type_valid(type)) {
3538 errorf(&size->base.source_position,
3539 "array size '%E' must have integer type but has type '%T'",
3544 mark_vars_read(size, NULL);
3547 if (is_static && size == NULL)
3548 errorf(HERE, "static array parameters require a size");
3550 rem_anchor_token(']');
3551 expect(']', end_error);
3558 static construct_type_t *parse_function_declarator(scope_t *scope)
3560 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3562 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3563 function_type_t *ftype = &type->function;
3565 ftype->linkage = current_linkage;
3566 ftype->calling_convention = CC_DEFAULT;
3568 parse_parameters(ftype, scope);
3570 cons->function.function_type = type;
3575 typedef struct parse_declarator_env_t {
3576 bool may_be_abstract : 1;
3577 bool must_be_abstract : 1;
3578 decl_modifiers_t modifiers;
3580 source_position_t source_position;
3582 attribute_t *attributes;
3583 } parse_declarator_env_t;
3586 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3588 /* construct a single linked list of construct_type_t's which describe
3589 * how to construct the final declarator type */
3590 construct_type_t *first = NULL;
3591 construct_type_t **anchor = &first;
3593 env->attributes = parse_attributes(env->attributes);
3596 construct_type_t *type;
3597 //variable_t *based = NULL; /* MS __based extension */
3598 switch (token.type) {
3600 type = parse_reference_declarator();
3604 panic("based not supported anymore");
3609 type = parse_pointer_declarator();
3613 goto ptr_operator_end;
3617 anchor = &type->base.next;
3619 /* TODO: find out if this is correct */
3620 env->attributes = parse_attributes(env->attributes);
3624 construct_type_t *inner_types = NULL;
3626 switch (token.type) {
3628 if (env->must_be_abstract) {
3629 errorf(HERE, "no identifier expected in typename");
3631 env->symbol = token.symbol;
3632 env->source_position = token.source_position;
3638 /* Parenthesized declarator or function declarator? */
3639 token_t const *const la1 = look_ahead(1);
3640 switch (la1->type) {
3642 if (is_typedef_symbol(la1->symbol)) {
3644 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3645 * interpreted as ``function with no parameter specification'', rather
3646 * than redundant parentheses around the omitted identifier. */
3648 /* Function declarator. */
3649 if (!env->may_be_abstract) {
3650 errorf(HERE, "function declarator must have a name");
3658 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3659 /* Paranthesized declarator. */
3661 add_anchor_token(')');
3662 inner_types = parse_inner_declarator(env);
3663 if (inner_types != NULL) {
3664 /* All later declarators only modify the return type */
3665 env->must_be_abstract = true;
3667 rem_anchor_token(')');
3668 expect(')', end_error);
3676 if (env->may_be_abstract)
3678 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3684 construct_type_t **const p = anchor;
3687 construct_type_t *type;
3688 switch (token.type) {
3690 scope_t *scope = NULL;
3691 if (!env->must_be_abstract) {
3692 scope = &env->parameters;
3695 type = parse_function_declarator(scope);
3699 type = parse_array_declarator();
3702 goto declarator_finished;
3705 /* insert in the middle of the list (at p) */
3706 type->base.next = *p;
3709 anchor = &type->base.next;
3712 declarator_finished:
3713 /* append inner_types at the end of the list, we don't to set anchor anymore
3714 * as it's not needed anymore */
3715 *anchor = inner_types;
3722 static type_t *construct_declarator_type(construct_type_t *construct_list,
3725 construct_type_t *iter = construct_list;
3726 for (; iter != NULL; iter = iter->base.next) {
3727 source_position_t const* const pos = &iter->base.pos;
3728 switch (iter->kind) {
3729 case CONSTRUCT_INVALID:
3731 case CONSTRUCT_FUNCTION: {
3732 construct_function_type_t *function = &iter->function;
3733 type_t *function_type = function->function_type;
3735 function_type->function.return_type = type;
3737 type_t *skipped_return_type = skip_typeref(type);
3739 if (is_type_function(skipped_return_type)) {
3740 errorf(pos, "function returning function is not allowed");
3741 } else if (is_type_array(skipped_return_type)) {
3742 errorf(pos, "function returning array is not allowed");
3744 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3745 warningf(pos, "type qualifiers in return type of function type are meaningless");
3749 /* The function type was constructed earlier. Freeing it here will
3750 * destroy other types. */
3751 type = typehash_insert(function_type);
3755 case CONSTRUCT_POINTER: {
3756 if (is_type_reference(skip_typeref(type)))
3757 errorf(pos, "cannot declare a pointer to reference");
3759 parsed_pointer_t *pointer = &iter->pointer;
3760 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3764 case CONSTRUCT_REFERENCE:
3765 if (is_type_reference(skip_typeref(type)))
3766 errorf(pos, "cannot declare a reference to reference");
3768 type = make_reference_type(type);
3771 case CONSTRUCT_ARRAY: {
3772 if (is_type_reference(skip_typeref(type)))
3773 errorf(pos, "cannot declare an array of references");
3775 parsed_array_t *array = &iter->array;
3776 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3778 expression_t *size_expression = array->size;
3779 if (size_expression != NULL) {
3781 = create_implicit_cast(size_expression, type_size_t);
3784 array_type->base.qualifiers = array->type_qualifiers;
3785 array_type->array.element_type = type;
3786 array_type->array.is_static = array->is_static;
3787 array_type->array.is_variable = array->is_variable;
3788 array_type->array.size_expression = size_expression;
3790 if (size_expression != NULL) {
3791 switch (is_constant_expression(size_expression)) {
3792 case EXPR_CLASS_CONSTANT: {
3793 long const size = fold_constant_to_int(size_expression);
3794 array_type->array.size = size;
3795 array_type->array.size_constant = true;
3796 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3797 * have a value greater than zero. */
3799 if (size < 0 || !GNU_MODE) {
3800 errorf(&size_expression->base.source_position,
3801 "size of array must be greater than zero");
3802 } else if (warning.other) {
3803 warningf(&size_expression->base.source_position,
3804 "zero length arrays are a GCC extension");
3810 case EXPR_CLASS_VARIABLE:
3811 array_type->array.is_vla = true;
3814 case EXPR_CLASS_ERROR:
3819 type_t *skipped_type = skip_typeref(type);
3821 if (is_type_incomplete(skipped_type)) {
3822 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3823 } else if (is_type_function(skipped_type)) {
3824 errorf(pos, "array of functions is not allowed");
3826 type = identify_new_type(array_type);
3830 internal_errorf(pos, "invalid type construction found");
3836 static type_t *automatic_type_conversion(type_t *orig_type);
3838 static type_t *semantic_parameter(const source_position_t *pos,
3840 const declaration_specifiers_t *specifiers,
3843 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3844 * shall be adjusted to ``qualified pointer to type'',
3846 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3847 * type'' shall be adjusted to ``pointer to function
3848 * returning type'', as in 6.3.2.1. */
3849 type = automatic_type_conversion(type);
3851 if (specifiers->is_inline && is_type_valid(type)) {
3852 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3855 /* §6.9.1:6 The declarations in the declaration list shall contain
3856 * no storage-class specifier other than register and no
3857 * initializations. */
3858 if (specifiers->thread_local || (
3859 specifiers->storage_class != STORAGE_CLASS_NONE &&
3860 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3862 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3865 /* delay test for incomplete type, because we might have (void)
3866 * which is legal but incomplete... */
3871 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3872 declarator_flags_t flags)
3874 parse_declarator_env_t env;
3875 memset(&env, 0, sizeof(env));
3876 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3878 construct_type_t *construct_type = parse_inner_declarator(&env);
3880 construct_declarator_type(construct_type, specifiers->type);
3881 type_t *type = skip_typeref(orig_type);
3883 if (construct_type != NULL) {
3884 obstack_free(&temp_obst, construct_type);
3887 attribute_t *attributes = parse_attributes(env.attributes);
3888 /* append (shared) specifier attribute behind attributes of this
3890 attribute_t **anchor = &attributes;
3891 while (*anchor != NULL)
3892 anchor = &(*anchor)->next;
3893 *anchor = specifiers->attributes;
3896 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3897 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3898 entity->base.namespc = NAMESPACE_NORMAL;
3899 entity->base.symbol = env.symbol;
3900 entity->base.source_position = env.source_position;
3901 entity->typedefe.type = orig_type;
3903 if (anonymous_entity != NULL) {
3904 if (is_type_compound(type)) {
3905 assert(anonymous_entity->compound.alias == NULL);
3906 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3907 anonymous_entity->kind == ENTITY_UNION);
3908 anonymous_entity->compound.alias = entity;
3909 anonymous_entity = NULL;
3910 } else if (is_type_enum(type)) {
3911 assert(anonymous_entity->enume.alias == NULL);
3912 assert(anonymous_entity->kind == ENTITY_ENUM);
3913 anonymous_entity->enume.alias = entity;
3914 anonymous_entity = NULL;
3918 /* create a declaration type entity */
3919 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3920 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3922 if (env.symbol != NULL) {
3923 if (specifiers->is_inline && is_type_valid(type)) {
3924 errorf(&env.source_position,
3925 "compound member '%Y' declared 'inline'", env.symbol);
3928 if (specifiers->thread_local ||
3929 specifiers->storage_class != STORAGE_CLASS_NONE) {
3930 errorf(&env.source_position,
3931 "compound member '%Y' must have no storage class",
3935 } else if (flags & DECL_IS_PARAMETER) {
3936 orig_type = semantic_parameter(&env.source_position, orig_type,
3937 specifiers, env.symbol);
3939 entity = allocate_entity_zero(ENTITY_PARAMETER);
3940 } else if (is_type_function(type)) {
3941 entity = allocate_entity_zero(ENTITY_FUNCTION);
3943 entity->function.is_inline = specifiers->is_inline;
3944 entity->function.parameters = env.parameters;
3946 if (env.symbol != NULL) {
3947 /* this needs fixes for C++ */
3948 bool in_function_scope = current_function != NULL;
3950 if (specifiers->thread_local || (
3951 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3952 specifiers->storage_class != STORAGE_CLASS_NONE &&
3953 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3955 errorf(&env.source_position,
3956 "invalid storage class for function '%Y'", env.symbol);
3960 entity = allocate_entity_zero(ENTITY_VARIABLE);
3962 entity->variable.thread_local = specifiers->thread_local;
3964 if (env.symbol != NULL) {
3965 if (specifiers->is_inline && is_type_valid(type)) {
3966 errorf(&env.source_position,
3967 "variable '%Y' declared 'inline'", env.symbol);
3970 bool invalid_storage_class = false;
3971 if (current_scope == file_scope) {
3972 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3973 specifiers->storage_class != STORAGE_CLASS_NONE &&
3974 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3975 invalid_storage_class = true;
3978 if (specifiers->thread_local &&
3979 specifiers->storage_class == STORAGE_CLASS_NONE) {
3980 invalid_storage_class = true;
3983 if (invalid_storage_class) {
3984 errorf(&env.source_position,
3985 "invalid storage class for variable '%Y'", env.symbol);
3990 if (env.symbol != NULL) {
3991 entity->base.symbol = env.symbol;
3992 entity->base.source_position = env.source_position;
3994 entity->base.source_position = specifiers->source_position;
3996 entity->base.namespc = NAMESPACE_NORMAL;
3997 entity->declaration.type = orig_type;
3998 entity->declaration.alignment = get_type_alignment(orig_type);
3999 entity->declaration.modifiers = env.modifiers;
4000 entity->declaration.attributes = attributes;
4002 storage_class_t storage_class = specifiers->storage_class;
4003 entity->declaration.declared_storage_class = storage_class;
4005 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4006 storage_class = STORAGE_CLASS_AUTO;
4007 entity->declaration.storage_class = storage_class;
4010 if (attributes != NULL) {
4011 handle_entity_attributes(attributes, entity);
4017 static type_t *parse_abstract_declarator(type_t *base_type)
4019 parse_declarator_env_t env;
4020 memset(&env, 0, sizeof(env));
4021 env.may_be_abstract = true;
4022 env.must_be_abstract = true;
4024 construct_type_t *construct_type = parse_inner_declarator(&env);
4026 type_t *result = construct_declarator_type(construct_type, base_type);
4027 if (construct_type != NULL) {
4028 obstack_free(&temp_obst, construct_type);
4030 result = handle_type_attributes(env.attributes, result);
4036 * Check if the declaration of main is suspicious. main should be a
4037 * function with external linkage, returning int, taking either zero
4038 * arguments, two, or three arguments of appropriate types, ie.
4040 * int main([ int argc, char **argv [, char **env ] ]).
4042 * @param decl the declaration to check
4043 * @param type the function type of the declaration
4045 static void check_main(const entity_t *entity)
4047 const source_position_t *pos = &entity->base.source_position;
4048 if (entity->kind != ENTITY_FUNCTION) {
4049 warningf(pos, "'main' is not a function");
4053 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4054 warningf(pos, "'main' is normally a non-static function");
4057 type_t *type = skip_typeref(entity->declaration.type);
4058 assert(is_type_function(type));
4060 function_type_t *func_type = &type->function;
4061 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4062 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4063 func_type->return_type);
4065 const function_parameter_t *parm = func_type->parameters;
4067 type_t *const first_type = skip_typeref(parm->type);
4068 type_t *const first_type_unqual = get_unqualified_type(first_type);
4069 if (!types_compatible(first_type_unqual, type_int)) {
4071 "first argument of 'main' should be 'int', but is '%T'",
4076 type_t *const second_type = skip_typeref(parm->type);
4077 type_t *const second_type_unqual
4078 = get_unqualified_type(second_type);
4079 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4080 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'",
4085 type_t *const third_type = skip_typeref(parm->type);
4086 type_t *const third_type_unqual
4087 = get_unqualified_type(third_type);
4088 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4089 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'",
4094 goto warn_arg_count;
4098 warningf(pos, "'main' takes only zero, two or three arguments");
4104 * Check if a symbol is the equal to "main".
4106 static bool is_sym_main(const symbol_t *const sym)
4108 return strcmp(sym->string, "main") == 0;
4111 static void error_redefined_as_different_kind(const source_position_t *pos,
4112 const entity_t *old, entity_kind_t new_kind)
4114 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4115 get_entity_kind_name(old->kind), old->base.symbol,
4116 get_entity_kind_name(new_kind), &old->base.source_position);
4119 static bool is_entity_valid(entity_t *const ent)
4121 if (is_declaration(ent)) {
4122 return is_type_valid(skip_typeref(ent->declaration.type));
4123 } else if (ent->kind == ENTITY_TYPEDEF) {
4124 return is_type_valid(skip_typeref(ent->typedefe.type));
4129 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4131 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4132 if (attributes_equal(tattr, attr))
4139 * test wether new_list contains any attributes not included in old_list
4141 static bool has_new_attributes(const attribute_t *old_list,
4142 const attribute_t *new_list)
4144 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4145 if (!contains_attribute(old_list, attr))
4152 * Merge in attributes from an attribute list (probably from a previous
4153 * declaration with the same name). Warning: destroys the old structure
4154 * of the attribute list - don't reuse attributes after this call.
4156 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4159 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4161 if (contains_attribute(decl->attributes, attr))
4164 /* move attribute to new declarations attributes list */
4165 attr->next = decl->attributes;
4166 decl->attributes = attr;
4171 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4172 * for various problems that occur for multiple definitions
4174 entity_t *record_entity(entity_t *entity, const bool is_definition)
4176 const symbol_t *const symbol = entity->base.symbol;
4177 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4178 const source_position_t *pos = &entity->base.source_position;
4180 /* can happen in error cases */
4184 entity_t *const previous_entity = get_entity(symbol, namespc);
4185 /* pushing the same entity twice will break the stack structure */
4186 assert(previous_entity != entity);
4188 if (entity->kind == ENTITY_FUNCTION) {
4189 type_t *const orig_type = entity->declaration.type;
4190 type_t *const type = skip_typeref(orig_type);
4192 assert(is_type_function(type));
4193 if (type->function.unspecified_parameters &&
4194 warning.strict_prototypes &&
4195 previous_entity == NULL) {
4196 warningf(pos, "function declaration '%#T' is not a prototype",
4200 if (warning.main && current_scope == file_scope
4201 && is_sym_main(symbol)) {
4206 if (is_declaration(entity) &&
4207 warning.nested_externs &&
4208 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4209 current_scope != file_scope) {
4210 warningf(pos, "nested extern declaration of '%#T'",
4211 entity->declaration.type, symbol);
4214 if (previous_entity != NULL) {
4215 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4216 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4217 assert(previous_entity->kind == ENTITY_PARAMETER);
4219 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4220 entity->declaration.type, symbol,
4221 previous_entity->declaration.type, symbol,
4222 &previous_entity->base.source_position);
4226 if (previous_entity->base.parent_scope == current_scope) {
4227 if (previous_entity->kind != entity->kind) {
4228 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4229 error_redefined_as_different_kind(pos, previous_entity,
4234 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4235 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4236 symbol, &previous_entity->base.source_position);
4239 if (previous_entity->kind == ENTITY_TYPEDEF) {
4240 /* TODO: C++ allows this for exactly the same type */
4241 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4242 symbol, &previous_entity->base.source_position);
4246 /* at this point we should have only VARIABLES or FUNCTIONS */
4247 assert(is_declaration(previous_entity) && is_declaration(entity));
4249 declaration_t *const prev_decl = &previous_entity->declaration;
4250 declaration_t *const decl = &entity->declaration;
4252 /* can happen for K&R style declarations */
4253 if (prev_decl->type == NULL &&
4254 previous_entity->kind == ENTITY_PARAMETER &&
4255 entity->kind == ENTITY_PARAMETER) {
4256 prev_decl->type = decl->type;
4257 prev_decl->storage_class = decl->storage_class;
4258 prev_decl->declared_storage_class = decl->declared_storage_class;
4259 prev_decl->modifiers = decl->modifiers;
4260 return previous_entity;
4263 type_t *const orig_type = decl->type;
4264 assert(orig_type != NULL);
4265 type_t *const type = skip_typeref(orig_type);
4266 type_t *const prev_type = skip_typeref(prev_decl->type);
4268 if (!types_compatible(type, prev_type)) {
4270 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4271 orig_type, symbol, prev_decl->type, symbol,
4272 &previous_entity->base.source_position);
4274 unsigned old_storage_class = prev_decl->storage_class;
4276 if (warning.redundant_decls &&
4279 !(prev_decl->modifiers & DM_USED) &&
4280 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4281 warningf(&previous_entity->base.source_position,
4282 "unnecessary static forward declaration for '%#T'",
4283 prev_decl->type, symbol);
4286 storage_class_t new_storage_class = decl->storage_class;
4288 /* pretend no storage class means extern for function
4289 * declarations (except if the previous declaration is neither
4290 * none nor extern) */
4291 if (entity->kind == ENTITY_FUNCTION) {
4292 /* the previous declaration could have unspecified parameters or
4293 * be a typedef, so use the new type */
4294 if (prev_type->function.unspecified_parameters || is_definition)
4295 prev_decl->type = type;
4297 switch (old_storage_class) {
4298 case STORAGE_CLASS_NONE:
4299 old_storage_class = STORAGE_CLASS_EXTERN;
4302 case STORAGE_CLASS_EXTERN:
4303 if (is_definition) {
4304 if (warning.missing_prototypes &&
4305 prev_type->function.unspecified_parameters &&
4306 !is_sym_main(symbol)) {
4307 warningf(pos, "no previous prototype for '%#T'",
4310 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4311 new_storage_class = STORAGE_CLASS_EXTERN;
4318 } else if (is_type_incomplete(prev_type)) {
4319 prev_decl->type = type;
4322 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4323 new_storage_class == STORAGE_CLASS_EXTERN) {
4325 warn_redundant_declaration: ;
4327 = has_new_attributes(prev_decl->attributes,
4329 if (has_new_attrs) {
4330 merge_in_attributes(decl, prev_decl->attributes);
4331 } else if (!is_definition &&
4332 warning.redundant_decls &&
4333 is_type_valid(prev_type) &&
4334 strcmp(previous_entity->base.source_position.input_name,
4335 "<builtin>") != 0) {
4337 "redundant declaration for '%Y' (declared %P)",
4338 symbol, &previous_entity->base.source_position);
4340 } else if (current_function == NULL) {
4341 if (old_storage_class != STORAGE_CLASS_STATIC &&
4342 new_storage_class == STORAGE_CLASS_STATIC) {
4344 "static declaration of '%Y' follows non-static declaration (declared %P)",
4345 symbol, &previous_entity->base.source_position);
4346 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4347 prev_decl->storage_class = STORAGE_CLASS_NONE;
4348 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4350 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4352 goto error_redeclaration;
4353 goto warn_redundant_declaration;
4355 } else if (is_type_valid(prev_type)) {
4356 if (old_storage_class == new_storage_class) {
4357 error_redeclaration:
4358 errorf(pos, "redeclaration of '%Y' (declared %P)",
4359 symbol, &previous_entity->base.source_position);
4362 "redeclaration of '%Y' with different linkage (declared %P)",
4363 symbol, &previous_entity->base.source_position);
4368 prev_decl->modifiers |= decl->modifiers;
4369 if (entity->kind == ENTITY_FUNCTION) {
4370 previous_entity->function.is_inline |= entity->function.is_inline;
4372 return previous_entity;
4375 if (warning.shadow) {
4376 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4377 get_entity_kind_name(entity->kind), symbol,
4378 get_entity_kind_name(previous_entity->kind),
4379 &previous_entity->base.source_position);
4383 if (entity->kind == ENTITY_FUNCTION) {
4384 if (is_definition &&
4385 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4386 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4387 warningf(pos, "no previous prototype for '%#T'",
4388 entity->declaration.type, symbol);
4389 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4390 warningf(pos, "no previous declaration for '%#T'",
4391 entity->declaration.type, symbol);
4394 } else if (warning.missing_declarations &&
4395 entity->kind == ENTITY_VARIABLE &&
4396 current_scope == file_scope) {
4397 declaration_t *declaration = &entity->declaration;
4398 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4399 warningf(pos, "no previous declaration for '%#T'",
4400 declaration->type, symbol);
4405 assert(entity->base.parent_scope == NULL);
4406 assert(current_scope != NULL);
4408 entity->base.parent_scope = current_scope;
4409 entity->base.namespc = NAMESPACE_NORMAL;
4410 environment_push(entity);
4411 append_entity(current_scope, entity);
4416 static void parser_error_multiple_definition(entity_t *entity,
4417 const source_position_t *source_position)
4419 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4420 entity->base.symbol, &entity->base.source_position);
4423 static bool is_declaration_specifier(const token_t *token,
4424 bool only_specifiers_qualifiers)
4426 switch (token->type) {
4431 return is_typedef_symbol(token->symbol);
4433 case T___extension__:
4435 return !only_specifiers_qualifiers;
4442 static void parse_init_declarator_rest(entity_t *entity)
4444 type_t *orig_type = type_error_type;
4446 if (entity->base.kind == ENTITY_TYPEDEF) {
4447 errorf(&entity->base.source_position,
4448 "typedef '%Y' is initialized (use __typeof__ instead)",
4449 entity->base.symbol);
4451 assert(is_declaration(entity));
4452 orig_type = entity->declaration.type;
4456 type_t *type = skip_typeref(orig_type);
4458 if (entity->kind == ENTITY_VARIABLE
4459 && entity->variable.initializer != NULL) {
4460 parser_error_multiple_definition(entity, HERE);
4463 declaration_t *const declaration = &entity->declaration;
4464 bool must_be_constant = false;
4465 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4466 entity->base.parent_scope == file_scope) {
4467 must_be_constant = true;
4470 if (is_type_function(type)) {
4471 errorf(&entity->base.source_position,
4472 "function '%#T' is initialized like a variable",
4473 orig_type, entity->base.symbol);
4474 orig_type = type_error_type;
4477 parse_initializer_env_t env;
4478 env.type = orig_type;
4479 env.must_be_constant = must_be_constant;
4480 env.entity = entity;
4481 current_init_decl = entity;
4483 initializer_t *initializer = parse_initializer(&env);
4484 current_init_decl = NULL;
4486 if (entity->kind == ENTITY_VARIABLE) {
4487 /* §6.7.5:22 array initializers for arrays with unknown size
4488 * determine the array type size */
4489 declaration->type = env.type;
4490 entity->variable.initializer = initializer;
4494 /* parse rest of a declaration without any declarator */
4495 static void parse_anonymous_declaration_rest(
4496 const declaration_specifiers_t *specifiers)
4499 anonymous_entity = NULL;
4501 if (warning.other) {
4502 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4503 specifiers->thread_local) {
4504 warningf(&specifiers->source_position,
4505 "useless storage class in empty declaration");
4508 type_t *type = specifiers->type;
4509 switch (type->kind) {
4510 case TYPE_COMPOUND_STRUCT:
4511 case TYPE_COMPOUND_UNION: {
4512 if (type->compound.compound->base.symbol == NULL) {
4513 warningf(&specifiers->source_position,
4514 "unnamed struct/union that defines no instances");
4523 warningf(&specifiers->source_position, "empty declaration");
4529 static void check_variable_type_complete(entity_t *ent)
4531 if (ent->kind != ENTITY_VARIABLE)
4534 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4535 * type for the object shall be complete [...] */
4536 declaration_t *decl = &ent->declaration;
4537 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4538 decl->storage_class == STORAGE_CLASS_STATIC)
4541 type_t *const orig_type = decl->type;
4542 type_t *const type = skip_typeref(orig_type);
4543 if (!is_type_incomplete(type))
4546 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4547 * are given length one. */
4548 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4549 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4553 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4554 orig_type, ent->base.symbol);
4558 static void parse_declaration_rest(entity_t *ndeclaration,
4559 const declaration_specifiers_t *specifiers,
4560 parsed_declaration_func finished_declaration,
4561 declarator_flags_t flags)
4563 add_anchor_token(';');
4564 add_anchor_token(',');
4566 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4568 if (token.type == '=') {
4569 parse_init_declarator_rest(entity);
4570 } else if (entity->kind == ENTITY_VARIABLE) {
4571 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4572 * [...] where the extern specifier is explicitly used. */
4573 declaration_t *decl = &entity->declaration;
4574 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4575 type_t *type = decl->type;
4576 if (is_type_reference(skip_typeref(type))) {
4577 errorf(&entity->base.source_position,
4578 "reference '%#T' must be initialized",
4579 type, entity->base.symbol);
4584 check_variable_type_complete(entity);
4589 add_anchor_token('=');
4590 ndeclaration = parse_declarator(specifiers, flags);
4591 rem_anchor_token('=');
4593 expect(';', end_error);
4596 anonymous_entity = NULL;
4597 rem_anchor_token(';');
4598 rem_anchor_token(',');
4601 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4603 symbol_t *symbol = entity->base.symbol;
4604 if (symbol == NULL) {
4605 errorf(HERE, "anonymous declaration not valid as function parameter");
4609 assert(entity->base.namespc == NAMESPACE_NORMAL);
4610 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4611 if (previous_entity == NULL
4612 || previous_entity->base.parent_scope != current_scope) {
4613 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4618 if (is_definition) {
4619 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4622 return record_entity(entity, false);
4625 static void parse_declaration(parsed_declaration_func finished_declaration,
4626 declarator_flags_t flags)
4628 declaration_specifiers_t specifiers;
4629 memset(&specifiers, 0, sizeof(specifiers));
4631 add_anchor_token(';');
4632 parse_declaration_specifiers(&specifiers);
4633 rem_anchor_token(';');
4635 if (token.type == ';') {
4636 parse_anonymous_declaration_rest(&specifiers);
4638 entity_t *entity = parse_declarator(&specifiers, flags);
4639 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4644 static type_t *get_default_promoted_type(type_t *orig_type)
4646 type_t *result = orig_type;
4648 type_t *type = skip_typeref(orig_type);
4649 if (is_type_integer(type)) {
4650 result = promote_integer(type);
4651 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4652 result = type_double;
4658 static void parse_kr_declaration_list(entity_t *entity)
4660 if (entity->kind != ENTITY_FUNCTION)
4663 type_t *type = skip_typeref(entity->declaration.type);
4664 assert(is_type_function(type));
4665 if (!type->function.kr_style_parameters)
4668 add_anchor_token('{');
4670 /* push function parameters */
4671 size_t const top = environment_top();
4672 scope_t *old_scope = scope_push(&entity->function.parameters);
4674 entity_t *parameter = entity->function.parameters.entities;
4675 for ( ; parameter != NULL; parameter = parameter->base.next) {
4676 assert(parameter->base.parent_scope == NULL);
4677 parameter->base.parent_scope = current_scope;
4678 environment_push(parameter);
4681 /* parse declaration list */
4683 switch (token.type) {
4685 case T___extension__:
4686 /* This covers symbols, which are no type, too, and results in
4687 * better error messages. The typical cases are misspelled type
4688 * names and missing includes. */
4690 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4698 /* pop function parameters */
4699 assert(current_scope == &entity->function.parameters);
4700 scope_pop(old_scope);
4701 environment_pop_to(top);
4703 /* update function type */
4704 type_t *new_type = duplicate_type(type);
4706 function_parameter_t *parameters = NULL;
4707 function_parameter_t **anchor = ¶meters;
4709 /* did we have an earlier prototype? */
4710 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4711 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4714 function_parameter_t *proto_parameter = NULL;
4715 if (proto_type != NULL) {
4716 type_t *proto_type_type = proto_type->declaration.type;
4717 proto_parameter = proto_type_type->function.parameters;
4718 /* If a K&R function definition has a variadic prototype earlier, then
4719 * make the function definition variadic, too. This should conform to
4720 * §6.7.5.3:15 and §6.9.1:8. */
4721 new_type->function.variadic = proto_type_type->function.variadic;
4723 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4725 new_type->function.unspecified_parameters = true;
4728 bool need_incompatible_warning = false;
4729 parameter = entity->function.parameters.entities;
4730 for (; parameter != NULL; parameter = parameter->base.next,
4732 proto_parameter == NULL ? NULL : proto_parameter->next) {
4733 if (parameter->kind != ENTITY_PARAMETER)
4736 type_t *parameter_type = parameter->declaration.type;
4737 if (parameter_type == NULL) {
4739 errorf(HERE, "no type specified for function parameter '%Y'",
4740 parameter->base.symbol);
4741 parameter_type = type_error_type;
4743 if (warning.implicit_int) {
4744 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4745 parameter->base.symbol);
4747 parameter_type = type_int;
4749 parameter->declaration.type = parameter_type;
4752 semantic_parameter_incomplete(parameter);
4754 /* we need the default promoted types for the function type */
4755 type_t *not_promoted = parameter_type;
4756 parameter_type = get_default_promoted_type(parameter_type);
4758 /* gcc special: if the type of the prototype matches the unpromoted
4759 * type don't promote */
4760 if (!strict_mode && proto_parameter != NULL) {
4761 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4762 type_t *promo_skip = skip_typeref(parameter_type);
4763 type_t *param_skip = skip_typeref(not_promoted);
4764 if (!types_compatible(proto_p_type, promo_skip)
4765 && types_compatible(proto_p_type, param_skip)) {
4767 need_incompatible_warning = true;
4768 parameter_type = not_promoted;
4771 function_parameter_t *const parameter
4772 = allocate_parameter(parameter_type);
4774 *anchor = parameter;
4775 anchor = ¶meter->next;
4778 new_type->function.parameters = parameters;
4779 new_type = identify_new_type(new_type);
4781 if (warning.other && need_incompatible_warning) {
4782 type_t *proto_type_type = proto_type->declaration.type;
4784 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4785 proto_type_type, proto_type->base.symbol,
4786 new_type, entity->base.symbol,
4787 &proto_type->base.source_position);
4790 entity->declaration.type = new_type;
4792 rem_anchor_token('{');
4795 static bool first_err = true;
4798 * When called with first_err set, prints the name of the current function,
4801 static void print_in_function(void)
4805 diagnosticf("%s: In function '%Y':\n",
4806 current_function->base.base.source_position.input_name,
4807 current_function->base.base.symbol);
4812 * Check if all labels are defined in the current function.
4813 * Check if all labels are used in the current function.
4815 static void check_labels(void)
4817 for (const goto_statement_t *goto_statement = goto_first;
4818 goto_statement != NULL;
4819 goto_statement = goto_statement->next) {
4820 /* skip computed gotos */
4821 if (goto_statement->expression != NULL)
4824 label_t *label = goto_statement->label;
4827 if (label->base.source_position.input_name == NULL) {
4828 print_in_function();
4829 errorf(&goto_statement->base.source_position,
4830 "label '%Y' used but not defined", label->base.symbol);
4834 if (warning.unused_label) {
4835 for (const label_statement_t *label_statement = label_first;
4836 label_statement != NULL;
4837 label_statement = label_statement->next) {
4838 label_t *label = label_statement->label;
4840 if (! label->used) {
4841 print_in_function();
4842 warningf(&label_statement->base.source_position,
4843 "label '%Y' defined but not used", label->base.symbol);
4849 static void warn_unused_entity(entity_t *entity, entity_t *last)
4851 entity_t const *const end = last != NULL ? last->base.next : NULL;
4852 for (; entity != end; entity = entity->base.next) {
4853 if (!is_declaration(entity))
4856 declaration_t *declaration = &entity->declaration;
4857 if (declaration->implicit)
4860 if (!declaration->used) {
4861 print_in_function();
4862 const char *what = get_entity_kind_name(entity->kind);
4863 warningf(&entity->base.source_position, "%s '%Y' is unused",
4864 what, entity->base.symbol);
4865 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4866 print_in_function();
4867 const char *what = get_entity_kind_name(entity->kind);
4868 warningf(&entity->base.source_position, "%s '%Y' is never read",
4869 what, entity->base.symbol);
4874 static void check_unused_variables(statement_t *const stmt, void *const env)
4878 switch (stmt->kind) {
4879 case STATEMENT_DECLARATION: {
4880 declaration_statement_t const *const decls = &stmt->declaration;
4881 warn_unused_entity(decls->declarations_begin,
4882 decls->declarations_end);
4887 warn_unused_entity(stmt->fors.scope.entities, NULL);
4896 * Check declarations of current_function for unused entities.
4898 static void check_declarations(void)
4900 if (warning.unused_parameter) {
4901 const scope_t *scope = ¤t_function->parameters;
4903 /* do not issue unused warnings for main */
4904 if (!is_sym_main(current_function->base.base.symbol)) {
4905 warn_unused_entity(scope->entities, NULL);
4908 if (warning.unused_variable) {
4909 walk_statements(current_function->statement, check_unused_variables,
4914 static int determine_truth(expression_t const* const cond)
4917 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4918 fold_constant_to_bool(cond) ? 1 :
4922 static void check_reachable(statement_t *);
4923 static bool reaches_end;
4925 static bool expression_returns(expression_t const *const expr)
4927 switch (expr->kind) {
4929 expression_t const *const func = expr->call.function;
4930 if (func->kind == EXPR_REFERENCE) {
4931 entity_t *entity = func->reference.entity;
4932 if (entity->kind == ENTITY_FUNCTION
4933 && entity->declaration.modifiers & DM_NORETURN)
4937 if (!expression_returns(func))
4940 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4941 if (!expression_returns(arg->expression))
4948 case EXPR_REFERENCE:
4949 case EXPR_REFERENCE_ENUM_VALUE:
4951 case EXPR_STRING_LITERAL:
4952 case EXPR_WIDE_STRING_LITERAL:
4953 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4954 case EXPR_LABEL_ADDRESS:
4955 case EXPR_CLASSIFY_TYPE:
4956 case EXPR_SIZEOF: // TODO handle obscure VLA case
4959 case EXPR_BUILTIN_CONSTANT_P:
4960 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4965 case EXPR_STATEMENT: {
4966 bool old_reaches_end = reaches_end;
4967 reaches_end = false;
4968 check_reachable(expr->statement.statement);
4969 bool returns = reaches_end;
4970 reaches_end = old_reaches_end;
4974 case EXPR_CONDITIONAL:
4975 // TODO handle constant expression
4977 if (!expression_returns(expr->conditional.condition))
4980 if (expr->conditional.true_expression != NULL
4981 && expression_returns(expr->conditional.true_expression))
4984 return expression_returns(expr->conditional.false_expression);
4987 return expression_returns(expr->select.compound);
4989 case EXPR_ARRAY_ACCESS:
4991 expression_returns(expr->array_access.array_ref) &&
4992 expression_returns(expr->array_access.index);
4995 return expression_returns(expr->va_starte.ap);
4998 return expression_returns(expr->va_arge.ap);
5001 return expression_returns(expr->va_copye.src);
5003 EXPR_UNARY_CASES_MANDATORY
5004 return expression_returns(expr->unary.value);
5006 case EXPR_UNARY_THROW:
5010 // TODO handle constant lhs of && and ||
5012 expression_returns(expr->binary.left) &&
5013 expression_returns(expr->binary.right);
5019 panic("unhandled expression");
5022 static bool initializer_returns(initializer_t const *const init)
5024 switch (init->kind) {
5025 case INITIALIZER_VALUE:
5026 return expression_returns(init->value.value);
5028 case INITIALIZER_LIST: {
5029 initializer_t * const* i = init->list.initializers;
5030 initializer_t * const* const end = i + init->list.len;
5031 bool returns = true;
5032 for (; i != end; ++i) {
5033 if (!initializer_returns(*i))
5039 case INITIALIZER_STRING:
5040 case INITIALIZER_WIDE_STRING:
5041 case INITIALIZER_DESIGNATOR: // designators have no payload
5044 panic("unhandled initializer");
5047 static bool noreturn_candidate;
5049 static void check_reachable(statement_t *const stmt)
5051 if (stmt->base.reachable)
5053 if (stmt->kind != STATEMENT_DO_WHILE)
5054 stmt->base.reachable = true;
5056 statement_t *last = stmt;
5058 switch (stmt->kind) {
5059 case STATEMENT_INVALID:
5060 case STATEMENT_EMPTY:
5062 next = stmt->base.next;
5065 case STATEMENT_DECLARATION: {
5066 declaration_statement_t const *const decl = &stmt->declaration;
5067 entity_t const * ent = decl->declarations_begin;
5068 entity_t const *const last = decl->declarations_end;
5070 for (;; ent = ent->base.next) {
5071 if (ent->kind == ENTITY_VARIABLE &&
5072 ent->variable.initializer != NULL &&
5073 !initializer_returns(ent->variable.initializer)) {
5080 next = stmt->base.next;
5084 case STATEMENT_COMPOUND:
5085 next = stmt->compound.statements;
5087 next = stmt->base.next;
5090 case STATEMENT_RETURN: {
5091 expression_t const *const val = stmt->returns.value;
5092 if (val == NULL || expression_returns(val))
5093 noreturn_candidate = false;
5097 case STATEMENT_IF: {
5098 if_statement_t const *const ifs = &stmt->ifs;
5099 expression_t const *const cond = ifs->condition;
5101 if (!expression_returns(cond))
5104 int const val = determine_truth(cond);
5107 check_reachable(ifs->true_statement);
5112 if (ifs->false_statement != NULL) {
5113 check_reachable(ifs->false_statement);
5117 next = stmt->base.next;
5121 case STATEMENT_SWITCH: {
5122 switch_statement_t const *const switchs = &stmt->switchs;
5123 expression_t const *const expr = switchs->expression;
5125 if (!expression_returns(expr))
5128 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5129 long const val = fold_constant_to_int(expr);
5130 case_label_statement_t * defaults = NULL;
5131 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5132 if (i->expression == NULL) {
5137 if (i->first_case <= val && val <= i->last_case) {
5138 check_reachable((statement_t*)i);
5143 if (defaults != NULL) {
5144 check_reachable((statement_t*)defaults);
5148 bool has_default = false;
5149 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5150 if (i->expression == NULL)
5153 check_reachable((statement_t*)i);
5160 next = stmt->base.next;
5164 case STATEMENT_EXPRESSION: {
5165 /* Check for noreturn function call */
5166 expression_t const *const expr = stmt->expression.expression;
5167 if (!expression_returns(expr))
5170 next = stmt->base.next;
5174 case STATEMENT_CONTINUE:
5175 for (statement_t *parent = stmt;;) {
5176 parent = parent->base.parent;
5177 if (parent == NULL) /* continue not within loop */
5181 switch (parent->kind) {
5182 case STATEMENT_WHILE: goto continue_while;
5183 case STATEMENT_DO_WHILE: goto continue_do_while;
5184 case STATEMENT_FOR: goto continue_for;
5190 case STATEMENT_BREAK:
5191 for (statement_t *parent = stmt;;) {
5192 parent = parent->base.parent;
5193 if (parent == NULL) /* break not within loop/switch */
5196 switch (parent->kind) {
5197 case STATEMENT_SWITCH:
5198 case STATEMENT_WHILE:
5199 case STATEMENT_DO_WHILE:
5202 next = parent->base.next;
5203 goto found_break_parent;
5211 case STATEMENT_GOTO:
5212 if (stmt->gotos.expression) {
5213 if (!expression_returns(stmt->gotos.expression))
5216 statement_t *parent = stmt->base.parent;
5217 if (parent == NULL) /* top level goto */
5221 next = stmt->gotos.label->statement;
5222 if (next == NULL) /* missing label */
5227 case STATEMENT_LABEL:
5228 next = stmt->label.statement;
5231 case STATEMENT_CASE_LABEL:
5232 next = stmt->case_label.statement;
5235 case STATEMENT_WHILE: {
5236 while_statement_t const *const whiles = &stmt->whiles;
5237 expression_t const *const cond = whiles->condition;
5239 if (!expression_returns(cond))
5242 int const val = determine_truth(cond);
5245 check_reachable(whiles->body);
5250 next = stmt->base.next;
5254 case STATEMENT_DO_WHILE:
5255 next = stmt->do_while.body;
5258 case STATEMENT_FOR: {
5259 for_statement_t *const fors = &stmt->fors;
5261 if (fors->condition_reachable)
5263 fors->condition_reachable = true;
5265 expression_t const *const cond = fors->condition;
5270 } else if (expression_returns(cond)) {
5271 val = determine_truth(cond);
5277 check_reachable(fors->body);
5282 next = stmt->base.next;
5286 case STATEMENT_MS_TRY: {
5287 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5288 check_reachable(ms_try->try_statement);
5289 next = ms_try->final_statement;
5293 case STATEMENT_LEAVE: {
5294 statement_t *parent = stmt;
5296 parent = parent->base.parent;
5297 if (parent == NULL) /* __leave not within __try */
5300 if (parent->kind == STATEMENT_MS_TRY) {
5302 next = parent->ms_try.final_statement;
5310 panic("invalid statement kind");
5313 while (next == NULL) {
5314 next = last->base.parent;
5316 noreturn_candidate = false;
5318 type_t *const type = skip_typeref(current_function->base.type);
5319 assert(is_type_function(type));
5320 type_t *const ret = skip_typeref(type->function.return_type);
5321 if (warning.return_type &&
5322 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5323 is_type_valid(ret) &&
5324 !is_sym_main(current_function->base.base.symbol)) {
5325 warningf(&stmt->base.source_position,
5326 "control reaches end of non-void function");
5331 switch (next->kind) {
5332 case STATEMENT_INVALID:
5333 case STATEMENT_EMPTY:
5334 case STATEMENT_DECLARATION:
5335 case STATEMENT_EXPRESSION:
5337 case STATEMENT_RETURN:
5338 case STATEMENT_CONTINUE:
5339 case STATEMENT_BREAK:
5340 case STATEMENT_GOTO:
5341 case STATEMENT_LEAVE:
5342 panic("invalid control flow in function");
5344 case STATEMENT_COMPOUND:
5345 if (next->compound.stmt_expr) {
5351 case STATEMENT_SWITCH:
5352 case STATEMENT_LABEL:
5353 case STATEMENT_CASE_LABEL:
5355 next = next->base.next;
5358 case STATEMENT_WHILE: {
5360 if (next->base.reachable)
5362 next->base.reachable = true;
5364 while_statement_t const *const whiles = &next->whiles;
5365 expression_t const *const cond = whiles->condition;
5367 if (!expression_returns(cond))
5370 int const val = determine_truth(cond);
5373 check_reachable(whiles->body);
5379 next = next->base.next;
5383 case STATEMENT_DO_WHILE: {
5385 if (next->base.reachable)
5387 next->base.reachable = true;
5389 do_while_statement_t const *const dw = &next->do_while;
5390 expression_t const *const cond = dw->condition;
5392 if (!expression_returns(cond))
5395 int const val = determine_truth(cond);
5398 check_reachable(dw->body);
5404 next = next->base.next;
5408 case STATEMENT_FOR: {
5410 for_statement_t *const fors = &next->fors;
5412 fors->step_reachable = true;
5414 if (fors->condition_reachable)
5416 fors->condition_reachable = true;
5418 expression_t const *const cond = fors->condition;
5423 } else if (expression_returns(cond)) {
5424 val = determine_truth(cond);
5430 check_reachable(fors->body);
5436 next = next->base.next;
5440 case STATEMENT_MS_TRY:
5442 next = next->ms_try.final_statement;
5447 check_reachable(next);
5450 static void check_unreachable(statement_t* const stmt, void *const env)
5454 switch (stmt->kind) {
5455 case STATEMENT_DO_WHILE:
5456 if (!stmt->base.reachable) {
5457 expression_t const *const cond = stmt->do_while.condition;
5458 if (determine_truth(cond) >= 0) {
5459 warningf(&cond->base.source_position,
5460 "condition of do-while-loop is unreachable");
5465 case STATEMENT_FOR: {
5466 for_statement_t const* const fors = &stmt->fors;
5468 // if init and step are unreachable, cond is unreachable, too
5469 if (!stmt->base.reachable && !fors->step_reachable) {
5470 warningf(&stmt->base.source_position, "statement is unreachable");
5472 if (!stmt->base.reachable && fors->initialisation != NULL) {
5473 warningf(&fors->initialisation->base.source_position,
5474 "initialisation of for-statement is unreachable");
5477 if (!fors->condition_reachable && fors->condition != NULL) {
5478 warningf(&fors->condition->base.source_position,
5479 "condition of for-statement is unreachable");
5482 if (!fors->step_reachable && fors->step != NULL) {
5483 warningf(&fors->step->base.source_position,
5484 "step of for-statement is unreachable");
5490 case STATEMENT_COMPOUND:
5491 if (stmt->compound.statements != NULL)
5493 goto warn_unreachable;
5495 case STATEMENT_DECLARATION: {
5496 /* Only warn if there is at least one declarator with an initializer.
5497 * This typically occurs in switch statements. */
5498 declaration_statement_t const *const decl = &stmt->declaration;
5499 entity_t const * ent = decl->declarations_begin;
5500 entity_t const *const last = decl->declarations_end;
5502 for (;; ent = ent->base.next) {
5503 if (ent->kind == ENTITY_VARIABLE &&
5504 ent->variable.initializer != NULL) {
5505 goto warn_unreachable;
5515 if (!stmt->base.reachable)
5516 warningf(&stmt->base.source_position, "statement is unreachable");
5521 static void parse_external_declaration(void)
5523 /* function-definitions and declarations both start with declaration
5525 declaration_specifiers_t specifiers;
5526 memset(&specifiers, 0, sizeof(specifiers));
5528 add_anchor_token(';');
5529 parse_declaration_specifiers(&specifiers);
5530 rem_anchor_token(';');
5532 /* must be a declaration */
5533 if (token.type == ';') {
5534 parse_anonymous_declaration_rest(&specifiers);
5538 add_anchor_token(',');
5539 add_anchor_token('=');
5540 add_anchor_token(';');
5541 add_anchor_token('{');
5543 /* declarator is common to both function-definitions and declarations */
5544 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5546 rem_anchor_token('{');
5547 rem_anchor_token(';');
5548 rem_anchor_token('=');
5549 rem_anchor_token(',');
5551 /* must be a declaration */
5552 switch (token.type) {
5556 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5561 /* must be a function definition */
5562 parse_kr_declaration_list(ndeclaration);
5564 if (token.type != '{') {
5565 parse_error_expected("while parsing function definition", '{', NULL);
5566 eat_until_matching_token(';');
5570 assert(is_declaration(ndeclaration));
5571 type_t *const orig_type = ndeclaration->declaration.type;
5572 type_t * type = skip_typeref(orig_type);
5574 if (!is_type_function(type)) {
5575 if (is_type_valid(type)) {
5576 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5577 type, ndeclaration->base.symbol);
5581 } else if (is_typeref(orig_type)) {
5583 errorf(&ndeclaration->base.source_position,
5584 "type of function definition '%#T' is a typedef",
5585 orig_type, ndeclaration->base.symbol);
5588 if (warning.aggregate_return &&
5589 is_type_compound(skip_typeref(type->function.return_type))) {
5590 warningf(HERE, "function '%Y' returns an aggregate",
5591 ndeclaration->base.symbol);
5593 if (warning.traditional && !type->function.unspecified_parameters) {
5594 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5595 ndeclaration->base.symbol);
5597 if (warning.old_style_definition && type->function.unspecified_parameters) {
5598 warningf(HERE, "old-style function definition '%Y'",
5599 ndeclaration->base.symbol);
5602 /* §6.7.5.3:14 a function definition with () means no
5603 * parameters (and not unspecified parameters) */
5604 if (type->function.unspecified_parameters &&
5605 type->function.parameters == NULL) {
5606 type_t *copy = duplicate_type(type);
5607 copy->function.unspecified_parameters = false;
5608 type = identify_new_type(copy);
5610 ndeclaration->declaration.type = type;
5613 entity_t *const entity = record_entity(ndeclaration, true);
5614 assert(entity->kind == ENTITY_FUNCTION);
5615 assert(ndeclaration->kind == ENTITY_FUNCTION);
5617 function_t *const function = &entity->function;
5618 if (ndeclaration != entity) {
5619 function->parameters = ndeclaration->function.parameters;
5621 assert(is_declaration(entity));
5622 type = skip_typeref(entity->declaration.type);
5624 /* push function parameters and switch scope */
5625 size_t const top = environment_top();
5626 scope_t *old_scope = scope_push(&function->parameters);
5628 entity_t *parameter = function->parameters.entities;
5629 for (; parameter != NULL; parameter = parameter->base.next) {
5630 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5631 parameter->base.parent_scope = current_scope;
5633 assert(parameter->base.parent_scope == NULL
5634 || parameter->base.parent_scope == current_scope);
5635 parameter->base.parent_scope = current_scope;
5636 if (parameter->base.symbol == NULL) {
5637 errorf(¶meter->base.source_position, "parameter name omitted");
5640 environment_push(parameter);
5643 if (function->statement != NULL) {
5644 parser_error_multiple_definition(entity, HERE);
5647 /* parse function body */
5648 int label_stack_top = label_top();
5649 function_t *old_current_function = current_function;
5650 entity_t *old_current_entity = current_entity;
5651 current_function = function;
5652 current_entity = entity;
5653 current_parent = NULL;
5656 goto_anchor = &goto_first;
5658 label_anchor = &label_first;
5660 statement_t *const body = parse_compound_statement(false);
5661 function->statement = body;
5664 check_declarations();
5665 if (warning.return_type ||
5666 warning.unreachable_code ||
5667 (warning.missing_noreturn
5668 && !(function->base.modifiers & DM_NORETURN))) {
5669 noreturn_candidate = true;
5670 check_reachable(body);
5671 if (warning.unreachable_code)
5672 walk_statements(body, check_unreachable, NULL);
5673 if (warning.missing_noreturn &&
5674 noreturn_candidate &&
5675 !(function->base.modifiers & DM_NORETURN)) {
5676 warningf(&body->base.source_position,
5677 "function '%#T' is candidate for attribute 'noreturn'",
5678 type, entity->base.symbol);
5682 assert(current_parent == NULL);
5683 assert(current_function == function);
5684 assert(current_entity == entity);
5685 current_entity = old_current_entity;
5686 current_function = old_current_function;
5687 label_pop_to(label_stack_top);
5690 assert(current_scope == &function->parameters);
5691 scope_pop(old_scope);
5692 environment_pop_to(top);
5695 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5696 source_position_t *source_position,
5697 const symbol_t *symbol)
5699 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5701 type->bitfield.base_type = base_type;
5702 type->bitfield.size_expression = size;
5705 type_t *skipped_type = skip_typeref(base_type);
5706 if (!is_type_integer(skipped_type)) {
5707 errorf(HERE, "bitfield base type '%T' is not an integer type",
5711 bit_size = get_type_size(base_type) * 8;
5714 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5715 long v = fold_constant_to_int(size);
5716 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5719 errorf(source_position, "negative width in bit-field '%Y'",
5721 } else if (v == 0 && symbol != NULL) {
5722 errorf(source_position, "zero width for bit-field '%Y'",
5724 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5725 errorf(source_position, "width of '%Y' exceeds its type",
5728 type->bitfield.bit_size = v;
5735 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5737 entity_t *iter = compound->members.entities;
5738 for (; iter != NULL; iter = iter->base.next) {
5739 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5742 if (iter->base.symbol == symbol) {
5744 } else if (iter->base.symbol == NULL) {
5745 /* search in anonymous structs and unions */
5746 type_t *type = skip_typeref(iter->declaration.type);
5747 if (is_type_compound(type)) {
5748 if (find_compound_entry(type->compound.compound, symbol)
5759 static void check_deprecated(const source_position_t *source_position,
5760 const entity_t *entity)
5762 if (!warning.deprecated_declarations)
5764 if (!is_declaration(entity))
5766 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5769 char const *const prefix = get_entity_kind_name(entity->kind);
5770 const char *deprecated_string
5771 = get_deprecated_string(entity->declaration.attributes);
5772 if (deprecated_string != NULL) {
5773 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5774 prefix, entity->base.symbol, &entity->base.source_position,
5777 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5778 entity->base.symbol, &entity->base.source_position);
5783 static expression_t *create_select(const source_position_t *pos,
5785 type_qualifiers_t qualifiers,
5788 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5790 check_deprecated(pos, entry);
5792 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5793 select->select.compound = addr;
5794 select->select.compound_entry = entry;
5796 type_t *entry_type = entry->declaration.type;
5797 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5799 /* we always do the auto-type conversions; the & and sizeof parser contains
5800 * code to revert this! */
5801 select->base.type = automatic_type_conversion(res_type);
5802 if (res_type->kind == TYPE_BITFIELD) {
5803 select->base.type = res_type->bitfield.base_type;
5810 * Find entry with symbol in compound. Search anonymous structs and unions and
5811 * creates implicit select expressions for them.
5812 * Returns the adress for the innermost compound.
5814 static expression_t *find_create_select(const source_position_t *pos,
5816 type_qualifiers_t qualifiers,
5817 compound_t *compound, symbol_t *symbol)
5819 entity_t *iter = compound->members.entities;
5820 for (; iter != NULL; iter = iter->base.next) {
5821 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5824 symbol_t *iter_symbol = iter->base.symbol;
5825 if (iter_symbol == NULL) {
5826 type_t *type = iter->declaration.type;
5827 if (type->kind != TYPE_COMPOUND_STRUCT
5828 && type->kind != TYPE_COMPOUND_UNION)
5831 compound_t *sub_compound = type->compound.compound;
5833 if (find_compound_entry(sub_compound, symbol) == NULL)
5836 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5837 sub_addr->base.source_position = *pos;
5838 sub_addr->select.implicit = true;
5839 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5843 if (iter_symbol == symbol) {
5844 return create_select(pos, addr, qualifiers, iter);
5851 static void parse_compound_declarators(compound_t *compound,
5852 const declaration_specifiers_t *specifiers)
5857 if (token.type == ':') {
5858 source_position_t source_position = *HERE;
5861 type_t *base_type = specifiers->type;
5862 expression_t *size = parse_constant_expression();
5864 type_t *type = make_bitfield_type(base_type, size,
5865 &source_position, NULL);
5867 attribute_t *attributes = parse_attributes(NULL);
5868 attribute_t **anchor = &attributes;
5869 while (*anchor != NULL)
5870 anchor = &(*anchor)->next;
5871 *anchor = specifiers->attributes;
5873 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5874 entity->base.namespc = NAMESPACE_NORMAL;
5875 entity->base.source_position = source_position;
5876 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5877 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5878 entity->declaration.type = type;
5879 entity->declaration.attributes = attributes;
5881 if (attributes != NULL) {
5882 handle_entity_attributes(attributes, entity);
5884 append_entity(&compound->members, entity);
5886 entity = parse_declarator(specifiers,
5887 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5888 if (entity->kind == ENTITY_TYPEDEF) {
5889 errorf(&entity->base.source_position,
5890 "typedef not allowed as compound member");
5892 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5894 /* make sure we don't define a symbol multiple times */
5895 symbol_t *symbol = entity->base.symbol;
5896 if (symbol != NULL) {
5897 entity_t *prev = find_compound_entry(compound, symbol);
5899 errorf(&entity->base.source_position,
5900 "multiple declarations of symbol '%Y' (declared %P)",
5901 symbol, &prev->base.source_position);
5905 if (token.type == ':') {
5906 source_position_t source_position = *HERE;
5908 expression_t *size = parse_constant_expression();
5910 type_t *type = entity->declaration.type;
5911 type_t *bitfield_type = make_bitfield_type(type, size,
5912 &source_position, entity->base.symbol);
5914 attribute_t *attributes = parse_attributes(NULL);
5915 entity->declaration.type = bitfield_type;
5916 handle_entity_attributes(attributes, entity);
5918 type_t *orig_type = entity->declaration.type;
5919 type_t *type = skip_typeref(orig_type);
5920 if (is_type_function(type)) {
5921 errorf(&entity->base.source_position,
5922 "compound member '%Y' must not have function type '%T'",
5923 entity->base.symbol, orig_type);
5924 } else if (is_type_incomplete(type)) {
5925 /* §6.7.2.1:16 flexible array member */
5926 if (!is_type_array(type) ||
5927 token.type != ';' ||
5928 look_ahead(1)->type != '}') {
5929 errorf(&entity->base.source_position,
5930 "compound member '%Y' has incomplete type '%T'",
5931 entity->base.symbol, orig_type);
5936 append_entity(&compound->members, entity);
5939 } while (next_if(','));
5940 expect(';', end_error);
5943 anonymous_entity = NULL;
5946 static void parse_compound_type_entries(compound_t *compound)
5949 add_anchor_token('}');
5951 while (token.type != '}') {
5952 if (token.type == T_EOF) {
5953 errorf(HERE, "EOF while parsing struct");
5956 declaration_specifiers_t specifiers;
5957 memset(&specifiers, 0, sizeof(specifiers));
5958 parse_declaration_specifiers(&specifiers);
5960 parse_compound_declarators(compound, &specifiers);
5962 rem_anchor_token('}');
5966 compound->complete = true;
5969 static type_t *parse_typename(void)
5971 declaration_specifiers_t specifiers;
5972 memset(&specifiers, 0, sizeof(specifiers));
5973 parse_declaration_specifiers(&specifiers);
5974 if (specifiers.storage_class != STORAGE_CLASS_NONE
5975 || specifiers.thread_local) {
5976 /* TODO: improve error message, user does probably not know what a
5977 * storage class is...
5979 errorf(HERE, "typename must not have a storage class");
5982 type_t *result = parse_abstract_declarator(specifiers.type);
5990 typedef expression_t* (*parse_expression_function)(void);
5991 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5993 typedef struct expression_parser_function_t expression_parser_function_t;
5994 struct expression_parser_function_t {
5995 parse_expression_function parser;
5996 precedence_t infix_precedence;
5997 parse_expression_infix_function infix_parser;
6000 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6003 * Prints an error message if an expression was expected but not read
6005 static expression_t *expected_expression_error(void)
6007 /* skip the error message if the error token was read */
6008 if (token.type != T_ERROR) {
6009 errorf(HERE, "expected expression, got token %K", &token);
6013 return create_invalid_expression();
6016 static type_t *get_string_type(void)
6018 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6021 static type_t *get_wide_string_type(void)
6023 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6027 * Parse a string constant.
6029 static expression_t *parse_string_literal(void)
6031 source_position_t begin = token.source_position;
6032 string_t res = token.literal;
6033 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6036 while (token.type == T_STRING_LITERAL
6037 || token.type == T_WIDE_STRING_LITERAL) {
6038 warn_string_concat(&token.source_position);
6039 res = concat_strings(&res, &token.literal);
6041 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6044 expression_t *literal;
6046 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6047 literal->base.type = get_wide_string_type();
6049 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6050 literal->base.type = get_string_type();
6052 literal->base.source_position = begin;
6053 literal->literal.value = res;
6059 * Parse a boolean constant.
6061 static expression_t *parse_boolean_literal(bool value)
6063 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6064 literal->base.source_position = token.source_position;
6065 literal->base.type = type_bool;
6066 literal->literal.value.begin = value ? "true" : "false";
6067 literal->literal.value.size = value ? 4 : 5;
6073 static void warn_traditional_suffix(void)
6075 if (!warning.traditional)
6077 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6081 static void check_integer_suffix(void)
6083 symbol_t *suffix = token.symbol;
6087 bool not_traditional = false;
6088 const char *c = suffix->string;
6089 if (*c == 'l' || *c == 'L') {
6092 not_traditional = true;
6094 if (*c == 'u' || *c == 'U') {
6097 } else if (*c == 'u' || *c == 'U') {
6098 not_traditional = true;
6101 } else if (*c == 'u' || *c == 'U') {
6102 not_traditional = true;
6104 if (*c == 'l' || *c == 'L') {
6112 errorf(&token.source_position,
6113 "invalid suffix '%s' on integer constant", suffix->string);
6114 } else if (not_traditional) {
6115 warn_traditional_suffix();
6119 static type_t *check_floatingpoint_suffix(void)
6121 symbol_t *suffix = token.symbol;
6122 type_t *type = type_double;
6126 bool not_traditional = false;
6127 const char *c = suffix->string;
6128 if (*c == 'f' || *c == 'F') {
6131 } else if (*c == 'l' || *c == 'L') {
6133 type = type_long_double;
6136 errorf(&token.source_position,
6137 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6138 } else if (not_traditional) {
6139 warn_traditional_suffix();
6146 * Parse an integer constant.
6148 static expression_t *parse_number_literal(void)
6150 expression_kind_t kind;
6153 switch (token.type) {
6155 kind = EXPR_LITERAL_INTEGER;
6156 check_integer_suffix();
6159 case T_INTEGER_OCTAL:
6160 kind = EXPR_LITERAL_INTEGER_OCTAL;
6161 check_integer_suffix();
6164 case T_INTEGER_HEXADECIMAL:
6165 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6166 check_integer_suffix();
6169 case T_FLOATINGPOINT:
6170 kind = EXPR_LITERAL_FLOATINGPOINT;
6171 type = check_floatingpoint_suffix();
6173 case T_FLOATINGPOINT_HEXADECIMAL:
6174 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6175 type = check_floatingpoint_suffix();
6178 panic("unexpected token type in parse_number_literal");
6181 expression_t *literal = allocate_expression_zero(kind);
6182 literal->base.source_position = token.source_position;
6183 literal->base.type = type;
6184 literal->literal.value = token.literal;
6185 literal->literal.suffix = token.symbol;
6188 /* integer type depends on the size of the number and the size
6189 * representable by the types. The backend/codegeneration has to determine
6192 determine_literal_type(&literal->literal);
6197 * Parse a character constant.
6199 static expression_t *parse_character_constant(void)
6201 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6202 literal->base.source_position = token.source_position;
6203 literal->base.type = c_mode & _CXX ? type_char : type_int;
6204 literal->literal.value = token.literal;
6206 size_t len = literal->literal.value.size;
6208 if (!GNU_MODE && !(c_mode & _C99)) {
6209 errorf(HERE, "more than 1 character in character constant");
6210 } else if (warning.multichar) {
6211 literal->base.type = type_int;
6212 warningf(HERE, "multi-character character constant");
6221 * Parse a wide character constant.
6223 static expression_t *parse_wide_character_constant(void)
6225 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6226 literal->base.source_position = token.source_position;
6227 literal->base.type = type_int;
6228 literal->literal.value = token.literal;
6230 size_t len = wstrlen(&literal->literal.value);
6232 warningf(HERE, "multi-character character constant");
6239 static entity_t *create_implicit_function(symbol_t *symbol,
6240 const source_position_t *source_position)
6242 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6243 ntype->function.return_type = type_int;
6244 ntype->function.unspecified_parameters = true;
6245 ntype->function.linkage = LINKAGE_C;
6246 type_t *type = identify_new_type(ntype);
6248 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6249 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6250 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6251 entity->declaration.type = type;
6252 entity->declaration.implicit = true;
6253 entity->base.namespc = NAMESPACE_NORMAL;
6254 entity->base.symbol = symbol;
6255 entity->base.source_position = *source_position;
6257 if (current_scope != NULL) {
6258 bool strict_prototypes_old = warning.strict_prototypes;
6259 warning.strict_prototypes = false;
6260 record_entity(entity, false);
6261 warning.strict_prototypes = strict_prototypes_old;
6268 * Performs automatic type cast as described in §6.3.2.1.
6270 * @param orig_type the original type
6272 static type_t *automatic_type_conversion(type_t *orig_type)
6274 type_t *type = skip_typeref(orig_type);
6275 if (is_type_array(type)) {
6276 array_type_t *array_type = &type->array;
6277 type_t *element_type = array_type->element_type;
6278 unsigned qualifiers = array_type->base.qualifiers;
6280 return make_pointer_type(element_type, qualifiers);
6283 if (is_type_function(type)) {
6284 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6291 * reverts the automatic casts of array to pointer types and function
6292 * to function-pointer types as defined §6.3.2.1
6294 type_t *revert_automatic_type_conversion(const expression_t *expression)
6296 switch (expression->kind) {
6297 case EXPR_REFERENCE: {
6298 entity_t *entity = expression->reference.entity;
6299 if (is_declaration(entity)) {
6300 return entity->declaration.type;
6301 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6302 return entity->enum_value.enum_type;
6304 panic("no declaration or enum in reference");
6309 entity_t *entity = expression->select.compound_entry;
6310 assert(is_declaration(entity));
6311 type_t *type = entity->declaration.type;
6312 return get_qualified_type(type,
6313 expression->base.type->base.qualifiers);
6316 case EXPR_UNARY_DEREFERENCE: {
6317 const expression_t *const value = expression->unary.value;
6318 type_t *const type = skip_typeref(value->base.type);
6319 if (!is_type_pointer(type))
6320 return type_error_type;
6321 return type->pointer.points_to;
6324 case EXPR_ARRAY_ACCESS: {
6325 const expression_t *array_ref = expression->array_access.array_ref;
6326 type_t *type_left = skip_typeref(array_ref->base.type);
6327 if (!is_type_pointer(type_left))
6328 return type_error_type;
6329 return type_left->pointer.points_to;
6332 case EXPR_STRING_LITERAL: {
6333 size_t size = expression->string_literal.value.size;
6334 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6337 case EXPR_WIDE_STRING_LITERAL: {
6338 size_t size = wstrlen(&expression->string_literal.value);
6339 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6342 case EXPR_COMPOUND_LITERAL:
6343 return expression->compound_literal.type;
6348 return expression->base.type;
6352 * Find an entity matching a symbol in a scope.
6353 * Uses current scope if scope is NULL
6355 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6356 namespace_tag_t namespc)
6358 if (scope == NULL) {
6359 return get_entity(symbol, namespc);
6362 /* we should optimize here, if scope grows above a certain size we should
6363 construct a hashmap here... */
6364 entity_t *entity = scope->entities;
6365 for ( ; entity != NULL; entity = entity->base.next) {
6366 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6373 static entity_t *parse_qualified_identifier(void)
6375 /* namespace containing the symbol */
6377 source_position_t pos;
6378 const scope_t *lookup_scope = NULL;
6380 if (next_if(T_COLONCOLON))
6381 lookup_scope = &unit->scope;
6385 if (token.type != T_IDENTIFIER) {
6386 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6387 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6389 symbol = token.symbol;
6394 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6396 if (!next_if(T_COLONCOLON))
6399 switch (entity->kind) {
6400 case ENTITY_NAMESPACE:
6401 lookup_scope = &entity->namespacee.members;
6406 lookup_scope = &entity->compound.members;
6409 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6410 symbol, get_entity_kind_name(entity->kind));
6415 if (entity == NULL) {
6416 if (!strict_mode && token.type == '(') {
6417 /* an implicitly declared function */
6418 if (warning.error_implicit_function_declaration) {
6419 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6420 } else if (warning.implicit_function_declaration) {
6421 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6424 entity = create_implicit_function(symbol, &pos);
6426 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6427 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6434 /* skip further qualifications */
6435 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6437 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6440 static expression_t *parse_reference(void)
6442 entity_t *entity = parse_qualified_identifier();
6445 if (is_declaration(entity)) {
6446 orig_type = entity->declaration.type;
6447 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6448 orig_type = entity->enum_value.enum_type;
6450 panic("expected declaration or enum value in reference");
6453 /* we always do the auto-type conversions; the & and sizeof parser contains
6454 * code to revert this! */
6455 type_t *type = automatic_type_conversion(orig_type);
6457 expression_kind_t kind = EXPR_REFERENCE;
6458 if (entity->kind == ENTITY_ENUM_VALUE)
6459 kind = EXPR_REFERENCE_ENUM_VALUE;
6461 expression_t *expression = allocate_expression_zero(kind);
6462 expression->reference.entity = entity;
6463 expression->base.type = type;
6465 /* this declaration is used */
6466 if (is_declaration(entity)) {
6467 entity->declaration.used = true;
6470 if (entity->base.parent_scope != file_scope
6471 && (current_function != NULL
6472 && entity->base.parent_scope->depth < current_function->parameters.depth)
6473 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6474 if (entity->kind == ENTITY_VARIABLE) {
6475 /* access of a variable from an outer function */
6476 entity->variable.address_taken = true;
6477 } else if (entity->kind == ENTITY_PARAMETER) {
6478 entity->parameter.address_taken = true;
6480 current_function->need_closure = true;
6483 check_deprecated(HERE, entity);
6485 if (warning.init_self && entity == current_init_decl && !in_type_prop
6486 && entity->kind == ENTITY_VARIABLE) {
6487 current_init_decl = NULL;
6488 warningf(HERE, "variable '%#T' is initialized by itself",
6489 entity->declaration.type, entity->base.symbol);
6495 static bool semantic_cast(expression_t *cast)
6497 expression_t *expression = cast->unary.value;
6498 type_t *orig_dest_type = cast->base.type;
6499 type_t *orig_type_right = expression->base.type;
6500 type_t const *dst_type = skip_typeref(orig_dest_type);
6501 type_t const *src_type = skip_typeref(orig_type_right);
6502 source_position_t const *pos = &cast->base.source_position;
6504 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6505 if (dst_type == type_void)
6508 /* only integer and pointer can be casted to pointer */
6509 if (is_type_pointer(dst_type) &&
6510 !is_type_pointer(src_type) &&
6511 !is_type_integer(src_type) &&
6512 is_type_valid(src_type)) {
6513 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6517 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6518 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6522 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6523 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6527 if (warning.cast_qual &&
6528 is_type_pointer(src_type) &&
6529 is_type_pointer(dst_type)) {
6530 type_t *src = skip_typeref(src_type->pointer.points_to);
6531 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6532 unsigned missing_qualifiers =
6533 src->base.qualifiers & ~dst->base.qualifiers;
6534 if (missing_qualifiers != 0) {
6536 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6537 missing_qualifiers, orig_type_right);
6543 static expression_t *parse_compound_literal(type_t *type)
6545 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6547 parse_initializer_env_t env;
6550 env.must_be_constant = false;
6551 initializer_t *initializer = parse_initializer(&env);
6554 expression->compound_literal.initializer = initializer;
6555 expression->compound_literal.type = type;
6556 expression->base.type = automatic_type_conversion(type);
6562 * Parse a cast expression.
6564 static expression_t *parse_cast(void)
6566 add_anchor_token(')');
6568 source_position_t source_position = token.source_position;
6570 type_t *type = parse_typename();
6572 rem_anchor_token(')');
6573 expect(')', end_error);
6575 if (token.type == '{') {
6576 return parse_compound_literal(type);
6579 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6580 cast->base.source_position = source_position;
6582 expression_t *value = parse_subexpression(PREC_CAST);
6583 cast->base.type = type;
6584 cast->unary.value = value;
6586 if (! semantic_cast(cast)) {
6587 /* TODO: record the error in the AST. else it is impossible to detect it */
6592 return create_invalid_expression();
6596 * Parse a statement expression.
6598 static expression_t *parse_statement_expression(void)
6600 add_anchor_token(')');
6602 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6604 statement_t *statement = parse_compound_statement(true);
6605 statement->compound.stmt_expr = true;
6606 expression->statement.statement = statement;
6608 /* find last statement and use its type */
6609 type_t *type = type_void;
6610 const statement_t *stmt = statement->compound.statements;
6612 while (stmt->base.next != NULL)
6613 stmt = stmt->base.next;
6615 if (stmt->kind == STATEMENT_EXPRESSION) {
6616 type = stmt->expression.expression->base.type;
6618 } else if (warning.other) {
6619 warningf(&expression->base.source_position, "empty statement expression ({})");
6621 expression->base.type = type;
6623 rem_anchor_token(')');
6624 expect(')', end_error);
6631 * Parse a parenthesized expression.
6633 static expression_t *parse_parenthesized_expression(void)
6637 switch (token.type) {
6639 /* gcc extension: a statement expression */
6640 return parse_statement_expression();
6644 return parse_cast();
6646 if (is_typedef_symbol(token.symbol)) {
6647 return parse_cast();
6651 add_anchor_token(')');
6652 expression_t *result = parse_expression();
6653 result->base.parenthesized = true;
6654 rem_anchor_token(')');
6655 expect(')', end_error);
6661 static expression_t *parse_function_keyword(void)
6665 if (current_function == NULL) {
6666 errorf(HERE, "'__func__' used outside of a function");
6669 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6670 expression->base.type = type_char_ptr;
6671 expression->funcname.kind = FUNCNAME_FUNCTION;
6678 static expression_t *parse_pretty_function_keyword(void)
6680 if (current_function == NULL) {
6681 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6684 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6685 expression->base.type = type_char_ptr;
6686 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6688 eat(T___PRETTY_FUNCTION__);
6693 static expression_t *parse_funcsig_keyword(void)
6695 if (current_function == NULL) {
6696 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6699 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6700 expression->base.type = type_char_ptr;
6701 expression->funcname.kind = FUNCNAME_FUNCSIG;
6708 static expression_t *parse_funcdname_keyword(void)
6710 if (current_function == NULL) {
6711 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6714 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6715 expression->base.type = type_char_ptr;
6716 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6718 eat(T___FUNCDNAME__);
6723 static designator_t *parse_designator(void)
6725 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6726 result->source_position = *HERE;
6728 if (token.type != T_IDENTIFIER) {
6729 parse_error_expected("while parsing member designator",
6730 T_IDENTIFIER, NULL);
6733 result->symbol = token.symbol;
6736 designator_t *last_designator = result;
6739 if (token.type != T_IDENTIFIER) {
6740 parse_error_expected("while parsing member designator",
6741 T_IDENTIFIER, NULL);
6744 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6745 designator->source_position = *HERE;
6746 designator->symbol = token.symbol;
6749 last_designator->next = designator;
6750 last_designator = designator;
6754 add_anchor_token(']');
6755 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6756 designator->source_position = *HERE;
6757 designator->array_index = parse_expression();
6758 rem_anchor_token(']');
6759 expect(']', end_error);
6760 if (designator->array_index == NULL) {
6764 last_designator->next = designator;
6765 last_designator = designator;
6777 * Parse the __builtin_offsetof() expression.
6779 static expression_t *parse_offsetof(void)
6781 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6782 expression->base.type = type_size_t;
6784 eat(T___builtin_offsetof);
6786 expect('(', end_error);
6787 add_anchor_token(',');
6788 type_t *type = parse_typename();
6789 rem_anchor_token(',');
6790 expect(',', end_error);
6791 add_anchor_token(')');
6792 designator_t *designator = parse_designator();
6793 rem_anchor_token(')');
6794 expect(')', end_error);
6796 expression->offsetofe.type = type;
6797 expression->offsetofe.designator = designator;
6800 memset(&path, 0, sizeof(path));
6801 path.top_type = type;
6802 path.path = NEW_ARR_F(type_path_entry_t, 0);
6804 descend_into_subtype(&path);
6806 if (!walk_designator(&path, designator, true)) {
6807 return create_invalid_expression();
6810 DEL_ARR_F(path.path);
6814 return create_invalid_expression();
6818 * Parses a _builtin_va_start() expression.
6820 static expression_t *parse_va_start(void)
6822 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6824 eat(T___builtin_va_start);
6826 expect('(', end_error);
6827 add_anchor_token(',');
6828 expression->va_starte.ap = parse_assignment_expression();
6829 rem_anchor_token(',');
6830 expect(',', end_error);
6831 expression_t *const expr = parse_assignment_expression();
6832 if (expr->kind == EXPR_REFERENCE) {
6833 entity_t *const entity = expr->reference.entity;
6834 if (!current_function->base.type->function.variadic) {
6835 errorf(&expr->base.source_position,
6836 "'va_start' used in non-variadic function");
6837 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6838 entity->base.next != NULL ||
6839 entity->kind != ENTITY_PARAMETER) {
6840 errorf(&expr->base.source_position,
6841 "second argument of 'va_start' must be last parameter of the current function");
6843 expression->va_starte.parameter = &entity->variable;
6845 expect(')', end_error);
6848 expect(')', end_error);
6850 return create_invalid_expression();
6854 * Parses a __builtin_va_arg() expression.
6856 static expression_t *parse_va_arg(void)
6858 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6860 eat(T___builtin_va_arg);
6862 expect('(', end_error);
6864 ap.expression = parse_assignment_expression();
6865 expression->va_arge.ap = ap.expression;
6866 check_call_argument(type_valist, &ap, 1);
6868 expect(',', end_error);
6869 expression->base.type = parse_typename();
6870 expect(')', end_error);
6874 return create_invalid_expression();
6878 * Parses a __builtin_va_copy() expression.
6880 static expression_t *parse_va_copy(void)
6882 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6884 eat(T___builtin_va_copy);
6886 expect('(', end_error);
6887 expression_t *dst = parse_assignment_expression();
6888 assign_error_t error = semantic_assign(type_valist, dst);
6889 report_assign_error(error, type_valist, dst, "call argument 1",
6890 &dst->base.source_position);
6891 expression->va_copye.dst = dst;
6893 expect(',', end_error);
6895 call_argument_t src;
6896 src.expression = parse_assignment_expression();
6897 check_call_argument(type_valist, &src, 2);
6898 expression->va_copye.src = src.expression;
6899 expect(')', end_error);
6903 return create_invalid_expression();
6907 * Parses a __builtin_constant_p() expression.
6909 static expression_t *parse_builtin_constant(void)
6911 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6913 eat(T___builtin_constant_p);
6915 expect('(', end_error);
6916 add_anchor_token(')');
6917 expression->builtin_constant.value = parse_assignment_expression();
6918 rem_anchor_token(')');
6919 expect(')', end_error);
6920 expression->base.type = type_int;
6924 return create_invalid_expression();
6928 * Parses a __builtin_types_compatible_p() expression.
6930 static expression_t *parse_builtin_types_compatible(void)
6932 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6934 eat(T___builtin_types_compatible_p);
6936 expect('(', end_error);
6937 add_anchor_token(')');
6938 add_anchor_token(',');
6939 expression->builtin_types_compatible.left = parse_typename();
6940 rem_anchor_token(',');
6941 expect(',', end_error);
6942 expression->builtin_types_compatible.right = parse_typename();
6943 rem_anchor_token(')');
6944 expect(')', end_error);
6945 expression->base.type = type_int;
6949 return create_invalid_expression();
6953 * Parses a __builtin_is_*() compare expression.
6955 static expression_t *parse_compare_builtin(void)
6957 expression_t *expression;
6959 switch (token.type) {
6960 case T___builtin_isgreater:
6961 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6963 case T___builtin_isgreaterequal:
6964 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6966 case T___builtin_isless:
6967 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6969 case T___builtin_islessequal:
6970 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6972 case T___builtin_islessgreater:
6973 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6975 case T___builtin_isunordered:
6976 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6979 internal_errorf(HERE, "invalid compare builtin found");
6981 expression->base.source_position = *HERE;
6984 expect('(', end_error);
6985 expression->binary.left = parse_assignment_expression();
6986 expect(',', end_error);
6987 expression->binary.right = parse_assignment_expression();
6988 expect(')', end_error);
6990 type_t *const orig_type_left = expression->binary.left->base.type;
6991 type_t *const orig_type_right = expression->binary.right->base.type;
6993 type_t *const type_left = skip_typeref(orig_type_left);
6994 type_t *const type_right = skip_typeref(orig_type_right);
6995 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6996 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6997 type_error_incompatible("invalid operands in comparison",
6998 &expression->base.source_position, orig_type_left, orig_type_right);
7001 semantic_comparison(&expression->binary);
7006 return create_invalid_expression();
7010 * Parses a MS assume() expression.
7012 static expression_t *parse_assume(void)
7014 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7018 expect('(', end_error);
7019 add_anchor_token(')');
7020 expression->unary.value = parse_assignment_expression();
7021 rem_anchor_token(')');
7022 expect(')', end_error);
7024 expression->base.type = type_void;
7027 return create_invalid_expression();
7031 * Return the declaration for a given label symbol or create a new one.
7033 * @param symbol the symbol of the label
7035 static label_t *get_label(symbol_t *symbol)
7038 assert(current_function != NULL);
7040 label = get_entity(symbol, NAMESPACE_LABEL);
7041 /* if we found a local label, we already created the declaration */
7042 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7043 if (label->base.parent_scope != current_scope) {
7044 assert(label->base.parent_scope->depth < current_scope->depth);
7045 current_function->goto_to_outer = true;
7047 return &label->label;
7050 label = get_entity(symbol, NAMESPACE_LABEL);
7051 /* if we found a label in the same function, then we already created the
7054 && label->base.parent_scope == ¤t_function->parameters) {
7055 return &label->label;
7058 /* otherwise we need to create a new one */
7059 label = allocate_entity_zero(ENTITY_LABEL);
7060 label->base.namespc = NAMESPACE_LABEL;
7061 label->base.symbol = symbol;
7065 return &label->label;
7069 * Parses a GNU && label address expression.
7071 static expression_t *parse_label_address(void)
7073 source_position_t source_position = token.source_position;
7075 if (token.type != T_IDENTIFIER) {
7076 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7079 symbol_t *symbol = token.symbol;
7082 label_t *label = get_label(symbol);
7084 label->address_taken = true;
7086 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7087 expression->base.source_position = source_position;
7089 /* label address is threaten as a void pointer */
7090 expression->base.type = type_void_ptr;
7091 expression->label_address.label = label;
7094 return create_invalid_expression();
7098 * Parse a microsoft __noop expression.
7100 static expression_t *parse_noop_expression(void)
7102 /* the result is a (int)0 */
7103 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7104 literal->base.type = type_int;
7105 literal->base.source_position = token.source_position;
7106 literal->literal.value.begin = "__noop";
7107 literal->literal.value.size = 6;
7111 if (token.type == '(') {
7112 /* parse arguments */
7114 add_anchor_token(')');
7115 add_anchor_token(',');
7117 if (token.type != ')') do {
7118 (void)parse_assignment_expression();
7119 } while (next_if(','));
7121 rem_anchor_token(',');
7122 rem_anchor_token(')');
7123 expect(')', end_error);
7130 * Parses a primary expression.
7132 static expression_t *parse_primary_expression(void)
7134 switch (token.type) {
7135 case T_false: return parse_boolean_literal(false);
7136 case T_true: return parse_boolean_literal(true);
7138 case T_INTEGER_OCTAL:
7139 case T_INTEGER_HEXADECIMAL:
7140 case T_FLOATINGPOINT:
7141 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7142 case T_CHARACTER_CONSTANT: return parse_character_constant();
7143 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7144 case T_STRING_LITERAL:
7145 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7146 case T___FUNCTION__:
7147 case T___func__: return parse_function_keyword();
7148 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7149 case T___FUNCSIG__: return parse_funcsig_keyword();
7150 case T___FUNCDNAME__: return parse_funcdname_keyword();
7151 case T___builtin_offsetof: return parse_offsetof();
7152 case T___builtin_va_start: return parse_va_start();
7153 case T___builtin_va_arg: return parse_va_arg();
7154 case T___builtin_va_copy: return parse_va_copy();
7155 case T___builtin_isgreater:
7156 case T___builtin_isgreaterequal:
7157 case T___builtin_isless:
7158 case T___builtin_islessequal:
7159 case T___builtin_islessgreater:
7160 case T___builtin_isunordered: return parse_compare_builtin();
7161 case T___builtin_constant_p: return parse_builtin_constant();
7162 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7163 case T__assume: return parse_assume();
7166 return parse_label_address();
7169 case '(': return parse_parenthesized_expression();
7170 case T___noop: return parse_noop_expression();
7172 /* Gracefully handle type names while parsing expressions. */
7174 return parse_reference();
7176 if (!is_typedef_symbol(token.symbol)) {
7177 return parse_reference();
7181 source_position_t const pos = *HERE;
7182 type_t const *const type = parse_typename();
7183 errorf(&pos, "encountered type '%T' while parsing expression", type);
7184 return create_invalid_expression();
7188 errorf(HERE, "unexpected token %K, expected an expression", &token);
7190 return create_invalid_expression();
7193 static expression_t *parse_array_expression(expression_t *left)
7195 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7196 array_access_expression_t *const arr = &expr->array_access;
7199 add_anchor_token(']');
7201 expression_t *const inside = parse_expression();
7203 type_t *const orig_type_left = left->base.type;
7204 type_t *const orig_type_inside = inside->base.type;
7206 type_t *const type_left = skip_typeref(orig_type_left);
7207 type_t *const type_inside = skip_typeref(orig_type_inside);
7213 if (is_type_pointer(type_left)) {
7216 idx_type = type_inside;
7217 res_type = type_left->pointer.points_to;
7219 } else if (is_type_pointer(type_inside)) {
7220 arr->flipped = true;
7223 idx_type = type_left;
7224 res_type = type_inside->pointer.points_to;
7226 res_type = automatic_type_conversion(res_type);
7227 if (!is_type_integer(idx_type)) {
7228 errorf(&idx->base.source_position, "array subscript must have integer type");
7229 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR) && warning.char_subscripts) {
7230 warningf(&idx->base.source_position, "array subscript has char type");
7233 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7235 "array access on object with non-pointer types '%T', '%T'",
7236 orig_type_left, orig_type_inside);
7238 res_type = type_error_type;
7243 arr->array_ref = ref;
7245 arr->base.type = res_type;
7247 rem_anchor_token(']');
7248 expect(']', end_error);
7253 static expression_t *parse_typeprop(expression_kind_t const kind)
7255 expression_t *tp_expression = allocate_expression_zero(kind);
7256 tp_expression->base.type = type_size_t;
7258 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7260 /* we only refer to a type property, mark this case */
7261 bool old = in_type_prop;
7262 in_type_prop = true;
7265 expression_t *expression;
7266 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7268 add_anchor_token(')');
7269 orig_type = parse_typename();
7270 rem_anchor_token(')');
7271 expect(')', end_error);
7273 if (token.type == '{') {
7274 /* It was not sizeof(type) after all. It is sizeof of an expression
7275 * starting with a compound literal */
7276 expression = parse_compound_literal(orig_type);
7277 goto typeprop_expression;
7280 expression = parse_subexpression(PREC_UNARY);
7282 typeprop_expression:
7283 tp_expression->typeprop.tp_expression = expression;
7285 orig_type = revert_automatic_type_conversion(expression);
7286 expression->base.type = orig_type;
7289 tp_expression->typeprop.type = orig_type;
7290 type_t const* const type = skip_typeref(orig_type);
7291 char const* wrong_type = NULL;
7292 if (is_type_incomplete(type)) {
7293 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7294 wrong_type = "incomplete";
7295 } else if (type->kind == TYPE_FUNCTION) {
7297 /* function types are allowed (and return 1) */
7298 if (warning.other) {
7299 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7300 warningf(&tp_expression->base.source_position,
7301 "%s expression with function argument returns invalid result", what);
7304 wrong_type = "function";
7307 if (is_type_incomplete(type))
7308 wrong_type = "incomplete";
7310 if (type->kind == TYPE_BITFIELD)
7311 wrong_type = "bitfield";
7313 if (wrong_type != NULL) {
7314 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7315 errorf(&tp_expression->base.source_position,
7316 "operand of %s expression must not be of %s type '%T'",
7317 what, wrong_type, orig_type);
7322 return tp_expression;
7325 static expression_t *parse_sizeof(void)
7327 return parse_typeprop(EXPR_SIZEOF);
7330 static expression_t *parse_alignof(void)
7332 return parse_typeprop(EXPR_ALIGNOF);
7335 static expression_t *parse_select_expression(expression_t *addr)
7337 assert(token.type == '.' || token.type == T_MINUSGREATER);
7338 bool select_left_arrow = (token.type == T_MINUSGREATER);
7339 source_position_t const pos = *HERE;
7342 if (token.type != T_IDENTIFIER) {
7343 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7344 return create_invalid_expression();
7346 symbol_t *symbol = token.symbol;
7349 type_t *const orig_type = addr->base.type;
7350 type_t *const type = skip_typeref(orig_type);
7353 bool saw_error = false;
7354 if (is_type_pointer(type)) {
7355 if (!select_left_arrow) {
7357 "request for member '%Y' in something not a struct or union, but '%T'",
7361 type_left = skip_typeref(type->pointer.points_to);
7363 if (select_left_arrow && is_type_valid(type)) {
7364 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7370 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7371 type_left->kind != TYPE_COMPOUND_UNION) {
7373 if (is_type_valid(type_left) && !saw_error) {
7375 "request for member '%Y' in something not a struct or union, but '%T'",
7378 return create_invalid_expression();
7381 compound_t *compound = type_left->compound.compound;
7382 if (!compound->complete) {
7383 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7385 return create_invalid_expression();
7388 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7389 expression_t *result =
7390 find_create_select(&pos, addr, qualifiers, compound, symbol);
7392 if (result == NULL) {
7393 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7394 return create_invalid_expression();
7400 static void check_call_argument(type_t *expected_type,
7401 call_argument_t *argument, unsigned pos)
7403 type_t *expected_type_skip = skip_typeref(expected_type);
7404 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7405 expression_t *arg_expr = argument->expression;
7406 type_t *arg_type = skip_typeref(arg_expr->base.type);
7408 /* handle transparent union gnu extension */
7409 if (is_type_union(expected_type_skip)
7410 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7411 compound_t *union_decl = expected_type_skip->compound.compound;
7412 type_t *best_type = NULL;
7413 entity_t *entry = union_decl->members.entities;
7414 for ( ; entry != NULL; entry = entry->base.next) {
7415 assert(is_declaration(entry));
7416 type_t *decl_type = entry->declaration.type;
7417 error = semantic_assign(decl_type, arg_expr);
7418 if (error == ASSIGN_ERROR_INCOMPATIBLE
7419 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7422 if (error == ASSIGN_SUCCESS) {
7423 best_type = decl_type;
7424 } else if (best_type == NULL) {
7425 best_type = decl_type;
7429 if (best_type != NULL) {
7430 expected_type = best_type;
7434 error = semantic_assign(expected_type, arg_expr);
7435 argument->expression = create_implicit_cast(arg_expr, expected_type);
7437 if (error != ASSIGN_SUCCESS) {
7438 /* report exact scope in error messages (like "in argument 3") */
7440 snprintf(buf, sizeof(buf), "call argument %u", pos);
7441 report_assign_error(error, expected_type, arg_expr, buf,
7442 &arg_expr->base.source_position);
7443 } else if (warning.traditional || warning.conversion) {
7444 type_t *const promoted_type = get_default_promoted_type(arg_type);
7445 if (!types_compatible(expected_type_skip, promoted_type) &&
7446 !types_compatible(expected_type_skip, type_void_ptr) &&
7447 !types_compatible(type_void_ptr, promoted_type)) {
7448 /* Deliberately show the skipped types in this warning */
7449 warningf(&arg_expr->base.source_position,
7450 "passing call argument %u as '%T' rather than '%T' due to prototype",
7451 pos, expected_type_skip, promoted_type);
7457 * Handle the semantic restrictions of builtin calls
7459 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7460 switch (call->function->reference.entity->function.btk) {
7461 case bk_gnu_builtin_return_address:
7462 case bk_gnu_builtin_frame_address: {
7463 /* argument must be constant */
7464 call_argument_t *argument = call->arguments;
7466 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7467 errorf(&call->base.source_position,
7468 "argument of '%Y' must be a constant expression",
7469 call->function->reference.entity->base.symbol);
7473 case bk_gnu_builtin_object_size:
7474 if (call->arguments == NULL)
7477 call_argument_t *arg = call->arguments->next;
7478 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7479 errorf(&call->base.source_position,
7480 "second argument of '%Y' must be a constant expression",
7481 call->function->reference.entity->base.symbol);
7484 case bk_gnu_builtin_prefetch:
7485 /* second and third argument must be constant if existent */
7486 if (call->arguments == NULL)
7488 call_argument_t *rw = call->arguments->next;
7489 call_argument_t *locality = NULL;
7492 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7493 errorf(&call->base.source_position,
7494 "second argument of '%Y' must be a constant expression",
7495 call->function->reference.entity->base.symbol);
7497 locality = rw->next;
7499 if (locality != NULL) {
7500 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7501 errorf(&call->base.source_position,
7502 "third argument of '%Y' must be a constant expression",
7503 call->function->reference.entity->base.symbol);
7505 locality = rw->next;
7514 * Parse a call expression, ie. expression '( ... )'.
7516 * @param expression the function address
7518 static expression_t *parse_call_expression(expression_t *expression)
7520 expression_t *result = allocate_expression_zero(EXPR_CALL);
7521 call_expression_t *call = &result->call;
7522 call->function = expression;
7524 type_t *const orig_type = expression->base.type;
7525 type_t *const type = skip_typeref(orig_type);
7527 function_type_t *function_type = NULL;
7528 if (is_type_pointer(type)) {
7529 type_t *const to_type = skip_typeref(type->pointer.points_to);
7531 if (is_type_function(to_type)) {
7532 function_type = &to_type->function;
7533 call->base.type = function_type->return_type;
7537 if (function_type == NULL && is_type_valid(type)) {
7539 "called object '%E' (type '%T') is not a pointer to a function",
7540 expression, orig_type);
7543 /* parse arguments */
7545 add_anchor_token(')');
7546 add_anchor_token(',');
7548 if (token.type != ')') {
7549 call_argument_t **anchor = &call->arguments;
7551 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7552 argument->expression = parse_assignment_expression();
7555 anchor = &argument->next;
7556 } while (next_if(','));
7558 rem_anchor_token(',');
7559 rem_anchor_token(')');
7560 expect(')', end_error);
7562 if (function_type == NULL)
7565 /* check type and count of call arguments */
7566 function_parameter_t *parameter = function_type->parameters;
7567 call_argument_t *argument = call->arguments;
7568 if (!function_type->unspecified_parameters) {
7569 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7570 parameter = parameter->next, argument = argument->next) {
7571 check_call_argument(parameter->type, argument, ++pos);
7574 if (parameter != NULL) {
7575 errorf(HERE, "too few arguments to function '%E'", expression);
7576 } else if (argument != NULL && !function_type->variadic) {
7577 errorf(HERE, "too many arguments to function '%E'", expression);
7581 /* do default promotion for other arguments */
7582 for (; argument != NULL; argument = argument->next) {
7583 type_t *type = argument->expression->base.type;
7584 if (!is_type_object(skip_typeref(type))) {
7585 errorf(&argument->expression->base.source_position,
7586 "call argument '%E' must not be void", argument->expression);
7589 type = get_default_promoted_type(type);
7591 argument->expression
7592 = create_implicit_cast(argument->expression, type);
7595 check_format(&result->call);
7597 if (warning.aggregate_return &&
7598 is_type_compound(skip_typeref(function_type->return_type))) {
7599 warningf(&result->base.source_position,
7600 "function call has aggregate value");
7603 if (call->function->kind == EXPR_REFERENCE) {
7604 reference_expression_t *reference = &call->function->reference;
7605 if (reference->entity->kind == ENTITY_FUNCTION &&
7606 reference->entity->function.btk != bk_none)
7607 handle_builtin_argument_restrictions(call);
7614 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7616 static bool same_compound_type(const type_t *type1, const type_t *type2)
7619 is_type_compound(type1) &&
7620 type1->kind == type2->kind &&
7621 type1->compound.compound == type2->compound.compound;
7624 static expression_t const *get_reference_address(expression_t const *expr)
7626 bool regular_take_address = true;
7628 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7629 expr = expr->unary.value;
7631 regular_take_address = false;
7634 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7637 expr = expr->unary.value;
7640 if (expr->kind != EXPR_REFERENCE)
7643 /* special case for functions which are automatically converted to a
7644 * pointer to function without an extra TAKE_ADDRESS operation */
7645 if (!regular_take_address &&
7646 expr->reference.entity->kind != ENTITY_FUNCTION) {
7653 static void warn_reference_address_as_bool(expression_t const* expr)
7655 if (!warning.address)
7658 expr = get_reference_address(expr);
7660 warningf(&expr->base.source_position,
7661 "the address of '%Y' will always evaluate as 'true'",
7662 expr->reference.entity->base.symbol);
7666 static void warn_assignment_in_condition(const expression_t *const expr)
7668 if (!warning.parentheses)
7670 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7672 if (expr->base.parenthesized)
7674 warningf(&expr->base.source_position,
7675 "suggest parentheses around assignment used as truth value");
7678 static void semantic_condition(expression_t const *const expr,
7679 char const *const context)
7681 type_t *const type = skip_typeref(expr->base.type);
7682 if (is_type_scalar(type)) {
7683 warn_reference_address_as_bool(expr);
7684 warn_assignment_in_condition(expr);
7685 } else if (is_type_valid(type)) {
7686 errorf(&expr->base.source_position,
7687 "%s must have scalar type", context);
7692 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7694 * @param expression the conditional expression
7696 static expression_t *parse_conditional_expression(expression_t *expression)
7698 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7700 conditional_expression_t *conditional = &result->conditional;
7701 conditional->condition = expression;
7704 add_anchor_token(':');
7706 /* §6.5.15:2 The first operand shall have scalar type. */
7707 semantic_condition(expression, "condition of conditional operator");
7709 expression_t *true_expression = expression;
7710 bool gnu_cond = false;
7711 if (GNU_MODE && token.type == ':') {
7714 true_expression = parse_expression();
7716 rem_anchor_token(':');
7717 expect(':', end_error);
7719 expression_t *false_expression =
7720 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7722 type_t *const orig_true_type = true_expression->base.type;
7723 type_t *const orig_false_type = false_expression->base.type;
7724 type_t *const true_type = skip_typeref(orig_true_type);
7725 type_t *const false_type = skip_typeref(orig_false_type);
7728 type_t *result_type;
7729 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7730 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7731 /* ISO/IEC 14882:1998(E) §5.16:2 */
7732 if (true_expression->kind == EXPR_UNARY_THROW) {
7733 result_type = false_type;
7734 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7735 result_type = true_type;
7737 if (warning.other && (
7738 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7739 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7741 warningf(&conditional->base.source_position,
7742 "ISO C forbids conditional expression with only one void side");
7744 result_type = type_void;
7746 } else if (is_type_arithmetic(true_type)
7747 && is_type_arithmetic(false_type)) {
7748 result_type = semantic_arithmetic(true_type, false_type);
7749 } else if (same_compound_type(true_type, false_type)) {
7750 /* just take 1 of the 2 types */
7751 result_type = true_type;
7752 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7753 type_t *pointer_type;
7755 expression_t *other_expression;
7756 if (is_type_pointer(true_type) &&
7757 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7758 pointer_type = true_type;
7759 other_type = false_type;
7760 other_expression = false_expression;
7762 pointer_type = false_type;
7763 other_type = true_type;
7764 other_expression = true_expression;
7767 if (is_null_pointer_constant(other_expression)) {
7768 result_type = pointer_type;
7769 } else if (is_type_pointer(other_type)) {
7770 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7771 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7774 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7775 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7777 } else if (types_compatible(get_unqualified_type(to1),
7778 get_unqualified_type(to2))) {
7781 if (warning.other) {
7782 warningf(&conditional->base.source_position,
7783 "pointer types '%T' and '%T' in conditional expression are incompatible",
7784 true_type, false_type);
7789 type_t *const type =
7790 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7791 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7792 } else if (is_type_integer(other_type)) {
7793 if (warning.other) {
7794 warningf(&conditional->base.source_position,
7795 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7797 result_type = pointer_type;
7799 if (is_type_valid(other_type)) {
7800 type_error_incompatible("while parsing conditional",
7801 &expression->base.source_position, true_type, false_type);
7803 result_type = type_error_type;
7806 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7807 type_error_incompatible("while parsing conditional",
7808 &conditional->base.source_position, true_type,
7811 result_type = type_error_type;
7814 conditional->true_expression
7815 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7816 conditional->false_expression
7817 = create_implicit_cast(false_expression, result_type);
7818 conditional->base.type = result_type;
7823 * Parse an extension expression.
7825 static expression_t *parse_extension(void)
7827 eat(T___extension__);
7829 bool old_gcc_extension = in_gcc_extension;
7830 in_gcc_extension = true;
7831 expression_t *expression = parse_subexpression(PREC_UNARY);
7832 in_gcc_extension = old_gcc_extension;
7837 * Parse a __builtin_classify_type() expression.
7839 static expression_t *parse_builtin_classify_type(void)
7841 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7842 result->base.type = type_int;
7844 eat(T___builtin_classify_type);
7846 expect('(', end_error);
7847 add_anchor_token(')');
7848 expression_t *expression = parse_expression();
7849 rem_anchor_token(')');
7850 expect(')', end_error);
7851 result->classify_type.type_expression = expression;
7855 return create_invalid_expression();
7859 * Parse a delete expression
7860 * ISO/IEC 14882:1998(E) §5.3.5
7862 static expression_t *parse_delete(void)
7864 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7865 result->base.type = type_void;
7870 result->kind = EXPR_UNARY_DELETE_ARRAY;
7871 expect(']', end_error);
7875 expression_t *const value = parse_subexpression(PREC_CAST);
7876 result->unary.value = value;
7878 type_t *const type = skip_typeref(value->base.type);
7879 if (!is_type_pointer(type)) {
7880 if (is_type_valid(type)) {
7881 errorf(&value->base.source_position,
7882 "operand of delete must have pointer type");
7884 } else if (warning.other &&
7885 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7886 warningf(&value->base.source_position,
7887 "deleting 'void*' is undefined");
7894 * Parse a throw expression
7895 * ISO/IEC 14882:1998(E) §15:1
7897 static expression_t *parse_throw(void)
7899 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7900 result->base.type = type_void;
7904 expression_t *value = NULL;
7905 switch (token.type) {
7907 value = parse_assignment_expression();
7908 /* ISO/IEC 14882:1998(E) §15.1:3 */
7909 type_t *const orig_type = value->base.type;
7910 type_t *const type = skip_typeref(orig_type);
7911 if (is_type_incomplete(type)) {
7912 errorf(&value->base.source_position,
7913 "cannot throw object of incomplete type '%T'", orig_type);
7914 } else if (is_type_pointer(type)) {
7915 type_t *const points_to = skip_typeref(type->pointer.points_to);
7916 if (is_type_incomplete(points_to) &&
7917 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7918 errorf(&value->base.source_position,
7919 "cannot throw pointer to incomplete type '%T'", orig_type);
7927 result->unary.value = value;
7932 static bool check_pointer_arithmetic(const source_position_t *source_position,
7933 type_t *pointer_type,
7934 type_t *orig_pointer_type)
7936 type_t *points_to = pointer_type->pointer.points_to;
7937 points_to = skip_typeref(points_to);
7939 if (is_type_incomplete(points_to)) {
7940 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7941 errorf(source_position,
7942 "arithmetic with pointer to incomplete type '%T' not allowed",
7945 } else if (warning.pointer_arith) {
7946 warningf(source_position,
7947 "pointer of type '%T' used in arithmetic",
7950 } else if (is_type_function(points_to)) {
7952 errorf(source_position,
7953 "arithmetic with pointer to function type '%T' not allowed",
7956 } else if (warning.pointer_arith) {
7957 warningf(source_position,
7958 "pointer to a function '%T' used in arithmetic",
7965 static bool is_lvalue(const expression_t *expression)
7967 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7968 switch (expression->kind) {
7969 case EXPR_ARRAY_ACCESS:
7970 case EXPR_COMPOUND_LITERAL:
7971 case EXPR_REFERENCE:
7973 case EXPR_UNARY_DEREFERENCE:
7977 type_t *type = skip_typeref(expression->base.type);
7979 /* ISO/IEC 14882:1998(E) §3.10:3 */
7980 is_type_reference(type) ||
7981 /* Claim it is an lvalue, if the type is invalid. There was a parse
7982 * error before, which maybe prevented properly recognizing it as
7984 !is_type_valid(type);
7989 static void semantic_incdec(unary_expression_t *expression)
7991 type_t *const orig_type = expression->value->base.type;
7992 type_t *const type = skip_typeref(orig_type);
7993 if (is_type_pointer(type)) {
7994 if (!check_pointer_arithmetic(&expression->base.source_position,
7998 } else if (!is_type_real(type) && is_type_valid(type)) {
7999 /* TODO: improve error message */
8000 errorf(&expression->base.source_position,
8001 "operation needs an arithmetic or pointer type");
8004 if (!is_lvalue(expression->value)) {
8005 /* TODO: improve error message */
8006 errorf(&expression->base.source_position, "lvalue required as operand");
8008 expression->base.type = orig_type;
8011 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8013 type_t *const orig_type = expression->value->base.type;
8014 type_t *const type = skip_typeref(orig_type);
8015 if (!is_type_arithmetic(type)) {
8016 if (is_type_valid(type)) {
8017 /* TODO: improve error message */
8018 errorf(&expression->base.source_position,
8019 "operation needs an arithmetic type");
8024 expression->base.type = orig_type;
8027 static void semantic_unexpr_plus(unary_expression_t *expression)
8029 semantic_unexpr_arithmetic(expression);
8030 if (warning.traditional)
8031 warningf(&expression->base.source_position,
8032 "traditional C rejects the unary plus operator");
8035 static void semantic_not(unary_expression_t *expression)
8037 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8038 semantic_condition(expression->value, "operand of !");
8039 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8042 static void semantic_unexpr_integer(unary_expression_t *expression)
8044 type_t *const orig_type = expression->value->base.type;
8045 type_t *const type = skip_typeref(orig_type);
8046 if (!is_type_integer(type)) {
8047 if (is_type_valid(type)) {
8048 errorf(&expression->base.source_position,
8049 "operand of ~ must be of integer type");
8054 expression->base.type = orig_type;
8057 static void semantic_dereference(unary_expression_t *expression)
8059 type_t *const orig_type = expression->value->base.type;
8060 type_t *const type = skip_typeref(orig_type);
8061 if (!is_type_pointer(type)) {
8062 if (is_type_valid(type)) {
8063 errorf(&expression->base.source_position,
8064 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8069 type_t *result_type = type->pointer.points_to;
8070 result_type = automatic_type_conversion(result_type);
8071 expression->base.type = result_type;
8075 * Record that an address is taken (expression represents an lvalue).
8077 * @param expression the expression
8078 * @param may_be_register if true, the expression might be an register
8080 static void set_address_taken(expression_t *expression, bool may_be_register)
8082 if (expression->kind != EXPR_REFERENCE)
8085 entity_t *const entity = expression->reference.entity;
8087 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8090 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8091 && !may_be_register) {
8092 errorf(&expression->base.source_position,
8093 "address of register %s '%Y' requested",
8094 get_entity_kind_name(entity->kind), entity->base.symbol);
8097 if (entity->kind == ENTITY_VARIABLE) {
8098 entity->variable.address_taken = true;
8100 assert(entity->kind == ENTITY_PARAMETER);
8101 entity->parameter.address_taken = true;
8106 * Check the semantic of the address taken expression.
8108 static void semantic_take_addr(unary_expression_t *expression)
8110 expression_t *value = expression->value;
8111 value->base.type = revert_automatic_type_conversion(value);
8113 type_t *orig_type = value->base.type;
8114 type_t *type = skip_typeref(orig_type);
8115 if (!is_type_valid(type))
8119 if (!is_lvalue(value)) {
8120 errorf(&expression->base.source_position, "'&' requires an lvalue");
8122 if (type->kind == TYPE_BITFIELD) {
8123 errorf(&expression->base.source_position,
8124 "'&' not allowed on object with bitfield type '%T'",
8128 set_address_taken(value, false);
8130 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8133 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8134 static expression_t *parse_##unexpression_type(void) \
8136 expression_t *unary_expression \
8137 = allocate_expression_zero(unexpression_type); \
8139 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8141 sfunc(&unary_expression->unary); \
8143 return unary_expression; \
8146 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8147 semantic_unexpr_arithmetic)
8148 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8149 semantic_unexpr_plus)
8150 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8152 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8153 semantic_dereference)
8154 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8156 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8157 semantic_unexpr_integer)
8158 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8160 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8163 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8165 static expression_t *parse_##unexpression_type(expression_t *left) \
8167 expression_t *unary_expression \
8168 = allocate_expression_zero(unexpression_type); \
8170 unary_expression->unary.value = left; \
8172 sfunc(&unary_expression->unary); \
8174 return unary_expression; \
8177 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8178 EXPR_UNARY_POSTFIX_INCREMENT,
8180 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8181 EXPR_UNARY_POSTFIX_DECREMENT,
8184 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8186 /* TODO: handle complex + imaginary types */
8188 type_left = get_unqualified_type(type_left);
8189 type_right = get_unqualified_type(type_right);
8191 /* §6.3.1.8 Usual arithmetic conversions */
8192 if (type_left == type_long_double || type_right == type_long_double) {
8193 return type_long_double;
8194 } else if (type_left == type_double || type_right == type_double) {
8196 } else if (type_left == type_float || type_right == type_float) {
8200 type_left = promote_integer(type_left);
8201 type_right = promote_integer(type_right);
8203 if (type_left == type_right)
8206 bool const signed_left = is_type_signed(type_left);
8207 bool const signed_right = is_type_signed(type_right);
8208 int const rank_left = get_rank(type_left);
8209 int const rank_right = get_rank(type_right);
8211 if (signed_left == signed_right)
8212 return rank_left >= rank_right ? type_left : type_right;
8221 u_rank = rank_right;
8222 u_type = type_right;
8224 s_rank = rank_right;
8225 s_type = type_right;
8230 if (u_rank >= s_rank)
8233 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8235 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8236 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8240 case ATOMIC_TYPE_INT: return type_unsigned_int;
8241 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8242 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8244 default: panic("invalid atomic type");
8249 * Check the semantic restrictions for a binary expression.
8251 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8253 expression_t *const left = expression->left;
8254 expression_t *const right = expression->right;
8255 type_t *const orig_type_left = left->base.type;
8256 type_t *const orig_type_right = right->base.type;
8257 type_t *const type_left = skip_typeref(orig_type_left);
8258 type_t *const type_right = skip_typeref(orig_type_right);
8260 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8261 /* TODO: improve error message */
8262 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8263 errorf(&expression->base.source_position,
8264 "operation needs arithmetic types");
8269 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8270 expression->left = create_implicit_cast(left, arithmetic_type);
8271 expression->right = create_implicit_cast(right, arithmetic_type);
8272 expression->base.type = arithmetic_type;
8275 static void semantic_binexpr_integer(binary_expression_t *const expression)
8277 expression_t *const left = expression->left;
8278 expression_t *const right = expression->right;
8279 type_t *const orig_type_left = left->base.type;
8280 type_t *const orig_type_right = right->base.type;
8281 type_t *const type_left = skip_typeref(orig_type_left);
8282 type_t *const type_right = skip_typeref(orig_type_right);
8284 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8285 /* TODO: improve error message */
8286 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8287 errorf(&expression->base.source_position,
8288 "operation needs integer types");
8293 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8294 expression->left = create_implicit_cast(left, result_type);
8295 expression->right = create_implicit_cast(right, result_type);
8296 expression->base.type = result_type;
8299 static void warn_div_by_zero(binary_expression_t const *const expression)
8301 if (!warning.div_by_zero ||
8302 !is_type_integer(expression->base.type))
8305 expression_t const *const right = expression->right;
8306 /* The type of the right operand can be different for /= */
8307 if (is_type_integer(right->base.type) &&
8308 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8309 !fold_constant_to_bool(right)) {
8310 warningf(&expression->base.source_position, "division by zero");
8315 * Check the semantic restrictions for a div/mod expression.
8317 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8319 semantic_binexpr_arithmetic(expression);
8320 warn_div_by_zero(expression);
8323 static void warn_addsub_in_shift(const expression_t *const expr)
8325 if (expr->base.parenthesized)
8329 switch (expr->kind) {
8330 case EXPR_BINARY_ADD: op = '+'; break;
8331 case EXPR_BINARY_SUB: op = '-'; break;
8335 warningf(&expr->base.source_position,
8336 "suggest parentheses around '%c' inside shift", op);
8339 static bool semantic_shift(binary_expression_t *expression)
8341 expression_t *const left = expression->left;
8342 expression_t *const right = expression->right;
8343 type_t *const orig_type_left = left->base.type;
8344 type_t *const orig_type_right = right->base.type;
8345 type_t * type_left = skip_typeref(orig_type_left);
8346 type_t * type_right = skip_typeref(orig_type_right);
8348 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8349 /* TODO: improve error message */
8350 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8351 errorf(&expression->base.source_position,
8352 "operands of shift operation must have integer types");
8357 type_left = promote_integer(type_left);
8359 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8360 long count = fold_constant_to_int(right);
8362 warningf(&right->base.source_position,
8363 "shift count must be non-negative");
8364 } else if ((unsigned long)count >=
8365 get_atomic_type_size(type_left->atomic.akind) * 8) {
8366 warningf(&right->base.source_position,
8367 "shift count must be less than type width");
8371 type_right = promote_integer(type_right);
8372 expression->right = create_implicit_cast(right, type_right);
8377 static void semantic_shift_op(binary_expression_t *expression)
8379 expression_t *const left = expression->left;
8380 expression_t *const right = expression->right;
8382 if (!semantic_shift(expression))
8385 if (warning.parentheses) {
8386 warn_addsub_in_shift(left);
8387 warn_addsub_in_shift(right);
8390 type_t *const orig_type_left = left->base.type;
8391 type_t * type_left = skip_typeref(orig_type_left);
8393 type_left = promote_integer(type_left);
8394 expression->left = create_implicit_cast(left, type_left);
8395 expression->base.type = type_left;
8398 static void semantic_add(binary_expression_t *expression)
8400 expression_t *const left = expression->left;
8401 expression_t *const right = expression->right;
8402 type_t *const orig_type_left = left->base.type;
8403 type_t *const orig_type_right = right->base.type;
8404 type_t *const type_left = skip_typeref(orig_type_left);
8405 type_t *const type_right = skip_typeref(orig_type_right);
8408 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8409 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8410 expression->left = create_implicit_cast(left, arithmetic_type);
8411 expression->right = create_implicit_cast(right, arithmetic_type);
8412 expression->base.type = arithmetic_type;
8413 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8414 check_pointer_arithmetic(&expression->base.source_position,
8415 type_left, orig_type_left);
8416 expression->base.type = type_left;
8417 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8418 check_pointer_arithmetic(&expression->base.source_position,
8419 type_right, orig_type_right);
8420 expression->base.type = type_right;
8421 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8422 errorf(&expression->base.source_position,
8423 "invalid operands to binary + ('%T', '%T')",
8424 orig_type_left, orig_type_right);
8428 static void semantic_sub(binary_expression_t *expression)
8430 expression_t *const left = expression->left;
8431 expression_t *const right = expression->right;
8432 type_t *const orig_type_left = left->base.type;
8433 type_t *const orig_type_right = right->base.type;
8434 type_t *const type_left = skip_typeref(orig_type_left);
8435 type_t *const type_right = skip_typeref(orig_type_right);
8436 source_position_t const *const pos = &expression->base.source_position;
8439 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8440 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8441 expression->left = create_implicit_cast(left, arithmetic_type);
8442 expression->right = create_implicit_cast(right, arithmetic_type);
8443 expression->base.type = arithmetic_type;
8444 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8445 check_pointer_arithmetic(&expression->base.source_position,
8446 type_left, orig_type_left);
8447 expression->base.type = type_left;
8448 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8449 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8450 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8451 if (!types_compatible(unqual_left, unqual_right)) {
8453 "subtracting pointers to incompatible types '%T' and '%T'",
8454 orig_type_left, orig_type_right);
8455 } else if (!is_type_object(unqual_left)) {
8456 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8457 errorf(pos, "subtracting pointers to non-object types '%T'",
8459 } else if (warning.other) {
8460 warningf(pos, "subtracting pointers to void");
8463 expression->base.type = type_ptrdiff_t;
8464 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8465 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8466 orig_type_left, orig_type_right);
8470 static void warn_string_literal_address(expression_t const* expr)
8472 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8473 expr = expr->unary.value;
8474 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8476 expr = expr->unary.value;
8479 if (expr->kind == EXPR_STRING_LITERAL
8480 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8481 warningf(&expr->base.source_position,
8482 "comparison with string literal results in unspecified behaviour");
8486 static void warn_comparison_in_comparison(const expression_t *const expr)
8488 if (expr->base.parenthesized)
8490 switch (expr->base.kind) {
8491 case EXPR_BINARY_LESS:
8492 case EXPR_BINARY_GREATER:
8493 case EXPR_BINARY_LESSEQUAL:
8494 case EXPR_BINARY_GREATEREQUAL:
8495 case EXPR_BINARY_NOTEQUAL:
8496 case EXPR_BINARY_EQUAL:
8497 warningf(&expr->base.source_position,
8498 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8505 static bool maybe_negative(expression_t const *const expr)
8507 switch (is_constant_expression(expr)) {
8508 case EXPR_CLASS_ERROR: return false;
8509 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8510 default: return true;
8515 * Check the semantics of comparison expressions.
8517 * @param expression The expression to check.
8519 static void semantic_comparison(binary_expression_t *expression)
8521 expression_t *left = expression->left;
8522 expression_t *right = expression->right;
8524 if (warning.address) {
8525 warn_string_literal_address(left);
8526 warn_string_literal_address(right);
8528 expression_t const* const func_left = get_reference_address(left);
8529 if (func_left != NULL && is_null_pointer_constant(right)) {
8530 warningf(&expression->base.source_position,
8531 "the address of '%Y' will never be NULL",
8532 func_left->reference.entity->base.symbol);
8535 expression_t const* const func_right = get_reference_address(right);
8536 if (func_right != NULL && is_null_pointer_constant(right)) {
8537 warningf(&expression->base.source_position,
8538 "the address of '%Y' will never be NULL",
8539 func_right->reference.entity->base.symbol);
8543 if (warning.parentheses) {
8544 warn_comparison_in_comparison(left);
8545 warn_comparison_in_comparison(right);
8548 type_t *orig_type_left = left->base.type;
8549 type_t *orig_type_right = right->base.type;
8550 type_t *type_left = skip_typeref(orig_type_left);
8551 type_t *type_right = skip_typeref(orig_type_right);
8553 /* TODO non-arithmetic types */
8554 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8555 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8557 /* test for signed vs unsigned compares */
8558 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8559 bool const signed_left = is_type_signed(type_left);
8560 bool const signed_right = is_type_signed(type_right);
8561 if (signed_left != signed_right) {
8562 /* FIXME long long needs better const folding magic */
8563 /* TODO check whether constant value can be represented by other type */
8564 if ((signed_left && maybe_negative(left)) ||
8565 (signed_right && maybe_negative(right))) {
8566 warningf(&expression->base.source_position,
8567 "comparison between signed and unsigned");
8572 expression->left = create_implicit_cast(left, arithmetic_type);
8573 expression->right = create_implicit_cast(right, arithmetic_type);
8574 expression->base.type = arithmetic_type;
8575 if (warning.float_equal &&
8576 (expression->base.kind == EXPR_BINARY_EQUAL ||
8577 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8578 is_type_float(arithmetic_type)) {
8579 warningf(&expression->base.source_position,
8580 "comparing floating point with == or != is unsafe");
8582 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8583 /* TODO check compatibility */
8584 } else if (is_type_pointer(type_left)) {
8585 expression->right = create_implicit_cast(right, type_left);
8586 } else if (is_type_pointer(type_right)) {
8587 expression->left = create_implicit_cast(left, type_right);
8588 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8589 type_error_incompatible("invalid operands in comparison",
8590 &expression->base.source_position,
8591 type_left, type_right);
8593 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8597 * Checks if a compound type has constant fields.
8599 static bool has_const_fields(const compound_type_t *type)
8601 compound_t *compound = type->compound;
8602 entity_t *entry = compound->members.entities;
8604 for (; entry != NULL; entry = entry->base.next) {
8605 if (!is_declaration(entry))
8608 const type_t *decl_type = skip_typeref(entry->declaration.type);
8609 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8616 static bool is_valid_assignment_lhs(expression_t const* const left)
8618 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8619 type_t *const type_left = skip_typeref(orig_type_left);
8621 if (!is_lvalue(left)) {
8622 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8627 if (left->kind == EXPR_REFERENCE
8628 && left->reference.entity->kind == ENTITY_FUNCTION) {
8629 errorf(HERE, "cannot assign to function '%E'", left);
8633 if (is_type_array(type_left)) {
8634 errorf(HERE, "cannot assign to array '%E'", left);
8637 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8638 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8642 if (is_type_incomplete(type_left)) {
8643 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8644 left, orig_type_left);
8647 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8648 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8649 left, orig_type_left);
8656 static void semantic_arithmetic_assign(binary_expression_t *expression)
8658 expression_t *left = expression->left;
8659 expression_t *right = expression->right;
8660 type_t *orig_type_left = left->base.type;
8661 type_t *orig_type_right = right->base.type;
8663 if (!is_valid_assignment_lhs(left))
8666 type_t *type_left = skip_typeref(orig_type_left);
8667 type_t *type_right = skip_typeref(orig_type_right);
8669 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8670 /* TODO: improve error message */
8671 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8672 errorf(&expression->base.source_position,
8673 "operation needs arithmetic types");
8678 /* combined instructions are tricky. We can't create an implicit cast on
8679 * the left side, because we need the uncasted form for the store.
8680 * The ast2firm pass has to know that left_type must be right_type
8681 * for the arithmetic operation and create a cast by itself */
8682 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8683 expression->right = create_implicit_cast(right, arithmetic_type);
8684 expression->base.type = type_left;
8687 static void semantic_divmod_assign(binary_expression_t *expression)
8689 semantic_arithmetic_assign(expression);
8690 warn_div_by_zero(expression);
8693 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8695 expression_t *const left = expression->left;
8696 expression_t *const right = expression->right;
8697 type_t *const orig_type_left = left->base.type;
8698 type_t *const orig_type_right = right->base.type;
8699 type_t *const type_left = skip_typeref(orig_type_left);
8700 type_t *const type_right = skip_typeref(orig_type_right);
8702 if (!is_valid_assignment_lhs(left))
8705 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8706 /* combined instructions are tricky. We can't create an implicit cast on
8707 * the left side, because we need the uncasted form for the store.
8708 * The ast2firm pass has to know that left_type must be right_type
8709 * for the arithmetic operation and create a cast by itself */
8710 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8711 expression->right = create_implicit_cast(right, arithmetic_type);
8712 expression->base.type = type_left;
8713 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8714 check_pointer_arithmetic(&expression->base.source_position,
8715 type_left, orig_type_left);
8716 expression->base.type = type_left;
8717 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8718 errorf(&expression->base.source_position,
8719 "incompatible types '%T' and '%T' in assignment",
8720 orig_type_left, orig_type_right);
8724 static void semantic_integer_assign(binary_expression_t *expression)
8726 expression_t *left = expression->left;
8727 expression_t *right = expression->right;
8728 type_t *orig_type_left = left->base.type;
8729 type_t *orig_type_right = right->base.type;
8731 if (!is_valid_assignment_lhs(left))
8734 type_t *type_left = skip_typeref(orig_type_left);
8735 type_t *type_right = skip_typeref(orig_type_right);
8737 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8738 /* TODO: improve error message */
8739 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8740 errorf(&expression->base.source_position,
8741 "operation needs integer types");
8746 /* combined instructions are tricky. We can't create an implicit cast on
8747 * the left side, because we need the uncasted form for the store.
8748 * The ast2firm pass has to know that left_type must be right_type
8749 * for the arithmetic operation and create a cast by itself */
8750 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8751 expression->right = create_implicit_cast(right, arithmetic_type);
8752 expression->base.type = type_left;
8755 static void semantic_shift_assign(binary_expression_t *expression)
8757 expression_t *left = expression->left;
8759 if (!is_valid_assignment_lhs(left))
8762 if (!semantic_shift(expression))
8765 expression->base.type = skip_typeref(left->base.type);
8768 static void warn_logical_and_within_or(const expression_t *const expr)
8770 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8772 if (expr->base.parenthesized)
8774 warningf(&expr->base.source_position,
8775 "suggest parentheses around && within ||");
8779 * Check the semantic restrictions of a logical expression.
8781 static void semantic_logical_op(binary_expression_t *expression)
8783 /* §6.5.13:2 Each of the operands shall have scalar type.
8784 * §6.5.14:2 Each of the operands shall have scalar type. */
8785 semantic_condition(expression->left, "left operand of logical operator");
8786 semantic_condition(expression->right, "right operand of logical operator");
8787 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8788 warning.parentheses) {
8789 warn_logical_and_within_or(expression->left);
8790 warn_logical_and_within_or(expression->right);
8792 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8796 * Check the semantic restrictions of a binary assign expression.
8798 static void semantic_binexpr_assign(binary_expression_t *expression)
8800 expression_t *left = expression->left;
8801 type_t *orig_type_left = left->base.type;
8803 if (!is_valid_assignment_lhs(left))
8806 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8807 report_assign_error(error, orig_type_left, expression->right,
8808 "assignment", &left->base.source_position);
8809 expression->right = create_implicit_cast(expression->right, orig_type_left);
8810 expression->base.type = orig_type_left;
8814 * Determine if the outermost operation (or parts thereof) of the given
8815 * expression has no effect in order to generate a warning about this fact.
8816 * Therefore in some cases this only examines some of the operands of the
8817 * expression (see comments in the function and examples below).
8819 * f() + 23; // warning, because + has no effect
8820 * x || f(); // no warning, because x controls execution of f()
8821 * x ? y : f(); // warning, because y has no effect
8822 * (void)x; // no warning to be able to suppress the warning
8823 * This function can NOT be used for an "expression has definitely no effect"-
8825 static bool expression_has_effect(const expression_t *const expr)
8827 switch (expr->kind) {
8828 case EXPR_UNKNOWN: break;
8829 case EXPR_INVALID: return true; /* do NOT warn */
8830 case EXPR_REFERENCE: return false;
8831 case EXPR_REFERENCE_ENUM_VALUE: return false;
8832 case EXPR_LABEL_ADDRESS: return false;
8834 /* suppress the warning for microsoft __noop operations */
8835 case EXPR_LITERAL_MS_NOOP: return true;
8836 case EXPR_LITERAL_BOOLEAN:
8837 case EXPR_LITERAL_CHARACTER:
8838 case EXPR_LITERAL_WIDE_CHARACTER:
8839 case EXPR_LITERAL_INTEGER:
8840 case EXPR_LITERAL_INTEGER_OCTAL:
8841 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8842 case EXPR_LITERAL_FLOATINGPOINT:
8843 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8844 case EXPR_STRING_LITERAL: return false;
8845 case EXPR_WIDE_STRING_LITERAL: return false;
8848 const call_expression_t *const call = &expr->call;
8849 if (call->function->kind != EXPR_REFERENCE)
8852 switch (call->function->reference.entity->function.btk) {
8853 /* FIXME: which builtins have no effect? */
8854 default: return true;
8858 /* Generate the warning if either the left or right hand side of a
8859 * conditional expression has no effect */
8860 case EXPR_CONDITIONAL: {
8861 conditional_expression_t const *const cond = &expr->conditional;
8862 expression_t const *const t = cond->true_expression;
8864 (t == NULL || expression_has_effect(t)) &&
8865 expression_has_effect(cond->false_expression);
8868 case EXPR_SELECT: return false;
8869 case EXPR_ARRAY_ACCESS: return false;
8870 case EXPR_SIZEOF: return false;
8871 case EXPR_CLASSIFY_TYPE: return false;
8872 case EXPR_ALIGNOF: return false;
8874 case EXPR_FUNCNAME: return false;
8875 case EXPR_BUILTIN_CONSTANT_P: return false;
8876 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8877 case EXPR_OFFSETOF: return false;
8878 case EXPR_VA_START: return true;
8879 case EXPR_VA_ARG: return true;
8880 case EXPR_VA_COPY: return true;
8881 case EXPR_STATEMENT: return true; // TODO
8882 case EXPR_COMPOUND_LITERAL: return false;
8884 case EXPR_UNARY_NEGATE: return false;
8885 case EXPR_UNARY_PLUS: return false;
8886 case EXPR_UNARY_BITWISE_NEGATE: return false;
8887 case EXPR_UNARY_NOT: return false;
8888 case EXPR_UNARY_DEREFERENCE: return false;
8889 case EXPR_UNARY_TAKE_ADDRESS: return false;
8890 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8891 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8892 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8893 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8895 /* Treat void casts as if they have an effect in order to being able to
8896 * suppress the warning */
8897 case EXPR_UNARY_CAST: {
8898 type_t *const type = skip_typeref(expr->base.type);
8899 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8902 case EXPR_UNARY_CAST_IMPLICIT: return true;
8903 case EXPR_UNARY_ASSUME: return true;
8904 case EXPR_UNARY_DELETE: return true;
8905 case EXPR_UNARY_DELETE_ARRAY: return true;
8906 case EXPR_UNARY_THROW: return true;
8908 case EXPR_BINARY_ADD: return false;
8909 case EXPR_BINARY_SUB: return false;
8910 case EXPR_BINARY_MUL: return false;
8911 case EXPR_BINARY_DIV: return false;
8912 case EXPR_BINARY_MOD: return false;
8913 case EXPR_BINARY_EQUAL: return false;
8914 case EXPR_BINARY_NOTEQUAL: return false;
8915 case EXPR_BINARY_LESS: return false;
8916 case EXPR_BINARY_LESSEQUAL: return false;
8917 case EXPR_BINARY_GREATER: return false;
8918 case EXPR_BINARY_GREATEREQUAL: return false;
8919 case EXPR_BINARY_BITWISE_AND: return false;
8920 case EXPR_BINARY_BITWISE_OR: return false;
8921 case EXPR_BINARY_BITWISE_XOR: return false;
8922 case EXPR_BINARY_SHIFTLEFT: return false;
8923 case EXPR_BINARY_SHIFTRIGHT: return false;
8924 case EXPR_BINARY_ASSIGN: return true;
8925 case EXPR_BINARY_MUL_ASSIGN: return true;
8926 case EXPR_BINARY_DIV_ASSIGN: return true;
8927 case EXPR_BINARY_MOD_ASSIGN: return true;
8928 case EXPR_BINARY_ADD_ASSIGN: return true;
8929 case EXPR_BINARY_SUB_ASSIGN: return true;
8930 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8931 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8932 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8933 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8934 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8936 /* Only examine the right hand side of && and ||, because the left hand
8937 * side already has the effect of controlling the execution of the right
8939 case EXPR_BINARY_LOGICAL_AND:
8940 case EXPR_BINARY_LOGICAL_OR:
8941 /* Only examine the right hand side of a comma expression, because the left
8942 * hand side has a separate warning */
8943 case EXPR_BINARY_COMMA:
8944 return expression_has_effect(expr->binary.right);
8946 case EXPR_BINARY_ISGREATER: return false;
8947 case EXPR_BINARY_ISGREATEREQUAL: return false;
8948 case EXPR_BINARY_ISLESS: return false;
8949 case EXPR_BINARY_ISLESSEQUAL: return false;
8950 case EXPR_BINARY_ISLESSGREATER: return false;
8951 case EXPR_BINARY_ISUNORDERED: return false;
8954 internal_errorf(HERE, "unexpected expression");
8957 static void semantic_comma(binary_expression_t *expression)
8959 if (warning.unused_value) {
8960 const expression_t *const left = expression->left;
8961 if (!expression_has_effect(left)) {
8962 warningf(&left->base.source_position,
8963 "left-hand operand of comma expression has no effect");
8966 expression->base.type = expression->right->base.type;
8970 * @param prec_r precedence of the right operand
8972 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8973 static expression_t *parse_##binexpression_type(expression_t *left) \
8975 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8976 binexpr->binary.left = left; \
8979 expression_t *right = parse_subexpression(prec_r); \
8981 binexpr->binary.right = right; \
8982 sfunc(&binexpr->binary); \
8987 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8988 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8989 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8990 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8991 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8992 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8993 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8994 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8995 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8996 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8997 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8998 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8999 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9000 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
9001 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
9002 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
9003 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9004 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9005 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9006 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9007 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9008 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9009 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9010 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9011 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9012 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9013 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9014 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9015 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9016 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9019 static expression_t *parse_subexpression(precedence_t precedence)
9021 if (token.type < 0) {
9022 return expected_expression_error();
9025 expression_parser_function_t *parser
9026 = &expression_parsers[token.type];
9027 source_position_t source_position = token.source_position;
9030 if (parser->parser != NULL) {
9031 left = parser->parser();
9033 left = parse_primary_expression();
9035 assert(left != NULL);
9036 left->base.source_position = source_position;
9039 if (token.type < 0) {
9040 return expected_expression_error();
9043 parser = &expression_parsers[token.type];
9044 if (parser->infix_parser == NULL)
9046 if (parser->infix_precedence < precedence)
9049 left = parser->infix_parser(left);
9051 assert(left != NULL);
9052 assert(left->kind != EXPR_UNKNOWN);
9053 left->base.source_position = source_position;
9060 * Parse an expression.
9062 static expression_t *parse_expression(void)
9064 return parse_subexpression(PREC_EXPRESSION);
9068 * Register a parser for a prefix-like operator.
9070 * @param parser the parser function
9071 * @param token_type the token type of the prefix token
9073 static void register_expression_parser(parse_expression_function parser,
9076 expression_parser_function_t *entry = &expression_parsers[token_type];
9078 if (entry->parser != NULL) {
9079 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9080 panic("trying to register multiple expression parsers for a token");
9082 entry->parser = parser;
9086 * Register a parser for an infix operator with given precedence.
9088 * @param parser the parser function
9089 * @param token_type the token type of the infix operator
9090 * @param precedence the precedence of the operator
9092 static void register_infix_parser(parse_expression_infix_function parser,
9093 int token_type, precedence_t precedence)
9095 expression_parser_function_t *entry = &expression_parsers[token_type];
9097 if (entry->infix_parser != NULL) {
9098 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9099 panic("trying to register multiple infix expression parsers for a "
9102 entry->infix_parser = parser;
9103 entry->infix_precedence = precedence;
9107 * Initialize the expression parsers.
9109 static void init_expression_parsers(void)
9111 memset(&expression_parsers, 0, sizeof(expression_parsers));
9113 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9114 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9115 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9116 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9117 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9118 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9119 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9120 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9121 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9122 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9123 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9124 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9125 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9126 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9127 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9128 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9129 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9130 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9131 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9132 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9133 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9134 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9135 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9136 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9137 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9138 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9139 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9140 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9141 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9142 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9143 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9144 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9145 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9146 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9147 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9148 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9149 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9151 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9152 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9153 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9154 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9155 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9156 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9157 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9158 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9159 register_expression_parser(parse_sizeof, T_sizeof);
9160 register_expression_parser(parse_alignof, T___alignof__);
9161 register_expression_parser(parse_extension, T___extension__);
9162 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9163 register_expression_parser(parse_delete, T_delete);
9164 register_expression_parser(parse_throw, T_throw);
9168 * Parse a asm statement arguments specification.
9170 static asm_argument_t *parse_asm_arguments(bool is_out)
9172 asm_argument_t *result = NULL;
9173 asm_argument_t **anchor = &result;
9175 while (token.type == T_STRING_LITERAL || token.type == '[') {
9176 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9177 memset(argument, 0, sizeof(argument[0]));
9180 if (token.type != T_IDENTIFIER) {
9181 parse_error_expected("while parsing asm argument",
9182 T_IDENTIFIER, NULL);
9185 argument->symbol = token.symbol;
9187 expect(']', end_error);
9190 argument->constraints = parse_string_literals();
9191 expect('(', end_error);
9192 add_anchor_token(')');
9193 expression_t *expression = parse_expression();
9194 rem_anchor_token(')');
9196 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9197 * change size or type representation (e.g. int -> long is ok, but
9198 * int -> float is not) */
9199 if (expression->kind == EXPR_UNARY_CAST) {
9200 type_t *const type = expression->base.type;
9201 type_kind_t const kind = type->kind;
9202 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9205 if (kind == TYPE_ATOMIC) {
9206 atomic_type_kind_t const akind = type->atomic.akind;
9207 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9208 size = get_atomic_type_size(akind);
9210 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9211 size = get_atomic_type_size(get_intptr_kind());
9215 expression_t *const value = expression->unary.value;
9216 type_t *const value_type = value->base.type;
9217 type_kind_t const value_kind = value_type->kind;
9219 unsigned value_flags;
9220 unsigned value_size;
9221 if (value_kind == TYPE_ATOMIC) {
9222 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9223 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9224 value_size = get_atomic_type_size(value_akind);
9225 } else if (value_kind == TYPE_POINTER) {
9226 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9227 value_size = get_atomic_type_size(get_intptr_kind());
9232 if (value_flags != flags || value_size != size)
9236 } while (expression->kind == EXPR_UNARY_CAST);
9240 if (!is_lvalue(expression)) {
9241 errorf(&expression->base.source_position,
9242 "asm output argument is not an lvalue");
9245 if (argument->constraints.begin[0] == '=')
9246 determine_lhs_ent(expression, NULL);
9248 mark_vars_read(expression, NULL);
9250 mark_vars_read(expression, NULL);
9252 argument->expression = expression;
9253 expect(')', end_error);
9255 set_address_taken(expression, true);
9258 anchor = &argument->next;
9270 * Parse a asm statement clobber specification.
9272 static asm_clobber_t *parse_asm_clobbers(void)
9274 asm_clobber_t *result = NULL;
9275 asm_clobber_t **anchor = &result;
9277 while (token.type == T_STRING_LITERAL) {
9278 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9279 clobber->clobber = parse_string_literals();
9282 anchor = &clobber->next;
9292 * Parse an asm statement.
9294 static statement_t *parse_asm_statement(void)
9296 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9297 asm_statement_t *asm_statement = &statement->asms;
9301 if (next_if(T_volatile))
9302 asm_statement->is_volatile = true;
9304 expect('(', end_error);
9305 add_anchor_token(')');
9306 if (token.type != T_STRING_LITERAL) {
9307 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9310 asm_statement->asm_text = parse_string_literals();
9312 add_anchor_token(':');
9313 if (!next_if(':')) {
9314 rem_anchor_token(':');
9318 asm_statement->outputs = parse_asm_arguments(true);
9319 if (!next_if(':')) {
9320 rem_anchor_token(':');
9324 asm_statement->inputs = parse_asm_arguments(false);
9325 if (!next_if(':')) {
9326 rem_anchor_token(':');
9329 rem_anchor_token(':');
9331 asm_statement->clobbers = parse_asm_clobbers();
9334 rem_anchor_token(')');
9335 expect(')', end_error);
9336 expect(';', end_error);
9338 if (asm_statement->outputs == NULL) {
9339 /* GCC: An 'asm' instruction without any output operands will be treated
9340 * identically to a volatile 'asm' instruction. */
9341 asm_statement->is_volatile = true;
9346 return create_invalid_statement();
9349 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9351 statement_t *inner_stmt;
9352 switch (token.type) {
9354 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9355 inner_stmt = create_invalid_statement();
9359 if (label->kind == STATEMENT_LABEL) {
9360 /* Eat an empty statement here, to avoid the warning about an empty
9361 * statement after a label. label:; is commonly used to have a label
9362 * before a closing brace. */
9363 inner_stmt = create_empty_statement();
9370 inner_stmt = parse_statement();
9371 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9372 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9373 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9381 * Parse a case statement.
9383 static statement_t *parse_case_statement(void)
9385 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9386 source_position_t *const pos = &statement->base.source_position;
9390 expression_t *const expression = parse_expression();
9391 statement->case_label.expression = expression;
9392 expression_classification_t const expr_class = is_constant_expression(expression);
9393 if (expr_class != EXPR_CLASS_CONSTANT) {
9394 if (expr_class != EXPR_CLASS_ERROR) {
9395 errorf(pos, "case label does not reduce to an integer constant");
9397 statement->case_label.is_bad = true;
9399 long const val = fold_constant_to_int(expression);
9400 statement->case_label.first_case = val;
9401 statement->case_label.last_case = val;
9405 if (next_if(T_DOTDOTDOT)) {
9406 expression_t *const end_range = parse_expression();
9407 statement->case_label.end_range = end_range;
9408 expression_classification_t const end_class = is_constant_expression(end_range);
9409 if (end_class != EXPR_CLASS_CONSTANT) {
9410 if (end_class != EXPR_CLASS_ERROR) {
9411 errorf(pos, "case range does not reduce to an integer constant");
9413 statement->case_label.is_bad = true;
9415 long const val = fold_constant_to_int(end_range);
9416 statement->case_label.last_case = val;
9418 if (warning.other && val < statement->case_label.first_case) {
9419 statement->case_label.is_empty_range = true;
9420 warningf(pos, "empty range specified");
9426 PUSH_PARENT(statement);
9428 expect(':', end_error);
9431 if (current_switch != NULL) {
9432 if (! statement->case_label.is_bad) {
9433 /* Check for duplicate case values */
9434 case_label_statement_t *c = &statement->case_label;
9435 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9436 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9439 if (c->last_case < l->first_case || c->first_case > l->last_case)
9442 errorf(pos, "duplicate case value (previously used %P)",
9443 &l->base.source_position);
9447 /* link all cases into the switch statement */
9448 if (current_switch->last_case == NULL) {
9449 current_switch->first_case = &statement->case_label;
9451 current_switch->last_case->next = &statement->case_label;
9453 current_switch->last_case = &statement->case_label;
9455 errorf(pos, "case label not within a switch statement");
9458 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9465 * Parse a default statement.
9467 static statement_t *parse_default_statement(void)
9469 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9473 PUSH_PARENT(statement);
9475 expect(':', end_error);
9478 if (current_switch != NULL) {
9479 const case_label_statement_t *def_label = current_switch->default_label;
9480 if (def_label != NULL) {
9481 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9482 &def_label->base.source_position);
9484 current_switch->default_label = &statement->case_label;
9486 /* link all cases into the switch statement */
9487 if (current_switch->last_case == NULL) {
9488 current_switch->first_case = &statement->case_label;
9490 current_switch->last_case->next = &statement->case_label;
9492 current_switch->last_case = &statement->case_label;
9495 errorf(&statement->base.source_position,
9496 "'default' label not within a switch statement");
9499 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9506 * Parse a label statement.
9508 static statement_t *parse_label_statement(void)
9510 assert(token.type == T_IDENTIFIER);
9511 symbol_t *symbol = token.symbol;
9512 label_t *label = get_label(symbol);
9514 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9515 statement->label.label = label;
9519 PUSH_PARENT(statement);
9521 /* if statement is already set then the label is defined twice,
9522 * otherwise it was just mentioned in a goto/local label declaration so far
9524 if (label->statement != NULL) {
9525 errorf(HERE, "duplicate label '%Y' (declared %P)",
9526 symbol, &label->base.source_position);
9528 label->base.source_position = token.source_position;
9529 label->statement = statement;
9534 statement->label.statement = parse_label_inner_statement(statement, "label");
9536 /* remember the labels in a list for later checking */
9537 *label_anchor = &statement->label;
9538 label_anchor = &statement->label.next;
9545 * Parse an if statement.
9547 static statement_t *parse_if(void)
9549 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9553 PUSH_PARENT(statement);
9555 add_anchor_token('{');
9557 expect('(', end_error);
9558 add_anchor_token(')');
9559 expression_t *const expr = parse_expression();
9560 statement->ifs.condition = expr;
9561 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9563 semantic_condition(expr, "condition of 'if'-statment");
9564 mark_vars_read(expr, NULL);
9565 rem_anchor_token(')');
9566 expect(')', end_error);
9569 rem_anchor_token('{');
9571 add_anchor_token(T_else);
9572 statement_t *const true_stmt = parse_statement();
9573 statement->ifs.true_statement = true_stmt;
9574 rem_anchor_token(T_else);
9576 if (next_if(T_else)) {
9577 statement->ifs.false_statement = parse_statement();
9578 } else if (warning.parentheses &&
9579 true_stmt->kind == STATEMENT_IF &&
9580 true_stmt->ifs.false_statement != NULL) {
9581 warningf(&true_stmt->base.source_position,
9582 "suggest explicit braces to avoid ambiguous 'else'");
9590 * Check that all enums are handled in a switch.
9592 * @param statement the switch statement to check
9594 static void check_enum_cases(const switch_statement_t *statement)
9596 const type_t *type = skip_typeref(statement->expression->base.type);
9597 if (! is_type_enum(type))
9599 const enum_type_t *enumt = &type->enumt;
9601 /* if we have a default, no warnings */
9602 if (statement->default_label != NULL)
9605 /* FIXME: calculation of value should be done while parsing */
9606 /* TODO: quadratic algorithm here. Change to an n log n one */
9607 long last_value = -1;
9608 const entity_t *entry = enumt->enume->base.next;
9609 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9610 entry = entry->base.next) {
9611 const expression_t *expression = entry->enum_value.value;
9612 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9614 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9615 if (l->expression == NULL)
9617 if (l->first_case <= value && value <= l->last_case) {
9623 warningf(&statement->base.source_position,
9624 "enumeration value '%Y' not handled in switch",
9625 entry->base.symbol);
9632 * Parse a switch statement.
9634 static statement_t *parse_switch(void)
9636 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9640 PUSH_PARENT(statement);
9642 expect('(', end_error);
9643 add_anchor_token(')');
9644 expression_t *const expr = parse_expression();
9645 mark_vars_read(expr, NULL);
9646 type_t * type = skip_typeref(expr->base.type);
9647 if (is_type_integer(type)) {
9648 type = promote_integer(type);
9649 if (warning.traditional) {
9650 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9651 warningf(&expr->base.source_position,
9652 "'%T' switch expression not converted to '%T' in ISO C",
9656 } else if (is_type_valid(type)) {
9657 errorf(&expr->base.source_position,
9658 "switch quantity is not an integer, but '%T'", type);
9659 type = type_error_type;
9661 statement->switchs.expression = create_implicit_cast(expr, type);
9662 expect(')', end_error);
9663 rem_anchor_token(')');
9665 switch_statement_t *rem = current_switch;
9666 current_switch = &statement->switchs;
9667 statement->switchs.body = parse_statement();
9668 current_switch = rem;
9670 if (warning.switch_default &&
9671 statement->switchs.default_label == NULL) {
9672 warningf(&statement->base.source_position, "switch has no default case");
9674 if (warning.switch_enum)
9675 check_enum_cases(&statement->switchs);
9681 return create_invalid_statement();
9684 static statement_t *parse_loop_body(statement_t *const loop)
9686 statement_t *const rem = current_loop;
9687 current_loop = loop;
9689 statement_t *const body = parse_statement();
9696 * Parse a while statement.
9698 static statement_t *parse_while(void)
9700 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9704 PUSH_PARENT(statement);
9706 expect('(', end_error);
9707 add_anchor_token(')');
9708 expression_t *const cond = parse_expression();
9709 statement->whiles.condition = cond;
9710 /* §6.8.5:2 The controlling expression of an iteration statement shall
9711 * have scalar type. */
9712 semantic_condition(cond, "condition of 'while'-statement");
9713 mark_vars_read(cond, NULL);
9714 rem_anchor_token(')');
9715 expect(')', end_error);
9717 statement->whiles.body = parse_loop_body(statement);
9723 return create_invalid_statement();
9727 * Parse a do statement.
9729 static statement_t *parse_do(void)
9731 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9735 PUSH_PARENT(statement);
9737 add_anchor_token(T_while);
9738 statement->do_while.body = parse_loop_body(statement);
9739 rem_anchor_token(T_while);
9741 expect(T_while, end_error);
9742 expect('(', end_error);
9743 add_anchor_token(')');
9744 expression_t *const cond = parse_expression();
9745 statement->do_while.condition = cond;
9746 /* §6.8.5:2 The controlling expression of an iteration statement shall
9747 * have scalar type. */
9748 semantic_condition(cond, "condition of 'do-while'-statement");
9749 mark_vars_read(cond, NULL);
9750 rem_anchor_token(')');
9751 expect(')', end_error);
9752 expect(';', end_error);
9758 return create_invalid_statement();
9762 * Parse a for statement.
9764 static statement_t *parse_for(void)
9766 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9770 expect('(', end_error1);
9771 add_anchor_token(')');
9773 PUSH_PARENT(statement);
9775 size_t const top = environment_top();
9776 scope_t *old_scope = scope_push(&statement->fors.scope);
9778 bool old_gcc_extension = in_gcc_extension;
9779 while (next_if(T___extension__)) {
9780 in_gcc_extension = true;
9784 } else if (is_declaration_specifier(&token, false)) {
9785 parse_declaration(record_entity, DECL_FLAGS_NONE);
9787 add_anchor_token(';');
9788 expression_t *const init = parse_expression();
9789 statement->fors.initialisation = init;
9790 mark_vars_read(init, ENT_ANY);
9791 if (warning.unused_value && !expression_has_effect(init)) {
9792 warningf(&init->base.source_position,
9793 "initialisation of 'for'-statement has no effect");
9795 rem_anchor_token(';');
9796 expect(';', end_error2);
9798 in_gcc_extension = old_gcc_extension;
9800 if (token.type != ';') {
9801 add_anchor_token(';');
9802 expression_t *const cond = parse_expression();
9803 statement->fors.condition = cond;
9804 /* §6.8.5:2 The controlling expression of an iteration statement
9805 * shall have scalar type. */
9806 semantic_condition(cond, "condition of 'for'-statement");
9807 mark_vars_read(cond, NULL);
9808 rem_anchor_token(';');
9810 expect(';', end_error2);
9811 if (token.type != ')') {
9812 expression_t *const step = parse_expression();
9813 statement->fors.step = step;
9814 mark_vars_read(step, ENT_ANY);
9815 if (warning.unused_value && !expression_has_effect(step)) {
9816 warningf(&step->base.source_position,
9817 "step of 'for'-statement has no effect");
9820 expect(')', end_error2);
9821 rem_anchor_token(')');
9822 statement->fors.body = parse_loop_body(statement);
9824 assert(current_scope == &statement->fors.scope);
9825 scope_pop(old_scope);
9826 environment_pop_to(top);
9833 rem_anchor_token(')');
9834 assert(current_scope == &statement->fors.scope);
9835 scope_pop(old_scope);
9836 environment_pop_to(top);
9840 return create_invalid_statement();
9844 * Parse a goto statement.
9846 static statement_t *parse_goto(void)
9848 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9851 if (GNU_MODE && next_if('*')) {
9852 expression_t *expression = parse_expression();
9853 mark_vars_read(expression, NULL);
9855 /* Argh: although documentation says the expression must be of type void*,
9856 * gcc accepts anything that can be casted into void* without error */
9857 type_t *type = expression->base.type;
9859 if (type != type_error_type) {
9860 if (!is_type_pointer(type) && !is_type_integer(type)) {
9861 errorf(&expression->base.source_position,
9862 "cannot convert to a pointer type");
9863 } else if (warning.other && type != type_void_ptr) {
9864 warningf(&expression->base.source_position,
9865 "type of computed goto expression should be 'void*' not '%T'", type);
9867 expression = create_implicit_cast(expression, type_void_ptr);
9870 statement->gotos.expression = expression;
9871 } else if (token.type == T_IDENTIFIER) {
9872 symbol_t *symbol = token.symbol;
9874 statement->gotos.label = get_label(symbol);
9877 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9879 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9881 return create_invalid_statement();
9884 /* remember the goto's in a list for later checking */
9885 *goto_anchor = &statement->gotos;
9886 goto_anchor = &statement->gotos.next;
9888 expect(';', end_error);
9895 * Parse a continue statement.
9897 static statement_t *parse_continue(void)
9899 if (current_loop == NULL) {
9900 errorf(HERE, "continue statement not within loop");
9903 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9906 expect(';', end_error);
9913 * Parse a break statement.
9915 static statement_t *parse_break(void)
9917 if (current_switch == NULL && current_loop == NULL) {
9918 errorf(HERE, "break statement not within loop or switch");
9921 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9924 expect(';', end_error);
9931 * Parse a __leave statement.
9933 static statement_t *parse_leave_statement(void)
9935 if (current_try == NULL) {
9936 errorf(HERE, "__leave statement not within __try");
9939 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9942 expect(';', end_error);
9949 * Check if a given entity represents a local variable.
9951 static bool is_local_variable(const entity_t *entity)
9953 if (entity->kind != ENTITY_VARIABLE)
9956 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9957 case STORAGE_CLASS_AUTO:
9958 case STORAGE_CLASS_REGISTER: {
9959 const type_t *type = skip_typeref(entity->declaration.type);
9960 if (is_type_function(type)) {
9972 * Check if a given expression represents a local variable.
9974 static bool expression_is_local_variable(const expression_t *expression)
9976 if (expression->base.kind != EXPR_REFERENCE) {
9979 const entity_t *entity = expression->reference.entity;
9980 return is_local_variable(entity);
9984 * Check if a given expression represents a local variable and
9985 * return its declaration then, else return NULL.
9987 entity_t *expression_is_variable(const expression_t *expression)
9989 if (expression->base.kind != EXPR_REFERENCE) {
9992 entity_t *entity = expression->reference.entity;
9993 if (entity->kind != ENTITY_VARIABLE)
10000 * Parse a return statement.
10002 static statement_t *parse_return(void)
10006 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10008 expression_t *return_value = NULL;
10009 if (token.type != ';') {
10010 return_value = parse_expression();
10011 mark_vars_read(return_value, NULL);
10014 const type_t *const func_type = skip_typeref(current_function->base.type);
10015 assert(is_type_function(func_type));
10016 type_t *const return_type = skip_typeref(func_type->function.return_type);
10018 source_position_t const *const pos = &statement->base.source_position;
10019 if (return_value != NULL) {
10020 type_t *return_value_type = skip_typeref(return_value->base.type);
10022 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10023 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10024 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10025 /* Only warn in C mode, because GCC does the same */
10026 if (c_mode & _CXX || strict_mode) {
10028 "'return' with a value, in function returning 'void'");
10029 } else if (warning.other) {
10031 "'return' with a value, in function returning 'void'");
10033 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10034 /* Only warn in C mode, because GCC does the same */
10037 "'return' with expression in function returning 'void'");
10038 } else if (warning.other) {
10040 "'return' with expression in function returning 'void'");
10044 assign_error_t error = semantic_assign(return_type, return_value);
10045 report_assign_error(error, return_type, return_value, "'return'",
10048 return_value = create_implicit_cast(return_value, return_type);
10049 /* check for returning address of a local var */
10050 if (warning.other && return_value != NULL
10051 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10052 const expression_t *expression = return_value->unary.value;
10053 if (expression_is_local_variable(expression)) {
10054 warningf(pos, "function returns address of local variable");
10057 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10058 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10059 if (c_mode & _CXX || strict_mode) {
10061 "'return' without value, in function returning non-void");
10064 "'return' without value, in function returning non-void");
10067 statement->returns.value = return_value;
10069 expect(';', end_error);
10076 * Parse a declaration statement.
10078 static statement_t *parse_declaration_statement(void)
10080 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10082 entity_t *before = current_scope->last_entity;
10084 parse_external_declaration();
10086 parse_declaration(record_entity, DECL_FLAGS_NONE);
10089 declaration_statement_t *const decl = &statement->declaration;
10090 entity_t *const begin =
10091 before != NULL ? before->base.next : current_scope->entities;
10092 decl->declarations_begin = begin;
10093 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10099 * Parse an expression statement, ie. expr ';'.
10101 static statement_t *parse_expression_statement(void)
10103 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10105 expression_t *const expr = parse_expression();
10106 statement->expression.expression = expr;
10107 mark_vars_read(expr, ENT_ANY);
10109 expect(';', end_error);
10116 * Parse a microsoft __try { } __finally { } or
10117 * __try{ } __except() { }
10119 static statement_t *parse_ms_try_statment(void)
10121 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10124 PUSH_PARENT(statement);
10126 ms_try_statement_t *rem = current_try;
10127 current_try = &statement->ms_try;
10128 statement->ms_try.try_statement = parse_compound_statement(false);
10133 if (next_if(T___except)) {
10134 expect('(', end_error);
10135 add_anchor_token(')');
10136 expression_t *const expr = parse_expression();
10137 mark_vars_read(expr, NULL);
10138 type_t * type = skip_typeref(expr->base.type);
10139 if (is_type_integer(type)) {
10140 type = promote_integer(type);
10141 } else if (is_type_valid(type)) {
10142 errorf(&expr->base.source_position,
10143 "__expect expression is not an integer, but '%T'", type);
10144 type = type_error_type;
10146 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10147 rem_anchor_token(')');
10148 expect(')', end_error);
10149 statement->ms_try.final_statement = parse_compound_statement(false);
10150 } else if (next_if(T__finally)) {
10151 statement->ms_try.final_statement = parse_compound_statement(false);
10153 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10154 return create_invalid_statement();
10158 return create_invalid_statement();
10161 static statement_t *parse_empty_statement(void)
10163 if (warning.empty_statement) {
10164 warningf(HERE, "statement is empty");
10166 statement_t *const statement = create_empty_statement();
10171 static statement_t *parse_local_label_declaration(void)
10173 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10177 entity_t *begin = NULL;
10178 entity_t *end = NULL;
10179 entity_t **anchor = &begin;
10181 if (token.type != T_IDENTIFIER) {
10182 parse_error_expected("while parsing local label declaration",
10183 T_IDENTIFIER, NULL);
10186 symbol_t *symbol = token.symbol;
10187 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10188 if (entity != NULL && entity->base.parent_scope == current_scope) {
10189 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10190 symbol, &entity->base.source_position);
10192 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10194 entity->base.parent_scope = current_scope;
10195 entity->base.namespc = NAMESPACE_LABEL;
10196 entity->base.source_position = token.source_position;
10197 entity->base.symbol = symbol;
10200 anchor = &entity->base.next;
10203 environment_push(entity);
10206 } while (next_if(','));
10207 expect(';', end_error);
10209 statement->declaration.declarations_begin = begin;
10210 statement->declaration.declarations_end = end;
10214 static void parse_namespace_definition(void)
10218 entity_t *entity = NULL;
10219 symbol_t *symbol = NULL;
10221 if (token.type == T_IDENTIFIER) {
10222 symbol = token.symbol;
10225 entity = get_entity(symbol, NAMESPACE_NORMAL);
10227 && entity->kind != ENTITY_NAMESPACE
10228 && entity->base.parent_scope == current_scope) {
10229 if (is_entity_valid(entity)) {
10230 error_redefined_as_different_kind(&token.source_position,
10231 entity, ENTITY_NAMESPACE);
10237 if (entity == NULL) {
10238 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10239 entity->base.symbol = symbol;
10240 entity->base.source_position = token.source_position;
10241 entity->base.namespc = NAMESPACE_NORMAL;
10242 entity->base.parent_scope = current_scope;
10245 if (token.type == '=') {
10246 /* TODO: parse namespace alias */
10247 panic("namespace alias definition not supported yet");
10250 environment_push(entity);
10251 append_entity(current_scope, entity);
10253 size_t const top = environment_top();
10254 scope_t *old_scope = scope_push(&entity->namespacee.members);
10256 entity_t *old_current_entity = current_entity;
10257 current_entity = entity;
10259 expect('{', end_error);
10261 expect('}', end_error);
10264 assert(current_scope == &entity->namespacee.members);
10265 assert(current_entity == entity);
10266 current_entity = old_current_entity;
10267 scope_pop(old_scope);
10268 environment_pop_to(top);
10272 * Parse a statement.
10273 * There's also parse_statement() which additionally checks for
10274 * "statement has no effect" warnings
10276 static statement_t *intern_parse_statement(void)
10278 statement_t *statement = NULL;
10280 /* declaration or statement */
10281 add_anchor_token(';');
10282 switch (token.type) {
10283 case T_IDENTIFIER: {
10284 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10285 if (la1_type == ':') {
10286 statement = parse_label_statement();
10287 } else if (is_typedef_symbol(token.symbol)) {
10288 statement = parse_declaration_statement();
10290 /* it's an identifier, the grammar says this must be an
10291 * expression statement. However it is common that users mistype
10292 * declaration types, so we guess a bit here to improve robustness
10293 * for incorrect programs */
10294 switch (la1_type) {
10297 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10299 statement = parse_expression_statement();
10303 statement = parse_declaration_statement();
10311 case T___extension__:
10312 /* This can be a prefix to a declaration or an expression statement.
10313 * We simply eat it now and parse the rest with tail recursion. */
10314 while (next_if(T___extension__)) {}
10315 bool old_gcc_extension = in_gcc_extension;
10316 in_gcc_extension = true;
10317 statement = intern_parse_statement();
10318 in_gcc_extension = old_gcc_extension;
10322 statement = parse_declaration_statement();
10326 statement = parse_local_label_declaration();
10329 case ';': statement = parse_empty_statement(); break;
10330 case '{': statement = parse_compound_statement(false); break;
10331 case T___leave: statement = parse_leave_statement(); break;
10332 case T___try: statement = parse_ms_try_statment(); break;
10333 case T_asm: statement = parse_asm_statement(); break;
10334 case T_break: statement = parse_break(); break;
10335 case T_case: statement = parse_case_statement(); break;
10336 case T_continue: statement = parse_continue(); break;
10337 case T_default: statement = parse_default_statement(); break;
10338 case T_do: statement = parse_do(); break;
10339 case T_for: statement = parse_for(); break;
10340 case T_goto: statement = parse_goto(); break;
10341 case T_if: statement = parse_if(); break;
10342 case T_return: statement = parse_return(); break;
10343 case T_switch: statement = parse_switch(); break;
10344 case T_while: statement = parse_while(); break;
10347 statement = parse_expression_statement();
10351 errorf(HERE, "unexpected token %K while parsing statement", &token);
10352 statement = create_invalid_statement();
10357 rem_anchor_token(';');
10359 assert(statement != NULL
10360 && statement->base.source_position.input_name != NULL);
10366 * parse a statement and emits "statement has no effect" warning if needed
10367 * (This is really a wrapper around intern_parse_statement with check for 1
10368 * single warning. It is needed, because for statement expressions we have
10369 * to avoid the warning on the last statement)
10371 static statement_t *parse_statement(void)
10373 statement_t *statement = intern_parse_statement();
10375 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10376 expression_t *expression = statement->expression.expression;
10377 if (!expression_has_effect(expression)) {
10378 warningf(&expression->base.source_position,
10379 "statement has no effect");
10387 * Parse a compound statement.
10389 static statement_t *parse_compound_statement(bool inside_expression_statement)
10391 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10393 PUSH_PARENT(statement);
10396 add_anchor_token('}');
10397 /* tokens, which can start a statement */
10398 /* TODO MS, __builtin_FOO */
10399 add_anchor_token('!');
10400 add_anchor_token('&');
10401 add_anchor_token('(');
10402 add_anchor_token('*');
10403 add_anchor_token('+');
10404 add_anchor_token('-');
10405 add_anchor_token('{');
10406 add_anchor_token('~');
10407 add_anchor_token(T_CHARACTER_CONSTANT);
10408 add_anchor_token(T_COLONCOLON);
10409 add_anchor_token(T_FLOATINGPOINT);
10410 add_anchor_token(T_IDENTIFIER);
10411 add_anchor_token(T_INTEGER);
10412 add_anchor_token(T_MINUSMINUS);
10413 add_anchor_token(T_PLUSPLUS);
10414 add_anchor_token(T_STRING_LITERAL);
10415 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10416 add_anchor_token(T_WIDE_STRING_LITERAL);
10417 add_anchor_token(T__Bool);
10418 add_anchor_token(T__Complex);
10419 add_anchor_token(T__Imaginary);
10420 add_anchor_token(T___FUNCTION__);
10421 add_anchor_token(T___PRETTY_FUNCTION__);
10422 add_anchor_token(T___alignof__);
10423 add_anchor_token(T___attribute__);
10424 add_anchor_token(T___builtin_va_start);
10425 add_anchor_token(T___extension__);
10426 add_anchor_token(T___func__);
10427 add_anchor_token(T___imag__);
10428 add_anchor_token(T___label__);
10429 add_anchor_token(T___real__);
10430 add_anchor_token(T___thread);
10431 add_anchor_token(T_asm);
10432 add_anchor_token(T_auto);
10433 add_anchor_token(T_bool);
10434 add_anchor_token(T_break);
10435 add_anchor_token(T_case);
10436 add_anchor_token(T_char);
10437 add_anchor_token(T_class);
10438 add_anchor_token(T_const);
10439 add_anchor_token(T_const_cast);
10440 add_anchor_token(T_continue);
10441 add_anchor_token(T_default);
10442 add_anchor_token(T_delete);
10443 add_anchor_token(T_double);
10444 add_anchor_token(T_do);
10445 add_anchor_token(T_dynamic_cast);
10446 add_anchor_token(T_enum);
10447 add_anchor_token(T_extern);
10448 add_anchor_token(T_false);
10449 add_anchor_token(T_float);
10450 add_anchor_token(T_for);
10451 add_anchor_token(T_goto);
10452 add_anchor_token(T_if);
10453 add_anchor_token(T_inline);
10454 add_anchor_token(T_int);
10455 add_anchor_token(T_long);
10456 add_anchor_token(T_new);
10457 add_anchor_token(T_operator);
10458 add_anchor_token(T_register);
10459 add_anchor_token(T_reinterpret_cast);
10460 add_anchor_token(T_restrict);
10461 add_anchor_token(T_return);
10462 add_anchor_token(T_short);
10463 add_anchor_token(T_signed);
10464 add_anchor_token(T_sizeof);
10465 add_anchor_token(T_static);
10466 add_anchor_token(T_static_cast);
10467 add_anchor_token(T_struct);
10468 add_anchor_token(T_switch);
10469 add_anchor_token(T_template);
10470 add_anchor_token(T_this);
10471 add_anchor_token(T_throw);
10472 add_anchor_token(T_true);
10473 add_anchor_token(T_try);
10474 add_anchor_token(T_typedef);
10475 add_anchor_token(T_typeid);
10476 add_anchor_token(T_typename);
10477 add_anchor_token(T_typeof);
10478 add_anchor_token(T_union);
10479 add_anchor_token(T_unsigned);
10480 add_anchor_token(T_using);
10481 add_anchor_token(T_void);
10482 add_anchor_token(T_volatile);
10483 add_anchor_token(T_wchar_t);
10484 add_anchor_token(T_while);
10486 size_t const top = environment_top();
10487 scope_t *old_scope = scope_push(&statement->compound.scope);
10489 statement_t **anchor = &statement->compound.statements;
10490 bool only_decls_so_far = true;
10491 while (token.type != '}') {
10492 if (token.type == T_EOF) {
10493 errorf(&statement->base.source_position,
10494 "EOF while parsing compound statement");
10497 statement_t *sub_statement = intern_parse_statement();
10498 if (is_invalid_statement(sub_statement)) {
10499 /* an error occurred. if we are at an anchor, return */
10505 if (warning.declaration_after_statement) {
10506 if (sub_statement->kind != STATEMENT_DECLARATION) {
10507 only_decls_so_far = false;
10508 } else if (!only_decls_so_far) {
10509 warningf(&sub_statement->base.source_position,
10510 "ISO C90 forbids mixed declarations and code");
10514 *anchor = sub_statement;
10516 while (sub_statement->base.next != NULL)
10517 sub_statement = sub_statement->base.next;
10519 anchor = &sub_statement->base.next;
10523 /* look over all statements again to produce no effect warnings */
10524 if (warning.unused_value) {
10525 statement_t *sub_statement = statement->compound.statements;
10526 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10527 if (sub_statement->kind != STATEMENT_EXPRESSION)
10529 /* don't emit a warning for the last expression in an expression
10530 * statement as it has always an effect */
10531 if (inside_expression_statement && sub_statement->base.next == NULL)
10534 expression_t *expression = sub_statement->expression.expression;
10535 if (!expression_has_effect(expression)) {
10536 warningf(&expression->base.source_position,
10537 "statement has no effect");
10543 rem_anchor_token(T_while);
10544 rem_anchor_token(T_wchar_t);
10545 rem_anchor_token(T_volatile);
10546 rem_anchor_token(T_void);
10547 rem_anchor_token(T_using);
10548 rem_anchor_token(T_unsigned);
10549 rem_anchor_token(T_union);
10550 rem_anchor_token(T_typeof);
10551 rem_anchor_token(T_typename);
10552 rem_anchor_token(T_typeid);
10553 rem_anchor_token(T_typedef);
10554 rem_anchor_token(T_try);
10555 rem_anchor_token(T_true);
10556 rem_anchor_token(T_throw);
10557 rem_anchor_token(T_this);
10558 rem_anchor_token(T_template);
10559 rem_anchor_token(T_switch);
10560 rem_anchor_token(T_struct);
10561 rem_anchor_token(T_static_cast);
10562 rem_anchor_token(T_static);
10563 rem_anchor_token(T_sizeof);
10564 rem_anchor_token(T_signed);
10565 rem_anchor_token(T_short);
10566 rem_anchor_token(T_return);
10567 rem_anchor_token(T_restrict);
10568 rem_anchor_token(T_reinterpret_cast);
10569 rem_anchor_token(T_register);
10570 rem_anchor_token(T_operator);
10571 rem_anchor_token(T_new);
10572 rem_anchor_token(T_long);
10573 rem_anchor_token(T_int);
10574 rem_anchor_token(T_inline);
10575 rem_anchor_token(T_if);
10576 rem_anchor_token(T_goto);
10577 rem_anchor_token(T_for);
10578 rem_anchor_token(T_float);
10579 rem_anchor_token(T_false);
10580 rem_anchor_token(T_extern);
10581 rem_anchor_token(T_enum);
10582 rem_anchor_token(T_dynamic_cast);
10583 rem_anchor_token(T_do);
10584 rem_anchor_token(T_double);
10585 rem_anchor_token(T_delete);
10586 rem_anchor_token(T_default);
10587 rem_anchor_token(T_continue);
10588 rem_anchor_token(T_const_cast);
10589 rem_anchor_token(T_const);
10590 rem_anchor_token(T_class);
10591 rem_anchor_token(T_char);
10592 rem_anchor_token(T_case);
10593 rem_anchor_token(T_break);
10594 rem_anchor_token(T_bool);
10595 rem_anchor_token(T_auto);
10596 rem_anchor_token(T_asm);
10597 rem_anchor_token(T___thread);
10598 rem_anchor_token(T___real__);
10599 rem_anchor_token(T___label__);
10600 rem_anchor_token(T___imag__);
10601 rem_anchor_token(T___func__);
10602 rem_anchor_token(T___extension__);
10603 rem_anchor_token(T___builtin_va_start);
10604 rem_anchor_token(T___attribute__);
10605 rem_anchor_token(T___alignof__);
10606 rem_anchor_token(T___PRETTY_FUNCTION__);
10607 rem_anchor_token(T___FUNCTION__);
10608 rem_anchor_token(T__Imaginary);
10609 rem_anchor_token(T__Complex);
10610 rem_anchor_token(T__Bool);
10611 rem_anchor_token(T_WIDE_STRING_LITERAL);
10612 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10613 rem_anchor_token(T_STRING_LITERAL);
10614 rem_anchor_token(T_PLUSPLUS);
10615 rem_anchor_token(T_MINUSMINUS);
10616 rem_anchor_token(T_INTEGER);
10617 rem_anchor_token(T_IDENTIFIER);
10618 rem_anchor_token(T_FLOATINGPOINT);
10619 rem_anchor_token(T_COLONCOLON);
10620 rem_anchor_token(T_CHARACTER_CONSTANT);
10621 rem_anchor_token('~');
10622 rem_anchor_token('{');
10623 rem_anchor_token('-');
10624 rem_anchor_token('+');
10625 rem_anchor_token('*');
10626 rem_anchor_token('(');
10627 rem_anchor_token('&');
10628 rem_anchor_token('!');
10629 rem_anchor_token('}');
10630 assert(current_scope == &statement->compound.scope);
10631 scope_pop(old_scope);
10632 environment_pop_to(top);
10639 * Check for unused global static functions and variables
10641 static void check_unused_globals(void)
10643 if (!warning.unused_function && !warning.unused_variable)
10646 for (const entity_t *entity = file_scope->entities; entity != NULL;
10647 entity = entity->base.next) {
10648 if (!is_declaration(entity))
10651 const declaration_t *declaration = &entity->declaration;
10652 if (declaration->used ||
10653 declaration->modifiers & DM_UNUSED ||
10654 declaration->modifiers & DM_USED ||
10655 declaration->storage_class != STORAGE_CLASS_STATIC)
10658 type_t *const type = declaration->type;
10660 if (entity->kind == ENTITY_FUNCTION) {
10661 /* inhibit warning for static inline functions */
10662 if (entity->function.is_inline)
10665 s = entity->function.statement != NULL ? "defined" : "declared";
10670 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10671 type, declaration->base.symbol, s);
10675 static void parse_global_asm(void)
10677 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10680 expect('(', end_error);
10682 statement->asms.asm_text = parse_string_literals();
10683 statement->base.next = unit->global_asm;
10684 unit->global_asm = statement;
10686 expect(')', end_error);
10687 expect(';', end_error);
10692 static void parse_linkage_specification(void)
10696 const char *linkage = parse_string_literals().begin;
10698 linkage_kind_t old_linkage = current_linkage;
10699 linkage_kind_t new_linkage;
10700 if (strcmp(linkage, "C") == 0) {
10701 new_linkage = LINKAGE_C;
10702 } else if (strcmp(linkage, "C++") == 0) {
10703 new_linkage = LINKAGE_CXX;
10705 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10706 new_linkage = LINKAGE_INVALID;
10708 current_linkage = new_linkage;
10710 if (next_if('{')) {
10712 expect('}', end_error);
10718 assert(current_linkage == new_linkage);
10719 current_linkage = old_linkage;
10722 static void parse_external(void)
10724 switch (token.type) {
10725 DECLARATION_START_NO_EXTERN
10727 case T___extension__:
10728 /* tokens below are for implicit int */
10729 case '&': /* & x; -> int& x; (and error later, because C++ has no
10731 case '*': /* * x; -> int* x; */
10732 case '(': /* (x); -> int (x); */
10733 parse_external_declaration();
10737 if (look_ahead(1)->type == T_STRING_LITERAL) {
10738 parse_linkage_specification();
10740 parse_external_declaration();
10745 parse_global_asm();
10749 parse_namespace_definition();
10753 if (!strict_mode) {
10755 warningf(HERE, "stray ';' outside of function");
10762 errorf(HERE, "stray %K outside of function", &token);
10763 if (token.type == '(' || token.type == '{' || token.type == '[')
10764 eat_until_matching_token(token.type);
10770 static void parse_externals(void)
10772 add_anchor_token('}');
10773 add_anchor_token(T_EOF);
10776 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10777 unsigned char token_anchor_copy[T_LAST_TOKEN];
10778 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10781 while (token.type != T_EOF && token.type != '}') {
10783 bool anchor_leak = false;
10784 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10785 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10787 /* the anchor set and its copy differs */
10788 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10789 anchor_leak = true;
10792 if (in_gcc_extension) {
10793 /* an gcc extension scope was not closed */
10794 errorf(HERE, "Leaked __extension__");
10795 anchor_leak = true;
10805 rem_anchor_token(T_EOF);
10806 rem_anchor_token('}');
10810 * Parse a translation unit.
10812 static void parse_translation_unit(void)
10814 add_anchor_token(T_EOF);
10819 if (token.type == T_EOF)
10822 errorf(HERE, "stray %K outside of function", &token);
10823 if (token.type == '(' || token.type == '{' || token.type == '[')
10824 eat_until_matching_token(token.type);
10832 * @return the translation unit or NULL if errors occurred.
10834 void start_parsing(void)
10836 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10837 label_stack = NEW_ARR_F(stack_entry_t, 0);
10838 diagnostic_count = 0;
10842 print_to_file(stderr);
10844 assert(unit == NULL);
10845 unit = allocate_ast_zero(sizeof(unit[0]));
10847 assert(file_scope == NULL);
10848 file_scope = &unit->scope;
10850 assert(current_scope == NULL);
10851 scope_push(&unit->scope);
10853 create_gnu_builtins();
10855 create_microsoft_intrinsics();
10858 translation_unit_t *finish_parsing(void)
10860 assert(current_scope == &unit->scope);
10863 assert(file_scope == &unit->scope);
10864 check_unused_globals();
10867 DEL_ARR_F(environment_stack);
10868 DEL_ARR_F(label_stack);
10870 translation_unit_t *result = unit;
10875 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10876 * are given length one. */
10877 static void complete_incomplete_arrays(void)
10879 size_t n = ARR_LEN(incomplete_arrays);
10880 for (size_t i = 0; i != n; ++i) {
10881 declaration_t *const decl = incomplete_arrays[i];
10882 type_t *const orig_type = decl->type;
10883 type_t *const type = skip_typeref(orig_type);
10885 if (!is_type_incomplete(type))
10888 if (warning.other) {
10889 warningf(&decl->base.source_position,
10890 "array '%#T' assumed to have one element",
10891 orig_type, decl->base.symbol);
10894 type_t *const new_type = duplicate_type(type);
10895 new_type->array.size_constant = true;
10896 new_type->array.has_implicit_size = true;
10897 new_type->array.size = 1;
10899 type_t *const result = identify_new_type(new_type);
10901 decl->type = result;
10905 void prepare_main_collect2(entity_t *entity)
10907 // create call to __main
10908 symbol_t *symbol = symbol_table_insert("__main");
10909 entity_t *subsubmain_ent
10910 = create_implicit_function(symbol, &builtin_source_position);
10912 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10913 type_t *ftype = subsubmain_ent->declaration.type;
10914 ref->base.source_position = builtin_source_position;
10915 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10916 ref->reference.entity = subsubmain_ent;
10918 expression_t *call = allocate_expression_zero(EXPR_CALL);
10919 call->base.source_position = builtin_source_position;
10920 call->base.type = type_void;
10921 call->call.function = ref;
10923 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10924 expr_statement->base.source_position = builtin_source_position;
10925 expr_statement->expression.expression = call;
10927 statement_t *statement = entity->function.statement;
10928 assert(statement->kind == STATEMENT_COMPOUND);
10929 compound_statement_t *compounds = &statement->compound;
10931 expr_statement->base.next = compounds->statements;
10932 compounds->statements = expr_statement;
10937 lookahead_bufpos = 0;
10938 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10941 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10942 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10943 parse_translation_unit();
10944 complete_incomplete_arrays();
10945 DEL_ARR_F(incomplete_arrays);
10946 incomplete_arrays = NULL;
10950 * Initialize the parser.
10952 void init_parser(void)
10954 sym_anonymous = symbol_table_insert("<anonymous>");
10956 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10958 init_expression_parsers();
10959 obstack_init(&temp_obst);
10963 * Terminate the parser.
10965 void exit_parser(void)
10967 obstack_free(&temp_obst, NULL);