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);
2027 static void advance_current_object(type_path_t *path, size_t top_path_level)
2029 type_path_entry_t *top = get_type_path_top(path);
2031 type_t *type = skip_typeref(top->type);
2032 if (is_type_union(type)) {
2033 /* in unions only the first element is initialized */
2034 top->v.compound_entry = NULL;
2035 } else if (is_type_struct(type)) {
2036 declaration_t *entry = top->v.compound_entry;
2038 entity_t *next_entity = entry->base.next;
2039 if (next_entity != NULL) {
2040 assert(is_declaration(next_entity));
2041 entry = &next_entity->declaration;
2046 top->v.compound_entry = entry;
2047 if (entry != NULL) {
2048 path->top_type = entry->type;
2051 } else if (is_type_array(type)) {
2052 assert(is_type_array(type));
2056 if (!type->array.size_constant || top->v.index < type->array.size) {
2060 assert(!is_type_valid(type));
2064 /* we're past the last member of the current sub-aggregate, try if we
2065 * can ascend in the type hierarchy and continue with another subobject */
2066 size_t len = ARR_LEN(path->path);
2068 if (len > top_path_level) {
2069 ascend_from_subtype(path);
2070 advance_current_object(path, top_path_level);
2072 path->top_type = NULL;
2077 * skip any {...} blocks until a closing bracket is reached.
2079 static void skip_initializers(void)
2083 while (token.type != '}') {
2084 if (token.type == T_EOF)
2086 if (token.type == '{') {
2094 static initializer_t *create_empty_initializer(void)
2096 static initializer_t empty_initializer
2097 = { .list = { { INITIALIZER_LIST }, 0 } };
2098 return &empty_initializer;
2102 * Parse a part of an initialiser for a struct or union,
2104 static initializer_t *parse_sub_initializer(type_path_t *path,
2105 type_t *outer_type, size_t top_path_level,
2106 parse_initializer_env_t *env)
2108 if (token.type == '}') {
2109 /* empty initializer */
2110 return create_empty_initializer();
2113 type_t *orig_type = path->top_type;
2114 type_t *type = NULL;
2116 if (orig_type == NULL) {
2117 /* We are initializing an empty compound. */
2119 type = skip_typeref(orig_type);
2122 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2125 designator_t *designator = NULL;
2126 if (token.type == '.' || token.type == '[') {
2127 designator = parse_designation();
2128 goto finish_designator;
2129 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2130 /* GNU-style designator ("identifier: value") */
2131 designator = allocate_ast_zero(sizeof(designator[0]));
2132 designator->source_position = token.source_position;
2133 designator->symbol = token.symbol;
2138 /* reset path to toplevel, evaluate designator from there */
2139 ascend_to(path, top_path_level);
2140 if (!walk_designator(path, designator, false)) {
2141 /* can't continue after designation error */
2145 initializer_t *designator_initializer
2146 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2147 designator_initializer->designator.designator = designator;
2148 ARR_APP1(initializer_t*, initializers, designator_initializer);
2150 orig_type = path->top_type;
2151 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2156 if (token.type == '{') {
2157 if (type != NULL && is_type_scalar(type)) {
2158 sub = parse_scalar_initializer(type, env->must_be_constant);
2162 if (env->entity != NULL) {
2164 "extra brace group at end of initializer for '%Y'",
2165 env->entity->base.symbol);
2167 errorf(HERE, "extra brace group at end of initializer");
2170 descend_into_subtype(path);
2172 add_anchor_token('}');
2173 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2175 rem_anchor_token('}');
2178 ascend_from_subtype(path);
2179 expect('}', end_error);
2181 expect('}', end_error);
2182 goto error_parse_next;
2186 /* must be an expression */
2187 expression_t *expression = parse_assignment_expression();
2188 mark_vars_read(expression, NULL);
2190 if (env->must_be_constant && !is_initializer_constant(expression)) {
2191 errorf(&expression->base.source_position,
2192 "Initialisation expression '%E' is not constant",
2197 /* we are already outside, ... */
2198 if (outer_type == NULL)
2199 goto error_parse_next;
2200 type_t *const outer_type_skip = skip_typeref(outer_type);
2201 if (is_type_compound(outer_type_skip) &&
2202 !outer_type_skip->compound.compound->complete) {
2203 goto error_parse_next;
2208 /* handle { "string" } special case */
2209 if ((expression->kind == EXPR_STRING_LITERAL
2210 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2211 && outer_type != NULL) {
2212 sub = initializer_from_expression(outer_type, expression);
2215 if (token.type != '}' && warning.other) {
2216 warningf(HERE, "excessive elements in initializer for type '%T'",
2219 /* TODO: eat , ... */
2224 /* descend into subtypes until expression matches type */
2226 orig_type = path->top_type;
2227 type = skip_typeref(orig_type);
2229 sub = initializer_from_expression(orig_type, expression);
2233 if (!is_type_valid(type)) {
2236 if (is_type_scalar(type)) {
2237 errorf(&expression->base.source_position,
2238 "expression '%E' doesn't match expected type '%T'",
2239 expression, orig_type);
2243 descend_into_subtype(path);
2247 /* update largest index of top array */
2248 const type_path_entry_t *first = &path->path[0];
2249 type_t *first_type = first->type;
2250 first_type = skip_typeref(first_type);
2251 if (is_type_array(first_type)) {
2252 size_t index = first->v.index;
2253 if (index > path->max_index)
2254 path->max_index = index;
2258 /* append to initializers list */
2259 ARR_APP1(initializer_t*, initializers, sub);
2262 if (warning.other) {
2263 if (env->entity != NULL) {
2264 warningf(HERE, "excess elements in initializer for '%Y'",
2265 env->entity->base.symbol);
2267 warningf(HERE, "excess elements in initializer");
2273 if (token.type == '}') {
2276 expect(',', end_error);
2277 if (token.type == '}') {
2282 /* advance to the next declaration if we are not at the end */
2283 advance_current_object(path, top_path_level);
2284 orig_type = path->top_type;
2285 if (orig_type != NULL)
2286 type = skip_typeref(orig_type);
2292 size_t len = ARR_LEN(initializers);
2293 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2294 initializer_t *result = allocate_ast_zero(size);
2295 result->kind = INITIALIZER_LIST;
2296 result->list.len = len;
2297 memcpy(&result->list.initializers, initializers,
2298 len * sizeof(initializers[0]));
2300 DEL_ARR_F(initializers);
2301 ascend_to(path, top_path_level+1);
2306 skip_initializers();
2307 DEL_ARR_F(initializers);
2308 ascend_to(path, top_path_level+1);
2312 static expression_t *make_size_literal(size_t value)
2314 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2315 literal->base.type = type_size_t;
2318 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2319 literal->literal.value = make_string(buf);
2325 * Parses an initializer. Parsers either a compound literal
2326 * (env->declaration == NULL) or an initializer of a declaration.
2328 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2330 type_t *type = skip_typeref(env->type);
2331 size_t max_index = 0;
2332 initializer_t *result;
2334 if (is_type_scalar(type)) {
2335 result = parse_scalar_initializer(type, env->must_be_constant);
2336 } else if (token.type == '{') {
2340 memset(&path, 0, sizeof(path));
2341 path.top_type = env->type;
2342 path.path = NEW_ARR_F(type_path_entry_t, 0);
2344 descend_into_subtype(&path);
2346 add_anchor_token('}');
2347 result = parse_sub_initializer(&path, env->type, 1, env);
2348 rem_anchor_token('}');
2350 max_index = path.max_index;
2351 DEL_ARR_F(path.path);
2353 expect('}', end_error);
2355 /* parse_scalar_initializer() also works in this case: we simply
2356 * have an expression without {} around it */
2357 result = parse_scalar_initializer(type, env->must_be_constant);
2360 /* §6.7.8:22 array initializers for arrays with unknown size determine
2361 * the array type size */
2362 if (is_type_array(type) && type->array.size_expression == NULL
2363 && result != NULL) {
2365 switch (result->kind) {
2366 case INITIALIZER_LIST:
2367 assert(max_index != 0xdeadbeaf);
2368 size = max_index + 1;
2371 case INITIALIZER_STRING:
2372 size = result->string.string.size;
2375 case INITIALIZER_WIDE_STRING:
2376 size = result->wide_string.string.size;
2379 case INITIALIZER_DESIGNATOR:
2380 case INITIALIZER_VALUE:
2381 /* can happen for parse errors */
2386 internal_errorf(HERE, "invalid initializer type");
2389 type_t *new_type = duplicate_type(type);
2391 new_type->array.size_expression = make_size_literal(size);
2392 new_type->array.size_constant = true;
2393 new_type->array.has_implicit_size = true;
2394 new_type->array.size = size;
2395 env->type = new_type;
2403 static void append_entity(scope_t *scope, entity_t *entity)
2405 if (scope->last_entity != NULL) {
2406 scope->last_entity->base.next = entity;
2408 scope->entities = entity;
2410 entity->base.parent_entity = current_entity;
2411 scope->last_entity = entity;
2415 static compound_t *parse_compound_type_specifier(bool is_struct)
2417 eat(is_struct ? T_struct : T_union);
2419 symbol_t *symbol = NULL;
2420 entity_t *entity = NULL;
2421 attribute_t *attributes = NULL;
2423 if (token.type == T___attribute__) {
2424 attributes = parse_attributes(NULL);
2427 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2428 if (token.type == T_IDENTIFIER) {
2429 /* the compound has a name, check if we have seen it already */
2430 symbol = token.symbol;
2433 entity = get_tag(symbol, kind);
2434 if (entity != NULL) {
2435 if (entity->base.parent_scope != current_scope &&
2436 (token.type == '{' || token.type == ';')) {
2437 /* we're in an inner scope and have a definition. Shadow
2438 * existing definition in outer scope */
2440 } else if (entity->compound.complete && token.type == '{') {
2441 assert(symbol != NULL);
2442 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2443 is_struct ? "struct" : "union", symbol,
2444 &entity->base.source_position);
2445 /* clear members in the hope to avoid further errors */
2446 entity->compound.members.entities = NULL;
2449 } else if (token.type != '{') {
2451 parse_error_expected("while parsing struct type specifier",
2452 T_IDENTIFIER, '{', NULL);
2454 parse_error_expected("while parsing union type specifier",
2455 T_IDENTIFIER, '{', NULL);
2461 if (entity == NULL) {
2462 entity = allocate_entity_zero(kind);
2464 entity->compound.alignment = 1;
2465 entity->base.namespc = NAMESPACE_TAG;
2466 entity->base.source_position = token.source_position;
2467 entity->base.symbol = symbol;
2468 entity->base.parent_scope = current_scope;
2469 if (symbol != NULL) {
2470 environment_push(entity);
2472 append_entity(current_scope, entity);
2475 if (token.type == '{') {
2476 parse_compound_type_entries(&entity->compound);
2478 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2479 if (symbol == NULL) {
2480 assert(anonymous_entity == NULL);
2481 anonymous_entity = entity;
2485 if (attributes != NULL) {
2486 handle_entity_attributes(attributes, entity);
2489 return &entity->compound;
2492 static void parse_enum_entries(type_t *const enum_type)
2496 if (token.type == '}') {
2497 errorf(HERE, "empty enum not allowed");
2502 add_anchor_token('}');
2504 if (token.type != T_IDENTIFIER) {
2505 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2507 rem_anchor_token('}');
2511 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2512 entity->enum_value.enum_type = enum_type;
2513 entity->base.namespc = NAMESPACE_NORMAL;
2514 entity->base.symbol = token.symbol;
2515 entity->base.source_position = token.source_position;
2519 expression_t *value = parse_constant_expression();
2521 value = create_implicit_cast(value, enum_type);
2522 entity->enum_value.value = value;
2527 record_entity(entity, false);
2528 } while (next_if(',') && token.type != '}');
2529 rem_anchor_token('}');
2531 expect('}', end_error);
2537 static type_t *parse_enum_specifier(void)
2543 switch (token.type) {
2545 symbol = token.symbol;
2548 entity = get_tag(symbol, ENTITY_ENUM);
2549 if (entity != NULL) {
2550 if (entity->base.parent_scope != current_scope &&
2551 (token.type == '{' || token.type == ';')) {
2552 /* we're in an inner scope and have a definition. Shadow
2553 * existing definition in outer scope */
2555 } else if (entity->enume.complete && token.type == '{') {
2556 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2557 symbol, &entity->base.source_position);
2568 parse_error_expected("while parsing enum type specifier",
2569 T_IDENTIFIER, '{', NULL);
2573 if (entity == NULL) {
2574 entity = allocate_entity_zero(ENTITY_ENUM);
2575 entity->base.namespc = NAMESPACE_TAG;
2576 entity->base.source_position = token.source_position;
2577 entity->base.symbol = symbol;
2578 entity->base.parent_scope = current_scope;
2581 type_t *const type = allocate_type_zero(TYPE_ENUM);
2582 type->enumt.enume = &entity->enume;
2583 type->enumt.akind = ATOMIC_TYPE_INT;
2585 if (token.type == '{') {
2586 if (symbol != NULL) {
2587 environment_push(entity);
2589 append_entity(current_scope, entity);
2590 entity->enume.complete = true;
2592 parse_enum_entries(type);
2593 parse_attributes(NULL);
2595 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2596 if (symbol == NULL) {
2597 assert(anonymous_entity == NULL);
2598 anonymous_entity = entity;
2600 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2601 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2609 * if a symbol is a typedef to another type, return true
2611 static bool is_typedef_symbol(symbol_t *symbol)
2613 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2614 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2617 static type_t *parse_typeof(void)
2623 expect('(', end_error);
2624 add_anchor_token(')');
2626 expression_t *expression = NULL;
2628 bool old_type_prop = in_type_prop;
2629 bool old_gcc_extension = in_gcc_extension;
2630 in_type_prop = true;
2632 while (next_if(T___extension__)) {
2633 /* This can be a prefix to a typename or an expression. */
2634 in_gcc_extension = true;
2636 switch (token.type) {
2638 if (is_typedef_symbol(token.symbol)) {
2640 type = parse_typename();
2643 expression = parse_expression();
2644 type = revert_automatic_type_conversion(expression);
2648 in_type_prop = old_type_prop;
2649 in_gcc_extension = old_gcc_extension;
2651 rem_anchor_token(')');
2652 expect(')', end_error);
2654 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2655 typeof_type->typeoft.expression = expression;
2656 typeof_type->typeoft.typeof_type = type;
2663 typedef enum specifiers_t {
2664 SPECIFIER_SIGNED = 1 << 0,
2665 SPECIFIER_UNSIGNED = 1 << 1,
2666 SPECIFIER_LONG = 1 << 2,
2667 SPECIFIER_INT = 1 << 3,
2668 SPECIFIER_DOUBLE = 1 << 4,
2669 SPECIFIER_CHAR = 1 << 5,
2670 SPECIFIER_WCHAR_T = 1 << 6,
2671 SPECIFIER_SHORT = 1 << 7,
2672 SPECIFIER_LONG_LONG = 1 << 8,
2673 SPECIFIER_FLOAT = 1 << 9,
2674 SPECIFIER_BOOL = 1 << 10,
2675 SPECIFIER_VOID = 1 << 11,
2676 SPECIFIER_INT8 = 1 << 12,
2677 SPECIFIER_INT16 = 1 << 13,
2678 SPECIFIER_INT32 = 1 << 14,
2679 SPECIFIER_INT64 = 1 << 15,
2680 SPECIFIER_INT128 = 1 << 16,
2681 SPECIFIER_COMPLEX = 1 << 17,
2682 SPECIFIER_IMAGINARY = 1 << 18,
2685 static type_t *get_typedef_type(symbol_t *symbol)
2687 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2688 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2691 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2692 type->typedeft.typedefe = &entity->typedefe;
2697 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2699 expect('(', end_error);
2701 attribute_property_argument_t *property
2702 = allocate_ast_zero(sizeof(*property));
2705 if (token.type != T_IDENTIFIER) {
2706 parse_error_expected("while parsing property declspec",
2707 T_IDENTIFIER, NULL);
2712 symbol_t *symbol = token.symbol;
2714 if (strcmp(symbol->string, "put") == 0) {
2716 } else if (strcmp(symbol->string, "get") == 0) {
2719 errorf(HERE, "expected put or get in property declspec");
2722 expect('=', end_error);
2723 if (token.type != T_IDENTIFIER) {
2724 parse_error_expected("while parsing property declspec",
2725 T_IDENTIFIER, NULL);
2729 property->put_symbol = token.symbol;
2731 property->get_symbol = token.symbol;
2734 } while (next_if(','));
2736 attribute->a.property = property;
2738 expect(')', end_error);
2744 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2746 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2747 if (next_if(T_restrict)) {
2748 kind = ATTRIBUTE_MS_RESTRICT;
2749 } else if (token.type == T_IDENTIFIER) {
2750 const char *name = token.symbol->string;
2752 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2754 const char *attribute_name = get_attribute_name(k);
2755 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2761 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2762 warningf(HERE, "unknown __declspec '%s' ignored", name);
2765 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2769 attribute_t *attribute = allocate_attribute_zero(kind);
2771 if (kind == ATTRIBUTE_MS_PROPERTY) {
2772 return parse_attribute_ms_property(attribute);
2775 /* parse arguments */
2777 attribute->a.arguments = parse_attribute_arguments();
2782 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2786 expect('(', end_error);
2791 add_anchor_token(')');
2793 attribute_t **anchor = &first;
2795 while (*anchor != NULL)
2796 anchor = &(*anchor)->next;
2798 attribute_t *attribute
2799 = parse_microsoft_extended_decl_modifier_single();
2800 if (attribute == NULL)
2803 *anchor = attribute;
2804 anchor = &attribute->next;
2805 } while (next_if(','));
2807 rem_anchor_token(')');
2808 expect(')', end_error);
2812 rem_anchor_token(')');
2816 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2818 entity_t *entity = allocate_entity_zero(kind);
2819 entity->base.namespc = NAMESPACE_NORMAL;
2820 entity->base.source_position = *HERE;
2821 entity->base.symbol = symbol;
2822 if (is_declaration(entity)) {
2823 entity->declaration.type = type_error_type;
2824 entity->declaration.implicit = true;
2825 } else if (kind == ENTITY_TYPEDEF) {
2826 entity->typedefe.type = type_error_type;
2827 entity->typedefe.builtin = true;
2829 if (kind != ENTITY_COMPOUND_MEMBER)
2830 record_entity(entity, false);
2834 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2836 type_t *type = NULL;
2837 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2838 unsigned type_specifiers = 0;
2839 bool newtype = false;
2840 bool saw_error = false;
2841 bool old_gcc_extension = in_gcc_extension;
2843 specifiers->source_position = token.source_position;
2846 specifiers->attributes = parse_attributes(specifiers->attributes);
2848 switch (token.type) {
2850 #define MATCH_STORAGE_CLASS(token, class) \
2852 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2853 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2855 specifiers->storage_class = class; \
2856 if (specifiers->thread_local) \
2857 goto check_thread_storage_class; \
2861 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2862 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2863 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2864 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2865 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2868 specifiers->attributes
2869 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2873 if (specifiers->thread_local) {
2874 errorf(HERE, "duplicate '__thread'");
2876 specifiers->thread_local = true;
2877 check_thread_storage_class:
2878 switch (specifiers->storage_class) {
2879 case STORAGE_CLASS_EXTERN:
2880 case STORAGE_CLASS_NONE:
2881 case STORAGE_CLASS_STATIC:
2885 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2886 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2887 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2888 wrong_thread_storage_class:
2889 errorf(HERE, "'__thread' used with '%s'", wrong);
2896 /* type qualifiers */
2897 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2899 qualifiers |= qualifier; \
2903 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2904 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2905 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2906 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2907 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2908 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2909 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2910 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2912 case T___extension__:
2914 in_gcc_extension = true;
2917 /* type specifiers */
2918 #define MATCH_SPECIFIER(token, specifier, name) \
2920 if (type_specifiers & specifier) { \
2921 errorf(HERE, "multiple " name " type specifiers given"); \
2923 type_specifiers |= specifier; \
2928 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2929 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2930 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2931 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2932 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2933 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2934 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2935 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2936 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2937 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2938 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2939 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2940 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2941 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2942 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2943 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2944 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2945 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2949 specifiers->is_inline = true;
2953 case T__forceinline:
2955 specifiers->modifiers |= DM_FORCEINLINE;
2960 if (type_specifiers & SPECIFIER_LONG_LONG) {
2961 errorf(HERE, "multiple type specifiers given");
2962 } else if (type_specifiers & SPECIFIER_LONG) {
2963 type_specifiers |= SPECIFIER_LONG_LONG;
2965 type_specifiers |= SPECIFIER_LONG;
2970 #define CHECK_DOUBLE_TYPE() \
2971 if ( type != NULL) \
2972 errorf(HERE, "multiple data types in declaration specifiers");
2975 CHECK_DOUBLE_TYPE();
2976 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2978 type->compound.compound = parse_compound_type_specifier(true);
2981 CHECK_DOUBLE_TYPE();
2982 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2983 type->compound.compound = parse_compound_type_specifier(false);
2986 CHECK_DOUBLE_TYPE();
2987 type = parse_enum_specifier();
2990 CHECK_DOUBLE_TYPE();
2991 type = parse_typeof();
2993 case T___builtin_va_list:
2994 CHECK_DOUBLE_TYPE();
2995 type = duplicate_type(type_valist);
2999 case T_IDENTIFIER: {
3000 /* only parse identifier if we haven't found a type yet */
3001 if (type != NULL || type_specifiers != 0) {
3002 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3003 * declaration, so it doesn't generate errors about expecting '(' or
3005 switch (look_ahead(1)->type) {
3012 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3016 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3021 goto finish_specifiers;
3025 type_t *const typedef_type = get_typedef_type(token.symbol);
3026 if (typedef_type == NULL) {
3027 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3028 * declaration, so it doesn't generate 'implicit int' followed by more
3029 * errors later on. */
3030 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3036 errorf(HERE, "%K does not name a type", &token);
3039 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3041 type = allocate_type_zero(TYPE_TYPEDEF);
3042 type->typedeft.typedefe = &entity->typedefe;
3046 if (la1_type == '&' || la1_type == '*')
3047 goto finish_specifiers;
3052 goto finish_specifiers;
3057 type = typedef_type;
3061 /* function specifier */
3063 goto finish_specifiers;
3068 specifiers->attributes = parse_attributes(specifiers->attributes);
3070 in_gcc_extension = old_gcc_extension;
3072 if (type == NULL || (saw_error && type_specifiers != 0)) {
3073 atomic_type_kind_t atomic_type;
3075 /* match valid basic types */
3076 switch (type_specifiers) {
3077 case SPECIFIER_VOID:
3078 atomic_type = ATOMIC_TYPE_VOID;
3080 case SPECIFIER_WCHAR_T:
3081 atomic_type = ATOMIC_TYPE_WCHAR_T;
3083 case SPECIFIER_CHAR:
3084 atomic_type = ATOMIC_TYPE_CHAR;
3086 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3087 atomic_type = ATOMIC_TYPE_SCHAR;
3089 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3090 atomic_type = ATOMIC_TYPE_UCHAR;
3092 case SPECIFIER_SHORT:
3093 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3094 case SPECIFIER_SHORT | SPECIFIER_INT:
3095 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3096 atomic_type = ATOMIC_TYPE_SHORT;
3098 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3099 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3100 atomic_type = ATOMIC_TYPE_USHORT;
3103 case SPECIFIER_SIGNED:
3104 case SPECIFIER_SIGNED | SPECIFIER_INT:
3105 atomic_type = ATOMIC_TYPE_INT;
3107 case SPECIFIER_UNSIGNED:
3108 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3109 atomic_type = ATOMIC_TYPE_UINT;
3111 case SPECIFIER_LONG:
3112 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3113 case SPECIFIER_LONG | SPECIFIER_INT:
3114 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3115 atomic_type = ATOMIC_TYPE_LONG;
3117 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3118 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3119 atomic_type = ATOMIC_TYPE_ULONG;
3122 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3123 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3124 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3125 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3127 atomic_type = ATOMIC_TYPE_LONGLONG;
3128 goto warn_about_long_long;
3130 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3131 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3133 atomic_type = ATOMIC_TYPE_ULONGLONG;
3134 warn_about_long_long:
3135 if (warning.long_long) {
3136 warningf(&specifiers->source_position,
3137 "ISO C90 does not support 'long long'");
3141 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3142 atomic_type = unsigned_int8_type_kind;
3145 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3146 atomic_type = unsigned_int16_type_kind;
3149 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3150 atomic_type = unsigned_int32_type_kind;
3153 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3154 atomic_type = unsigned_int64_type_kind;
3157 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3158 atomic_type = unsigned_int128_type_kind;
3161 case SPECIFIER_INT8:
3162 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3163 atomic_type = int8_type_kind;
3166 case SPECIFIER_INT16:
3167 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3168 atomic_type = int16_type_kind;
3171 case SPECIFIER_INT32:
3172 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3173 atomic_type = int32_type_kind;
3176 case SPECIFIER_INT64:
3177 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3178 atomic_type = int64_type_kind;
3181 case SPECIFIER_INT128:
3182 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3183 atomic_type = int128_type_kind;
3186 case SPECIFIER_FLOAT:
3187 atomic_type = ATOMIC_TYPE_FLOAT;
3189 case SPECIFIER_DOUBLE:
3190 atomic_type = ATOMIC_TYPE_DOUBLE;
3192 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3193 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3195 case SPECIFIER_BOOL:
3196 atomic_type = ATOMIC_TYPE_BOOL;
3198 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3199 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3200 atomic_type = ATOMIC_TYPE_FLOAT;
3202 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3203 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3204 atomic_type = ATOMIC_TYPE_DOUBLE;
3206 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3207 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3208 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3211 /* invalid specifier combination, give an error message */
3212 if (type_specifiers == 0) {
3216 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3217 if (!(c_mode & _CXX) && !strict_mode) {
3218 if (warning.implicit_int) {
3219 warningf(HERE, "no type specifiers in declaration, using 'int'");
3221 atomic_type = ATOMIC_TYPE_INT;
3224 errorf(HERE, "no type specifiers given in declaration");
3226 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3227 (type_specifiers & SPECIFIER_UNSIGNED)) {
3228 errorf(HERE, "signed and unsigned specifiers given");
3229 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3230 errorf(HERE, "only integer types can be signed or unsigned");
3232 errorf(HERE, "multiple datatypes in declaration");
3237 if (type_specifiers & SPECIFIER_COMPLEX) {
3238 type = allocate_type_zero(TYPE_COMPLEX);
3239 type->complex.akind = atomic_type;
3240 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3241 type = allocate_type_zero(TYPE_IMAGINARY);
3242 type->imaginary.akind = atomic_type;
3244 type = allocate_type_zero(TYPE_ATOMIC);
3245 type->atomic.akind = atomic_type;
3248 } else if (type_specifiers != 0) {
3249 errorf(HERE, "multiple datatypes in declaration");
3252 /* FIXME: check type qualifiers here */
3253 type->base.qualifiers = qualifiers;
3256 type = identify_new_type(type);
3258 type = typehash_insert(type);
3261 if (specifiers->attributes != NULL)
3262 type = handle_type_attributes(specifiers->attributes, type);
3263 specifiers->type = type;
3267 specifiers->type = type_error_type;
3270 static type_qualifiers_t parse_type_qualifiers(void)
3272 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3275 switch (token.type) {
3276 /* type qualifiers */
3277 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3278 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3279 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3280 /* microsoft extended type modifiers */
3281 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3282 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3283 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3284 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3285 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3294 * Parses an K&R identifier list
3296 static void parse_identifier_list(scope_t *scope)
3299 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3300 entity->base.source_position = token.source_position;
3301 entity->base.namespc = NAMESPACE_NORMAL;
3302 entity->base.symbol = token.symbol;
3303 /* a K&R parameter has no type, yet */
3307 append_entity(scope, entity);
3308 } while (next_if(',') && token.type == T_IDENTIFIER);
3311 static entity_t *parse_parameter(void)
3313 declaration_specifiers_t specifiers;
3314 memset(&specifiers, 0, sizeof(specifiers));
3316 parse_declaration_specifiers(&specifiers);
3318 entity_t *entity = parse_declarator(&specifiers,
3319 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3320 anonymous_entity = NULL;
3324 static void semantic_parameter_incomplete(const entity_t *entity)
3326 assert(entity->kind == ENTITY_PARAMETER);
3328 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3329 * list in a function declarator that is part of a
3330 * definition of that function shall not have
3331 * incomplete type. */
3332 type_t *type = skip_typeref(entity->declaration.type);
3333 if (is_type_incomplete(type)) {
3334 errorf(&entity->base.source_position,
3335 "parameter '%#T' has incomplete type",
3336 entity->declaration.type, entity->base.symbol);
3340 static bool has_parameters(void)
3342 /* func(void) is not a parameter */
3343 if (token.type == T_IDENTIFIER) {
3344 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3347 if (entity->kind != ENTITY_TYPEDEF)
3349 if (skip_typeref(entity->typedefe.type) != type_void)
3351 } else if (token.type != T_void) {
3354 if (look_ahead(1)->type != ')')
3361 * Parses function type parameters (and optionally creates variable_t entities
3362 * for them in a scope)
3364 static void parse_parameters(function_type_t *type, scope_t *scope)
3367 add_anchor_token(')');
3368 int saved_comma_state = save_and_reset_anchor_state(',');
3370 if (token.type == T_IDENTIFIER &&
3371 !is_typedef_symbol(token.symbol)) {
3372 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3373 if (la1_type == ',' || la1_type == ')') {
3374 type->kr_style_parameters = true;
3375 parse_identifier_list(scope);
3376 goto parameters_finished;
3380 if (token.type == ')') {
3381 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3382 if (!(c_mode & _CXX))
3383 type->unspecified_parameters = true;
3384 goto parameters_finished;
3387 if (has_parameters()) {
3388 function_parameter_t **anchor = &type->parameters;
3390 switch (token.type) {
3393 type->variadic = true;
3394 goto parameters_finished;
3397 case T___extension__:
3400 entity_t *entity = parse_parameter();
3401 if (entity->kind == ENTITY_TYPEDEF) {
3402 errorf(&entity->base.source_position,
3403 "typedef not allowed as function parameter");
3406 assert(is_declaration(entity));
3408 semantic_parameter_incomplete(entity);
3410 function_parameter_t *const parameter =
3411 allocate_parameter(entity->declaration.type);
3413 if (scope != NULL) {
3414 append_entity(scope, entity);
3417 *anchor = parameter;
3418 anchor = ¶meter->next;
3423 goto parameters_finished;
3425 } while (next_if(','));
3429 parameters_finished:
3430 rem_anchor_token(')');
3431 expect(')', end_error);
3434 restore_anchor_state(',', saved_comma_state);
3437 typedef enum construct_type_kind_t {
3440 CONSTRUCT_REFERENCE,
3443 } construct_type_kind_t;
3445 typedef union construct_type_t construct_type_t;
3447 typedef struct construct_type_base_t {
3448 construct_type_kind_t kind;
3449 source_position_t pos;
3450 construct_type_t *next;
3451 } construct_type_base_t;
3453 typedef struct parsed_pointer_t {
3454 construct_type_base_t base;
3455 type_qualifiers_t type_qualifiers;
3456 variable_t *base_variable; /**< MS __based extension. */
3459 typedef struct parsed_reference_t {
3460 construct_type_base_t base;
3461 } parsed_reference_t;
3463 typedef struct construct_function_type_t {
3464 construct_type_base_t base;
3465 type_t *function_type;
3466 } construct_function_type_t;
3468 typedef struct parsed_array_t {
3469 construct_type_base_t base;
3470 type_qualifiers_t type_qualifiers;
3476 union construct_type_t {
3477 construct_type_kind_t kind;
3478 construct_type_base_t base;
3479 parsed_pointer_t pointer;
3480 parsed_reference_t reference;
3481 construct_function_type_t function;
3482 parsed_array_t array;
3485 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3487 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3488 memset(cons, 0, size);
3490 cons->base.pos = *HERE;
3495 static construct_type_t *parse_pointer_declarator(void)
3497 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3499 cons->pointer.type_qualifiers = parse_type_qualifiers();
3500 //cons->pointer.base_variable = base_variable;
3505 /* ISO/IEC 14882:1998(E) §8.3.2 */
3506 static construct_type_t *parse_reference_declarator(void)
3508 if (!(c_mode & _CXX))
3509 errorf(HERE, "references are only available for C++");
3511 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3518 static construct_type_t *parse_array_declarator(void)
3520 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3521 parsed_array_t *const array = &cons->array;
3524 add_anchor_token(']');
3526 bool is_static = next_if(T_static);
3528 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3531 is_static = next_if(T_static);
3533 array->type_qualifiers = type_qualifiers;
3534 array->is_static = is_static;
3536 expression_t *size = NULL;
3537 if (token.type == '*' && look_ahead(1)->type == ']') {
3538 array->is_variable = true;
3540 } else if (token.type != ']') {
3541 size = parse_assignment_expression();
3543 /* §6.7.5.2:1 Array size must have integer type */
3544 type_t *const orig_type = size->base.type;
3545 type_t *const type = skip_typeref(orig_type);
3546 if (!is_type_integer(type) && is_type_valid(type)) {
3547 errorf(&size->base.source_position,
3548 "array size '%E' must have integer type but has type '%T'",
3553 mark_vars_read(size, NULL);
3556 if (is_static && size == NULL)
3557 errorf(HERE, "static array parameters require a size");
3559 rem_anchor_token(']');
3560 expect(']', end_error);
3567 static construct_type_t *parse_function_declarator(scope_t *scope)
3569 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3571 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3572 function_type_t *ftype = &type->function;
3574 ftype->linkage = current_linkage;
3575 ftype->calling_convention = CC_DEFAULT;
3577 parse_parameters(ftype, scope);
3579 cons->function.function_type = type;
3584 typedef struct parse_declarator_env_t {
3585 bool may_be_abstract : 1;
3586 bool must_be_abstract : 1;
3587 decl_modifiers_t modifiers;
3589 source_position_t source_position;
3591 attribute_t *attributes;
3592 } parse_declarator_env_t;
3595 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3597 /* construct a single linked list of construct_type_t's which describe
3598 * how to construct the final declarator type */
3599 construct_type_t *first = NULL;
3600 construct_type_t **anchor = &first;
3602 env->attributes = parse_attributes(env->attributes);
3605 construct_type_t *type;
3606 //variable_t *based = NULL; /* MS __based extension */
3607 switch (token.type) {
3609 type = parse_reference_declarator();
3613 panic("based not supported anymore");
3618 type = parse_pointer_declarator();
3622 goto ptr_operator_end;
3626 anchor = &type->base.next;
3628 /* TODO: find out if this is correct */
3629 env->attributes = parse_attributes(env->attributes);
3633 construct_type_t *inner_types = NULL;
3635 switch (token.type) {
3637 if (env->must_be_abstract) {
3638 errorf(HERE, "no identifier expected in typename");
3640 env->symbol = token.symbol;
3641 env->source_position = token.source_position;
3646 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3647 * interpreted as ``function with no parameter specification'', rather
3648 * than redundant parentheses around the omitted identifier. */
3649 if (look_ahead(1)->type != ')') {
3651 add_anchor_token(')');
3652 inner_types = parse_inner_declarator(env);
3653 if (inner_types != NULL) {
3654 /* All later declarators only modify the return type */
3655 env->must_be_abstract = true;
3657 rem_anchor_token(')');
3658 expect(')', end_error);
3659 } else if (!env->may_be_abstract) {
3660 errorf(HERE, "declarator must have a name");
3665 if (env->may_be_abstract)
3667 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3673 construct_type_t **const p = anchor;
3676 construct_type_t *type;
3677 switch (token.type) {
3679 scope_t *scope = NULL;
3680 if (!env->must_be_abstract) {
3681 scope = &env->parameters;
3684 type = parse_function_declarator(scope);
3688 type = parse_array_declarator();
3691 goto declarator_finished;
3694 /* insert in the middle of the list (at p) */
3695 type->base.next = *p;
3698 anchor = &type->base.next;
3701 declarator_finished:
3702 /* append inner_types at the end of the list, we don't to set anchor anymore
3703 * as it's not needed anymore */
3704 *anchor = inner_types;
3711 static type_t *construct_declarator_type(construct_type_t *construct_list,
3714 construct_type_t *iter = construct_list;
3715 for (; iter != NULL; iter = iter->base.next) {
3716 source_position_t const* const pos = &iter->base.pos;
3717 switch (iter->kind) {
3718 case CONSTRUCT_INVALID:
3720 case CONSTRUCT_FUNCTION: {
3721 construct_function_type_t *function = &iter->function;
3722 type_t *function_type = function->function_type;
3724 function_type->function.return_type = type;
3726 type_t *skipped_return_type = skip_typeref(type);
3728 if (is_type_function(skipped_return_type)) {
3729 errorf(pos, "function returning function is not allowed");
3730 } else if (is_type_array(skipped_return_type)) {
3731 errorf(pos, "function returning array is not allowed");
3733 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3734 warningf(pos, "type qualifiers in return type of function type are meaningless");
3738 /* The function type was constructed earlier. Freeing it here will
3739 * destroy other types. */
3740 type = typehash_insert(function_type);
3744 case CONSTRUCT_POINTER: {
3745 if (is_type_reference(skip_typeref(type)))
3746 errorf(pos, "cannot declare a pointer to reference");
3748 parsed_pointer_t *pointer = &iter->pointer;
3749 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3753 case CONSTRUCT_REFERENCE:
3754 if (is_type_reference(skip_typeref(type)))
3755 errorf(pos, "cannot declare a reference to reference");
3757 type = make_reference_type(type);
3760 case CONSTRUCT_ARRAY: {
3761 if (is_type_reference(skip_typeref(type)))
3762 errorf(pos, "cannot declare an array of references");
3764 parsed_array_t *array = &iter->array;
3765 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3767 expression_t *size_expression = array->size;
3768 if (size_expression != NULL) {
3770 = create_implicit_cast(size_expression, type_size_t);
3773 array_type->base.qualifiers = array->type_qualifiers;
3774 array_type->array.element_type = type;
3775 array_type->array.is_static = array->is_static;
3776 array_type->array.is_variable = array->is_variable;
3777 array_type->array.size_expression = size_expression;
3779 if (size_expression != NULL) {
3780 switch (is_constant_expression(size_expression)) {
3781 case EXPR_CLASS_CONSTANT: {
3782 long const size = fold_constant_to_int(size_expression);
3783 array_type->array.size = size;
3784 array_type->array.size_constant = true;
3785 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3786 * have a value greater than zero. */
3788 if (size < 0 || !GNU_MODE) {
3789 errorf(&size_expression->base.source_position,
3790 "size of array must be greater than zero");
3791 } else if (warning.other) {
3792 warningf(&size_expression->base.source_position,
3793 "zero length arrays are a GCC extension");
3799 case EXPR_CLASS_VARIABLE:
3800 array_type->array.is_vla = true;
3803 case EXPR_CLASS_ERROR:
3808 type_t *skipped_type = skip_typeref(type);
3810 if (is_type_incomplete(skipped_type)) {
3811 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3812 } else if (is_type_function(skipped_type)) {
3813 errorf(pos, "array of functions is not allowed");
3815 type = identify_new_type(array_type);
3819 internal_errorf(pos, "invalid type construction found");
3825 static type_t *automatic_type_conversion(type_t *orig_type);
3827 static type_t *semantic_parameter(const source_position_t *pos,
3829 const declaration_specifiers_t *specifiers,
3832 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3833 * shall be adjusted to ``qualified pointer to type'',
3835 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3836 * type'' shall be adjusted to ``pointer to function
3837 * returning type'', as in 6.3.2.1. */
3838 type = automatic_type_conversion(type);
3840 if (specifiers->is_inline && is_type_valid(type)) {
3841 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3844 /* §6.9.1:6 The declarations in the declaration list shall contain
3845 * no storage-class specifier other than register and no
3846 * initializations. */
3847 if (specifiers->thread_local || (
3848 specifiers->storage_class != STORAGE_CLASS_NONE &&
3849 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3851 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3854 /* delay test for incomplete type, because we might have (void)
3855 * which is legal but incomplete... */
3860 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3861 declarator_flags_t flags)
3863 parse_declarator_env_t env;
3864 memset(&env, 0, sizeof(env));
3865 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3867 construct_type_t *construct_type = parse_inner_declarator(&env);
3869 construct_declarator_type(construct_type, specifiers->type);
3870 type_t *type = skip_typeref(orig_type);
3872 if (construct_type != NULL) {
3873 obstack_free(&temp_obst, construct_type);
3876 attribute_t *attributes = parse_attributes(env.attributes);
3877 /* append (shared) specifier attribute behind attributes of this
3879 attribute_t **anchor = &attributes;
3880 while (*anchor != NULL)
3881 anchor = &(*anchor)->next;
3882 *anchor = specifiers->attributes;
3885 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3886 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3887 entity->base.namespc = NAMESPACE_NORMAL;
3888 entity->base.symbol = env.symbol;
3889 entity->base.source_position = env.source_position;
3890 entity->typedefe.type = orig_type;
3892 if (anonymous_entity != NULL) {
3893 if (is_type_compound(type)) {
3894 assert(anonymous_entity->compound.alias == NULL);
3895 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3896 anonymous_entity->kind == ENTITY_UNION);
3897 anonymous_entity->compound.alias = entity;
3898 anonymous_entity = NULL;
3899 } else if (is_type_enum(type)) {
3900 assert(anonymous_entity->enume.alias == NULL);
3901 assert(anonymous_entity->kind == ENTITY_ENUM);
3902 anonymous_entity->enume.alias = entity;
3903 anonymous_entity = NULL;
3907 /* create a declaration type entity */
3908 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3909 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3911 if (env.symbol != NULL) {
3912 if (specifiers->is_inline && is_type_valid(type)) {
3913 errorf(&env.source_position,
3914 "compound member '%Y' declared 'inline'", env.symbol);
3917 if (specifiers->thread_local ||
3918 specifiers->storage_class != STORAGE_CLASS_NONE) {
3919 errorf(&env.source_position,
3920 "compound member '%Y' must have no storage class",
3924 } else if (flags & DECL_IS_PARAMETER) {
3925 orig_type = semantic_parameter(&env.source_position, orig_type,
3926 specifiers, env.symbol);
3928 entity = allocate_entity_zero(ENTITY_PARAMETER);
3929 } else if (is_type_function(type)) {
3930 entity = allocate_entity_zero(ENTITY_FUNCTION);
3932 entity->function.is_inline = specifiers->is_inline;
3933 entity->function.parameters = env.parameters;
3935 if (env.symbol != NULL) {
3936 /* this needs fixes for C++ */
3937 bool in_function_scope = current_function != NULL;
3939 if (specifiers->thread_local || (
3940 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3941 specifiers->storage_class != STORAGE_CLASS_NONE &&
3942 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3944 errorf(&env.source_position,
3945 "invalid storage class for function '%Y'", env.symbol);
3949 entity = allocate_entity_zero(ENTITY_VARIABLE);
3951 entity->variable.thread_local = specifiers->thread_local;
3953 if (env.symbol != NULL) {
3954 if (specifiers->is_inline && is_type_valid(type)) {
3955 errorf(&env.source_position,
3956 "variable '%Y' declared 'inline'", env.symbol);
3959 bool invalid_storage_class = false;
3960 if (current_scope == file_scope) {
3961 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3962 specifiers->storage_class != STORAGE_CLASS_NONE &&
3963 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3964 invalid_storage_class = true;
3967 if (specifiers->thread_local &&
3968 specifiers->storage_class == STORAGE_CLASS_NONE) {
3969 invalid_storage_class = true;
3972 if (invalid_storage_class) {
3973 errorf(&env.source_position,
3974 "invalid storage class for variable '%Y'", env.symbol);
3979 if (env.symbol != NULL) {
3980 entity->base.symbol = env.symbol;
3981 entity->base.source_position = env.source_position;
3983 entity->base.source_position = specifiers->source_position;
3985 entity->base.namespc = NAMESPACE_NORMAL;
3986 entity->declaration.type = orig_type;
3987 entity->declaration.alignment = get_type_alignment(orig_type);
3988 entity->declaration.modifiers = env.modifiers;
3989 entity->declaration.attributes = attributes;
3991 storage_class_t storage_class = specifiers->storage_class;
3992 entity->declaration.declared_storage_class = storage_class;
3994 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3995 storage_class = STORAGE_CLASS_AUTO;
3996 entity->declaration.storage_class = storage_class;
3999 if (attributes != NULL) {
4000 handle_entity_attributes(attributes, entity);
4006 static type_t *parse_abstract_declarator(type_t *base_type)
4008 parse_declarator_env_t env;
4009 memset(&env, 0, sizeof(env));
4010 env.may_be_abstract = true;
4011 env.must_be_abstract = true;
4013 construct_type_t *construct_type = parse_inner_declarator(&env);
4015 type_t *result = construct_declarator_type(construct_type, base_type);
4016 if (construct_type != NULL) {
4017 obstack_free(&temp_obst, construct_type);
4019 result = handle_type_attributes(env.attributes, result);
4025 * Check if the declaration of main is suspicious. main should be a
4026 * function with external linkage, returning int, taking either zero
4027 * arguments, two, or three arguments of appropriate types, ie.
4029 * int main([ int argc, char **argv [, char **env ] ]).
4031 * @param decl the declaration to check
4032 * @param type the function type of the declaration
4034 static void check_main(const entity_t *entity)
4036 const source_position_t *pos = &entity->base.source_position;
4037 if (entity->kind != ENTITY_FUNCTION) {
4038 warningf(pos, "'main' is not a function");
4042 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4043 warningf(pos, "'main' is normally a non-static function");
4046 type_t *type = skip_typeref(entity->declaration.type);
4047 assert(is_type_function(type));
4049 function_type_t *func_type = &type->function;
4050 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4051 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4052 func_type->return_type);
4054 const function_parameter_t *parm = func_type->parameters;
4056 type_t *const first_type = skip_typeref(parm->type);
4057 type_t *const first_type_unqual = get_unqualified_type(first_type);
4058 if (!types_compatible(first_type_unqual, type_int)) {
4060 "first argument of 'main' should be 'int', but is '%T'",
4065 type_t *const second_type = skip_typeref(parm->type);
4066 type_t *const second_type_unqual
4067 = get_unqualified_type(second_type);
4068 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4069 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'",
4074 type_t *const third_type = skip_typeref(parm->type);
4075 type_t *const third_type_unqual
4076 = get_unqualified_type(third_type);
4077 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4078 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'",
4083 goto warn_arg_count;
4087 warningf(pos, "'main' takes only zero, two or three arguments");
4093 * Check if a symbol is the equal to "main".
4095 static bool is_sym_main(const symbol_t *const sym)
4097 return strcmp(sym->string, "main") == 0;
4100 static void error_redefined_as_different_kind(const source_position_t *pos,
4101 const entity_t *old, entity_kind_t new_kind)
4103 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4104 get_entity_kind_name(old->kind), old->base.symbol,
4105 get_entity_kind_name(new_kind), &old->base.source_position);
4108 static bool is_entity_valid(entity_t *const ent)
4110 if (is_declaration(ent)) {
4111 return is_type_valid(skip_typeref(ent->declaration.type));
4112 } else if (ent->kind == ENTITY_TYPEDEF) {
4113 return is_type_valid(skip_typeref(ent->typedefe.type));
4118 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4120 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4121 if (attributes_equal(tattr, attr))
4128 * test wether new_list contains any attributes not included in old_list
4130 static bool has_new_attributes(const attribute_t *old_list,
4131 const attribute_t *new_list)
4133 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4134 if (!contains_attribute(old_list, attr))
4141 * Merge in attributes from an attribute list (probably from a previous
4142 * declaration with the same name). Warning: destroys the old structure
4143 * of the attribute list - don't reuse attributes after this call.
4145 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4148 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4150 if (contains_attribute(decl->attributes, attr))
4153 /* move attribute to new declarations attributes list */
4154 attr->next = decl->attributes;
4155 decl->attributes = attr;
4160 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4161 * for various problems that occur for multiple definitions
4163 entity_t *record_entity(entity_t *entity, const bool is_definition)
4165 const symbol_t *const symbol = entity->base.symbol;
4166 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4167 const source_position_t *pos = &entity->base.source_position;
4169 /* can happen in error cases */
4173 entity_t *const previous_entity = get_entity(symbol, namespc);
4174 /* pushing the same entity twice will break the stack structure */
4175 assert(previous_entity != entity);
4177 if (entity->kind == ENTITY_FUNCTION) {
4178 type_t *const orig_type = entity->declaration.type;
4179 type_t *const type = skip_typeref(orig_type);
4181 assert(is_type_function(type));
4182 if (type->function.unspecified_parameters &&
4183 warning.strict_prototypes &&
4184 previous_entity == NULL) {
4185 warningf(pos, "function declaration '%#T' is not a prototype",
4189 if (warning.main && current_scope == file_scope
4190 && is_sym_main(symbol)) {
4195 if (is_declaration(entity) &&
4196 warning.nested_externs &&
4197 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4198 current_scope != file_scope) {
4199 warningf(pos, "nested extern declaration of '%#T'",
4200 entity->declaration.type, symbol);
4203 if (previous_entity != NULL) {
4204 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4205 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4206 assert(previous_entity->kind == ENTITY_PARAMETER);
4208 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4209 entity->declaration.type, symbol,
4210 previous_entity->declaration.type, symbol,
4211 &previous_entity->base.source_position);
4215 if (previous_entity->base.parent_scope == current_scope) {
4216 if (previous_entity->kind != entity->kind) {
4217 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4218 error_redefined_as_different_kind(pos, previous_entity,
4223 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4224 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4225 symbol, &previous_entity->base.source_position);
4228 if (previous_entity->kind == ENTITY_TYPEDEF) {
4229 /* TODO: C++ allows this for exactly the same type */
4230 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4231 symbol, &previous_entity->base.source_position);
4235 /* at this point we should have only VARIABLES or FUNCTIONS */
4236 assert(is_declaration(previous_entity) && is_declaration(entity));
4238 declaration_t *const prev_decl = &previous_entity->declaration;
4239 declaration_t *const decl = &entity->declaration;
4241 /* can happen for K&R style declarations */
4242 if (prev_decl->type == NULL &&
4243 previous_entity->kind == ENTITY_PARAMETER &&
4244 entity->kind == ENTITY_PARAMETER) {
4245 prev_decl->type = decl->type;
4246 prev_decl->storage_class = decl->storage_class;
4247 prev_decl->declared_storage_class = decl->declared_storage_class;
4248 prev_decl->modifiers = decl->modifiers;
4249 return previous_entity;
4252 type_t *const orig_type = decl->type;
4253 assert(orig_type != NULL);
4254 type_t *const type = skip_typeref(orig_type);
4255 type_t *const prev_type = skip_typeref(prev_decl->type);
4257 if (!types_compatible(type, prev_type)) {
4259 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4260 orig_type, symbol, prev_decl->type, symbol,
4261 &previous_entity->base.source_position);
4263 unsigned old_storage_class = prev_decl->storage_class;
4265 if (warning.redundant_decls &&
4268 !(prev_decl->modifiers & DM_USED) &&
4269 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4270 warningf(&previous_entity->base.source_position,
4271 "unnecessary static forward declaration for '%#T'",
4272 prev_decl->type, symbol);
4275 storage_class_t new_storage_class = decl->storage_class;
4277 /* pretend no storage class means extern for function
4278 * declarations (except if the previous declaration is neither
4279 * none nor extern) */
4280 if (entity->kind == ENTITY_FUNCTION) {
4281 /* the previous declaration could have unspecified parameters or
4282 * be a typedef, so use the new type */
4283 if (prev_type->function.unspecified_parameters || is_definition)
4284 prev_decl->type = type;
4286 switch (old_storage_class) {
4287 case STORAGE_CLASS_NONE:
4288 old_storage_class = STORAGE_CLASS_EXTERN;
4291 case STORAGE_CLASS_EXTERN:
4292 if (is_definition) {
4293 if (warning.missing_prototypes &&
4294 prev_type->function.unspecified_parameters &&
4295 !is_sym_main(symbol)) {
4296 warningf(pos, "no previous prototype for '%#T'",
4299 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4300 new_storage_class = STORAGE_CLASS_EXTERN;
4307 } else if (is_type_incomplete(prev_type)) {
4308 prev_decl->type = type;
4311 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4312 new_storage_class == STORAGE_CLASS_EXTERN) {
4314 warn_redundant_declaration: ;
4316 = has_new_attributes(prev_decl->attributes,
4318 if (has_new_attrs) {
4319 merge_in_attributes(decl, prev_decl->attributes);
4320 } else if (!is_definition &&
4321 warning.redundant_decls &&
4322 is_type_valid(prev_type) &&
4323 strcmp(previous_entity->base.source_position.input_name,
4324 "<builtin>") != 0) {
4326 "redundant declaration for '%Y' (declared %P)",
4327 symbol, &previous_entity->base.source_position);
4329 } else if (current_function == NULL) {
4330 if (old_storage_class != STORAGE_CLASS_STATIC &&
4331 new_storage_class == STORAGE_CLASS_STATIC) {
4333 "static declaration of '%Y' follows non-static declaration (declared %P)",
4334 symbol, &previous_entity->base.source_position);
4335 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4336 prev_decl->storage_class = STORAGE_CLASS_NONE;
4337 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4339 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4341 goto error_redeclaration;
4342 goto warn_redundant_declaration;
4344 } else if (is_type_valid(prev_type)) {
4345 if (old_storage_class == new_storage_class) {
4346 error_redeclaration:
4347 errorf(pos, "redeclaration of '%Y' (declared %P)",
4348 symbol, &previous_entity->base.source_position);
4351 "redeclaration of '%Y' with different linkage (declared %P)",
4352 symbol, &previous_entity->base.source_position);
4357 prev_decl->modifiers |= decl->modifiers;
4358 if (entity->kind == ENTITY_FUNCTION) {
4359 previous_entity->function.is_inline |= entity->function.is_inline;
4361 return previous_entity;
4364 if (warning.shadow) {
4365 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4366 get_entity_kind_name(entity->kind), symbol,
4367 get_entity_kind_name(previous_entity->kind),
4368 &previous_entity->base.source_position);
4372 if (entity->kind == ENTITY_FUNCTION) {
4373 if (is_definition &&
4374 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4375 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4376 warningf(pos, "no previous prototype for '%#T'",
4377 entity->declaration.type, symbol);
4378 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4379 warningf(pos, "no previous declaration for '%#T'",
4380 entity->declaration.type, symbol);
4383 } else if (warning.missing_declarations &&
4384 entity->kind == ENTITY_VARIABLE &&
4385 current_scope == file_scope) {
4386 declaration_t *declaration = &entity->declaration;
4387 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4388 warningf(pos, "no previous declaration for '%#T'",
4389 declaration->type, symbol);
4394 assert(entity->base.parent_scope == NULL);
4395 assert(current_scope != NULL);
4397 entity->base.parent_scope = current_scope;
4398 entity->base.namespc = NAMESPACE_NORMAL;
4399 environment_push(entity);
4400 append_entity(current_scope, entity);
4405 static void parser_error_multiple_definition(entity_t *entity,
4406 const source_position_t *source_position)
4408 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4409 entity->base.symbol, &entity->base.source_position);
4412 static bool is_declaration_specifier(const token_t *token,
4413 bool only_specifiers_qualifiers)
4415 switch (token->type) {
4420 return is_typedef_symbol(token->symbol);
4422 case T___extension__:
4424 return !only_specifiers_qualifiers;
4431 static void parse_init_declarator_rest(entity_t *entity)
4433 type_t *orig_type = type_error_type;
4435 if (entity->base.kind == ENTITY_TYPEDEF) {
4436 errorf(&entity->base.source_position,
4437 "typedef '%Y' is initialized (use __typeof__ instead)",
4438 entity->base.symbol);
4440 assert(is_declaration(entity));
4441 orig_type = entity->declaration.type;
4445 type_t *type = skip_typeref(orig_type);
4447 if (entity->kind == ENTITY_VARIABLE
4448 && entity->variable.initializer != NULL) {
4449 parser_error_multiple_definition(entity, HERE);
4452 declaration_t *const declaration = &entity->declaration;
4453 bool must_be_constant = false;
4454 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4455 entity->base.parent_scope == file_scope) {
4456 must_be_constant = true;
4459 if (is_type_function(type)) {
4460 errorf(&entity->base.source_position,
4461 "function '%#T' is initialized like a variable",
4462 orig_type, entity->base.symbol);
4463 orig_type = type_error_type;
4466 parse_initializer_env_t env;
4467 env.type = orig_type;
4468 env.must_be_constant = must_be_constant;
4469 env.entity = entity;
4470 current_init_decl = entity;
4472 initializer_t *initializer = parse_initializer(&env);
4473 current_init_decl = NULL;
4475 if (entity->kind == ENTITY_VARIABLE) {
4476 /* §6.7.5:22 array initializers for arrays with unknown size
4477 * determine the array type size */
4478 declaration->type = env.type;
4479 entity->variable.initializer = initializer;
4483 /* parse rest of a declaration without any declarator */
4484 static void parse_anonymous_declaration_rest(
4485 const declaration_specifiers_t *specifiers)
4488 anonymous_entity = NULL;
4490 if (warning.other) {
4491 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4492 specifiers->thread_local) {
4493 warningf(&specifiers->source_position,
4494 "useless storage class in empty declaration");
4497 type_t *type = specifiers->type;
4498 switch (type->kind) {
4499 case TYPE_COMPOUND_STRUCT:
4500 case TYPE_COMPOUND_UNION: {
4501 if (type->compound.compound->base.symbol == NULL) {
4502 warningf(&specifiers->source_position,
4503 "unnamed struct/union that defines no instances");
4512 warningf(&specifiers->source_position, "empty declaration");
4518 static void check_variable_type_complete(entity_t *ent)
4520 if (ent->kind != ENTITY_VARIABLE)
4523 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4524 * type for the object shall be complete [...] */
4525 declaration_t *decl = &ent->declaration;
4526 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4527 decl->storage_class == STORAGE_CLASS_STATIC)
4530 type_t *const orig_type = decl->type;
4531 type_t *const type = skip_typeref(orig_type);
4532 if (!is_type_incomplete(type))
4535 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4536 * are given length one. */
4537 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4538 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4542 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4543 orig_type, ent->base.symbol);
4547 static void parse_declaration_rest(entity_t *ndeclaration,
4548 const declaration_specifiers_t *specifiers,
4549 parsed_declaration_func finished_declaration,
4550 declarator_flags_t flags)
4552 add_anchor_token(';');
4553 add_anchor_token(',');
4555 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4557 if (token.type == '=') {
4558 parse_init_declarator_rest(entity);
4559 } else if (entity->kind == ENTITY_VARIABLE) {
4560 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4561 * [...] where the extern specifier is explicitly used. */
4562 declaration_t *decl = &entity->declaration;
4563 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4564 type_t *type = decl->type;
4565 if (is_type_reference(skip_typeref(type))) {
4566 errorf(&entity->base.source_position,
4567 "reference '%#T' must be initialized",
4568 type, entity->base.symbol);
4573 check_variable_type_complete(entity);
4578 add_anchor_token('=');
4579 ndeclaration = parse_declarator(specifiers, flags);
4580 rem_anchor_token('=');
4582 expect(';', end_error);
4585 anonymous_entity = NULL;
4586 rem_anchor_token(';');
4587 rem_anchor_token(',');
4590 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4592 symbol_t *symbol = entity->base.symbol;
4593 if (symbol == NULL) {
4594 errorf(HERE, "anonymous declaration not valid as function parameter");
4598 assert(entity->base.namespc == NAMESPACE_NORMAL);
4599 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4600 if (previous_entity == NULL
4601 || previous_entity->base.parent_scope != current_scope) {
4602 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4607 if (is_definition) {
4608 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4611 return record_entity(entity, false);
4614 static void parse_declaration(parsed_declaration_func finished_declaration,
4615 declarator_flags_t flags)
4617 declaration_specifiers_t specifiers;
4618 memset(&specifiers, 0, sizeof(specifiers));
4620 add_anchor_token(';');
4621 parse_declaration_specifiers(&specifiers);
4622 rem_anchor_token(';');
4624 if (token.type == ';') {
4625 parse_anonymous_declaration_rest(&specifiers);
4627 entity_t *entity = parse_declarator(&specifiers, flags);
4628 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4633 static type_t *get_default_promoted_type(type_t *orig_type)
4635 type_t *result = orig_type;
4637 type_t *type = skip_typeref(orig_type);
4638 if (is_type_integer(type)) {
4639 result = promote_integer(type);
4640 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4641 result = type_double;
4647 static void parse_kr_declaration_list(entity_t *entity)
4649 if (entity->kind != ENTITY_FUNCTION)
4652 type_t *type = skip_typeref(entity->declaration.type);
4653 assert(is_type_function(type));
4654 if (!type->function.kr_style_parameters)
4657 add_anchor_token('{');
4659 /* push function parameters */
4660 size_t const top = environment_top();
4661 scope_t *old_scope = scope_push(&entity->function.parameters);
4663 entity_t *parameter = entity->function.parameters.entities;
4664 for ( ; parameter != NULL; parameter = parameter->base.next) {
4665 assert(parameter->base.parent_scope == NULL);
4666 parameter->base.parent_scope = current_scope;
4667 environment_push(parameter);
4670 /* parse declaration list */
4672 switch (token.type) {
4674 case T___extension__:
4675 /* This covers symbols, which are no type, too, and results in
4676 * better error messages. The typical cases are misspelled type
4677 * names and missing includes. */
4679 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4687 /* pop function parameters */
4688 assert(current_scope == &entity->function.parameters);
4689 scope_pop(old_scope);
4690 environment_pop_to(top);
4692 /* update function type */
4693 type_t *new_type = duplicate_type(type);
4695 function_parameter_t *parameters = NULL;
4696 function_parameter_t **anchor = ¶meters;
4698 /* did we have an earlier prototype? */
4699 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4700 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4703 function_parameter_t *proto_parameter = NULL;
4704 if (proto_type != NULL) {
4705 type_t *proto_type_type = proto_type->declaration.type;
4706 proto_parameter = proto_type_type->function.parameters;
4707 /* If a K&R function definition has a variadic prototype earlier, then
4708 * make the function definition variadic, too. This should conform to
4709 * §6.7.5.3:15 and §6.9.1:8. */
4710 new_type->function.variadic = proto_type_type->function.variadic;
4712 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4714 new_type->function.unspecified_parameters = true;
4717 bool need_incompatible_warning = false;
4718 parameter = entity->function.parameters.entities;
4719 for (; parameter != NULL; parameter = parameter->base.next,
4721 proto_parameter == NULL ? NULL : proto_parameter->next) {
4722 if (parameter->kind != ENTITY_PARAMETER)
4725 type_t *parameter_type = parameter->declaration.type;
4726 if (parameter_type == NULL) {
4728 errorf(HERE, "no type specified for function parameter '%Y'",
4729 parameter->base.symbol);
4730 parameter_type = type_error_type;
4732 if (warning.implicit_int) {
4733 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4734 parameter->base.symbol);
4736 parameter_type = type_int;
4738 parameter->declaration.type = parameter_type;
4741 semantic_parameter_incomplete(parameter);
4743 /* we need the default promoted types for the function type */
4744 type_t *not_promoted = parameter_type;
4745 parameter_type = get_default_promoted_type(parameter_type);
4747 /* gcc special: if the type of the prototype matches the unpromoted
4748 * type don't promote */
4749 if (!strict_mode && proto_parameter != NULL) {
4750 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4751 type_t *promo_skip = skip_typeref(parameter_type);
4752 type_t *param_skip = skip_typeref(not_promoted);
4753 if (!types_compatible(proto_p_type, promo_skip)
4754 && types_compatible(proto_p_type, param_skip)) {
4756 need_incompatible_warning = true;
4757 parameter_type = not_promoted;
4760 function_parameter_t *const parameter
4761 = allocate_parameter(parameter_type);
4763 *anchor = parameter;
4764 anchor = ¶meter->next;
4767 new_type->function.parameters = parameters;
4768 new_type = identify_new_type(new_type);
4770 if (warning.other && need_incompatible_warning) {
4771 type_t *proto_type_type = proto_type->declaration.type;
4773 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4774 proto_type_type, proto_type->base.symbol,
4775 new_type, entity->base.symbol,
4776 &proto_type->base.source_position);
4779 entity->declaration.type = new_type;
4781 rem_anchor_token('{');
4784 static bool first_err = true;
4787 * When called with first_err set, prints the name of the current function,
4790 static void print_in_function(void)
4794 diagnosticf("%s: In function '%Y':\n",
4795 current_function->base.base.source_position.input_name,
4796 current_function->base.base.symbol);
4801 * Check if all labels are defined in the current function.
4802 * Check if all labels are used in the current function.
4804 static void check_labels(void)
4806 for (const goto_statement_t *goto_statement = goto_first;
4807 goto_statement != NULL;
4808 goto_statement = goto_statement->next) {
4809 /* skip computed gotos */
4810 if (goto_statement->expression != NULL)
4813 label_t *label = goto_statement->label;
4816 if (label->base.source_position.input_name == NULL) {
4817 print_in_function();
4818 errorf(&goto_statement->base.source_position,
4819 "label '%Y' used but not defined", label->base.symbol);
4823 if (warning.unused_label) {
4824 for (const label_statement_t *label_statement = label_first;
4825 label_statement != NULL;
4826 label_statement = label_statement->next) {
4827 label_t *label = label_statement->label;
4829 if (! label->used) {
4830 print_in_function();
4831 warningf(&label_statement->base.source_position,
4832 "label '%Y' defined but not used", label->base.symbol);
4838 static void warn_unused_entity(entity_t *entity, entity_t *last)
4840 entity_t const *const end = last != NULL ? last->base.next : NULL;
4841 for (; entity != end; entity = entity->base.next) {
4842 if (!is_declaration(entity))
4845 declaration_t *declaration = &entity->declaration;
4846 if (declaration->implicit)
4849 if (!declaration->used) {
4850 print_in_function();
4851 const char *what = get_entity_kind_name(entity->kind);
4852 warningf(&entity->base.source_position, "%s '%Y' is unused",
4853 what, entity->base.symbol);
4854 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4855 print_in_function();
4856 const char *what = get_entity_kind_name(entity->kind);
4857 warningf(&entity->base.source_position, "%s '%Y' is never read",
4858 what, entity->base.symbol);
4863 static void check_unused_variables(statement_t *const stmt, void *const env)
4867 switch (stmt->kind) {
4868 case STATEMENT_DECLARATION: {
4869 declaration_statement_t const *const decls = &stmt->declaration;
4870 warn_unused_entity(decls->declarations_begin,
4871 decls->declarations_end);
4876 warn_unused_entity(stmt->fors.scope.entities, NULL);
4885 * Check declarations of current_function for unused entities.
4887 static void check_declarations(void)
4889 if (warning.unused_parameter) {
4890 const scope_t *scope = ¤t_function->parameters;
4892 /* do not issue unused warnings for main */
4893 if (!is_sym_main(current_function->base.base.symbol)) {
4894 warn_unused_entity(scope->entities, NULL);
4897 if (warning.unused_variable) {
4898 walk_statements(current_function->statement, check_unused_variables,
4903 static int determine_truth(expression_t const* const cond)
4906 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4907 fold_constant_to_bool(cond) ? 1 :
4911 static void check_reachable(statement_t *);
4912 static bool reaches_end;
4914 static bool expression_returns(expression_t const *const expr)
4916 switch (expr->kind) {
4918 expression_t const *const func = expr->call.function;
4919 if (func->kind == EXPR_REFERENCE) {
4920 entity_t *entity = func->reference.entity;
4921 if (entity->kind == ENTITY_FUNCTION
4922 && entity->declaration.modifiers & DM_NORETURN)
4926 if (!expression_returns(func))
4929 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4930 if (!expression_returns(arg->expression))
4937 case EXPR_REFERENCE:
4938 case EXPR_REFERENCE_ENUM_VALUE:
4940 case EXPR_STRING_LITERAL:
4941 case EXPR_WIDE_STRING_LITERAL:
4942 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4943 case EXPR_LABEL_ADDRESS:
4944 case EXPR_CLASSIFY_TYPE:
4945 case EXPR_SIZEOF: // TODO handle obscure VLA case
4948 case EXPR_BUILTIN_CONSTANT_P:
4949 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4954 case EXPR_STATEMENT: {
4955 bool old_reaches_end = reaches_end;
4956 reaches_end = false;
4957 check_reachable(expr->statement.statement);
4958 bool returns = reaches_end;
4959 reaches_end = old_reaches_end;
4963 case EXPR_CONDITIONAL:
4964 // TODO handle constant expression
4966 if (!expression_returns(expr->conditional.condition))
4969 if (expr->conditional.true_expression != NULL
4970 && expression_returns(expr->conditional.true_expression))
4973 return expression_returns(expr->conditional.false_expression);
4976 return expression_returns(expr->select.compound);
4978 case EXPR_ARRAY_ACCESS:
4980 expression_returns(expr->array_access.array_ref) &&
4981 expression_returns(expr->array_access.index);
4984 return expression_returns(expr->va_starte.ap);
4987 return expression_returns(expr->va_arge.ap);
4990 return expression_returns(expr->va_copye.src);
4992 EXPR_UNARY_CASES_MANDATORY
4993 return expression_returns(expr->unary.value);
4995 case EXPR_UNARY_THROW:
4999 // TODO handle constant lhs of && and ||
5001 expression_returns(expr->binary.left) &&
5002 expression_returns(expr->binary.right);
5008 panic("unhandled expression");
5011 static bool initializer_returns(initializer_t const *const init)
5013 switch (init->kind) {
5014 case INITIALIZER_VALUE:
5015 return expression_returns(init->value.value);
5017 case INITIALIZER_LIST: {
5018 initializer_t * const* i = init->list.initializers;
5019 initializer_t * const* const end = i + init->list.len;
5020 bool returns = true;
5021 for (; i != end; ++i) {
5022 if (!initializer_returns(*i))
5028 case INITIALIZER_STRING:
5029 case INITIALIZER_WIDE_STRING:
5030 case INITIALIZER_DESIGNATOR: // designators have no payload
5033 panic("unhandled initializer");
5036 static bool noreturn_candidate;
5038 static void check_reachable(statement_t *const stmt)
5040 if (stmt->base.reachable)
5042 if (stmt->kind != STATEMENT_DO_WHILE)
5043 stmt->base.reachable = true;
5045 statement_t *last = stmt;
5047 switch (stmt->kind) {
5048 case STATEMENT_INVALID:
5049 case STATEMENT_EMPTY:
5051 next = stmt->base.next;
5054 case STATEMENT_DECLARATION: {
5055 declaration_statement_t const *const decl = &stmt->declaration;
5056 entity_t const * ent = decl->declarations_begin;
5057 entity_t const *const last = decl->declarations_end;
5059 for (;; ent = ent->base.next) {
5060 if (ent->kind == ENTITY_VARIABLE &&
5061 ent->variable.initializer != NULL &&
5062 !initializer_returns(ent->variable.initializer)) {
5069 next = stmt->base.next;
5073 case STATEMENT_COMPOUND:
5074 next = stmt->compound.statements;
5076 next = stmt->base.next;
5079 case STATEMENT_RETURN: {
5080 expression_t const *const val = stmt->returns.value;
5081 if (val == NULL || expression_returns(val))
5082 noreturn_candidate = false;
5086 case STATEMENT_IF: {
5087 if_statement_t const *const ifs = &stmt->ifs;
5088 expression_t const *const cond = ifs->condition;
5090 if (!expression_returns(cond))
5093 int const val = determine_truth(cond);
5096 check_reachable(ifs->true_statement);
5101 if (ifs->false_statement != NULL) {
5102 check_reachable(ifs->false_statement);
5106 next = stmt->base.next;
5110 case STATEMENT_SWITCH: {
5111 switch_statement_t const *const switchs = &stmt->switchs;
5112 expression_t const *const expr = switchs->expression;
5114 if (!expression_returns(expr))
5117 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5118 long const val = fold_constant_to_int(expr);
5119 case_label_statement_t * defaults = NULL;
5120 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5121 if (i->expression == NULL) {
5126 if (i->first_case <= val && val <= i->last_case) {
5127 check_reachable((statement_t*)i);
5132 if (defaults != NULL) {
5133 check_reachable((statement_t*)defaults);
5137 bool has_default = false;
5138 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5139 if (i->expression == NULL)
5142 check_reachable((statement_t*)i);
5149 next = stmt->base.next;
5153 case STATEMENT_EXPRESSION: {
5154 /* Check for noreturn function call */
5155 expression_t const *const expr = stmt->expression.expression;
5156 if (!expression_returns(expr))
5159 next = stmt->base.next;
5163 case STATEMENT_CONTINUE:
5164 for (statement_t *parent = stmt;;) {
5165 parent = parent->base.parent;
5166 if (parent == NULL) /* continue not within loop */
5170 switch (parent->kind) {
5171 case STATEMENT_WHILE: goto continue_while;
5172 case STATEMENT_DO_WHILE: goto continue_do_while;
5173 case STATEMENT_FOR: goto continue_for;
5179 case STATEMENT_BREAK:
5180 for (statement_t *parent = stmt;;) {
5181 parent = parent->base.parent;
5182 if (parent == NULL) /* break not within loop/switch */
5185 switch (parent->kind) {
5186 case STATEMENT_SWITCH:
5187 case STATEMENT_WHILE:
5188 case STATEMENT_DO_WHILE:
5191 next = parent->base.next;
5192 goto found_break_parent;
5200 case STATEMENT_GOTO:
5201 if (stmt->gotos.expression) {
5202 if (!expression_returns(stmt->gotos.expression))
5205 statement_t *parent = stmt->base.parent;
5206 if (parent == NULL) /* top level goto */
5210 next = stmt->gotos.label->statement;
5211 if (next == NULL) /* missing label */
5216 case STATEMENT_LABEL:
5217 next = stmt->label.statement;
5220 case STATEMENT_CASE_LABEL:
5221 next = stmt->case_label.statement;
5224 case STATEMENT_WHILE: {
5225 while_statement_t const *const whiles = &stmt->whiles;
5226 expression_t const *const cond = whiles->condition;
5228 if (!expression_returns(cond))
5231 int const val = determine_truth(cond);
5234 check_reachable(whiles->body);
5239 next = stmt->base.next;
5243 case STATEMENT_DO_WHILE:
5244 next = stmt->do_while.body;
5247 case STATEMENT_FOR: {
5248 for_statement_t *const fors = &stmt->fors;
5250 if (fors->condition_reachable)
5252 fors->condition_reachable = true;
5254 expression_t const *const cond = fors->condition;
5259 } else if (expression_returns(cond)) {
5260 val = determine_truth(cond);
5266 check_reachable(fors->body);
5271 next = stmt->base.next;
5275 case STATEMENT_MS_TRY: {
5276 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5277 check_reachable(ms_try->try_statement);
5278 next = ms_try->final_statement;
5282 case STATEMENT_LEAVE: {
5283 statement_t *parent = stmt;
5285 parent = parent->base.parent;
5286 if (parent == NULL) /* __leave not within __try */
5289 if (parent->kind == STATEMENT_MS_TRY) {
5291 next = parent->ms_try.final_statement;
5299 panic("invalid statement kind");
5302 while (next == NULL) {
5303 next = last->base.parent;
5305 noreturn_candidate = false;
5307 type_t *const type = skip_typeref(current_function->base.type);
5308 assert(is_type_function(type));
5309 type_t *const ret = skip_typeref(type->function.return_type);
5310 if (warning.return_type &&
5311 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5312 is_type_valid(ret) &&
5313 !is_sym_main(current_function->base.base.symbol)) {
5314 warningf(&stmt->base.source_position,
5315 "control reaches end of non-void function");
5320 switch (next->kind) {
5321 case STATEMENT_INVALID:
5322 case STATEMENT_EMPTY:
5323 case STATEMENT_DECLARATION:
5324 case STATEMENT_EXPRESSION:
5326 case STATEMENT_RETURN:
5327 case STATEMENT_CONTINUE:
5328 case STATEMENT_BREAK:
5329 case STATEMENT_GOTO:
5330 case STATEMENT_LEAVE:
5331 panic("invalid control flow in function");
5333 case STATEMENT_COMPOUND:
5334 if (next->compound.stmt_expr) {
5340 case STATEMENT_SWITCH:
5341 case STATEMENT_LABEL:
5342 case STATEMENT_CASE_LABEL:
5344 next = next->base.next;
5347 case STATEMENT_WHILE: {
5349 if (next->base.reachable)
5351 next->base.reachable = true;
5353 while_statement_t const *const whiles = &next->whiles;
5354 expression_t const *const cond = whiles->condition;
5356 if (!expression_returns(cond))
5359 int const val = determine_truth(cond);
5362 check_reachable(whiles->body);
5368 next = next->base.next;
5372 case STATEMENT_DO_WHILE: {
5374 if (next->base.reachable)
5376 next->base.reachable = true;
5378 do_while_statement_t const *const dw = &next->do_while;
5379 expression_t const *const cond = dw->condition;
5381 if (!expression_returns(cond))
5384 int const val = determine_truth(cond);
5387 check_reachable(dw->body);
5393 next = next->base.next;
5397 case STATEMENT_FOR: {
5399 for_statement_t *const fors = &next->fors;
5401 fors->step_reachable = true;
5403 if (fors->condition_reachable)
5405 fors->condition_reachable = true;
5407 expression_t const *const cond = fors->condition;
5412 } else if (expression_returns(cond)) {
5413 val = determine_truth(cond);
5419 check_reachable(fors->body);
5425 next = next->base.next;
5429 case STATEMENT_MS_TRY:
5431 next = next->ms_try.final_statement;
5436 check_reachable(next);
5439 static void check_unreachable(statement_t* const stmt, void *const env)
5443 switch (stmt->kind) {
5444 case STATEMENT_DO_WHILE:
5445 if (!stmt->base.reachable) {
5446 expression_t const *const cond = stmt->do_while.condition;
5447 if (determine_truth(cond) >= 0) {
5448 warningf(&cond->base.source_position,
5449 "condition of do-while-loop is unreachable");
5454 case STATEMENT_FOR: {
5455 for_statement_t const* const fors = &stmt->fors;
5457 // if init and step are unreachable, cond is unreachable, too
5458 if (!stmt->base.reachable && !fors->step_reachable) {
5459 warningf(&stmt->base.source_position, "statement is unreachable");
5461 if (!stmt->base.reachable && fors->initialisation != NULL) {
5462 warningf(&fors->initialisation->base.source_position,
5463 "initialisation of for-statement is unreachable");
5466 if (!fors->condition_reachable && fors->condition != NULL) {
5467 warningf(&fors->condition->base.source_position,
5468 "condition of for-statement is unreachable");
5471 if (!fors->step_reachable && fors->step != NULL) {
5472 warningf(&fors->step->base.source_position,
5473 "step of for-statement is unreachable");
5479 case STATEMENT_COMPOUND:
5480 if (stmt->compound.statements != NULL)
5482 goto warn_unreachable;
5484 case STATEMENT_DECLARATION: {
5485 /* Only warn if there is at least one declarator with an initializer.
5486 * This typically occurs in switch statements. */
5487 declaration_statement_t const *const decl = &stmt->declaration;
5488 entity_t const * ent = decl->declarations_begin;
5489 entity_t const *const last = decl->declarations_end;
5491 for (;; ent = ent->base.next) {
5492 if (ent->kind == ENTITY_VARIABLE &&
5493 ent->variable.initializer != NULL) {
5494 goto warn_unreachable;
5504 if (!stmt->base.reachable)
5505 warningf(&stmt->base.source_position, "statement is unreachable");
5510 static void parse_external_declaration(void)
5512 /* function-definitions and declarations both start with declaration
5514 declaration_specifiers_t specifiers;
5515 memset(&specifiers, 0, sizeof(specifiers));
5517 add_anchor_token(';');
5518 parse_declaration_specifiers(&specifiers);
5519 rem_anchor_token(';');
5521 /* must be a declaration */
5522 if (token.type == ';') {
5523 parse_anonymous_declaration_rest(&specifiers);
5527 add_anchor_token(',');
5528 add_anchor_token('=');
5529 add_anchor_token(';');
5530 add_anchor_token('{');
5532 /* declarator is common to both function-definitions and declarations */
5533 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5535 rem_anchor_token('{');
5536 rem_anchor_token(';');
5537 rem_anchor_token('=');
5538 rem_anchor_token(',');
5540 /* must be a declaration */
5541 switch (token.type) {
5545 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5550 /* must be a function definition */
5551 parse_kr_declaration_list(ndeclaration);
5553 if (token.type != '{') {
5554 parse_error_expected("while parsing function definition", '{', NULL);
5555 eat_until_matching_token(';');
5559 assert(is_declaration(ndeclaration));
5560 type_t *const orig_type = ndeclaration->declaration.type;
5561 type_t * type = skip_typeref(orig_type);
5563 if (!is_type_function(type)) {
5564 if (is_type_valid(type)) {
5565 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5566 type, ndeclaration->base.symbol);
5570 } else if (is_typeref(orig_type)) {
5572 errorf(&ndeclaration->base.source_position,
5573 "type of function definition '%#T' is a typedef",
5574 orig_type, ndeclaration->base.symbol);
5577 if (warning.aggregate_return &&
5578 is_type_compound(skip_typeref(type->function.return_type))) {
5579 warningf(HERE, "function '%Y' returns an aggregate",
5580 ndeclaration->base.symbol);
5582 if (warning.traditional && !type->function.unspecified_parameters) {
5583 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5584 ndeclaration->base.symbol);
5586 if (warning.old_style_definition && type->function.unspecified_parameters) {
5587 warningf(HERE, "old-style function definition '%Y'",
5588 ndeclaration->base.symbol);
5591 /* §6.7.5.3:14 a function definition with () means no
5592 * parameters (and not unspecified parameters) */
5593 if (type->function.unspecified_parameters &&
5594 type->function.parameters == NULL) {
5595 type_t *copy = duplicate_type(type);
5596 copy->function.unspecified_parameters = false;
5597 type = identify_new_type(copy);
5599 ndeclaration->declaration.type = type;
5602 entity_t *const entity = record_entity(ndeclaration, true);
5603 assert(entity->kind == ENTITY_FUNCTION);
5604 assert(ndeclaration->kind == ENTITY_FUNCTION);
5606 function_t *const function = &entity->function;
5607 if (ndeclaration != entity) {
5608 function->parameters = ndeclaration->function.parameters;
5610 assert(is_declaration(entity));
5611 type = skip_typeref(entity->declaration.type);
5613 /* push function parameters and switch scope */
5614 size_t const top = environment_top();
5615 scope_t *old_scope = scope_push(&function->parameters);
5617 entity_t *parameter = function->parameters.entities;
5618 for (; parameter != NULL; parameter = parameter->base.next) {
5619 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5620 parameter->base.parent_scope = current_scope;
5622 assert(parameter->base.parent_scope == NULL
5623 || parameter->base.parent_scope == current_scope);
5624 parameter->base.parent_scope = current_scope;
5625 if (parameter->base.symbol == NULL) {
5626 errorf(¶meter->base.source_position, "parameter name omitted");
5629 environment_push(parameter);
5632 if (function->statement != NULL) {
5633 parser_error_multiple_definition(entity, HERE);
5636 /* parse function body */
5637 int label_stack_top = label_top();
5638 function_t *old_current_function = current_function;
5639 entity_t *old_current_entity = current_entity;
5640 current_function = function;
5641 current_entity = entity;
5642 current_parent = NULL;
5645 goto_anchor = &goto_first;
5647 label_anchor = &label_first;
5649 statement_t *const body = parse_compound_statement(false);
5650 function->statement = body;
5653 check_declarations();
5654 if (warning.return_type ||
5655 warning.unreachable_code ||
5656 (warning.missing_noreturn
5657 && !(function->base.modifiers & DM_NORETURN))) {
5658 noreturn_candidate = true;
5659 check_reachable(body);
5660 if (warning.unreachable_code)
5661 walk_statements(body, check_unreachable, NULL);
5662 if (warning.missing_noreturn &&
5663 noreturn_candidate &&
5664 !(function->base.modifiers & DM_NORETURN)) {
5665 warningf(&body->base.source_position,
5666 "function '%#T' is candidate for attribute 'noreturn'",
5667 type, entity->base.symbol);
5671 assert(current_parent == NULL);
5672 assert(current_function == function);
5673 assert(current_entity == entity);
5674 current_entity = old_current_entity;
5675 current_function = old_current_function;
5676 label_pop_to(label_stack_top);
5679 assert(current_scope == &function->parameters);
5680 scope_pop(old_scope);
5681 environment_pop_to(top);
5684 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5685 source_position_t *source_position,
5686 const symbol_t *symbol)
5688 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5690 type->bitfield.base_type = base_type;
5691 type->bitfield.size_expression = size;
5694 type_t *skipped_type = skip_typeref(base_type);
5695 if (!is_type_integer(skipped_type)) {
5696 errorf(HERE, "bitfield base type '%T' is not an integer type",
5700 bit_size = get_type_size(base_type) * 8;
5703 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5704 long v = fold_constant_to_int(size);
5705 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5708 errorf(source_position, "negative width in bit-field '%Y'",
5710 } else if (v == 0 && symbol != NULL) {
5711 errorf(source_position, "zero width for bit-field '%Y'",
5713 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5714 errorf(source_position, "width of '%Y' exceeds its type",
5717 type->bitfield.bit_size = v;
5724 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5726 entity_t *iter = compound->members.entities;
5727 for (; iter != NULL; iter = iter->base.next) {
5728 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5731 if (iter->base.symbol == symbol) {
5733 } else if (iter->base.symbol == NULL) {
5734 /* search in anonymous structs and unions */
5735 type_t *type = skip_typeref(iter->declaration.type);
5736 if (is_type_compound(type)) {
5737 if (find_compound_entry(type->compound.compound, symbol)
5748 static void check_deprecated(const source_position_t *source_position,
5749 const entity_t *entity)
5751 if (!warning.deprecated_declarations)
5753 if (!is_declaration(entity))
5755 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5758 char const *const prefix = get_entity_kind_name(entity->kind);
5759 const char *deprecated_string
5760 = get_deprecated_string(entity->declaration.attributes);
5761 if (deprecated_string != NULL) {
5762 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5763 prefix, entity->base.symbol, &entity->base.source_position,
5766 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5767 entity->base.symbol, &entity->base.source_position);
5772 static expression_t *create_select(const source_position_t *pos,
5774 type_qualifiers_t qualifiers,
5777 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5779 check_deprecated(pos, entry);
5781 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5782 select->select.compound = addr;
5783 select->select.compound_entry = entry;
5785 type_t *entry_type = entry->declaration.type;
5786 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5788 /* we always do the auto-type conversions; the & and sizeof parser contains
5789 * code to revert this! */
5790 select->base.type = automatic_type_conversion(res_type);
5791 if (res_type->kind == TYPE_BITFIELD) {
5792 select->base.type = res_type->bitfield.base_type;
5799 * Find entry with symbol in compound. Search anonymous structs and unions and
5800 * creates implicit select expressions for them.
5801 * Returns the adress for the innermost compound.
5803 static expression_t *find_create_select(const source_position_t *pos,
5805 type_qualifiers_t qualifiers,
5806 compound_t *compound, symbol_t *symbol)
5808 entity_t *iter = compound->members.entities;
5809 for (; iter != NULL; iter = iter->base.next) {
5810 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5813 symbol_t *iter_symbol = iter->base.symbol;
5814 if (iter_symbol == NULL) {
5815 type_t *type = iter->declaration.type;
5816 if (type->kind != TYPE_COMPOUND_STRUCT
5817 && type->kind != TYPE_COMPOUND_UNION)
5820 compound_t *sub_compound = type->compound.compound;
5822 if (find_compound_entry(sub_compound, symbol) == NULL)
5825 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5826 sub_addr->base.source_position = *pos;
5827 sub_addr->select.implicit = true;
5828 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5832 if (iter_symbol == symbol) {
5833 return create_select(pos, addr, qualifiers, iter);
5840 static void parse_compound_declarators(compound_t *compound,
5841 const declaration_specifiers_t *specifiers)
5846 if (token.type == ':') {
5847 source_position_t source_position = *HERE;
5850 type_t *base_type = specifiers->type;
5851 expression_t *size = parse_constant_expression();
5853 type_t *type = make_bitfield_type(base_type, size,
5854 &source_position, NULL);
5856 attribute_t *attributes = parse_attributes(NULL);
5857 attribute_t **anchor = &attributes;
5858 while (*anchor != NULL)
5859 anchor = &(*anchor)->next;
5860 *anchor = specifiers->attributes;
5862 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5863 entity->base.namespc = NAMESPACE_NORMAL;
5864 entity->base.source_position = source_position;
5865 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5866 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5867 entity->declaration.type = type;
5868 entity->declaration.attributes = attributes;
5870 if (attributes != NULL) {
5871 handle_entity_attributes(attributes, entity);
5873 append_entity(&compound->members, entity);
5875 entity = parse_declarator(specifiers,
5876 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5877 if (entity->kind == ENTITY_TYPEDEF) {
5878 errorf(&entity->base.source_position,
5879 "typedef not allowed as compound member");
5881 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5883 /* make sure we don't define a symbol multiple times */
5884 symbol_t *symbol = entity->base.symbol;
5885 if (symbol != NULL) {
5886 entity_t *prev = find_compound_entry(compound, symbol);
5888 errorf(&entity->base.source_position,
5889 "multiple declarations of symbol '%Y' (declared %P)",
5890 symbol, &prev->base.source_position);
5894 if (token.type == ':') {
5895 source_position_t source_position = *HERE;
5897 expression_t *size = parse_constant_expression();
5899 type_t *type = entity->declaration.type;
5900 type_t *bitfield_type = make_bitfield_type(type, size,
5901 &source_position, entity->base.symbol);
5903 attribute_t *attributes = parse_attributes(NULL);
5904 entity->declaration.type = bitfield_type;
5905 handle_entity_attributes(attributes, entity);
5907 type_t *orig_type = entity->declaration.type;
5908 type_t *type = skip_typeref(orig_type);
5909 if (is_type_function(type)) {
5910 errorf(&entity->base.source_position,
5911 "compound member '%Y' must not have function type '%T'",
5912 entity->base.symbol, orig_type);
5913 } else if (is_type_incomplete(type)) {
5914 /* §6.7.2.1:16 flexible array member */
5915 if (!is_type_array(type) ||
5916 token.type != ';' ||
5917 look_ahead(1)->type != '}') {
5918 errorf(&entity->base.source_position,
5919 "compound member '%Y' has incomplete type '%T'",
5920 entity->base.symbol, orig_type);
5925 append_entity(&compound->members, entity);
5928 } while (next_if(','));
5929 expect(';', end_error);
5932 anonymous_entity = NULL;
5935 static void parse_compound_type_entries(compound_t *compound)
5938 add_anchor_token('}');
5940 while (token.type != '}') {
5941 if (token.type == T_EOF) {
5942 errorf(HERE, "EOF while parsing struct");
5945 declaration_specifiers_t specifiers;
5946 memset(&specifiers, 0, sizeof(specifiers));
5947 parse_declaration_specifiers(&specifiers);
5949 parse_compound_declarators(compound, &specifiers);
5951 rem_anchor_token('}');
5955 compound->complete = true;
5958 static type_t *parse_typename(void)
5960 declaration_specifiers_t specifiers;
5961 memset(&specifiers, 0, sizeof(specifiers));
5962 parse_declaration_specifiers(&specifiers);
5963 if (specifiers.storage_class != STORAGE_CLASS_NONE
5964 || specifiers.thread_local) {
5965 /* TODO: improve error message, user does probably not know what a
5966 * storage class is...
5968 errorf(HERE, "typename must not have a storage class");
5971 type_t *result = parse_abstract_declarator(specifiers.type);
5979 typedef expression_t* (*parse_expression_function)(void);
5980 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5982 typedef struct expression_parser_function_t expression_parser_function_t;
5983 struct expression_parser_function_t {
5984 parse_expression_function parser;
5985 precedence_t infix_precedence;
5986 parse_expression_infix_function infix_parser;
5989 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5992 * Prints an error message if an expression was expected but not read
5994 static expression_t *expected_expression_error(void)
5996 /* skip the error message if the error token was read */
5997 if (token.type != T_ERROR) {
5998 errorf(HERE, "expected expression, got token %K", &token);
6002 return create_invalid_expression();
6005 static type_t *get_string_type(void)
6007 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6010 static type_t *get_wide_string_type(void)
6012 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6016 * Parse a string constant.
6018 static expression_t *parse_string_literal(void)
6020 source_position_t begin = token.source_position;
6021 string_t res = token.literal;
6022 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6025 while (token.type == T_STRING_LITERAL
6026 || token.type == T_WIDE_STRING_LITERAL) {
6027 warn_string_concat(&token.source_position);
6028 res = concat_strings(&res, &token.literal);
6030 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6033 expression_t *literal;
6035 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6036 literal->base.type = get_wide_string_type();
6038 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6039 literal->base.type = get_string_type();
6041 literal->base.source_position = begin;
6042 literal->literal.value = res;
6048 * Parse a boolean constant.
6050 static expression_t *parse_boolean_literal(bool value)
6052 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6053 literal->base.source_position = token.source_position;
6054 literal->base.type = type_bool;
6055 literal->literal.value.begin = value ? "true" : "false";
6056 literal->literal.value.size = value ? 4 : 5;
6062 static void warn_traditional_suffix(void)
6064 if (!warning.traditional)
6066 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6070 static void check_integer_suffix(void)
6072 symbol_t *suffix = token.symbol;
6076 bool not_traditional = false;
6077 const char *c = suffix->string;
6078 if (*c == 'l' || *c == 'L') {
6081 not_traditional = true;
6083 if (*c == 'u' || *c == 'U') {
6086 } else if (*c == 'u' || *c == 'U') {
6087 not_traditional = true;
6090 } else if (*c == 'u' || *c == 'U') {
6091 not_traditional = true;
6093 if (*c == 'l' || *c == 'L') {
6101 errorf(&token.source_position,
6102 "invalid suffix '%s' on integer constant", suffix->string);
6103 } else if (not_traditional) {
6104 warn_traditional_suffix();
6108 static type_t *check_floatingpoint_suffix(void)
6110 symbol_t *suffix = token.symbol;
6111 type_t *type = type_double;
6115 bool not_traditional = false;
6116 const char *c = suffix->string;
6117 if (*c == 'f' || *c == 'F') {
6120 } else if (*c == 'l' || *c == 'L') {
6122 type = type_long_double;
6125 errorf(&token.source_position,
6126 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6127 } else if (not_traditional) {
6128 warn_traditional_suffix();
6135 * Parse an integer constant.
6137 static expression_t *parse_number_literal(void)
6139 expression_kind_t kind;
6142 switch (token.type) {
6144 kind = EXPR_LITERAL_INTEGER;
6145 check_integer_suffix();
6148 case T_INTEGER_OCTAL:
6149 kind = EXPR_LITERAL_INTEGER_OCTAL;
6150 check_integer_suffix();
6153 case T_INTEGER_HEXADECIMAL:
6154 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6155 check_integer_suffix();
6158 case T_FLOATINGPOINT:
6159 kind = EXPR_LITERAL_FLOATINGPOINT;
6160 type = check_floatingpoint_suffix();
6162 case T_FLOATINGPOINT_HEXADECIMAL:
6163 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6164 type = check_floatingpoint_suffix();
6167 panic("unexpected token type in parse_number_literal");
6170 expression_t *literal = allocate_expression_zero(kind);
6171 literal->base.source_position = token.source_position;
6172 literal->base.type = type;
6173 literal->literal.value = token.literal;
6174 literal->literal.suffix = token.symbol;
6177 /* integer type depends on the size of the number and the size
6178 * representable by the types. The backend/codegeneration has to determine
6181 determine_literal_type(&literal->literal);
6186 * Parse a character constant.
6188 static expression_t *parse_character_constant(void)
6190 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6191 literal->base.source_position = token.source_position;
6192 literal->base.type = c_mode & _CXX ? type_char : type_int;
6193 literal->literal.value = token.literal;
6195 size_t len = literal->literal.value.size;
6197 if (!GNU_MODE && !(c_mode & _C99)) {
6198 errorf(HERE, "more than 1 character in character constant");
6199 } else if (warning.multichar) {
6200 literal->base.type = type_int;
6201 warningf(HERE, "multi-character character constant");
6210 * Parse a wide character constant.
6212 static expression_t *parse_wide_character_constant(void)
6214 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6215 literal->base.source_position = token.source_position;
6216 literal->base.type = type_int;
6217 literal->literal.value = token.literal;
6219 size_t len = wstrlen(&literal->literal.value);
6221 warningf(HERE, "multi-character character constant");
6228 static entity_t *create_implicit_function(symbol_t *symbol,
6229 const source_position_t *source_position)
6231 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6232 ntype->function.return_type = type_int;
6233 ntype->function.unspecified_parameters = true;
6234 ntype->function.linkage = LINKAGE_C;
6235 type_t *type = identify_new_type(ntype);
6237 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6238 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6239 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6240 entity->declaration.type = type;
6241 entity->declaration.implicit = true;
6242 entity->base.namespc = NAMESPACE_NORMAL;
6243 entity->base.symbol = symbol;
6244 entity->base.source_position = *source_position;
6246 if (current_scope != NULL) {
6247 bool strict_prototypes_old = warning.strict_prototypes;
6248 warning.strict_prototypes = false;
6249 record_entity(entity, false);
6250 warning.strict_prototypes = strict_prototypes_old;
6257 * Performs automatic type cast as described in §6.3.2.1.
6259 * @param orig_type the original type
6261 static type_t *automatic_type_conversion(type_t *orig_type)
6263 type_t *type = skip_typeref(orig_type);
6264 if (is_type_array(type)) {
6265 array_type_t *array_type = &type->array;
6266 type_t *element_type = array_type->element_type;
6267 unsigned qualifiers = array_type->base.qualifiers;
6269 return make_pointer_type(element_type, qualifiers);
6272 if (is_type_function(type)) {
6273 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6280 * reverts the automatic casts of array to pointer types and function
6281 * to function-pointer types as defined §6.3.2.1
6283 type_t *revert_automatic_type_conversion(const expression_t *expression)
6285 switch (expression->kind) {
6286 case EXPR_REFERENCE: {
6287 entity_t *entity = expression->reference.entity;
6288 if (is_declaration(entity)) {
6289 return entity->declaration.type;
6290 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6291 return entity->enum_value.enum_type;
6293 panic("no declaration or enum in reference");
6298 entity_t *entity = expression->select.compound_entry;
6299 assert(is_declaration(entity));
6300 type_t *type = entity->declaration.type;
6301 return get_qualified_type(type,
6302 expression->base.type->base.qualifiers);
6305 case EXPR_UNARY_DEREFERENCE: {
6306 const expression_t *const value = expression->unary.value;
6307 type_t *const type = skip_typeref(value->base.type);
6308 if (!is_type_pointer(type))
6309 return type_error_type;
6310 return type->pointer.points_to;
6313 case EXPR_ARRAY_ACCESS: {
6314 const expression_t *array_ref = expression->array_access.array_ref;
6315 type_t *type_left = skip_typeref(array_ref->base.type);
6316 if (!is_type_pointer(type_left))
6317 return type_error_type;
6318 return type_left->pointer.points_to;
6321 case EXPR_STRING_LITERAL: {
6322 size_t size = expression->string_literal.value.size;
6323 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6326 case EXPR_WIDE_STRING_LITERAL: {
6327 size_t size = wstrlen(&expression->string_literal.value);
6328 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6331 case EXPR_COMPOUND_LITERAL:
6332 return expression->compound_literal.type;
6337 return expression->base.type;
6341 * Find an entity matching a symbol in a scope.
6342 * Uses current scope if scope is NULL
6344 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6345 namespace_tag_t namespc)
6347 if (scope == NULL) {
6348 return get_entity(symbol, namespc);
6351 /* we should optimize here, if scope grows above a certain size we should
6352 construct a hashmap here... */
6353 entity_t *entity = scope->entities;
6354 for ( ; entity != NULL; entity = entity->base.next) {
6355 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6362 static entity_t *parse_qualified_identifier(void)
6364 /* namespace containing the symbol */
6366 source_position_t pos;
6367 const scope_t *lookup_scope = NULL;
6369 if (next_if(T_COLONCOLON))
6370 lookup_scope = &unit->scope;
6374 if (token.type != T_IDENTIFIER) {
6375 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6376 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6378 symbol = token.symbol;
6383 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6385 if (!next_if(T_COLONCOLON))
6388 switch (entity->kind) {
6389 case ENTITY_NAMESPACE:
6390 lookup_scope = &entity->namespacee.members;
6395 lookup_scope = &entity->compound.members;
6398 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6399 symbol, get_entity_kind_name(entity->kind));
6404 if (entity == NULL) {
6405 if (!strict_mode && token.type == '(') {
6406 /* an implicitly declared function */
6407 if (warning.error_implicit_function_declaration) {
6408 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6409 } else if (warning.implicit_function_declaration) {
6410 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6413 entity = create_implicit_function(symbol, &pos);
6415 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6416 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6423 /* skip further qualifications */
6424 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6426 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6429 static expression_t *parse_reference(void)
6431 entity_t *entity = parse_qualified_identifier();
6434 if (is_declaration(entity)) {
6435 orig_type = entity->declaration.type;
6436 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6437 orig_type = entity->enum_value.enum_type;
6439 panic("expected declaration or enum value in reference");
6442 /* we always do the auto-type conversions; the & and sizeof parser contains
6443 * code to revert this! */
6444 type_t *type = automatic_type_conversion(orig_type);
6446 expression_kind_t kind = EXPR_REFERENCE;
6447 if (entity->kind == ENTITY_ENUM_VALUE)
6448 kind = EXPR_REFERENCE_ENUM_VALUE;
6450 expression_t *expression = allocate_expression_zero(kind);
6451 expression->reference.entity = entity;
6452 expression->base.type = type;
6454 /* this declaration is used */
6455 if (is_declaration(entity)) {
6456 entity->declaration.used = true;
6459 if (entity->base.parent_scope != file_scope
6460 && (current_function != NULL
6461 && entity->base.parent_scope->depth < current_function->parameters.depth)
6462 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6463 if (entity->kind == ENTITY_VARIABLE) {
6464 /* access of a variable from an outer function */
6465 entity->variable.address_taken = true;
6466 } else if (entity->kind == ENTITY_PARAMETER) {
6467 entity->parameter.address_taken = true;
6469 current_function->need_closure = true;
6472 check_deprecated(HERE, entity);
6474 if (warning.init_self && entity == current_init_decl && !in_type_prop
6475 && entity->kind == ENTITY_VARIABLE) {
6476 current_init_decl = NULL;
6477 warningf(HERE, "variable '%#T' is initialized by itself",
6478 entity->declaration.type, entity->base.symbol);
6484 static bool semantic_cast(expression_t *cast)
6486 expression_t *expression = cast->unary.value;
6487 type_t *orig_dest_type = cast->base.type;
6488 type_t *orig_type_right = expression->base.type;
6489 type_t const *dst_type = skip_typeref(orig_dest_type);
6490 type_t const *src_type = skip_typeref(orig_type_right);
6491 source_position_t const *pos = &cast->base.source_position;
6493 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6494 if (dst_type == type_void)
6497 /* only integer and pointer can be casted to pointer */
6498 if (is_type_pointer(dst_type) &&
6499 !is_type_pointer(src_type) &&
6500 !is_type_integer(src_type) &&
6501 is_type_valid(src_type)) {
6502 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6506 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6507 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6511 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6512 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6516 if (warning.cast_qual &&
6517 is_type_pointer(src_type) &&
6518 is_type_pointer(dst_type)) {
6519 type_t *src = skip_typeref(src_type->pointer.points_to);
6520 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6521 unsigned missing_qualifiers =
6522 src->base.qualifiers & ~dst->base.qualifiers;
6523 if (missing_qualifiers != 0) {
6525 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6526 missing_qualifiers, orig_type_right);
6532 static expression_t *parse_compound_literal(type_t *type)
6534 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6536 parse_initializer_env_t env;
6539 env.must_be_constant = false;
6540 initializer_t *initializer = parse_initializer(&env);
6543 expression->compound_literal.initializer = initializer;
6544 expression->compound_literal.type = type;
6545 expression->base.type = automatic_type_conversion(type);
6551 * Parse a cast expression.
6553 static expression_t *parse_cast(void)
6555 add_anchor_token(')');
6557 source_position_t source_position = token.source_position;
6559 type_t *type = parse_typename();
6561 rem_anchor_token(')');
6562 expect(')', end_error);
6564 if (token.type == '{') {
6565 return parse_compound_literal(type);
6568 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6569 cast->base.source_position = source_position;
6571 expression_t *value = parse_subexpression(PREC_CAST);
6572 cast->base.type = type;
6573 cast->unary.value = value;
6575 if (! semantic_cast(cast)) {
6576 /* TODO: record the error in the AST. else it is impossible to detect it */
6581 return create_invalid_expression();
6585 * Parse a statement expression.
6587 static expression_t *parse_statement_expression(void)
6589 add_anchor_token(')');
6591 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6593 statement_t *statement = parse_compound_statement(true);
6594 statement->compound.stmt_expr = true;
6595 expression->statement.statement = statement;
6597 /* find last statement and use its type */
6598 type_t *type = type_void;
6599 const statement_t *stmt = statement->compound.statements;
6601 while (stmt->base.next != NULL)
6602 stmt = stmt->base.next;
6604 if (stmt->kind == STATEMENT_EXPRESSION) {
6605 type = stmt->expression.expression->base.type;
6607 } else if (warning.other) {
6608 warningf(&expression->base.source_position, "empty statement expression ({})");
6610 expression->base.type = type;
6612 rem_anchor_token(')');
6613 expect(')', end_error);
6620 * Parse a parenthesized expression.
6622 static expression_t *parse_parenthesized_expression(void)
6626 switch (token.type) {
6628 /* gcc extension: a statement expression */
6629 return parse_statement_expression();
6633 return parse_cast();
6635 if (is_typedef_symbol(token.symbol)) {
6636 return parse_cast();
6640 add_anchor_token(')');
6641 expression_t *result = parse_expression();
6642 result->base.parenthesized = true;
6643 rem_anchor_token(')');
6644 expect(')', end_error);
6650 static expression_t *parse_function_keyword(void)
6654 if (current_function == NULL) {
6655 errorf(HERE, "'__func__' used outside of a function");
6658 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6659 expression->base.type = type_char_ptr;
6660 expression->funcname.kind = FUNCNAME_FUNCTION;
6667 static expression_t *parse_pretty_function_keyword(void)
6669 if (current_function == NULL) {
6670 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6673 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6674 expression->base.type = type_char_ptr;
6675 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6677 eat(T___PRETTY_FUNCTION__);
6682 static expression_t *parse_funcsig_keyword(void)
6684 if (current_function == NULL) {
6685 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6688 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6689 expression->base.type = type_char_ptr;
6690 expression->funcname.kind = FUNCNAME_FUNCSIG;
6697 static expression_t *parse_funcdname_keyword(void)
6699 if (current_function == NULL) {
6700 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6703 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6704 expression->base.type = type_char_ptr;
6705 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6707 eat(T___FUNCDNAME__);
6712 static designator_t *parse_designator(void)
6714 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6715 result->source_position = *HERE;
6717 if (token.type != T_IDENTIFIER) {
6718 parse_error_expected("while parsing member designator",
6719 T_IDENTIFIER, NULL);
6722 result->symbol = token.symbol;
6725 designator_t *last_designator = result;
6728 if (token.type != T_IDENTIFIER) {
6729 parse_error_expected("while parsing member designator",
6730 T_IDENTIFIER, NULL);
6733 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6734 designator->source_position = *HERE;
6735 designator->symbol = token.symbol;
6738 last_designator->next = designator;
6739 last_designator = designator;
6743 add_anchor_token(']');
6744 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6745 designator->source_position = *HERE;
6746 designator->array_index = parse_expression();
6747 rem_anchor_token(']');
6748 expect(']', end_error);
6749 if (designator->array_index == NULL) {
6753 last_designator->next = designator;
6754 last_designator = designator;
6766 * Parse the __builtin_offsetof() expression.
6768 static expression_t *parse_offsetof(void)
6770 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6771 expression->base.type = type_size_t;
6773 eat(T___builtin_offsetof);
6775 expect('(', end_error);
6776 add_anchor_token(',');
6777 type_t *type = parse_typename();
6778 rem_anchor_token(',');
6779 expect(',', end_error);
6780 add_anchor_token(')');
6781 designator_t *designator = parse_designator();
6782 rem_anchor_token(')');
6783 expect(')', end_error);
6785 expression->offsetofe.type = type;
6786 expression->offsetofe.designator = designator;
6789 memset(&path, 0, sizeof(path));
6790 path.top_type = type;
6791 path.path = NEW_ARR_F(type_path_entry_t, 0);
6793 descend_into_subtype(&path);
6795 if (!walk_designator(&path, designator, true)) {
6796 return create_invalid_expression();
6799 DEL_ARR_F(path.path);
6803 return create_invalid_expression();
6807 * Parses a _builtin_va_start() expression.
6809 static expression_t *parse_va_start(void)
6811 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6813 eat(T___builtin_va_start);
6815 expect('(', end_error);
6816 add_anchor_token(',');
6817 expression->va_starte.ap = parse_assignment_expression();
6818 rem_anchor_token(',');
6819 expect(',', end_error);
6820 expression_t *const expr = parse_assignment_expression();
6821 if (expr->kind == EXPR_REFERENCE) {
6822 entity_t *const entity = expr->reference.entity;
6823 if (!current_function->base.type->function.variadic) {
6824 errorf(&expr->base.source_position,
6825 "'va_start' used in non-variadic function");
6826 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6827 entity->base.next != NULL ||
6828 entity->kind != ENTITY_PARAMETER) {
6829 errorf(&expr->base.source_position,
6830 "second argument of 'va_start' must be last parameter of the current function");
6832 expression->va_starte.parameter = &entity->variable;
6834 expect(')', end_error);
6837 expect(')', end_error);
6839 return create_invalid_expression();
6843 * Parses a __builtin_va_arg() expression.
6845 static expression_t *parse_va_arg(void)
6847 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6849 eat(T___builtin_va_arg);
6851 expect('(', end_error);
6853 ap.expression = parse_assignment_expression();
6854 expression->va_arge.ap = ap.expression;
6855 check_call_argument(type_valist, &ap, 1);
6857 expect(',', end_error);
6858 expression->base.type = parse_typename();
6859 expect(')', end_error);
6863 return create_invalid_expression();
6867 * Parses a __builtin_va_copy() expression.
6869 static expression_t *parse_va_copy(void)
6871 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6873 eat(T___builtin_va_copy);
6875 expect('(', end_error);
6876 expression_t *dst = parse_assignment_expression();
6877 assign_error_t error = semantic_assign(type_valist, dst);
6878 report_assign_error(error, type_valist, dst, "call argument 1",
6879 &dst->base.source_position);
6880 expression->va_copye.dst = dst;
6882 expect(',', end_error);
6884 call_argument_t src;
6885 src.expression = parse_assignment_expression();
6886 check_call_argument(type_valist, &src, 2);
6887 expression->va_copye.src = src.expression;
6888 expect(')', end_error);
6892 return create_invalid_expression();
6896 * Parses a __builtin_constant_p() expression.
6898 static expression_t *parse_builtin_constant(void)
6900 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6902 eat(T___builtin_constant_p);
6904 expect('(', end_error);
6905 add_anchor_token(')');
6906 expression->builtin_constant.value = parse_assignment_expression();
6907 rem_anchor_token(')');
6908 expect(')', end_error);
6909 expression->base.type = type_int;
6913 return create_invalid_expression();
6917 * Parses a __builtin_types_compatible_p() expression.
6919 static expression_t *parse_builtin_types_compatible(void)
6921 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6923 eat(T___builtin_types_compatible_p);
6925 expect('(', end_error);
6926 add_anchor_token(')');
6927 add_anchor_token(',');
6928 expression->builtin_types_compatible.left = parse_typename();
6929 rem_anchor_token(',');
6930 expect(',', end_error);
6931 expression->builtin_types_compatible.right = parse_typename();
6932 rem_anchor_token(')');
6933 expect(')', end_error);
6934 expression->base.type = type_int;
6938 return create_invalid_expression();
6942 * Parses a __builtin_is_*() compare expression.
6944 static expression_t *parse_compare_builtin(void)
6946 expression_t *expression;
6948 switch (token.type) {
6949 case T___builtin_isgreater:
6950 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6952 case T___builtin_isgreaterequal:
6953 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6955 case T___builtin_isless:
6956 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6958 case T___builtin_islessequal:
6959 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6961 case T___builtin_islessgreater:
6962 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6964 case T___builtin_isunordered:
6965 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6968 internal_errorf(HERE, "invalid compare builtin found");
6970 expression->base.source_position = *HERE;
6973 expect('(', end_error);
6974 expression->binary.left = parse_assignment_expression();
6975 expect(',', end_error);
6976 expression->binary.right = parse_assignment_expression();
6977 expect(')', end_error);
6979 type_t *const orig_type_left = expression->binary.left->base.type;
6980 type_t *const orig_type_right = expression->binary.right->base.type;
6982 type_t *const type_left = skip_typeref(orig_type_left);
6983 type_t *const type_right = skip_typeref(orig_type_right);
6984 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6985 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6986 type_error_incompatible("invalid operands in comparison",
6987 &expression->base.source_position, orig_type_left, orig_type_right);
6990 semantic_comparison(&expression->binary);
6995 return create_invalid_expression();
6999 * Parses a MS assume() expression.
7001 static expression_t *parse_assume(void)
7003 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7007 expect('(', end_error);
7008 add_anchor_token(')');
7009 expression->unary.value = parse_assignment_expression();
7010 rem_anchor_token(')');
7011 expect(')', end_error);
7013 expression->base.type = type_void;
7016 return create_invalid_expression();
7020 * Return the declaration for a given label symbol or create a new one.
7022 * @param symbol the symbol of the label
7024 static label_t *get_label(symbol_t *symbol)
7027 assert(current_function != NULL);
7029 label = get_entity(symbol, NAMESPACE_LABEL);
7030 /* if we found a local label, we already created the declaration */
7031 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7032 if (label->base.parent_scope != current_scope) {
7033 assert(label->base.parent_scope->depth < current_scope->depth);
7034 current_function->goto_to_outer = true;
7036 return &label->label;
7039 label = get_entity(symbol, NAMESPACE_LABEL);
7040 /* if we found a label in the same function, then we already created the
7043 && label->base.parent_scope == ¤t_function->parameters) {
7044 return &label->label;
7047 /* otherwise we need to create a new one */
7048 label = allocate_entity_zero(ENTITY_LABEL);
7049 label->base.namespc = NAMESPACE_LABEL;
7050 label->base.symbol = symbol;
7054 return &label->label;
7058 * Parses a GNU && label address expression.
7060 static expression_t *parse_label_address(void)
7062 source_position_t source_position = token.source_position;
7064 if (token.type != T_IDENTIFIER) {
7065 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7068 symbol_t *symbol = token.symbol;
7071 label_t *label = get_label(symbol);
7073 label->address_taken = true;
7075 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7076 expression->base.source_position = source_position;
7078 /* label address is threaten as a void pointer */
7079 expression->base.type = type_void_ptr;
7080 expression->label_address.label = label;
7083 return create_invalid_expression();
7087 * Parse a microsoft __noop expression.
7089 static expression_t *parse_noop_expression(void)
7091 /* the result is a (int)0 */
7092 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7093 literal->base.type = type_int;
7094 literal->base.source_position = token.source_position;
7095 literal->literal.value.begin = "__noop";
7096 literal->literal.value.size = 6;
7100 if (token.type == '(') {
7101 /* parse arguments */
7103 add_anchor_token(')');
7104 add_anchor_token(',');
7106 if (token.type != ')') do {
7107 (void)parse_assignment_expression();
7108 } while (next_if(','));
7110 rem_anchor_token(',');
7111 rem_anchor_token(')');
7112 expect(')', end_error);
7119 * Parses a primary expression.
7121 static expression_t *parse_primary_expression(void)
7123 switch (token.type) {
7124 case T_false: return parse_boolean_literal(false);
7125 case T_true: return parse_boolean_literal(true);
7127 case T_INTEGER_OCTAL:
7128 case T_INTEGER_HEXADECIMAL:
7129 case T_FLOATINGPOINT:
7130 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7131 case T_CHARACTER_CONSTANT: return parse_character_constant();
7132 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7133 case T_STRING_LITERAL:
7134 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7135 case T___FUNCTION__:
7136 case T___func__: return parse_function_keyword();
7137 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7138 case T___FUNCSIG__: return parse_funcsig_keyword();
7139 case T___FUNCDNAME__: return parse_funcdname_keyword();
7140 case T___builtin_offsetof: return parse_offsetof();
7141 case T___builtin_va_start: return parse_va_start();
7142 case T___builtin_va_arg: return parse_va_arg();
7143 case T___builtin_va_copy: return parse_va_copy();
7144 case T___builtin_isgreater:
7145 case T___builtin_isgreaterequal:
7146 case T___builtin_isless:
7147 case T___builtin_islessequal:
7148 case T___builtin_islessgreater:
7149 case T___builtin_isunordered: return parse_compare_builtin();
7150 case T___builtin_constant_p: return parse_builtin_constant();
7151 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7152 case T__assume: return parse_assume();
7155 return parse_label_address();
7158 case '(': return parse_parenthesized_expression();
7159 case T___noop: return parse_noop_expression();
7161 /* Gracefully handle type names while parsing expressions. */
7163 return parse_reference();
7165 if (!is_typedef_symbol(token.symbol)) {
7166 return parse_reference();
7170 source_position_t const pos = *HERE;
7171 type_t const *const type = parse_typename();
7172 errorf(&pos, "encountered type '%T' while parsing expression", type);
7173 return create_invalid_expression();
7177 errorf(HERE, "unexpected token %K, expected an expression", &token);
7179 return create_invalid_expression();
7183 * Check if the expression has the character type and issue a warning then.
7185 static void check_for_char_index_type(const expression_t *expression)
7187 type_t *const type = expression->base.type;
7188 const type_t *const base_type = skip_typeref(type);
7190 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7191 warning.char_subscripts) {
7192 warningf(&expression->base.source_position,
7193 "array subscript has type '%T'", type);
7197 static expression_t *parse_array_expression(expression_t *left)
7199 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7202 add_anchor_token(']');
7204 expression_t *inside = parse_expression();
7206 type_t *const orig_type_left = left->base.type;
7207 type_t *const orig_type_inside = inside->base.type;
7209 type_t *const type_left = skip_typeref(orig_type_left);
7210 type_t *const type_inside = skip_typeref(orig_type_inside);
7212 type_t *return_type;
7213 array_access_expression_t *array_access = &expression->array_access;
7214 if (is_type_pointer(type_left)) {
7215 return_type = type_left->pointer.points_to;
7216 array_access->array_ref = left;
7217 array_access->index = inside;
7218 check_for_char_index_type(inside);
7219 } else if (is_type_pointer(type_inside)) {
7220 return_type = type_inside->pointer.points_to;
7221 array_access->array_ref = inside;
7222 array_access->index = left;
7223 array_access->flipped = true;
7224 check_for_char_index_type(left);
7226 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7228 "array access on object with non-pointer types '%T', '%T'",
7229 orig_type_left, orig_type_inside);
7231 return_type = type_error_type;
7232 array_access->array_ref = left;
7233 array_access->index = inside;
7236 expression->base.type = automatic_type_conversion(return_type);
7238 rem_anchor_token(']');
7239 expect(']', end_error);
7244 static expression_t *parse_typeprop(expression_kind_t const kind)
7246 expression_t *tp_expression = allocate_expression_zero(kind);
7247 tp_expression->base.type = type_size_t;
7249 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7251 /* we only refer to a type property, mark this case */
7252 bool old = in_type_prop;
7253 in_type_prop = true;
7256 expression_t *expression;
7257 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7259 add_anchor_token(')');
7260 orig_type = parse_typename();
7261 rem_anchor_token(')');
7262 expect(')', end_error);
7264 if (token.type == '{') {
7265 /* It was not sizeof(type) after all. It is sizeof of an expression
7266 * starting with a compound literal */
7267 expression = parse_compound_literal(orig_type);
7268 goto typeprop_expression;
7271 expression = parse_subexpression(PREC_UNARY);
7273 typeprop_expression:
7274 tp_expression->typeprop.tp_expression = expression;
7276 orig_type = revert_automatic_type_conversion(expression);
7277 expression->base.type = orig_type;
7280 tp_expression->typeprop.type = orig_type;
7281 type_t const* const type = skip_typeref(orig_type);
7282 char const* wrong_type = NULL;
7283 if (is_type_incomplete(type)) {
7284 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7285 wrong_type = "incomplete";
7286 } else if (type->kind == TYPE_FUNCTION) {
7288 /* function types are allowed (and return 1) */
7289 if (warning.other) {
7290 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7291 warningf(&tp_expression->base.source_position,
7292 "%s expression with function argument returns invalid result", what);
7295 wrong_type = "function";
7298 if (is_type_incomplete(type))
7299 wrong_type = "incomplete";
7301 if (type->kind == TYPE_BITFIELD)
7302 wrong_type = "bitfield";
7304 if (wrong_type != NULL) {
7305 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7306 errorf(&tp_expression->base.source_position,
7307 "operand of %s expression must not be of %s type '%T'",
7308 what, wrong_type, orig_type);
7313 return tp_expression;
7316 static expression_t *parse_sizeof(void)
7318 return parse_typeprop(EXPR_SIZEOF);
7321 static expression_t *parse_alignof(void)
7323 return parse_typeprop(EXPR_ALIGNOF);
7326 static expression_t *parse_select_expression(expression_t *addr)
7328 assert(token.type == '.' || token.type == T_MINUSGREATER);
7329 bool select_left_arrow = (token.type == T_MINUSGREATER);
7330 source_position_t const pos = *HERE;
7333 if (token.type != T_IDENTIFIER) {
7334 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7335 return create_invalid_expression();
7337 symbol_t *symbol = token.symbol;
7340 type_t *const orig_type = addr->base.type;
7341 type_t *const type = skip_typeref(orig_type);
7344 bool saw_error = false;
7345 if (is_type_pointer(type)) {
7346 if (!select_left_arrow) {
7348 "request for member '%Y' in something not a struct or union, but '%T'",
7352 type_left = skip_typeref(type->pointer.points_to);
7354 if (select_left_arrow && is_type_valid(type)) {
7355 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7361 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7362 type_left->kind != TYPE_COMPOUND_UNION) {
7364 if (is_type_valid(type_left) && !saw_error) {
7366 "request for member '%Y' in something not a struct or union, but '%T'",
7369 return create_invalid_expression();
7372 compound_t *compound = type_left->compound.compound;
7373 if (!compound->complete) {
7374 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7376 return create_invalid_expression();
7379 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7380 expression_t *result =
7381 find_create_select(&pos, addr, qualifiers, compound, symbol);
7383 if (result == NULL) {
7384 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7385 return create_invalid_expression();
7391 static void check_call_argument(type_t *expected_type,
7392 call_argument_t *argument, unsigned pos)
7394 type_t *expected_type_skip = skip_typeref(expected_type);
7395 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7396 expression_t *arg_expr = argument->expression;
7397 type_t *arg_type = skip_typeref(arg_expr->base.type);
7399 /* handle transparent union gnu extension */
7400 if (is_type_union(expected_type_skip)
7401 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7402 compound_t *union_decl = expected_type_skip->compound.compound;
7403 type_t *best_type = NULL;
7404 entity_t *entry = union_decl->members.entities;
7405 for ( ; entry != NULL; entry = entry->base.next) {
7406 assert(is_declaration(entry));
7407 type_t *decl_type = entry->declaration.type;
7408 error = semantic_assign(decl_type, arg_expr);
7409 if (error == ASSIGN_ERROR_INCOMPATIBLE
7410 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7413 if (error == ASSIGN_SUCCESS) {
7414 best_type = decl_type;
7415 } else if (best_type == NULL) {
7416 best_type = decl_type;
7420 if (best_type != NULL) {
7421 expected_type = best_type;
7425 error = semantic_assign(expected_type, arg_expr);
7426 argument->expression = create_implicit_cast(arg_expr, expected_type);
7428 if (error != ASSIGN_SUCCESS) {
7429 /* report exact scope in error messages (like "in argument 3") */
7431 snprintf(buf, sizeof(buf), "call argument %u", pos);
7432 report_assign_error(error, expected_type, arg_expr, buf,
7433 &arg_expr->base.source_position);
7434 } else if (warning.traditional || warning.conversion) {
7435 type_t *const promoted_type = get_default_promoted_type(arg_type);
7436 if (!types_compatible(expected_type_skip, promoted_type) &&
7437 !types_compatible(expected_type_skip, type_void_ptr) &&
7438 !types_compatible(type_void_ptr, promoted_type)) {
7439 /* Deliberately show the skipped types in this warning */
7440 warningf(&arg_expr->base.source_position,
7441 "passing call argument %u as '%T' rather than '%T' due to prototype",
7442 pos, expected_type_skip, promoted_type);
7448 * Handle the semantic restrictions of builtin calls
7450 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7451 switch (call->function->reference.entity->function.btk) {
7452 case bk_gnu_builtin_return_address:
7453 case bk_gnu_builtin_frame_address: {
7454 /* argument must be constant */
7455 call_argument_t *argument = call->arguments;
7457 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7458 errorf(&call->base.source_position,
7459 "argument of '%Y' must be a constant expression",
7460 call->function->reference.entity->base.symbol);
7464 case bk_gnu_builtin_object_size:
7465 if (call->arguments == NULL)
7468 call_argument_t *arg = call->arguments->next;
7469 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7470 errorf(&call->base.source_position,
7471 "second argument of '%Y' must be a constant expression",
7472 call->function->reference.entity->base.symbol);
7475 case bk_gnu_builtin_prefetch:
7476 /* second and third argument must be constant if existent */
7477 if (call->arguments == NULL)
7479 call_argument_t *rw = call->arguments->next;
7480 call_argument_t *locality = NULL;
7483 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7484 errorf(&call->base.source_position,
7485 "second argument of '%Y' must be a constant expression",
7486 call->function->reference.entity->base.symbol);
7488 locality = rw->next;
7490 if (locality != NULL) {
7491 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7492 errorf(&call->base.source_position,
7493 "third argument of '%Y' must be a constant expression",
7494 call->function->reference.entity->base.symbol);
7496 locality = rw->next;
7505 * Parse a call expression, ie. expression '( ... )'.
7507 * @param expression the function address
7509 static expression_t *parse_call_expression(expression_t *expression)
7511 expression_t *result = allocate_expression_zero(EXPR_CALL);
7512 call_expression_t *call = &result->call;
7513 call->function = expression;
7515 type_t *const orig_type = expression->base.type;
7516 type_t *const type = skip_typeref(orig_type);
7518 function_type_t *function_type = NULL;
7519 if (is_type_pointer(type)) {
7520 type_t *const to_type = skip_typeref(type->pointer.points_to);
7522 if (is_type_function(to_type)) {
7523 function_type = &to_type->function;
7524 call->base.type = function_type->return_type;
7528 if (function_type == NULL && is_type_valid(type)) {
7530 "called object '%E' (type '%T') is not a pointer to a function",
7531 expression, orig_type);
7534 /* parse arguments */
7536 add_anchor_token(')');
7537 add_anchor_token(',');
7539 if (token.type != ')') {
7540 call_argument_t **anchor = &call->arguments;
7542 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7543 argument->expression = parse_assignment_expression();
7546 anchor = &argument->next;
7547 } while (next_if(','));
7549 rem_anchor_token(',');
7550 rem_anchor_token(')');
7551 expect(')', end_error);
7553 if (function_type == NULL)
7556 /* check type and count of call arguments */
7557 function_parameter_t *parameter = function_type->parameters;
7558 call_argument_t *argument = call->arguments;
7559 if (!function_type->unspecified_parameters) {
7560 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7561 parameter = parameter->next, argument = argument->next) {
7562 check_call_argument(parameter->type, argument, ++pos);
7565 if (parameter != NULL) {
7566 errorf(HERE, "too few arguments to function '%E'", expression);
7567 } else if (argument != NULL && !function_type->variadic) {
7568 errorf(HERE, "too many arguments to function '%E'", expression);
7572 /* do default promotion for other arguments */
7573 for (; argument != NULL; argument = argument->next) {
7574 type_t *type = argument->expression->base.type;
7575 if (!is_type_object(skip_typeref(type))) {
7576 errorf(&argument->expression->base.source_position,
7577 "call argument '%E' must not be void", argument->expression);
7580 type = get_default_promoted_type(type);
7582 argument->expression
7583 = create_implicit_cast(argument->expression, type);
7586 check_format(&result->call);
7588 if (warning.aggregate_return &&
7589 is_type_compound(skip_typeref(function_type->return_type))) {
7590 warningf(&result->base.source_position,
7591 "function call has aggregate value");
7594 if (call->function->kind == EXPR_REFERENCE) {
7595 reference_expression_t *reference = &call->function->reference;
7596 if (reference->entity->kind == ENTITY_FUNCTION &&
7597 reference->entity->function.btk != bk_none)
7598 handle_builtin_argument_restrictions(call);
7605 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7607 static bool same_compound_type(const type_t *type1, const type_t *type2)
7610 is_type_compound(type1) &&
7611 type1->kind == type2->kind &&
7612 type1->compound.compound == type2->compound.compound;
7615 static expression_t const *get_reference_address(expression_t const *expr)
7617 bool regular_take_address = true;
7619 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7620 expr = expr->unary.value;
7622 regular_take_address = false;
7625 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7628 expr = expr->unary.value;
7631 if (expr->kind != EXPR_REFERENCE)
7634 /* special case for functions which are automatically converted to a
7635 * pointer to function without an extra TAKE_ADDRESS operation */
7636 if (!regular_take_address &&
7637 expr->reference.entity->kind != ENTITY_FUNCTION) {
7644 static void warn_reference_address_as_bool(expression_t const* expr)
7646 if (!warning.address)
7649 expr = get_reference_address(expr);
7651 warningf(&expr->base.source_position,
7652 "the address of '%Y' will always evaluate as 'true'",
7653 expr->reference.entity->base.symbol);
7657 static void warn_assignment_in_condition(const expression_t *const expr)
7659 if (!warning.parentheses)
7661 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7663 if (expr->base.parenthesized)
7665 warningf(&expr->base.source_position,
7666 "suggest parentheses around assignment used as truth value");
7669 static void semantic_condition(expression_t const *const expr,
7670 char const *const context)
7672 type_t *const type = skip_typeref(expr->base.type);
7673 if (is_type_scalar(type)) {
7674 warn_reference_address_as_bool(expr);
7675 warn_assignment_in_condition(expr);
7676 } else if (is_type_valid(type)) {
7677 errorf(&expr->base.source_position,
7678 "%s must have scalar type", context);
7683 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7685 * @param expression the conditional expression
7687 static expression_t *parse_conditional_expression(expression_t *expression)
7689 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7691 conditional_expression_t *conditional = &result->conditional;
7692 conditional->condition = expression;
7695 add_anchor_token(':');
7697 /* §6.5.15:2 The first operand shall have scalar type. */
7698 semantic_condition(expression, "condition of conditional operator");
7700 expression_t *true_expression = expression;
7701 bool gnu_cond = false;
7702 if (GNU_MODE && token.type == ':') {
7705 true_expression = parse_expression();
7707 rem_anchor_token(':');
7708 expect(':', end_error);
7710 expression_t *false_expression =
7711 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7713 type_t *const orig_true_type = true_expression->base.type;
7714 type_t *const orig_false_type = false_expression->base.type;
7715 type_t *const true_type = skip_typeref(orig_true_type);
7716 type_t *const false_type = skip_typeref(orig_false_type);
7719 type_t *result_type;
7720 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7721 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7722 /* ISO/IEC 14882:1998(E) §5.16:2 */
7723 if (true_expression->kind == EXPR_UNARY_THROW) {
7724 result_type = false_type;
7725 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7726 result_type = true_type;
7728 if (warning.other && (
7729 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7730 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7732 warningf(&conditional->base.source_position,
7733 "ISO C forbids conditional expression with only one void side");
7735 result_type = type_void;
7737 } else if (is_type_arithmetic(true_type)
7738 && is_type_arithmetic(false_type)) {
7739 result_type = semantic_arithmetic(true_type, false_type);
7740 } else if (same_compound_type(true_type, false_type)) {
7741 /* just take 1 of the 2 types */
7742 result_type = true_type;
7743 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7744 type_t *pointer_type;
7746 expression_t *other_expression;
7747 if (is_type_pointer(true_type) &&
7748 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7749 pointer_type = true_type;
7750 other_type = false_type;
7751 other_expression = false_expression;
7753 pointer_type = false_type;
7754 other_type = true_type;
7755 other_expression = true_expression;
7758 if (is_null_pointer_constant(other_expression)) {
7759 result_type = pointer_type;
7760 } else if (is_type_pointer(other_type)) {
7761 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7762 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7765 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7766 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7768 } else if (types_compatible(get_unqualified_type(to1),
7769 get_unqualified_type(to2))) {
7772 if (warning.other) {
7773 warningf(&conditional->base.source_position,
7774 "pointer types '%T' and '%T' in conditional expression are incompatible",
7775 true_type, false_type);
7780 type_t *const type =
7781 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7782 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7783 } else if (is_type_integer(other_type)) {
7784 if (warning.other) {
7785 warningf(&conditional->base.source_position,
7786 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7788 result_type = pointer_type;
7790 if (is_type_valid(other_type)) {
7791 type_error_incompatible("while parsing conditional",
7792 &expression->base.source_position, true_type, false_type);
7794 result_type = type_error_type;
7797 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7798 type_error_incompatible("while parsing conditional",
7799 &conditional->base.source_position, true_type,
7802 result_type = type_error_type;
7805 conditional->true_expression
7806 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7807 conditional->false_expression
7808 = create_implicit_cast(false_expression, result_type);
7809 conditional->base.type = result_type;
7814 * Parse an extension expression.
7816 static expression_t *parse_extension(void)
7818 eat(T___extension__);
7820 bool old_gcc_extension = in_gcc_extension;
7821 in_gcc_extension = true;
7822 expression_t *expression = parse_subexpression(PREC_UNARY);
7823 in_gcc_extension = old_gcc_extension;
7828 * Parse a __builtin_classify_type() expression.
7830 static expression_t *parse_builtin_classify_type(void)
7832 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7833 result->base.type = type_int;
7835 eat(T___builtin_classify_type);
7837 expect('(', end_error);
7838 add_anchor_token(')');
7839 expression_t *expression = parse_expression();
7840 rem_anchor_token(')');
7841 expect(')', end_error);
7842 result->classify_type.type_expression = expression;
7846 return create_invalid_expression();
7850 * Parse a delete expression
7851 * ISO/IEC 14882:1998(E) §5.3.5
7853 static expression_t *parse_delete(void)
7855 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7856 result->base.type = type_void;
7861 result->kind = EXPR_UNARY_DELETE_ARRAY;
7862 expect(']', end_error);
7866 expression_t *const value = parse_subexpression(PREC_CAST);
7867 result->unary.value = value;
7869 type_t *const type = skip_typeref(value->base.type);
7870 if (!is_type_pointer(type)) {
7871 if (is_type_valid(type)) {
7872 errorf(&value->base.source_position,
7873 "operand of delete must have pointer type");
7875 } else if (warning.other &&
7876 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7877 warningf(&value->base.source_position,
7878 "deleting 'void*' is undefined");
7885 * Parse a throw expression
7886 * ISO/IEC 14882:1998(E) §15:1
7888 static expression_t *parse_throw(void)
7890 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7891 result->base.type = type_void;
7895 expression_t *value = NULL;
7896 switch (token.type) {
7898 value = parse_assignment_expression();
7899 /* ISO/IEC 14882:1998(E) §15.1:3 */
7900 type_t *const orig_type = value->base.type;
7901 type_t *const type = skip_typeref(orig_type);
7902 if (is_type_incomplete(type)) {
7903 errorf(&value->base.source_position,
7904 "cannot throw object of incomplete type '%T'", orig_type);
7905 } else if (is_type_pointer(type)) {
7906 type_t *const points_to = skip_typeref(type->pointer.points_to);
7907 if (is_type_incomplete(points_to) &&
7908 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7909 errorf(&value->base.source_position,
7910 "cannot throw pointer to incomplete type '%T'", orig_type);
7918 result->unary.value = value;
7923 static bool check_pointer_arithmetic(const source_position_t *source_position,
7924 type_t *pointer_type,
7925 type_t *orig_pointer_type)
7927 type_t *points_to = pointer_type->pointer.points_to;
7928 points_to = skip_typeref(points_to);
7930 if (is_type_incomplete(points_to)) {
7931 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7932 errorf(source_position,
7933 "arithmetic with pointer to incomplete type '%T' not allowed",
7936 } else if (warning.pointer_arith) {
7937 warningf(source_position,
7938 "pointer of type '%T' used in arithmetic",
7941 } else if (is_type_function(points_to)) {
7943 errorf(source_position,
7944 "arithmetic with pointer to function type '%T' not allowed",
7947 } else if (warning.pointer_arith) {
7948 warningf(source_position,
7949 "pointer to a function '%T' used in arithmetic",
7956 static bool is_lvalue(const expression_t *expression)
7958 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7959 switch (expression->kind) {
7960 case EXPR_ARRAY_ACCESS:
7961 case EXPR_COMPOUND_LITERAL:
7962 case EXPR_REFERENCE:
7964 case EXPR_UNARY_DEREFERENCE:
7968 type_t *type = skip_typeref(expression->base.type);
7970 /* ISO/IEC 14882:1998(E) §3.10:3 */
7971 is_type_reference(type) ||
7972 /* Claim it is an lvalue, if the type is invalid. There was a parse
7973 * error before, which maybe prevented properly recognizing it as
7975 !is_type_valid(type);
7980 static void semantic_incdec(unary_expression_t *expression)
7982 type_t *const orig_type = expression->value->base.type;
7983 type_t *const type = skip_typeref(orig_type);
7984 if (is_type_pointer(type)) {
7985 if (!check_pointer_arithmetic(&expression->base.source_position,
7989 } else if (!is_type_real(type) && is_type_valid(type)) {
7990 /* TODO: improve error message */
7991 errorf(&expression->base.source_position,
7992 "operation needs an arithmetic or pointer type");
7995 if (!is_lvalue(expression->value)) {
7996 /* TODO: improve error message */
7997 errorf(&expression->base.source_position, "lvalue required as operand");
7999 expression->base.type = orig_type;
8002 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8004 type_t *const orig_type = expression->value->base.type;
8005 type_t *const type = skip_typeref(orig_type);
8006 if (!is_type_arithmetic(type)) {
8007 if (is_type_valid(type)) {
8008 /* TODO: improve error message */
8009 errorf(&expression->base.source_position,
8010 "operation needs an arithmetic type");
8015 expression->base.type = orig_type;
8018 static void semantic_unexpr_plus(unary_expression_t *expression)
8020 semantic_unexpr_arithmetic(expression);
8021 if (warning.traditional)
8022 warningf(&expression->base.source_position,
8023 "traditional C rejects the unary plus operator");
8026 static void semantic_not(unary_expression_t *expression)
8028 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8029 semantic_condition(expression->value, "operand of !");
8030 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8033 static void semantic_unexpr_integer(unary_expression_t *expression)
8035 type_t *const orig_type = expression->value->base.type;
8036 type_t *const type = skip_typeref(orig_type);
8037 if (!is_type_integer(type)) {
8038 if (is_type_valid(type)) {
8039 errorf(&expression->base.source_position,
8040 "operand of ~ must be of integer type");
8045 expression->base.type = orig_type;
8048 static void semantic_dereference(unary_expression_t *expression)
8050 type_t *const orig_type = expression->value->base.type;
8051 type_t *const type = skip_typeref(orig_type);
8052 if (!is_type_pointer(type)) {
8053 if (is_type_valid(type)) {
8054 errorf(&expression->base.source_position,
8055 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8060 type_t *result_type = type->pointer.points_to;
8061 result_type = automatic_type_conversion(result_type);
8062 expression->base.type = result_type;
8066 * Record that an address is taken (expression represents an lvalue).
8068 * @param expression the expression
8069 * @param may_be_register if true, the expression might be an register
8071 static void set_address_taken(expression_t *expression, bool may_be_register)
8073 if (expression->kind != EXPR_REFERENCE)
8076 entity_t *const entity = expression->reference.entity;
8078 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8081 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8082 && !may_be_register) {
8083 errorf(&expression->base.source_position,
8084 "address of register %s '%Y' requested",
8085 get_entity_kind_name(entity->kind), entity->base.symbol);
8088 if (entity->kind == ENTITY_VARIABLE) {
8089 entity->variable.address_taken = true;
8091 assert(entity->kind == ENTITY_PARAMETER);
8092 entity->parameter.address_taken = true;
8097 * Check the semantic of the address taken expression.
8099 static void semantic_take_addr(unary_expression_t *expression)
8101 expression_t *value = expression->value;
8102 value->base.type = revert_automatic_type_conversion(value);
8104 type_t *orig_type = value->base.type;
8105 type_t *type = skip_typeref(orig_type);
8106 if (!is_type_valid(type))
8110 if (!is_lvalue(value)) {
8111 errorf(&expression->base.source_position, "'&' requires an lvalue");
8113 if (type->kind == TYPE_BITFIELD) {
8114 errorf(&expression->base.source_position,
8115 "'&' not allowed on object with bitfield type '%T'",
8119 set_address_taken(value, false);
8121 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8124 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8125 static expression_t *parse_##unexpression_type(void) \
8127 expression_t *unary_expression \
8128 = allocate_expression_zero(unexpression_type); \
8130 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8132 sfunc(&unary_expression->unary); \
8134 return unary_expression; \
8137 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8138 semantic_unexpr_arithmetic)
8139 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8140 semantic_unexpr_plus)
8141 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8143 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8144 semantic_dereference)
8145 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8147 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8148 semantic_unexpr_integer)
8149 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8151 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8154 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8156 static expression_t *parse_##unexpression_type(expression_t *left) \
8158 expression_t *unary_expression \
8159 = allocate_expression_zero(unexpression_type); \
8161 unary_expression->unary.value = left; \
8163 sfunc(&unary_expression->unary); \
8165 return unary_expression; \
8168 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8169 EXPR_UNARY_POSTFIX_INCREMENT,
8171 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8172 EXPR_UNARY_POSTFIX_DECREMENT,
8175 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8177 /* TODO: handle complex + imaginary types */
8179 type_left = get_unqualified_type(type_left);
8180 type_right = get_unqualified_type(type_right);
8182 /* §6.3.1.8 Usual arithmetic conversions */
8183 if (type_left == type_long_double || type_right == type_long_double) {
8184 return type_long_double;
8185 } else if (type_left == type_double || type_right == type_double) {
8187 } else if (type_left == type_float || type_right == type_float) {
8191 type_left = promote_integer(type_left);
8192 type_right = promote_integer(type_right);
8194 if (type_left == type_right)
8197 bool const signed_left = is_type_signed(type_left);
8198 bool const signed_right = is_type_signed(type_right);
8199 int const rank_left = get_rank(type_left);
8200 int const rank_right = get_rank(type_right);
8202 if (signed_left == signed_right)
8203 return rank_left >= rank_right ? type_left : type_right;
8212 u_rank = rank_right;
8213 u_type = type_right;
8215 s_rank = rank_right;
8216 s_type = type_right;
8221 if (u_rank >= s_rank)
8224 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8226 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8227 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8231 case ATOMIC_TYPE_INT: return type_unsigned_int;
8232 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8233 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8235 default: panic("invalid atomic type");
8240 * Check the semantic restrictions for a binary expression.
8242 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8244 expression_t *const left = expression->left;
8245 expression_t *const right = expression->right;
8246 type_t *const orig_type_left = left->base.type;
8247 type_t *const orig_type_right = right->base.type;
8248 type_t *const type_left = skip_typeref(orig_type_left);
8249 type_t *const type_right = skip_typeref(orig_type_right);
8251 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8252 /* TODO: improve error message */
8253 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8254 errorf(&expression->base.source_position,
8255 "operation needs arithmetic types");
8260 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8261 expression->left = create_implicit_cast(left, arithmetic_type);
8262 expression->right = create_implicit_cast(right, arithmetic_type);
8263 expression->base.type = arithmetic_type;
8266 static void semantic_binexpr_integer(binary_expression_t *const expression)
8268 expression_t *const left = expression->left;
8269 expression_t *const right = expression->right;
8270 type_t *const orig_type_left = left->base.type;
8271 type_t *const orig_type_right = right->base.type;
8272 type_t *const type_left = skip_typeref(orig_type_left);
8273 type_t *const type_right = skip_typeref(orig_type_right);
8275 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8276 /* TODO: improve error message */
8277 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8278 errorf(&expression->base.source_position,
8279 "operation needs integer types");
8284 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8285 expression->left = create_implicit_cast(left, result_type);
8286 expression->right = create_implicit_cast(right, result_type);
8287 expression->base.type = result_type;
8290 static void warn_div_by_zero(binary_expression_t const *const expression)
8292 if (!warning.div_by_zero ||
8293 !is_type_integer(expression->base.type))
8296 expression_t const *const right = expression->right;
8297 /* The type of the right operand can be different for /= */
8298 if (is_type_integer(right->base.type) &&
8299 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8300 !fold_constant_to_bool(right)) {
8301 warningf(&expression->base.source_position, "division by zero");
8306 * Check the semantic restrictions for a div/mod expression.
8308 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8310 semantic_binexpr_arithmetic(expression);
8311 warn_div_by_zero(expression);
8314 static void warn_addsub_in_shift(const expression_t *const expr)
8316 if (expr->base.parenthesized)
8320 switch (expr->kind) {
8321 case EXPR_BINARY_ADD: op = '+'; break;
8322 case EXPR_BINARY_SUB: op = '-'; break;
8326 warningf(&expr->base.source_position,
8327 "suggest parentheses around '%c' inside shift", op);
8330 static bool semantic_shift(binary_expression_t *expression)
8332 expression_t *const left = expression->left;
8333 expression_t *const right = expression->right;
8334 type_t *const orig_type_left = left->base.type;
8335 type_t *const orig_type_right = right->base.type;
8336 type_t * type_left = skip_typeref(orig_type_left);
8337 type_t * type_right = skip_typeref(orig_type_right);
8339 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8340 /* TODO: improve error message */
8341 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8342 errorf(&expression->base.source_position,
8343 "operands of shift operation must have integer types");
8348 type_left = promote_integer(type_left);
8350 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8351 long count = fold_constant_to_int(right);
8353 warningf(&right->base.source_position,
8354 "shift count must be non-negative");
8355 } else if ((unsigned long)count >=
8356 get_atomic_type_size(type_left->atomic.akind) * 8) {
8357 warningf(&right->base.source_position,
8358 "shift count must be less than type width");
8362 type_right = promote_integer(type_right);
8363 expression->right = create_implicit_cast(right, type_right);
8368 static void semantic_shift_op(binary_expression_t *expression)
8370 expression_t *const left = expression->left;
8371 expression_t *const right = expression->right;
8373 if (!semantic_shift(expression))
8376 if (warning.parentheses) {
8377 warn_addsub_in_shift(left);
8378 warn_addsub_in_shift(right);
8381 type_t *const orig_type_left = left->base.type;
8382 type_t * type_left = skip_typeref(orig_type_left);
8384 type_left = promote_integer(type_left);
8385 expression->left = create_implicit_cast(left, type_left);
8386 expression->base.type = type_left;
8389 static void semantic_add(binary_expression_t *expression)
8391 expression_t *const left = expression->left;
8392 expression_t *const right = expression->right;
8393 type_t *const orig_type_left = left->base.type;
8394 type_t *const orig_type_right = right->base.type;
8395 type_t *const type_left = skip_typeref(orig_type_left);
8396 type_t *const type_right = skip_typeref(orig_type_right);
8399 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8400 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8401 expression->left = create_implicit_cast(left, arithmetic_type);
8402 expression->right = create_implicit_cast(right, arithmetic_type);
8403 expression->base.type = arithmetic_type;
8404 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8405 check_pointer_arithmetic(&expression->base.source_position,
8406 type_left, orig_type_left);
8407 expression->base.type = type_left;
8408 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8409 check_pointer_arithmetic(&expression->base.source_position,
8410 type_right, orig_type_right);
8411 expression->base.type = type_right;
8412 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8413 errorf(&expression->base.source_position,
8414 "invalid operands to binary + ('%T', '%T')",
8415 orig_type_left, orig_type_right);
8419 static void semantic_sub(binary_expression_t *expression)
8421 expression_t *const left = expression->left;
8422 expression_t *const right = expression->right;
8423 type_t *const orig_type_left = left->base.type;
8424 type_t *const orig_type_right = right->base.type;
8425 type_t *const type_left = skip_typeref(orig_type_left);
8426 type_t *const type_right = skip_typeref(orig_type_right);
8427 source_position_t const *const pos = &expression->base.source_position;
8430 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8431 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8432 expression->left = create_implicit_cast(left, arithmetic_type);
8433 expression->right = create_implicit_cast(right, arithmetic_type);
8434 expression->base.type = arithmetic_type;
8435 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8436 check_pointer_arithmetic(&expression->base.source_position,
8437 type_left, orig_type_left);
8438 expression->base.type = type_left;
8439 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8440 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8441 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8442 if (!types_compatible(unqual_left, unqual_right)) {
8444 "subtracting pointers to incompatible types '%T' and '%T'",
8445 orig_type_left, orig_type_right);
8446 } else if (!is_type_object(unqual_left)) {
8447 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8448 errorf(pos, "subtracting pointers to non-object types '%T'",
8450 } else if (warning.other) {
8451 warningf(pos, "subtracting pointers to void");
8454 expression->base.type = type_ptrdiff_t;
8455 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8456 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8457 orig_type_left, orig_type_right);
8461 static void warn_string_literal_address(expression_t const* expr)
8463 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8464 expr = expr->unary.value;
8465 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8467 expr = expr->unary.value;
8470 if (expr->kind == EXPR_STRING_LITERAL
8471 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8472 warningf(&expr->base.source_position,
8473 "comparison with string literal results in unspecified behaviour");
8477 static void warn_comparison_in_comparison(const expression_t *const expr)
8479 if (expr->base.parenthesized)
8481 switch (expr->base.kind) {
8482 case EXPR_BINARY_LESS:
8483 case EXPR_BINARY_GREATER:
8484 case EXPR_BINARY_LESSEQUAL:
8485 case EXPR_BINARY_GREATEREQUAL:
8486 case EXPR_BINARY_NOTEQUAL:
8487 case EXPR_BINARY_EQUAL:
8488 warningf(&expr->base.source_position,
8489 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8496 static bool maybe_negative(expression_t const *const expr)
8498 switch (is_constant_expression(expr)) {
8499 case EXPR_CLASS_ERROR: return false;
8500 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8501 default: return true;
8506 * Check the semantics of comparison expressions.
8508 * @param expression The expression to check.
8510 static void semantic_comparison(binary_expression_t *expression)
8512 expression_t *left = expression->left;
8513 expression_t *right = expression->right;
8515 if (warning.address) {
8516 warn_string_literal_address(left);
8517 warn_string_literal_address(right);
8519 expression_t const* const func_left = get_reference_address(left);
8520 if (func_left != NULL && is_null_pointer_constant(right)) {
8521 warningf(&expression->base.source_position,
8522 "the address of '%Y' will never be NULL",
8523 func_left->reference.entity->base.symbol);
8526 expression_t const* const func_right = get_reference_address(right);
8527 if (func_right != NULL && is_null_pointer_constant(right)) {
8528 warningf(&expression->base.source_position,
8529 "the address of '%Y' will never be NULL",
8530 func_right->reference.entity->base.symbol);
8534 if (warning.parentheses) {
8535 warn_comparison_in_comparison(left);
8536 warn_comparison_in_comparison(right);
8539 type_t *orig_type_left = left->base.type;
8540 type_t *orig_type_right = right->base.type;
8541 type_t *type_left = skip_typeref(orig_type_left);
8542 type_t *type_right = skip_typeref(orig_type_right);
8544 /* TODO non-arithmetic types */
8545 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8546 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8548 /* test for signed vs unsigned compares */
8549 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8550 bool const signed_left = is_type_signed(type_left);
8551 bool const signed_right = is_type_signed(type_right);
8552 if (signed_left != signed_right) {
8553 /* FIXME long long needs better const folding magic */
8554 /* TODO check whether constant value can be represented by other type */
8555 if ((signed_left && maybe_negative(left)) ||
8556 (signed_right && maybe_negative(right))) {
8557 warningf(&expression->base.source_position,
8558 "comparison between signed and unsigned");
8563 expression->left = create_implicit_cast(left, arithmetic_type);
8564 expression->right = create_implicit_cast(right, arithmetic_type);
8565 expression->base.type = arithmetic_type;
8566 if (warning.float_equal &&
8567 (expression->base.kind == EXPR_BINARY_EQUAL ||
8568 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8569 is_type_float(arithmetic_type)) {
8570 warningf(&expression->base.source_position,
8571 "comparing floating point with == or != is unsafe");
8573 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8574 /* TODO check compatibility */
8575 } else if (is_type_pointer(type_left)) {
8576 expression->right = create_implicit_cast(right, type_left);
8577 } else if (is_type_pointer(type_right)) {
8578 expression->left = create_implicit_cast(left, type_right);
8579 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8580 type_error_incompatible("invalid operands in comparison",
8581 &expression->base.source_position,
8582 type_left, type_right);
8584 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8588 * Checks if a compound type has constant fields.
8590 static bool has_const_fields(const compound_type_t *type)
8592 compound_t *compound = type->compound;
8593 entity_t *entry = compound->members.entities;
8595 for (; entry != NULL; entry = entry->base.next) {
8596 if (!is_declaration(entry))
8599 const type_t *decl_type = skip_typeref(entry->declaration.type);
8600 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8607 static bool is_valid_assignment_lhs(expression_t const* const left)
8609 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8610 type_t *const type_left = skip_typeref(orig_type_left);
8612 if (!is_lvalue(left)) {
8613 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8618 if (left->kind == EXPR_REFERENCE
8619 && left->reference.entity->kind == ENTITY_FUNCTION) {
8620 errorf(HERE, "cannot assign to function '%E'", left);
8624 if (is_type_array(type_left)) {
8625 errorf(HERE, "cannot assign to array '%E'", left);
8628 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8629 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8633 if (is_type_incomplete(type_left)) {
8634 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8635 left, orig_type_left);
8638 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8639 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8640 left, orig_type_left);
8647 static void semantic_arithmetic_assign(binary_expression_t *expression)
8649 expression_t *left = expression->left;
8650 expression_t *right = expression->right;
8651 type_t *orig_type_left = left->base.type;
8652 type_t *orig_type_right = right->base.type;
8654 if (!is_valid_assignment_lhs(left))
8657 type_t *type_left = skip_typeref(orig_type_left);
8658 type_t *type_right = skip_typeref(orig_type_right);
8660 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8661 /* TODO: improve error message */
8662 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8663 errorf(&expression->base.source_position,
8664 "operation needs arithmetic types");
8669 /* combined instructions are tricky. We can't create an implicit cast on
8670 * the left side, because we need the uncasted form for the store.
8671 * The ast2firm pass has to know that left_type must be right_type
8672 * for the arithmetic operation and create a cast by itself */
8673 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8674 expression->right = create_implicit_cast(right, arithmetic_type);
8675 expression->base.type = type_left;
8678 static void semantic_divmod_assign(binary_expression_t *expression)
8680 semantic_arithmetic_assign(expression);
8681 warn_div_by_zero(expression);
8684 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8686 expression_t *const left = expression->left;
8687 expression_t *const right = expression->right;
8688 type_t *const orig_type_left = left->base.type;
8689 type_t *const orig_type_right = right->base.type;
8690 type_t *const type_left = skip_typeref(orig_type_left);
8691 type_t *const type_right = skip_typeref(orig_type_right);
8693 if (!is_valid_assignment_lhs(left))
8696 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8697 /* combined instructions are tricky. We can't create an implicit cast on
8698 * the left side, because we need the uncasted form for the store.
8699 * The ast2firm pass has to know that left_type must be right_type
8700 * for the arithmetic operation and create a cast by itself */
8701 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8702 expression->right = create_implicit_cast(right, arithmetic_type);
8703 expression->base.type = type_left;
8704 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8705 check_pointer_arithmetic(&expression->base.source_position,
8706 type_left, orig_type_left);
8707 expression->base.type = type_left;
8708 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8709 errorf(&expression->base.source_position,
8710 "incompatible types '%T' and '%T' in assignment",
8711 orig_type_left, orig_type_right);
8715 static void semantic_integer_assign(binary_expression_t *expression)
8717 expression_t *left = expression->left;
8718 expression_t *right = expression->right;
8719 type_t *orig_type_left = left->base.type;
8720 type_t *orig_type_right = right->base.type;
8722 if (!is_valid_assignment_lhs(left))
8725 type_t *type_left = skip_typeref(orig_type_left);
8726 type_t *type_right = skip_typeref(orig_type_right);
8728 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8729 /* TODO: improve error message */
8730 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8731 errorf(&expression->base.source_position,
8732 "operation needs integer types");
8737 /* combined instructions are tricky. We can't create an implicit cast on
8738 * the left side, because we need the uncasted form for the store.
8739 * The ast2firm pass has to know that left_type must be right_type
8740 * for the arithmetic operation and create a cast by itself */
8741 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8742 expression->right = create_implicit_cast(right, arithmetic_type);
8743 expression->base.type = type_left;
8746 static void semantic_shift_assign(binary_expression_t *expression)
8748 expression_t *left = expression->left;
8750 if (!is_valid_assignment_lhs(left))
8753 if (!semantic_shift(expression))
8756 expression->base.type = skip_typeref(left->base.type);
8759 static void warn_logical_and_within_or(const expression_t *const expr)
8761 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8763 if (expr->base.parenthesized)
8765 warningf(&expr->base.source_position,
8766 "suggest parentheses around && within ||");
8770 * Check the semantic restrictions of a logical expression.
8772 static void semantic_logical_op(binary_expression_t *expression)
8774 /* §6.5.13:2 Each of the operands shall have scalar type.
8775 * §6.5.14:2 Each of the operands shall have scalar type. */
8776 semantic_condition(expression->left, "left operand of logical operator");
8777 semantic_condition(expression->right, "right operand of logical operator");
8778 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8779 warning.parentheses) {
8780 warn_logical_and_within_or(expression->left);
8781 warn_logical_and_within_or(expression->right);
8783 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8787 * Check the semantic restrictions of a binary assign expression.
8789 static void semantic_binexpr_assign(binary_expression_t *expression)
8791 expression_t *left = expression->left;
8792 type_t *orig_type_left = left->base.type;
8794 if (!is_valid_assignment_lhs(left))
8797 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8798 report_assign_error(error, orig_type_left, expression->right,
8799 "assignment", &left->base.source_position);
8800 expression->right = create_implicit_cast(expression->right, orig_type_left);
8801 expression->base.type = orig_type_left;
8805 * Determine if the outermost operation (or parts thereof) of the given
8806 * expression has no effect in order to generate a warning about this fact.
8807 * Therefore in some cases this only examines some of the operands of the
8808 * expression (see comments in the function and examples below).
8810 * f() + 23; // warning, because + has no effect
8811 * x || f(); // no warning, because x controls execution of f()
8812 * x ? y : f(); // warning, because y has no effect
8813 * (void)x; // no warning to be able to suppress the warning
8814 * This function can NOT be used for an "expression has definitely no effect"-
8816 static bool expression_has_effect(const expression_t *const expr)
8818 switch (expr->kind) {
8819 case EXPR_UNKNOWN: break;
8820 case EXPR_INVALID: return true; /* do NOT warn */
8821 case EXPR_REFERENCE: return false;
8822 case EXPR_REFERENCE_ENUM_VALUE: return false;
8823 case EXPR_LABEL_ADDRESS: return false;
8825 /* suppress the warning for microsoft __noop operations */
8826 case EXPR_LITERAL_MS_NOOP: return true;
8827 case EXPR_LITERAL_BOOLEAN:
8828 case EXPR_LITERAL_CHARACTER:
8829 case EXPR_LITERAL_WIDE_CHARACTER:
8830 case EXPR_LITERAL_INTEGER:
8831 case EXPR_LITERAL_INTEGER_OCTAL:
8832 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8833 case EXPR_LITERAL_FLOATINGPOINT:
8834 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8835 case EXPR_STRING_LITERAL: return false;
8836 case EXPR_WIDE_STRING_LITERAL: return false;
8839 const call_expression_t *const call = &expr->call;
8840 if (call->function->kind != EXPR_REFERENCE)
8843 switch (call->function->reference.entity->function.btk) {
8844 /* FIXME: which builtins have no effect? */
8845 default: return true;
8849 /* Generate the warning if either the left or right hand side of a
8850 * conditional expression has no effect */
8851 case EXPR_CONDITIONAL: {
8852 conditional_expression_t const *const cond = &expr->conditional;
8853 expression_t const *const t = cond->true_expression;
8855 (t == NULL || expression_has_effect(t)) &&
8856 expression_has_effect(cond->false_expression);
8859 case EXPR_SELECT: return false;
8860 case EXPR_ARRAY_ACCESS: return false;
8861 case EXPR_SIZEOF: return false;
8862 case EXPR_CLASSIFY_TYPE: return false;
8863 case EXPR_ALIGNOF: return false;
8865 case EXPR_FUNCNAME: return false;
8866 case EXPR_BUILTIN_CONSTANT_P: return false;
8867 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8868 case EXPR_OFFSETOF: return false;
8869 case EXPR_VA_START: return true;
8870 case EXPR_VA_ARG: return true;
8871 case EXPR_VA_COPY: return true;
8872 case EXPR_STATEMENT: return true; // TODO
8873 case EXPR_COMPOUND_LITERAL: return false;
8875 case EXPR_UNARY_NEGATE: return false;
8876 case EXPR_UNARY_PLUS: return false;
8877 case EXPR_UNARY_BITWISE_NEGATE: return false;
8878 case EXPR_UNARY_NOT: return false;
8879 case EXPR_UNARY_DEREFERENCE: return false;
8880 case EXPR_UNARY_TAKE_ADDRESS: return false;
8881 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8882 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8883 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8884 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8886 /* Treat void casts as if they have an effect in order to being able to
8887 * suppress the warning */
8888 case EXPR_UNARY_CAST: {
8889 type_t *const type = skip_typeref(expr->base.type);
8890 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8893 case EXPR_UNARY_CAST_IMPLICIT: return true;
8894 case EXPR_UNARY_ASSUME: return true;
8895 case EXPR_UNARY_DELETE: return true;
8896 case EXPR_UNARY_DELETE_ARRAY: return true;
8897 case EXPR_UNARY_THROW: return true;
8899 case EXPR_BINARY_ADD: return false;
8900 case EXPR_BINARY_SUB: return false;
8901 case EXPR_BINARY_MUL: return false;
8902 case EXPR_BINARY_DIV: return false;
8903 case EXPR_BINARY_MOD: return false;
8904 case EXPR_BINARY_EQUAL: return false;
8905 case EXPR_BINARY_NOTEQUAL: return false;
8906 case EXPR_BINARY_LESS: return false;
8907 case EXPR_BINARY_LESSEQUAL: return false;
8908 case EXPR_BINARY_GREATER: return false;
8909 case EXPR_BINARY_GREATEREQUAL: return false;
8910 case EXPR_BINARY_BITWISE_AND: return false;
8911 case EXPR_BINARY_BITWISE_OR: return false;
8912 case EXPR_BINARY_BITWISE_XOR: return false;
8913 case EXPR_BINARY_SHIFTLEFT: return false;
8914 case EXPR_BINARY_SHIFTRIGHT: return false;
8915 case EXPR_BINARY_ASSIGN: return true;
8916 case EXPR_BINARY_MUL_ASSIGN: return true;
8917 case EXPR_BINARY_DIV_ASSIGN: return true;
8918 case EXPR_BINARY_MOD_ASSIGN: return true;
8919 case EXPR_BINARY_ADD_ASSIGN: return true;
8920 case EXPR_BINARY_SUB_ASSIGN: return true;
8921 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8922 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8923 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8924 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8925 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8927 /* Only examine the right hand side of && and ||, because the left hand
8928 * side already has the effect of controlling the execution of the right
8930 case EXPR_BINARY_LOGICAL_AND:
8931 case EXPR_BINARY_LOGICAL_OR:
8932 /* Only examine the right hand side of a comma expression, because the left
8933 * hand side has a separate warning */
8934 case EXPR_BINARY_COMMA:
8935 return expression_has_effect(expr->binary.right);
8937 case EXPR_BINARY_ISGREATER: return false;
8938 case EXPR_BINARY_ISGREATEREQUAL: return false;
8939 case EXPR_BINARY_ISLESS: return false;
8940 case EXPR_BINARY_ISLESSEQUAL: return false;
8941 case EXPR_BINARY_ISLESSGREATER: return false;
8942 case EXPR_BINARY_ISUNORDERED: return false;
8945 internal_errorf(HERE, "unexpected expression");
8948 static void semantic_comma(binary_expression_t *expression)
8950 if (warning.unused_value) {
8951 const expression_t *const left = expression->left;
8952 if (!expression_has_effect(left)) {
8953 warningf(&left->base.source_position,
8954 "left-hand operand of comma expression has no effect");
8957 expression->base.type = expression->right->base.type;
8961 * @param prec_r precedence of the right operand
8963 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8964 static expression_t *parse_##binexpression_type(expression_t *left) \
8966 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8967 binexpr->binary.left = left; \
8970 expression_t *right = parse_subexpression(prec_r); \
8972 binexpr->binary.right = right; \
8973 sfunc(&binexpr->binary); \
8978 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8979 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8980 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8981 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8982 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8983 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8984 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8985 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8986 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8987 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8988 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8989 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8990 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8991 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8992 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8993 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8994 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8995 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8996 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8997 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8998 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8999 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9000 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9001 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9002 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9003 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9004 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9005 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9006 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9007 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9010 static expression_t *parse_subexpression(precedence_t precedence)
9012 if (token.type < 0) {
9013 return expected_expression_error();
9016 expression_parser_function_t *parser
9017 = &expression_parsers[token.type];
9018 source_position_t source_position = token.source_position;
9021 if (parser->parser != NULL) {
9022 left = parser->parser();
9024 left = parse_primary_expression();
9026 assert(left != NULL);
9027 left->base.source_position = source_position;
9030 if (token.type < 0) {
9031 return expected_expression_error();
9034 parser = &expression_parsers[token.type];
9035 if (parser->infix_parser == NULL)
9037 if (parser->infix_precedence < precedence)
9040 left = parser->infix_parser(left);
9042 assert(left != NULL);
9043 assert(left->kind != EXPR_UNKNOWN);
9044 left->base.source_position = source_position;
9051 * Parse an expression.
9053 static expression_t *parse_expression(void)
9055 return parse_subexpression(PREC_EXPRESSION);
9059 * Register a parser for a prefix-like operator.
9061 * @param parser the parser function
9062 * @param token_type the token type of the prefix token
9064 static void register_expression_parser(parse_expression_function parser,
9067 expression_parser_function_t *entry = &expression_parsers[token_type];
9069 if (entry->parser != NULL) {
9070 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9071 panic("trying to register multiple expression parsers for a token");
9073 entry->parser = parser;
9077 * Register a parser for an infix operator with given precedence.
9079 * @param parser the parser function
9080 * @param token_type the token type of the infix operator
9081 * @param precedence the precedence of the operator
9083 static void register_infix_parser(parse_expression_infix_function parser,
9084 int token_type, precedence_t precedence)
9086 expression_parser_function_t *entry = &expression_parsers[token_type];
9088 if (entry->infix_parser != NULL) {
9089 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9090 panic("trying to register multiple infix expression parsers for a "
9093 entry->infix_parser = parser;
9094 entry->infix_precedence = precedence;
9098 * Initialize the expression parsers.
9100 static void init_expression_parsers(void)
9102 memset(&expression_parsers, 0, sizeof(expression_parsers));
9104 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9105 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9106 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9107 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9108 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9109 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9110 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9111 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9112 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9113 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9114 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9115 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9116 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9117 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9118 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9119 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9120 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9121 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9122 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9123 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9124 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9125 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9126 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9127 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9128 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9129 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9130 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9131 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9132 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9133 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9134 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9135 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9136 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9137 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9138 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9139 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9140 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9142 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9143 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9144 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9145 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9146 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9147 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9148 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9149 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9150 register_expression_parser(parse_sizeof, T_sizeof);
9151 register_expression_parser(parse_alignof, T___alignof__);
9152 register_expression_parser(parse_extension, T___extension__);
9153 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9154 register_expression_parser(parse_delete, T_delete);
9155 register_expression_parser(parse_throw, T_throw);
9159 * Parse a asm statement arguments specification.
9161 static asm_argument_t *parse_asm_arguments(bool is_out)
9163 asm_argument_t *result = NULL;
9164 asm_argument_t **anchor = &result;
9166 while (token.type == T_STRING_LITERAL || token.type == '[') {
9167 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9168 memset(argument, 0, sizeof(argument[0]));
9171 if (token.type != T_IDENTIFIER) {
9172 parse_error_expected("while parsing asm argument",
9173 T_IDENTIFIER, NULL);
9176 argument->symbol = token.symbol;
9178 expect(']', end_error);
9181 argument->constraints = parse_string_literals();
9182 expect('(', end_error);
9183 add_anchor_token(')');
9184 expression_t *expression = parse_expression();
9185 rem_anchor_token(')');
9187 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9188 * change size or type representation (e.g. int -> long is ok, but
9189 * int -> float is not) */
9190 if (expression->kind == EXPR_UNARY_CAST) {
9191 type_t *const type = expression->base.type;
9192 type_kind_t const kind = type->kind;
9193 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9196 if (kind == TYPE_ATOMIC) {
9197 atomic_type_kind_t const akind = type->atomic.akind;
9198 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9199 size = get_atomic_type_size(akind);
9201 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9202 size = get_atomic_type_size(get_intptr_kind());
9206 expression_t *const value = expression->unary.value;
9207 type_t *const value_type = value->base.type;
9208 type_kind_t const value_kind = value_type->kind;
9210 unsigned value_flags;
9211 unsigned value_size;
9212 if (value_kind == TYPE_ATOMIC) {
9213 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9214 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9215 value_size = get_atomic_type_size(value_akind);
9216 } else if (value_kind == TYPE_POINTER) {
9217 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9218 value_size = get_atomic_type_size(get_intptr_kind());
9223 if (value_flags != flags || value_size != size)
9227 } while (expression->kind == EXPR_UNARY_CAST);
9231 if (!is_lvalue(expression)) {
9232 errorf(&expression->base.source_position,
9233 "asm output argument is not an lvalue");
9236 if (argument->constraints.begin[0] == '=')
9237 determine_lhs_ent(expression, NULL);
9239 mark_vars_read(expression, NULL);
9241 mark_vars_read(expression, NULL);
9243 argument->expression = expression;
9244 expect(')', end_error);
9246 set_address_taken(expression, true);
9249 anchor = &argument->next;
9261 * Parse a asm statement clobber specification.
9263 static asm_clobber_t *parse_asm_clobbers(void)
9265 asm_clobber_t *result = NULL;
9266 asm_clobber_t **anchor = &result;
9268 while (token.type == T_STRING_LITERAL) {
9269 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9270 clobber->clobber = parse_string_literals();
9273 anchor = &clobber->next;
9283 * Parse an asm statement.
9285 static statement_t *parse_asm_statement(void)
9287 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9288 asm_statement_t *asm_statement = &statement->asms;
9292 if (next_if(T_volatile))
9293 asm_statement->is_volatile = true;
9295 expect('(', end_error);
9296 add_anchor_token(')');
9297 if (token.type != T_STRING_LITERAL) {
9298 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9301 asm_statement->asm_text = parse_string_literals();
9303 add_anchor_token(':');
9304 if (!next_if(':')) {
9305 rem_anchor_token(':');
9309 asm_statement->outputs = parse_asm_arguments(true);
9310 if (!next_if(':')) {
9311 rem_anchor_token(':');
9315 asm_statement->inputs = parse_asm_arguments(false);
9316 if (!next_if(':')) {
9317 rem_anchor_token(':');
9320 rem_anchor_token(':');
9322 asm_statement->clobbers = parse_asm_clobbers();
9325 rem_anchor_token(')');
9326 expect(')', end_error);
9327 expect(';', end_error);
9329 if (asm_statement->outputs == NULL) {
9330 /* GCC: An 'asm' instruction without any output operands will be treated
9331 * identically to a volatile 'asm' instruction. */
9332 asm_statement->is_volatile = true;
9337 return create_invalid_statement();
9340 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9342 statement_t *inner_stmt;
9343 switch (token.type) {
9345 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9346 inner_stmt = create_invalid_statement();
9350 if (label->kind == STATEMENT_LABEL) {
9351 /* Eat an empty statement here, to avoid the warning about an empty
9352 * statement after a label. label:; is commonly used to have a label
9353 * before a closing brace. */
9354 inner_stmt = create_empty_statement();
9361 inner_stmt = parse_statement();
9362 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9363 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9364 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9372 * Parse a case statement.
9374 static statement_t *parse_case_statement(void)
9376 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9377 source_position_t *const pos = &statement->base.source_position;
9381 expression_t *const expression = parse_expression();
9382 statement->case_label.expression = expression;
9383 expression_classification_t const expr_class = is_constant_expression(expression);
9384 if (expr_class != EXPR_CLASS_CONSTANT) {
9385 if (expr_class != EXPR_CLASS_ERROR) {
9386 errorf(pos, "case label does not reduce to an integer constant");
9388 statement->case_label.is_bad = true;
9390 long const val = fold_constant_to_int(expression);
9391 statement->case_label.first_case = val;
9392 statement->case_label.last_case = val;
9396 if (next_if(T_DOTDOTDOT)) {
9397 expression_t *const end_range = parse_expression();
9398 statement->case_label.end_range = end_range;
9399 expression_classification_t const end_class = is_constant_expression(end_range);
9400 if (end_class != EXPR_CLASS_CONSTANT) {
9401 if (end_class != EXPR_CLASS_ERROR) {
9402 errorf(pos, "case range does not reduce to an integer constant");
9404 statement->case_label.is_bad = true;
9406 long const val = fold_constant_to_int(end_range);
9407 statement->case_label.last_case = val;
9409 if (warning.other && val < statement->case_label.first_case) {
9410 statement->case_label.is_empty_range = true;
9411 warningf(pos, "empty range specified");
9417 PUSH_PARENT(statement);
9419 expect(':', end_error);
9422 if (current_switch != NULL) {
9423 if (! statement->case_label.is_bad) {
9424 /* Check for duplicate case values */
9425 case_label_statement_t *c = &statement->case_label;
9426 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9427 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9430 if (c->last_case < l->first_case || c->first_case > l->last_case)
9433 errorf(pos, "duplicate case value (previously used %P)",
9434 &l->base.source_position);
9438 /* link all cases into the switch statement */
9439 if (current_switch->last_case == NULL) {
9440 current_switch->first_case = &statement->case_label;
9442 current_switch->last_case->next = &statement->case_label;
9444 current_switch->last_case = &statement->case_label;
9446 errorf(pos, "case label not within a switch statement");
9449 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9456 * Parse a default statement.
9458 static statement_t *parse_default_statement(void)
9460 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9464 PUSH_PARENT(statement);
9466 expect(':', end_error);
9469 if (current_switch != NULL) {
9470 const case_label_statement_t *def_label = current_switch->default_label;
9471 if (def_label != NULL) {
9472 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9473 &def_label->base.source_position);
9475 current_switch->default_label = &statement->case_label;
9477 /* link all cases into the switch statement */
9478 if (current_switch->last_case == NULL) {
9479 current_switch->first_case = &statement->case_label;
9481 current_switch->last_case->next = &statement->case_label;
9483 current_switch->last_case = &statement->case_label;
9486 errorf(&statement->base.source_position,
9487 "'default' label not within a switch statement");
9490 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9497 * Parse a label statement.
9499 static statement_t *parse_label_statement(void)
9501 assert(token.type == T_IDENTIFIER);
9502 symbol_t *symbol = token.symbol;
9503 label_t *label = get_label(symbol);
9505 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9506 statement->label.label = label;
9510 PUSH_PARENT(statement);
9512 /* if statement is already set then the label is defined twice,
9513 * otherwise it was just mentioned in a goto/local label declaration so far
9515 if (label->statement != NULL) {
9516 errorf(HERE, "duplicate label '%Y' (declared %P)",
9517 symbol, &label->base.source_position);
9519 label->base.source_position = token.source_position;
9520 label->statement = statement;
9525 statement->label.statement = parse_label_inner_statement(statement, "label");
9527 /* remember the labels in a list for later checking */
9528 *label_anchor = &statement->label;
9529 label_anchor = &statement->label.next;
9536 * Parse an if statement.
9538 static statement_t *parse_if(void)
9540 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9544 PUSH_PARENT(statement);
9546 add_anchor_token('{');
9548 expect('(', end_error);
9549 add_anchor_token(')');
9550 expression_t *const expr = parse_expression();
9551 statement->ifs.condition = expr;
9552 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9554 semantic_condition(expr, "condition of 'if'-statment");
9555 mark_vars_read(expr, NULL);
9556 rem_anchor_token(')');
9557 expect(')', end_error);
9560 rem_anchor_token('{');
9562 add_anchor_token(T_else);
9563 statement_t *const true_stmt = parse_statement();
9564 statement->ifs.true_statement = true_stmt;
9565 rem_anchor_token(T_else);
9567 if (next_if(T_else)) {
9568 statement->ifs.false_statement = parse_statement();
9569 } else if (warning.parentheses &&
9570 true_stmt->kind == STATEMENT_IF &&
9571 true_stmt->ifs.false_statement != NULL) {
9572 warningf(&true_stmt->base.source_position,
9573 "suggest explicit braces to avoid ambiguous 'else'");
9581 * Check that all enums are handled in a switch.
9583 * @param statement the switch statement to check
9585 static void check_enum_cases(const switch_statement_t *statement)
9587 const type_t *type = skip_typeref(statement->expression->base.type);
9588 if (! is_type_enum(type))
9590 const enum_type_t *enumt = &type->enumt;
9592 /* if we have a default, no warnings */
9593 if (statement->default_label != NULL)
9596 /* FIXME: calculation of value should be done while parsing */
9597 /* TODO: quadratic algorithm here. Change to an n log n one */
9598 long last_value = -1;
9599 const entity_t *entry = enumt->enume->base.next;
9600 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9601 entry = entry->base.next) {
9602 const expression_t *expression = entry->enum_value.value;
9603 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9605 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9606 if (l->expression == NULL)
9608 if (l->first_case <= value && value <= l->last_case) {
9614 warningf(&statement->base.source_position,
9615 "enumeration value '%Y' not handled in switch",
9616 entry->base.symbol);
9623 * Parse a switch statement.
9625 static statement_t *parse_switch(void)
9627 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9631 PUSH_PARENT(statement);
9633 expect('(', end_error);
9634 add_anchor_token(')');
9635 expression_t *const expr = parse_expression();
9636 mark_vars_read(expr, NULL);
9637 type_t * type = skip_typeref(expr->base.type);
9638 if (is_type_integer(type)) {
9639 type = promote_integer(type);
9640 if (warning.traditional) {
9641 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9642 warningf(&expr->base.source_position,
9643 "'%T' switch expression not converted to '%T' in ISO C",
9647 } else if (is_type_valid(type)) {
9648 errorf(&expr->base.source_position,
9649 "switch quantity is not an integer, but '%T'", type);
9650 type = type_error_type;
9652 statement->switchs.expression = create_implicit_cast(expr, type);
9653 expect(')', end_error);
9654 rem_anchor_token(')');
9656 switch_statement_t *rem = current_switch;
9657 current_switch = &statement->switchs;
9658 statement->switchs.body = parse_statement();
9659 current_switch = rem;
9661 if (warning.switch_default &&
9662 statement->switchs.default_label == NULL) {
9663 warningf(&statement->base.source_position, "switch has no default case");
9665 if (warning.switch_enum)
9666 check_enum_cases(&statement->switchs);
9672 return create_invalid_statement();
9675 static statement_t *parse_loop_body(statement_t *const loop)
9677 statement_t *const rem = current_loop;
9678 current_loop = loop;
9680 statement_t *const body = parse_statement();
9687 * Parse a while statement.
9689 static statement_t *parse_while(void)
9691 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9695 PUSH_PARENT(statement);
9697 expect('(', end_error);
9698 add_anchor_token(')');
9699 expression_t *const cond = parse_expression();
9700 statement->whiles.condition = cond;
9701 /* §6.8.5:2 The controlling expression of an iteration statement shall
9702 * have scalar type. */
9703 semantic_condition(cond, "condition of 'while'-statement");
9704 mark_vars_read(cond, NULL);
9705 rem_anchor_token(')');
9706 expect(')', end_error);
9708 statement->whiles.body = parse_loop_body(statement);
9714 return create_invalid_statement();
9718 * Parse a do statement.
9720 static statement_t *parse_do(void)
9722 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9726 PUSH_PARENT(statement);
9728 add_anchor_token(T_while);
9729 statement->do_while.body = parse_loop_body(statement);
9730 rem_anchor_token(T_while);
9732 expect(T_while, end_error);
9733 expect('(', end_error);
9734 add_anchor_token(')');
9735 expression_t *const cond = parse_expression();
9736 statement->do_while.condition = cond;
9737 /* §6.8.5:2 The controlling expression of an iteration statement shall
9738 * have scalar type. */
9739 semantic_condition(cond, "condition of 'do-while'-statement");
9740 mark_vars_read(cond, NULL);
9741 rem_anchor_token(')');
9742 expect(')', end_error);
9743 expect(';', end_error);
9749 return create_invalid_statement();
9753 * Parse a for statement.
9755 static statement_t *parse_for(void)
9757 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9761 expect('(', end_error1);
9762 add_anchor_token(')');
9764 PUSH_PARENT(statement);
9766 size_t const top = environment_top();
9767 scope_t *old_scope = scope_push(&statement->fors.scope);
9769 bool old_gcc_extension = in_gcc_extension;
9770 while (next_if(T___extension__)) {
9771 in_gcc_extension = true;
9775 } else if (is_declaration_specifier(&token, false)) {
9776 parse_declaration(record_entity, DECL_FLAGS_NONE);
9778 add_anchor_token(';');
9779 expression_t *const init = parse_expression();
9780 statement->fors.initialisation = init;
9781 mark_vars_read(init, ENT_ANY);
9782 if (warning.unused_value && !expression_has_effect(init)) {
9783 warningf(&init->base.source_position,
9784 "initialisation of 'for'-statement has no effect");
9786 rem_anchor_token(';');
9787 expect(';', end_error2);
9789 in_gcc_extension = old_gcc_extension;
9791 if (token.type != ';') {
9792 add_anchor_token(';');
9793 expression_t *const cond = parse_expression();
9794 statement->fors.condition = cond;
9795 /* §6.8.5:2 The controlling expression of an iteration statement
9796 * shall have scalar type. */
9797 semantic_condition(cond, "condition of 'for'-statement");
9798 mark_vars_read(cond, NULL);
9799 rem_anchor_token(';');
9801 expect(';', end_error2);
9802 if (token.type != ')') {
9803 expression_t *const step = parse_expression();
9804 statement->fors.step = step;
9805 mark_vars_read(step, ENT_ANY);
9806 if (warning.unused_value && !expression_has_effect(step)) {
9807 warningf(&step->base.source_position,
9808 "step of 'for'-statement has no effect");
9811 expect(')', end_error2);
9812 rem_anchor_token(')');
9813 statement->fors.body = parse_loop_body(statement);
9815 assert(current_scope == &statement->fors.scope);
9816 scope_pop(old_scope);
9817 environment_pop_to(top);
9824 rem_anchor_token(')');
9825 assert(current_scope == &statement->fors.scope);
9826 scope_pop(old_scope);
9827 environment_pop_to(top);
9831 return create_invalid_statement();
9835 * Parse a goto statement.
9837 static statement_t *parse_goto(void)
9839 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9842 if (GNU_MODE && next_if('*')) {
9843 expression_t *expression = parse_expression();
9844 mark_vars_read(expression, NULL);
9846 /* Argh: although documentation says the expression must be of type void*,
9847 * gcc accepts anything that can be casted into void* without error */
9848 type_t *type = expression->base.type;
9850 if (type != type_error_type) {
9851 if (!is_type_pointer(type) && !is_type_integer(type)) {
9852 errorf(&expression->base.source_position,
9853 "cannot convert to a pointer type");
9854 } else if (warning.other && type != type_void_ptr) {
9855 warningf(&expression->base.source_position,
9856 "type of computed goto expression should be 'void*' not '%T'", type);
9858 expression = create_implicit_cast(expression, type_void_ptr);
9861 statement->gotos.expression = expression;
9862 } else if (token.type == T_IDENTIFIER) {
9863 symbol_t *symbol = token.symbol;
9865 statement->gotos.label = get_label(symbol);
9868 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9870 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9872 return create_invalid_statement();
9875 /* remember the goto's in a list for later checking */
9876 *goto_anchor = &statement->gotos;
9877 goto_anchor = &statement->gotos.next;
9879 expect(';', end_error);
9886 * Parse a continue statement.
9888 static statement_t *parse_continue(void)
9890 if (current_loop == NULL) {
9891 errorf(HERE, "continue statement not within loop");
9894 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9897 expect(';', end_error);
9904 * Parse a break statement.
9906 static statement_t *parse_break(void)
9908 if (current_switch == NULL && current_loop == NULL) {
9909 errorf(HERE, "break statement not within loop or switch");
9912 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9915 expect(';', end_error);
9922 * Parse a __leave statement.
9924 static statement_t *parse_leave_statement(void)
9926 if (current_try == NULL) {
9927 errorf(HERE, "__leave statement not within __try");
9930 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9933 expect(';', end_error);
9940 * Check if a given entity represents a local variable.
9942 static bool is_local_variable(const entity_t *entity)
9944 if (entity->kind != ENTITY_VARIABLE)
9947 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9948 case STORAGE_CLASS_AUTO:
9949 case STORAGE_CLASS_REGISTER: {
9950 const type_t *type = skip_typeref(entity->declaration.type);
9951 if (is_type_function(type)) {
9963 * Check if a given expression represents a local variable.
9965 static bool expression_is_local_variable(const expression_t *expression)
9967 if (expression->base.kind != EXPR_REFERENCE) {
9970 const entity_t *entity = expression->reference.entity;
9971 return is_local_variable(entity);
9975 * Check if a given expression represents a local variable and
9976 * return its declaration then, else return NULL.
9978 entity_t *expression_is_variable(const expression_t *expression)
9980 if (expression->base.kind != EXPR_REFERENCE) {
9983 entity_t *entity = expression->reference.entity;
9984 if (entity->kind != ENTITY_VARIABLE)
9991 * Parse a return statement.
9993 static statement_t *parse_return(void)
9997 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9999 expression_t *return_value = NULL;
10000 if (token.type != ';') {
10001 return_value = parse_expression();
10002 mark_vars_read(return_value, NULL);
10005 const type_t *const func_type = skip_typeref(current_function->base.type);
10006 assert(is_type_function(func_type));
10007 type_t *const return_type = skip_typeref(func_type->function.return_type);
10009 source_position_t const *const pos = &statement->base.source_position;
10010 if (return_value != NULL) {
10011 type_t *return_value_type = skip_typeref(return_value->base.type);
10013 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10014 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10015 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10016 /* Only warn in C mode, because GCC does the same */
10017 if (c_mode & _CXX || strict_mode) {
10019 "'return' with a value, in function returning 'void'");
10020 } else if (warning.other) {
10022 "'return' with a value, in function returning 'void'");
10024 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10025 /* Only warn in C mode, because GCC does the same */
10028 "'return' with expression in function returning 'void'");
10029 } else if (warning.other) {
10031 "'return' with expression in function returning 'void'");
10035 assign_error_t error = semantic_assign(return_type, return_value);
10036 report_assign_error(error, return_type, return_value, "'return'",
10039 return_value = create_implicit_cast(return_value, return_type);
10040 /* check for returning address of a local var */
10041 if (warning.other && return_value != NULL
10042 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10043 const expression_t *expression = return_value->unary.value;
10044 if (expression_is_local_variable(expression)) {
10045 warningf(pos, "function returns address of local variable");
10048 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10049 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10050 if (c_mode & _CXX || strict_mode) {
10052 "'return' without value, in function returning non-void");
10055 "'return' without value, in function returning non-void");
10058 statement->returns.value = return_value;
10060 expect(';', end_error);
10067 * Parse a declaration statement.
10069 static statement_t *parse_declaration_statement(void)
10071 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10073 entity_t *before = current_scope->last_entity;
10075 parse_external_declaration();
10077 parse_declaration(record_entity, DECL_FLAGS_NONE);
10080 declaration_statement_t *const decl = &statement->declaration;
10081 entity_t *const begin =
10082 before != NULL ? before->base.next : current_scope->entities;
10083 decl->declarations_begin = begin;
10084 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10090 * Parse an expression statement, ie. expr ';'.
10092 static statement_t *parse_expression_statement(void)
10094 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10096 expression_t *const expr = parse_expression();
10097 statement->expression.expression = expr;
10098 mark_vars_read(expr, ENT_ANY);
10100 expect(';', end_error);
10107 * Parse a microsoft __try { } __finally { } or
10108 * __try{ } __except() { }
10110 static statement_t *parse_ms_try_statment(void)
10112 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10115 PUSH_PARENT(statement);
10117 ms_try_statement_t *rem = current_try;
10118 current_try = &statement->ms_try;
10119 statement->ms_try.try_statement = parse_compound_statement(false);
10124 if (next_if(T___except)) {
10125 expect('(', end_error);
10126 add_anchor_token(')');
10127 expression_t *const expr = parse_expression();
10128 mark_vars_read(expr, NULL);
10129 type_t * type = skip_typeref(expr->base.type);
10130 if (is_type_integer(type)) {
10131 type = promote_integer(type);
10132 } else if (is_type_valid(type)) {
10133 errorf(&expr->base.source_position,
10134 "__expect expression is not an integer, but '%T'", type);
10135 type = type_error_type;
10137 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10138 rem_anchor_token(')');
10139 expect(')', end_error);
10140 statement->ms_try.final_statement = parse_compound_statement(false);
10141 } else if (next_if(T__finally)) {
10142 statement->ms_try.final_statement = parse_compound_statement(false);
10144 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10145 return create_invalid_statement();
10149 return create_invalid_statement();
10152 static statement_t *parse_empty_statement(void)
10154 if (warning.empty_statement) {
10155 warningf(HERE, "statement is empty");
10157 statement_t *const statement = create_empty_statement();
10162 static statement_t *parse_local_label_declaration(void)
10164 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10168 entity_t *begin = NULL;
10169 entity_t *end = NULL;
10170 entity_t **anchor = &begin;
10172 if (token.type != T_IDENTIFIER) {
10173 parse_error_expected("while parsing local label declaration",
10174 T_IDENTIFIER, NULL);
10177 symbol_t *symbol = token.symbol;
10178 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10179 if (entity != NULL && entity->base.parent_scope == current_scope) {
10180 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10181 symbol, &entity->base.source_position);
10183 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10185 entity->base.parent_scope = current_scope;
10186 entity->base.namespc = NAMESPACE_LABEL;
10187 entity->base.source_position = token.source_position;
10188 entity->base.symbol = symbol;
10191 anchor = &entity->base.next;
10194 environment_push(entity);
10197 } while (next_if(','));
10198 expect(';', end_error);
10200 statement->declaration.declarations_begin = begin;
10201 statement->declaration.declarations_end = end;
10205 static void parse_namespace_definition(void)
10209 entity_t *entity = NULL;
10210 symbol_t *symbol = NULL;
10212 if (token.type == T_IDENTIFIER) {
10213 symbol = token.symbol;
10216 entity = get_entity(symbol, NAMESPACE_NORMAL);
10218 && entity->kind != ENTITY_NAMESPACE
10219 && entity->base.parent_scope == current_scope) {
10220 if (is_entity_valid(entity)) {
10221 error_redefined_as_different_kind(&token.source_position,
10222 entity, ENTITY_NAMESPACE);
10228 if (entity == NULL) {
10229 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10230 entity->base.symbol = symbol;
10231 entity->base.source_position = token.source_position;
10232 entity->base.namespc = NAMESPACE_NORMAL;
10233 entity->base.parent_scope = current_scope;
10236 if (token.type == '=') {
10237 /* TODO: parse namespace alias */
10238 panic("namespace alias definition not supported yet");
10241 environment_push(entity);
10242 append_entity(current_scope, entity);
10244 size_t const top = environment_top();
10245 scope_t *old_scope = scope_push(&entity->namespacee.members);
10247 entity_t *old_current_entity = current_entity;
10248 current_entity = entity;
10250 expect('{', end_error);
10252 expect('}', end_error);
10255 assert(current_scope == &entity->namespacee.members);
10256 assert(current_entity == entity);
10257 current_entity = old_current_entity;
10258 scope_pop(old_scope);
10259 environment_pop_to(top);
10263 * Parse a statement.
10264 * There's also parse_statement() which additionally checks for
10265 * "statement has no effect" warnings
10267 static statement_t *intern_parse_statement(void)
10269 statement_t *statement = NULL;
10271 /* declaration or statement */
10272 add_anchor_token(';');
10273 switch (token.type) {
10274 case T_IDENTIFIER: {
10275 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10276 if (la1_type == ':') {
10277 statement = parse_label_statement();
10278 } else if (is_typedef_symbol(token.symbol)) {
10279 statement = parse_declaration_statement();
10281 /* it's an identifier, the grammar says this must be an
10282 * expression statement. However it is common that users mistype
10283 * declaration types, so we guess a bit here to improve robustness
10284 * for incorrect programs */
10285 switch (la1_type) {
10288 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10290 statement = parse_expression_statement();
10294 statement = parse_declaration_statement();
10302 case T___extension__:
10303 /* This can be a prefix to a declaration or an expression statement.
10304 * We simply eat it now and parse the rest with tail recursion. */
10305 while (next_if(T___extension__)) {}
10306 bool old_gcc_extension = in_gcc_extension;
10307 in_gcc_extension = true;
10308 statement = intern_parse_statement();
10309 in_gcc_extension = old_gcc_extension;
10313 statement = parse_declaration_statement();
10317 statement = parse_local_label_declaration();
10320 case ';': statement = parse_empty_statement(); break;
10321 case '{': statement = parse_compound_statement(false); break;
10322 case T___leave: statement = parse_leave_statement(); break;
10323 case T___try: statement = parse_ms_try_statment(); break;
10324 case T_asm: statement = parse_asm_statement(); break;
10325 case T_break: statement = parse_break(); break;
10326 case T_case: statement = parse_case_statement(); break;
10327 case T_continue: statement = parse_continue(); break;
10328 case T_default: statement = parse_default_statement(); break;
10329 case T_do: statement = parse_do(); break;
10330 case T_for: statement = parse_for(); break;
10331 case T_goto: statement = parse_goto(); break;
10332 case T_if: statement = parse_if(); break;
10333 case T_return: statement = parse_return(); break;
10334 case T_switch: statement = parse_switch(); break;
10335 case T_while: statement = parse_while(); break;
10338 statement = parse_expression_statement();
10342 errorf(HERE, "unexpected token %K while parsing statement", &token);
10343 statement = create_invalid_statement();
10348 rem_anchor_token(';');
10350 assert(statement != NULL
10351 && statement->base.source_position.input_name != NULL);
10357 * parse a statement and emits "statement has no effect" warning if needed
10358 * (This is really a wrapper around intern_parse_statement with check for 1
10359 * single warning. It is needed, because for statement expressions we have
10360 * to avoid the warning on the last statement)
10362 static statement_t *parse_statement(void)
10364 statement_t *statement = intern_parse_statement();
10366 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10367 expression_t *expression = statement->expression.expression;
10368 if (!expression_has_effect(expression)) {
10369 warningf(&expression->base.source_position,
10370 "statement has no effect");
10378 * Parse a compound statement.
10380 static statement_t *parse_compound_statement(bool inside_expression_statement)
10382 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10384 PUSH_PARENT(statement);
10387 add_anchor_token('}');
10388 /* tokens, which can start a statement */
10389 /* TODO MS, __builtin_FOO */
10390 add_anchor_token('!');
10391 add_anchor_token('&');
10392 add_anchor_token('(');
10393 add_anchor_token('*');
10394 add_anchor_token('+');
10395 add_anchor_token('-');
10396 add_anchor_token('{');
10397 add_anchor_token('~');
10398 add_anchor_token(T_CHARACTER_CONSTANT);
10399 add_anchor_token(T_COLONCOLON);
10400 add_anchor_token(T_FLOATINGPOINT);
10401 add_anchor_token(T_IDENTIFIER);
10402 add_anchor_token(T_INTEGER);
10403 add_anchor_token(T_MINUSMINUS);
10404 add_anchor_token(T_PLUSPLUS);
10405 add_anchor_token(T_STRING_LITERAL);
10406 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10407 add_anchor_token(T_WIDE_STRING_LITERAL);
10408 add_anchor_token(T__Bool);
10409 add_anchor_token(T__Complex);
10410 add_anchor_token(T__Imaginary);
10411 add_anchor_token(T___FUNCTION__);
10412 add_anchor_token(T___PRETTY_FUNCTION__);
10413 add_anchor_token(T___alignof__);
10414 add_anchor_token(T___attribute__);
10415 add_anchor_token(T___builtin_va_start);
10416 add_anchor_token(T___extension__);
10417 add_anchor_token(T___func__);
10418 add_anchor_token(T___imag__);
10419 add_anchor_token(T___label__);
10420 add_anchor_token(T___real__);
10421 add_anchor_token(T___thread);
10422 add_anchor_token(T_asm);
10423 add_anchor_token(T_auto);
10424 add_anchor_token(T_bool);
10425 add_anchor_token(T_break);
10426 add_anchor_token(T_case);
10427 add_anchor_token(T_char);
10428 add_anchor_token(T_class);
10429 add_anchor_token(T_const);
10430 add_anchor_token(T_const_cast);
10431 add_anchor_token(T_continue);
10432 add_anchor_token(T_default);
10433 add_anchor_token(T_delete);
10434 add_anchor_token(T_double);
10435 add_anchor_token(T_do);
10436 add_anchor_token(T_dynamic_cast);
10437 add_anchor_token(T_enum);
10438 add_anchor_token(T_extern);
10439 add_anchor_token(T_false);
10440 add_anchor_token(T_float);
10441 add_anchor_token(T_for);
10442 add_anchor_token(T_goto);
10443 add_anchor_token(T_if);
10444 add_anchor_token(T_inline);
10445 add_anchor_token(T_int);
10446 add_anchor_token(T_long);
10447 add_anchor_token(T_new);
10448 add_anchor_token(T_operator);
10449 add_anchor_token(T_register);
10450 add_anchor_token(T_reinterpret_cast);
10451 add_anchor_token(T_restrict);
10452 add_anchor_token(T_return);
10453 add_anchor_token(T_short);
10454 add_anchor_token(T_signed);
10455 add_anchor_token(T_sizeof);
10456 add_anchor_token(T_static);
10457 add_anchor_token(T_static_cast);
10458 add_anchor_token(T_struct);
10459 add_anchor_token(T_switch);
10460 add_anchor_token(T_template);
10461 add_anchor_token(T_this);
10462 add_anchor_token(T_throw);
10463 add_anchor_token(T_true);
10464 add_anchor_token(T_try);
10465 add_anchor_token(T_typedef);
10466 add_anchor_token(T_typeid);
10467 add_anchor_token(T_typename);
10468 add_anchor_token(T_typeof);
10469 add_anchor_token(T_union);
10470 add_anchor_token(T_unsigned);
10471 add_anchor_token(T_using);
10472 add_anchor_token(T_void);
10473 add_anchor_token(T_volatile);
10474 add_anchor_token(T_wchar_t);
10475 add_anchor_token(T_while);
10477 size_t const top = environment_top();
10478 scope_t *old_scope = scope_push(&statement->compound.scope);
10480 statement_t **anchor = &statement->compound.statements;
10481 bool only_decls_so_far = true;
10482 while (token.type != '}') {
10483 if (token.type == T_EOF) {
10484 errorf(&statement->base.source_position,
10485 "EOF while parsing compound statement");
10488 statement_t *sub_statement = intern_parse_statement();
10489 if (is_invalid_statement(sub_statement)) {
10490 /* an error occurred. if we are at an anchor, return */
10496 if (warning.declaration_after_statement) {
10497 if (sub_statement->kind != STATEMENT_DECLARATION) {
10498 only_decls_so_far = false;
10499 } else if (!only_decls_so_far) {
10500 warningf(&sub_statement->base.source_position,
10501 "ISO C90 forbids mixed declarations and code");
10505 *anchor = sub_statement;
10507 while (sub_statement->base.next != NULL)
10508 sub_statement = sub_statement->base.next;
10510 anchor = &sub_statement->base.next;
10514 /* look over all statements again to produce no effect warnings */
10515 if (warning.unused_value) {
10516 statement_t *sub_statement = statement->compound.statements;
10517 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10518 if (sub_statement->kind != STATEMENT_EXPRESSION)
10520 /* don't emit a warning for the last expression in an expression
10521 * statement as it has always an effect */
10522 if (inside_expression_statement && sub_statement->base.next == NULL)
10525 expression_t *expression = sub_statement->expression.expression;
10526 if (!expression_has_effect(expression)) {
10527 warningf(&expression->base.source_position,
10528 "statement has no effect");
10534 rem_anchor_token(T_while);
10535 rem_anchor_token(T_wchar_t);
10536 rem_anchor_token(T_volatile);
10537 rem_anchor_token(T_void);
10538 rem_anchor_token(T_using);
10539 rem_anchor_token(T_unsigned);
10540 rem_anchor_token(T_union);
10541 rem_anchor_token(T_typeof);
10542 rem_anchor_token(T_typename);
10543 rem_anchor_token(T_typeid);
10544 rem_anchor_token(T_typedef);
10545 rem_anchor_token(T_try);
10546 rem_anchor_token(T_true);
10547 rem_anchor_token(T_throw);
10548 rem_anchor_token(T_this);
10549 rem_anchor_token(T_template);
10550 rem_anchor_token(T_switch);
10551 rem_anchor_token(T_struct);
10552 rem_anchor_token(T_static_cast);
10553 rem_anchor_token(T_static);
10554 rem_anchor_token(T_sizeof);
10555 rem_anchor_token(T_signed);
10556 rem_anchor_token(T_short);
10557 rem_anchor_token(T_return);
10558 rem_anchor_token(T_restrict);
10559 rem_anchor_token(T_reinterpret_cast);
10560 rem_anchor_token(T_register);
10561 rem_anchor_token(T_operator);
10562 rem_anchor_token(T_new);
10563 rem_anchor_token(T_long);
10564 rem_anchor_token(T_int);
10565 rem_anchor_token(T_inline);
10566 rem_anchor_token(T_if);
10567 rem_anchor_token(T_goto);
10568 rem_anchor_token(T_for);
10569 rem_anchor_token(T_float);
10570 rem_anchor_token(T_false);
10571 rem_anchor_token(T_extern);
10572 rem_anchor_token(T_enum);
10573 rem_anchor_token(T_dynamic_cast);
10574 rem_anchor_token(T_do);
10575 rem_anchor_token(T_double);
10576 rem_anchor_token(T_delete);
10577 rem_anchor_token(T_default);
10578 rem_anchor_token(T_continue);
10579 rem_anchor_token(T_const_cast);
10580 rem_anchor_token(T_const);
10581 rem_anchor_token(T_class);
10582 rem_anchor_token(T_char);
10583 rem_anchor_token(T_case);
10584 rem_anchor_token(T_break);
10585 rem_anchor_token(T_bool);
10586 rem_anchor_token(T_auto);
10587 rem_anchor_token(T_asm);
10588 rem_anchor_token(T___thread);
10589 rem_anchor_token(T___real__);
10590 rem_anchor_token(T___label__);
10591 rem_anchor_token(T___imag__);
10592 rem_anchor_token(T___func__);
10593 rem_anchor_token(T___extension__);
10594 rem_anchor_token(T___builtin_va_start);
10595 rem_anchor_token(T___attribute__);
10596 rem_anchor_token(T___alignof__);
10597 rem_anchor_token(T___PRETTY_FUNCTION__);
10598 rem_anchor_token(T___FUNCTION__);
10599 rem_anchor_token(T__Imaginary);
10600 rem_anchor_token(T__Complex);
10601 rem_anchor_token(T__Bool);
10602 rem_anchor_token(T_WIDE_STRING_LITERAL);
10603 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10604 rem_anchor_token(T_STRING_LITERAL);
10605 rem_anchor_token(T_PLUSPLUS);
10606 rem_anchor_token(T_MINUSMINUS);
10607 rem_anchor_token(T_INTEGER);
10608 rem_anchor_token(T_IDENTIFIER);
10609 rem_anchor_token(T_FLOATINGPOINT);
10610 rem_anchor_token(T_COLONCOLON);
10611 rem_anchor_token(T_CHARACTER_CONSTANT);
10612 rem_anchor_token('~');
10613 rem_anchor_token('{');
10614 rem_anchor_token('-');
10615 rem_anchor_token('+');
10616 rem_anchor_token('*');
10617 rem_anchor_token('(');
10618 rem_anchor_token('&');
10619 rem_anchor_token('!');
10620 rem_anchor_token('}');
10621 assert(current_scope == &statement->compound.scope);
10622 scope_pop(old_scope);
10623 environment_pop_to(top);
10630 * Check for unused global static functions and variables
10632 static void check_unused_globals(void)
10634 if (!warning.unused_function && !warning.unused_variable)
10637 for (const entity_t *entity = file_scope->entities; entity != NULL;
10638 entity = entity->base.next) {
10639 if (!is_declaration(entity))
10642 const declaration_t *declaration = &entity->declaration;
10643 if (declaration->used ||
10644 declaration->modifiers & DM_UNUSED ||
10645 declaration->modifiers & DM_USED ||
10646 declaration->storage_class != STORAGE_CLASS_STATIC)
10649 type_t *const type = declaration->type;
10651 if (entity->kind == ENTITY_FUNCTION) {
10652 /* inhibit warning for static inline functions */
10653 if (entity->function.is_inline)
10656 s = entity->function.statement != NULL ? "defined" : "declared";
10661 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10662 type, declaration->base.symbol, s);
10666 static void parse_global_asm(void)
10668 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10671 expect('(', end_error);
10673 statement->asms.asm_text = parse_string_literals();
10674 statement->base.next = unit->global_asm;
10675 unit->global_asm = statement;
10677 expect(')', end_error);
10678 expect(';', end_error);
10683 static void parse_linkage_specification(void)
10687 const char *linkage = parse_string_literals().begin;
10689 linkage_kind_t old_linkage = current_linkage;
10690 linkage_kind_t new_linkage;
10691 if (strcmp(linkage, "C") == 0) {
10692 new_linkage = LINKAGE_C;
10693 } else if (strcmp(linkage, "C++") == 0) {
10694 new_linkage = LINKAGE_CXX;
10696 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10697 new_linkage = LINKAGE_INVALID;
10699 current_linkage = new_linkage;
10701 if (next_if('{')) {
10703 expect('}', end_error);
10709 assert(current_linkage == new_linkage);
10710 current_linkage = old_linkage;
10713 static void parse_external(void)
10715 switch (token.type) {
10716 DECLARATION_START_NO_EXTERN
10718 case T___extension__:
10719 /* tokens below are for implicit int */
10720 case '&': /* & x; -> int& x; (and error later, because C++ has no
10722 case '*': /* * x; -> int* x; */
10723 case '(': /* (x); -> int (x); */
10724 parse_external_declaration();
10728 if (look_ahead(1)->type == T_STRING_LITERAL) {
10729 parse_linkage_specification();
10731 parse_external_declaration();
10736 parse_global_asm();
10740 parse_namespace_definition();
10744 if (!strict_mode) {
10746 warningf(HERE, "stray ';' outside of function");
10753 errorf(HERE, "stray %K outside of function", &token);
10754 if (token.type == '(' || token.type == '{' || token.type == '[')
10755 eat_until_matching_token(token.type);
10761 static void parse_externals(void)
10763 add_anchor_token('}');
10764 add_anchor_token(T_EOF);
10767 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10768 unsigned char token_anchor_copy[T_LAST_TOKEN];
10769 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10772 while (token.type != T_EOF && token.type != '}') {
10774 bool anchor_leak = false;
10775 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10776 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10778 /* the anchor set and its copy differs */
10779 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10780 anchor_leak = true;
10783 if (in_gcc_extension) {
10784 /* an gcc extension scope was not closed */
10785 errorf(HERE, "Leaked __extension__");
10786 anchor_leak = true;
10796 rem_anchor_token(T_EOF);
10797 rem_anchor_token('}');
10801 * Parse a translation unit.
10803 static void parse_translation_unit(void)
10805 add_anchor_token(T_EOF);
10810 if (token.type == T_EOF)
10813 errorf(HERE, "stray %K outside of function", &token);
10814 if (token.type == '(' || token.type == '{' || token.type == '[')
10815 eat_until_matching_token(token.type);
10823 * @return the translation unit or NULL if errors occurred.
10825 void start_parsing(void)
10827 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10828 label_stack = NEW_ARR_F(stack_entry_t, 0);
10829 diagnostic_count = 0;
10833 print_to_file(stderr);
10835 assert(unit == NULL);
10836 unit = allocate_ast_zero(sizeof(unit[0]));
10838 assert(file_scope == NULL);
10839 file_scope = &unit->scope;
10841 assert(current_scope == NULL);
10842 scope_push(&unit->scope);
10844 create_gnu_builtins();
10846 create_microsoft_intrinsics();
10849 translation_unit_t *finish_parsing(void)
10851 assert(current_scope == &unit->scope);
10854 assert(file_scope == &unit->scope);
10855 check_unused_globals();
10858 DEL_ARR_F(environment_stack);
10859 DEL_ARR_F(label_stack);
10861 translation_unit_t *result = unit;
10866 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10867 * are given length one. */
10868 static void complete_incomplete_arrays(void)
10870 size_t n = ARR_LEN(incomplete_arrays);
10871 for (size_t i = 0; i != n; ++i) {
10872 declaration_t *const decl = incomplete_arrays[i];
10873 type_t *const orig_type = decl->type;
10874 type_t *const type = skip_typeref(orig_type);
10876 if (!is_type_incomplete(type))
10879 if (warning.other) {
10880 warningf(&decl->base.source_position,
10881 "array '%#T' assumed to have one element",
10882 orig_type, decl->base.symbol);
10885 type_t *const new_type = duplicate_type(type);
10886 new_type->array.size_constant = true;
10887 new_type->array.has_implicit_size = true;
10888 new_type->array.size = 1;
10890 type_t *const result = identify_new_type(new_type);
10892 decl->type = result;
10896 void prepare_main_collect2(entity_t *entity)
10898 // create call to __main
10899 symbol_t *symbol = symbol_table_insert("__main");
10900 entity_t *subsubmain_ent
10901 = create_implicit_function(symbol, &builtin_source_position);
10903 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10904 type_t *ftype = subsubmain_ent->declaration.type;
10905 ref->base.source_position = builtin_source_position;
10906 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10907 ref->reference.entity = subsubmain_ent;
10909 expression_t *call = allocate_expression_zero(EXPR_CALL);
10910 call->base.source_position = builtin_source_position;
10911 call->base.type = type_void;
10912 call->call.function = ref;
10914 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10915 expr_statement->base.source_position = builtin_source_position;
10916 expr_statement->expression.expression = call;
10918 statement_t *statement = entity->function.statement;
10919 assert(statement->kind == STATEMENT_COMPOUND);
10920 compound_statement_t *compounds = &statement->compound;
10922 expr_statement->base.next = compounds->statements;
10923 compounds->statements = expr_statement;
10928 lookahead_bufpos = 0;
10929 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10932 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10933 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10934 parse_translation_unit();
10935 complete_incomplete_arrays();
10936 DEL_ARR_F(incomplete_arrays);
10937 incomplete_arrays = NULL;
10941 * Initialize the parser.
10943 void init_parser(void)
10945 sym_anonymous = symbol_table_insert("<anonymous>");
10947 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10949 init_expression_parsers();
10950 obstack_init(&temp_obst);
10954 * Terminate the parser.
10956 void exit_parser(void)
10958 obstack_free(&temp_obst, NULL);