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;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const prev_parent = current_parent; \
116 ((void)(current_parent = (stmt)))
117 #define POP_PARENT ((void)(current_parent = prev_parent))
119 /** special symbol used for anonymous entities. */
120 static symbol_t *sym_anonymous = NULL;
122 /** The token anchor set */
123 static unsigned char token_anchor_set[T_LAST_TOKEN];
125 /** The current source position. */
126 #define HERE (&token.source_position)
128 /** true if we are in GCC mode. */
129 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
131 static statement_t *parse_compound_statement(bool inside_expression_statement);
132 static statement_t *parse_statement(void);
134 static expression_t *parse_subexpression(precedence_t);
135 static expression_t *parse_expression(void);
136 static type_t *parse_typename(void);
137 static void parse_externals(void);
138 static void parse_external(void);
140 static void parse_compound_type_entries(compound_t *compound_declaration);
142 static void check_call_argument(type_t *expected_type,
143 call_argument_t *argument, unsigned pos);
145 typedef enum declarator_flags_t {
147 DECL_MAY_BE_ABSTRACT = 1U << 0,
148 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
149 DECL_IS_PARAMETER = 1U << 2
150 } declarator_flags_t;
152 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
153 declarator_flags_t flags);
155 static void semantic_comparison(binary_expression_t *expression);
157 #define STORAGE_CLASSES \
158 STORAGE_CLASSES_NO_EXTERN \
161 #define STORAGE_CLASSES_NO_EXTERN \
168 #define TYPE_QUALIFIERS \
173 case T__forceinline: \
174 case T___attribute__:
176 #define COMPLEX_SPECIFIERS \
178 #define IMAGINARY_SPECIFIERS \
181 #define TYPE_SPECIFIERS \
183 case T___builtin_va_list: \
208 #define DECLARATION_START \
213 #define DECLARATION_START_NO_EXTERN \
214 STORAGE_CLASSES_NO_EXTERN \
218 #define TYPENAME_START \
222 #define EXPRESSION_START \
231 case T_CHARACTER_CONSTANT: \
232 case T_FLOATINGPOINT: \
233 case T_FLOATINGPOINT_HEXADECIMAL: \
235 case T_INTEGER_HEXADECIMAL: \
236 case T_INTEGER_OCTAL: \
239 case T_STRING_LITERAL: \
240 case T_WIDE_CHARACTER_CONSTANT: \
241 case T_WIDE_STRING_LITERAL: \
242 case T___FUNCDNAME__: \
243 case T___FUNCSIG__: \
244 case T___FUNCTION__: \
245 case T___PRETTY_FUNCTION__: \
246 case T___alignof__: \
247 case T___builtin_classify_type: \
248 case T___builtin_constant_p: \
249 case T___builtin_isgreater: \
250 case T___builtin_isgreaterequal: \
251 case T___builtin_isless: \
252 case T___builtin_islessequal: \
253 case T___builtin_islessgreater: \
254 case T___builtin_isunordered: \
255 case T___builtin_offsetof: \
256 case T___builtin_va_arg: \
257 case T___builtin_va_copy: \
258 case T___builtin_va_start: \
269 * Returns the size of a statement node.
271 * @param kind the statement kind
273 static size_t get_statement_struct_size(statement_kind_t kind)
275 static const size_t sizes[] = {
276 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
277 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
278 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
279 [STATEMENT_RETURN] = sizeof(return_statement_t),
280 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
281 [STATEMENT_IF] = sizeof(if_statement_t),
282 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
283 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
284 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
285 [STATEMENT_BREAK] = sizeof(statement_base_t),
286 [STATEMENT_GOTO] = sizeof(goto_statement_t),
287 [STATEMENT_LABEL] = sizeof(label_statement_t),
288 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
289 [STATEMENT_WHILE] = sizeof(while_statement_t),
290 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
291 [STATEMENT_FOR] = sizeof(for_statement_t),
292 [STATEMENT_ASM] = sizeof(asm_statement_t),
293 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
294 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
296 assert(kind < lengthof(sizes));
297 assert(sizes[kind] != 0);
302 * Returns the size of an expression node.
304 * @param kind the expression kind
306 static size_t get_expression_struct_size(expression_kind_t kind)
308 static const size_t sizes[] = {
309 [EXPR_INVALID] = sizeof(expression_base_t),
310 [EXPR_REFERENCE] = sizeof(reference_expression_t),
311 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
312 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
316 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
317 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
318 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
319 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
320 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
321 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
322 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
323 [EXPR_CALL] = sizeof(call_expression_t),
324 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
325 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
326 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
327 [EXPR_SELECT] = sizeof(select_expression_t),
328 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
329 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
330 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
331 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
332 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
333 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
334 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
335 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
336 [EXPR_VA_START] = sizeof(va_start_expression_t),
337 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
338 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
339 [EXPR_STATEMENT] = sizeof(statement_expression_t),
340 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
342 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
343 return sizes[EXPR_UNARY_FIRST];
345 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
346 return sizes[EXPR_BINARY_FIRST];
348 assert(kind < lengthof(sizes));
349 assert(sizes[kind] != 0);
354 * Allocate a statement node of given kind and initialize all
355 * fields with zero. Sets its source position to the position
356 * of the current token.
358 static statement_t *allocate_statement_zero(statement_kind_t kind)
360 size_t size = get_statement_struct_size(kind);
361 statement_t *res = allocate_ast_zero(size);
363 res->base.kind = kind;
364 res->base.parent = current_parent;
365 res->base.source_position = token.source_position;
370 * Allocate an expression node of given kind and initialize all
373 * @param kind the kind of the expression to allocate
375 static expression_t *allocate_expression_zero(expression_kind_t kind)
377 size_t size = get_expression_struct_size(kind);
378 expression_t *res = allocate_ast_zero(size);
380 res->base.kind = kind;
381 res->base.type = type_error_type;
382 res->base.source_position = token.source_position;
387 * Creates a new invalid expression at the source position
388 * of the current token.
390 static expression_t *create_invalid_expression(void)
392 return allocate_expression_zero(EXPR_INVALID);
396 * Creates a new invalid statement.
398 static statement_t *create_invalid_statement(void)
400 return allocate_statement_zero(STATEMENT_INVALID);
404 * Allocate a new empty statement.
406 static statement_t *create_empty_statement(void)
408 return allocate_statement_zero(STATEMENT_EMPTY);
411 static function_parameter_t *allocate_parameter(type_t *const type)
413 function_parameter_t *const param
414 = obstack_alloc(type_obst, sizeof(*param));
415 memset(param, 0, sizeof(*param));
421 * Returns the size of an initializer node.
423 * @param kind the initializer kind
425 static size_t get_initializer_size(initializer_kind_t kind)
427 static const size_t sizes[] = {
428 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
429 [INITIALIZER_STRING] = sizeof(initializer_string_t),
430 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
431 [INITIALIZER_LIST] = sizeof(initializer_list_t),
432 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
434 assert(kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate an initializer node of given kind and initialize all
443 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
445 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
452 * Returns the index of the top element of the environment stack.
454 static size_t environment_top(void)
456 return ARR_LEN(environment_stack);
460 * Returns the index of the top element of the global label stack.
462 static size_t label_top(void)
464 return ARR_LEN(label_stack);
468 * Return the next token.
470 static inline void next_token(void)
472 token = lookahead_buffer[lookahead_bufpos];
473 lookahead_buffer[lookahead_bufpos] = lexer_token;
476 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
479 print_token(stderr, &token);
480 fprintf(stderr, "\n");
484 static inline bool next_if(int const type)
486 if (token.type == type) {
495 * Return the next token with a given lookahead.
497 static inline const token_t *look_ahead(size_t num)
499 assert(0 < num && num <= MAX_LOOKAHEAD);
500 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
501 return &lookahead_buffer[pos];
505 * Adds a token type to the token type anchor set (a multi-set).
507 static void add_anchor_token(int token_type)
509 assert(0 <= token_type && token_type < T_LAST_TOKEN);
510 ++token_anchor_set[token_type];
514 * Set the number of tokens types of the given type
515 * to zero and return the old count.
517 static int save_and_reset_anchor_state(int token_type)
519 assert(0 <= token_type && token_type < T_LAST_TOKEN);
520 int count = token_anchor_set[token_type];
521 token_anchor_set[token_type] = 0;
526 * Restore the number of token types to the given count.
528 static void restore_anchor_state(int token_type, int count)
530 assert(0 <= token_type && token_type < T_LAST_TOKEN);
531 token_anchor_set[token_type] = count;
535 * Remove a token type from the token type anchor set (a multi-set).
537 static void rem_anchor_token(int token_type)
539 assert(0 <= token_type && token_type < T_LAST_TOKEN);
540 assert(token_anchor_set[token_type] != 0);
541 --token_anchor_set[token_type];
545 * Return true if the token type of the current token is
548 static bool at_anchor(void)
552 return token_anchor_set[token.type];
556 * Eat tokens until a matching token type is found.
558 static void eat_until_matching_token(int type)
562 case '(': end_token = ')'; break;
563 case '{': end_token = '}'; break;
564 case '[': end_token = ']'; break;
565 default: end_token = type; break;
568 unsigned parenthesis_count = 0;
569 unsigned brace_count = 0;
570 unsigned bracket_count = 0;
571 while (token.type != end_token ||
572 parenthesis_count != 0 ||
574 bracket_count != 0) {
575 switch (token.type) {
577 case '(': ++parenthesis_count; break;
578 case '{': ++brace_count; break;
579 case '[': ++bracket_count; break;
582 if (parenthesis_count > 0)
592 if (bracket_count > 0)
595 if (token.type == end_token &&
596 parenthesis_count == 0 &&
610 * Eat input tokens until an anchor is found.
612 static void eat_until_anchor(void)
614 while (token_anchor_set[token.type] == 0) {
615 if (token.type == '(' || token.type == '{' || token.type == '[')
616 eat_until_matching_token(token.type);
622 * Eat a whole block from input tokens.
624 static void eat_block(void)
626 eat_until_matching_token('{');
630 #define eat(token_type) (assert(token.type == (token_type)), next_token())
633 * Report a parse error because an expected token was not found.
636 #if defined __GNUC__ && __GNUC__ >= 4
637 __attribute__((sentinel))
639 void parse_error_expected(const char *message, ...)
641 if (message != NULL) {
642 errorf(HERE, "%s", message);
645 va_start(ap, message);
646 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
651 * Report an incompatible type.
653 static void type_error_incompatible(const char *msg,
654 const source_position_t *source_position, type_t *type1, type_t *type2)
656 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
661 * Expect the current token is the expected token.
662 * If not, generate an error, eat the current statement,
663 * and goto the error_label label.
665 #define expect(expected, error_label) \
667 if (UNLIKELY(token.type != (expected))) { \
668 parse_error_expected(NULL, (expected), NULL); \
669 add_anchor_token(expected); \
670 eat_until_anchor(); \
671 next_if((expected)); \
672 rem_anchor_token(expected); \
679 * Push a given scope on the scope stack and make it the
682 static scope_t *scope_push(scope_t *new_scope)
684 if (current_scope != NULL) {
685 new_scope->depth = current_scope->depth + 1;
688 scope_t *old_scope = current_scope;
689 current_scope = new_scope;
694 * Pop the current scope from the scope stack.
696 static void scope_pop(scope_t *old_scope)
698 current_scope = old_scope;
702 * Search an entity by its symbol in a given namespace.
704 static entity_t *get_entity(const symbol_t *const symbol,
705 namespace_tag_t namespc)
707 assert(namespc != NAMESPACE_INVALID);
708 entity_t *entity = symbol->entity;
709 for (; entity != NULL; entity = entity->base.symbol_next) {
710 if (entity->base.namespc == namespc)
717 /* §6.2.3:1 24) There is only one name space for tags even though three are
719 static entity_t *get_tag(symbol_t const *const symbol,
720 entity_kind_tag_t const kind)
722 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
723 if (entity != NULL && entity->kind != kind) {
725 "'%Y' defined as wrong kind of tag (previous definition %P)",
726 symbol, &entity->base.source_position);
733 * pushs an entity on the environment stack and links the corresponding symbol
736 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
738 symbol_t *symbol = entity->base.symbol;
739 entity_namespace_t namespc = entity->base.namespc;
740 assert(namespc != NAMESPACE_INVALID);
742 /* replace/add entity into entity list of the symbol */
745 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
750 /* replace an entry? */
751 if (iter->base.namespc == namespc) {
752 entity->base.symbol_next = iter->base.symbol_next;
758 /* remember old declaration */
760 entry.symbol = symbol;
761 entry.old_entity = iter;
762 entry.namespc = namespc;
763 ARR_APP1(stack_entry_t, *stack_ptr, entry);
767 * Push an entity on the environment stack.
769 static void environment_push(entity_t *entity)
771 assert(entity->base.source_position.input_name != NULL);
772 assert(entity->base.parent_scope != NULL);
773 stack_push(&environment_stack, entity);
777 * Push a declaration on the global label stack.
779 * @param declaration the declaration
781 static void label_push(entity_t *label)
783 /* we abuse the parameters scope as parent for the labels */
784 label->base.parent_scope = ¤t_function->parameters;
785 stack_push(&label_stack, label);
789 * pops symbols from the environment stack until @p new_top is the top element
791 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
793 stack_entry_t *stack = *stack_ptr;
794 size_t top = ARR_LEN(stack);
797 assert(new_top <= top);
801 for (i = top; i > new_top; --i) {
802 stack_entry_t *entry = &stack[i - 1];
804 entity_t *old_entity = entry->old_entity;
805 symbol_t *symbol = entry->symbol;
806 entity_namespace_t namespc = entry->namespc;
808 /* replace with old_entity/remove */
811 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
813 assert(iter != NULL);
814 /* replace an entry? */
815 if (iter->base.namespc == namespc)
819 /* restore definition from outer scopes (if there was one) */
820 if (old_entity != NULL) {
821 old_entity->base.symbol_next = iter->base.symbol_next;
822 *anchor = old_entity;
824 /* remove entry from list */
825 *anchor = iter->base.symbol_next;
829 ARR_SHRINKLEN(*stack_ptr, new_top);
833 * Pop all entries from the environment stack until the new_top
836 * @param new_top the new stack top
838 static void environment_pop_to(size_t new_top)
840 stack_pop_to(&environment_stack, new_top);
844 * Pop all entries from the global label stack until the new_top
847 * @param new_top the new stack top
849 static void label_pop_to(size_t new_top)
851 stack_pop_to(&label_stack, new_top);
854 static int get_akind_rank(atomic_type_kind_t akind)
860 * Return the type rank for an atomic type.
862 static int get_rank(const type_t *type)
864 assert(!is_typeref(type));
865 if (type->kind == TYPE_ENUM)
866 return get_akind_rank(type->enumt.akind);
868 assert(type->kind == TYPE_ATOMIC);
869 return get_akind_rank(type->atomic.akind);
873 * §6.3.1.1:2 Do integer promotion for a given type.
875 * @param type the type to promote
876 * @return the promoted type
878 static type_t *promote_integer(type_t *type)
880 if (type->kind == TYPE_BITFIELD)
881 type = type->bitfield.base_type;
883 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
890 * Create a cast expression.
892 * @param expression the expression to cast
893 * @param dest_type the destination type
895 static expression_t *create_cast_expression(expression_t *expression,
898 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
900 cast->unary.value = expression;
901 cast->base.type = dest_type;
907 * Check if a given expression represents a null pointer constant.
909 * @param expression the expression to check
911 static bool is_null_pointer_constant(const expression_t *expression)
913 /* skip void* cast */
914 if (expression->kind == EXPR_UNARY_CAST ||
915 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
916 type_t *const type = skip_typeref(expression->base.type);
917 if (types_compatible(type, type_void_ptr))
918 expression = expression->unary.value;
921 type_t *const type = skip_typeref(expression->base.type);
922 if (!is_type_integer(type))
924 switch (is_constant_expression(expression)) {
925 case EXPR_CLASS_ERROR: return true;
926 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
927 default: return false;
932 * Create an implicit cast expression.
934 * @param expression the expression to cast
935 * @param dest_type the destination type
937 static expression_t *create_implicit_cast(expression_t *expression,
940 type_t *const source_type = expression->base.type;
942 if (source_type == dest_type)
945 return create_cast_expression(expression, dest_type);
948 typedef enum assign_error_t {
950 ASSIGN_ERROR_INCOMPATIBLE,
951 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
952 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
953 ASSIGN_WARNING_POINTER_FROM_INT,
954 ASSIGN_WARNING_INT_FROM_POINTER
957 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
958 const expression_t *const right,
960 const source_position_t *source_position)
962 type_t *const orig_type_right = right->base.type;
963 type_t *const type_left = skip_typeref(orig_type_left);
964 type_t *const type_right = skip_typeref(orig_type_right);
969 case ASSIGN_ERROR_INCOMPATIBLE:
970 errorf(source_position,
971 "destination type '%T' in %s is incompatible with type '%T'",
972 orig_type_left, context, orig_type_right);
975 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
977 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
978 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
980 /* the left type has all qualifiers from the right type */
981 unsigned missing_qualifiers
982 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
983 warningf(source_position,
984 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
985 orig_type_left, context, orig_type_right, missing_qualifiers);
990 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
992 warningf(source_position,
993 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
994 orig_type_left, context, right, orig_type_right);
998 case ASSIGN_WARNING_POINTER_FROM_INT:
1000 warningf(source_position,
1001 "%s makes pointer '%T' from integer '%T' without a cast",
1002 context, orig_type_left, orig_type_right);
1006 case ASSIGN_WARNING_INT_FROM_POINTER:
1007 if (warning.other) {
1008 warningf(source_position,
1009 "%s makes integer '%T' from pointer '%T' without a cast",
1010 context, orig_type_left, orig_type_right);
1015 panic("invalid error value");
1019 /** Implements the rules from §6.5.16.1 */
1020 static assign_error_t semantic_assign(type_t *orig_type_left,
1021 const expression_t *const right)
1023 type_t *const orig_type_right = right->base.type;
1024 type_t *const type_left = skip_typeref(orig_type_left);
1025 type_t *const type_right = skip_typeref(orig_type_right);
1027 if (is_type_pointer(type_left)) {
1028 if (is_null_pointer_constant(right)) {
1029 return ASSIGN_SUCCESS;
1030 } else if (is_type_pointer(type_right)) {
1031 type_t *points_to_left
1032 = skip_typeref(type_left->pointer.points_to);
1033 type_t *points_to_right
1034 = skip_typeref(type_right->pointer.points_to);
1035 assign_error_t res = ASSIGN_SUCCESS;
1037 /* the left type has all qualifiers from the right type */
1038 unsigned missing_qualifiers
1039 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1040 if (missing_qualifiers != 0) {
1041 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1044 points_to_left = get_unqualified_type(points_to_left);
1045 points_to_right = get_unqualified_type(points_to_right);
1047 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1050 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1051 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1052 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1055 if (!types_compatible(points_to_left, points_to_right)) {
1056 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1060 } else if (is_type_integer(type_right)) {
1061 return ASSIGN_WARNING_POINTER_FROM_INT;
1063 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1064 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1065 && is_type_pointer(type_right))) {
1066 return ASSIGN_SUCCESS;
1067 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1068 type_t *const unqual_type_left = get_unqualified_type(type_left);
1069 type_t *const unqual_type_right = get_unqualified_type(type_right);
1070 if (types_compatible(unqual_type_left, unqual_type_right)) {
1071 return ASSIGN_SUCCESS;
1073 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1074 return ASSIGN_WARNING_INT_FROM_POINTER;
1077 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1078 return ASSIGN_SUCCESS;
1080 return ASSIGN_ERROR_INCOMPATIBLE;
1083 static expression_t *parse_constant_expression(void)
1085 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1087 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1088 errorf(&result->base.source_position,
1089 "expression '%E' is not constant", result);
1095 static expression_t *parse_assignment_expression(void)
1097 return parse_subexpression(PREC_ASSIGNMENT);
1100 static void warn_string_concat(const source_position_t *pos)
1102 if (warning.traditional) {
1103 warningf(pos, "traditional C rejects string constant concatenation");
1107 static string_t parse_string_literals(void)
1109 assert(token.type == T_STRING_LITERAL);
1110 string_t result = token.literal;
1114 while (token.type == T_STRING_LITERAL) {
1115 warn_string_concat(&token.source_position);
1116 result = concat_strings(&result, &token.literal);
1124 * compare two string, ignoring double underscores on the second.
1126 static int strcmp_underscore(const char *s1, const char *s2)
1128 if (s2[0] == '_' && s2[1] == '_') {
1129 size_t len2 = strlen(s2);
1130 size_t len1 = strlen(s1);
1131 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1132 return strncmp(s1, s2+2, len2-4);
1136 return strcmp(s1, s2);
1139 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1141 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1142 attribute->kind = kind;
1147 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1150 * __attribute__ ( ( attribute-list ) )
1154 * attribute_list , attrib
1159 * any-word ( identifier )
1160 * any-word ( identifier , nonempty-expr-list )
1161 * any-word ( expr-list )
1163 * where the "identifier" must not be declared as a type, and
1164 * "any-word" may be any identifier (including one declared as a
1165 * type), a reserved word storage class specifier, type specifier or
1166 * type qualifier. ??? This still leaves out most reserved keywords
1167 * (following the old parser), shouldn't we include them, and why not
1168 * allow identifiers declared as types to start the arguments?
1170 * Matze: this all looks confusing and little systematic, so we're even less
1171 * strict and parse any list of things which are identifiers or
1172 * (assignment-)expressions.
1174 static attribute_argument_t *parse_attribute_arguments(void)
1176 attribute_argument_t *first = NULL;
1177 attribute_argument_t **anchor = &first;
1178 if (token.type != ')') do {
1179 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1181 /* is it an identifier */
1182 if (token.type == T_IDENTIFIER
1183 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1184 symbol_t *symbol = token.symbol;
1185 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1186 argument->v.symbol = symbol;
1189 /* must be an expression */
1190 expression_t *expression = parse_assignment_expression();
1192 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1193 argument->v.expression = expression;
1196 /* append argument */
1198 anchor = &argument->next;
1199 } while (next_if(','));
1200 expect(')', end_error);
1209 static attribute_t *parse_attribute_asm(void)
1213 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1215 expect('(', end_error);
1216 attribute->a.arguments = parse_attribute_arguments();
1223 static symbol_t *get_symbol_from_token(void)
1225 switch(token.type) {
1227 return token.symbol;
1256 /* maybe we need more tokens ... add them on demand */
1257 return get_token_symbol(&token);
1263 static attribute_t *parse_attribute_gnu_single(void)
1265 /* parse "any-word" */
1266 symbol_t *symbol = get_symbol_from_token();
1267 if (symbol == NULL) {
1268 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1272 const char *name = symbol->string;
1275 attribute_kind_t kind;
1276 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1277 const char *attribute_name = get_attribute_name(kind);
1278 if (attribute_name != NULL
1279 && strcmp_underscore(attribute_name, name) == 0)
1283 if (kind >= ATTRIBUTE_GNU_LAST) {
1284 if (warning.attribute) {
1285 warningf(HERE, "unknown attribute '%s' ignored", name);
1287 /* TODO: we should still save the attribute in the list... */
1288 kind = ATTRIBUTE_UNKNOWN;
1291 attribute_t *attribute = allocate_attribute_zero(kind);
1293 /* parse arguments */
1295 attribute->a.arguments = parse_attribute_arguments();
1300 static attribute_t *parse_attribute_gnu(void)
1302 attribute_t *first = NULL;
1303 attribute_t **anchor = &first;
1305 eat(T___attribute__);
1306 expect('(', end_error);
1307 expect('(', end_error);
1309 if (token.type != ')') do {
1310 attribute_t *attribute = parse_attribute_gnu_single();
1311 if (attribute == NULL)
1314 *anchor = attribute;
1315 anchor = &attribute->next;
1316 } while (next_if(','));
1317 expect(')', end_error);
1318 expect(')', end_error);
1324 /** Parse attributes. */
1325 static attribute_t *parse_attributes(attribute_t *first)
1327 attribute_t **anchor = &first;
1329 while (*anchor != NULL)
1330 anchor = &(*anchor)->next;
1332 attribute_t *attribute;
1333 switch (token.type) {
1334 case T___attribute__:
1335 attribute = parse_attribute_gnu();
1336 if (attribute == NULL)
1341 attribute = parse_attribute_asm();
1346 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1351 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1354 case T__forceinline:
1356 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1361 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1366 /* TODO record modifier */
1368 warningf(HERE, "Ignoring declaration modifier %K", &token);
1369 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1376 *anchor = attribute;
1377 anchor = &attribute->next;
1381 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1383 static entity_t *determine_lhs_ent(expression_t *const expr,
1386 switch (expr->kind) {
1387 case EXPR_REFERENCE: {
1388 entity_t *const entity = expr->reference.entity;
1389 /* we should only find variables as lvalues... */
1390 if (entity->base.kind != ENTITY_VARIABLE
1391 && entity->base.kind != ENTITY_PARAMETER)
1397 case EXPR_ARRAY_ACCESS: {
1398 expression_t *const ref = expr->array_access.array_ref;
1399 entity_t * ent = NULL;
1400 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1401 ent = determine_lhs_ent(ref, lhs_ent);
1404 mark_vars_read(expr->select.compound, lhs_ent);
1406 mark_vars_read(expr->array_access.index, lhs_ent);
1411 if (is_type_compound(skip_typeref(expr->base.type))) {
1412 return determine_lhs_ent(expr->select.compound, lhs_ent);
1414 mark_vars_read(expr->select.compound, lhs_ent);
1419 case EXPR_UNARY_DEREFERENCE: {
1420 expression_t *const val = expr->unary.value;
1421 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1423 return determine_lhs_ent(val->unary.value, lhs_ent);
1425 mark_vars_read(val, NULL);
1431 mark_vars_read(expr, NULL);
1436 #define ENT_ANY ((entity_t*)-1)
1439 * Mark declarations, which are read. This is used to detect variables, which
1443 * x is not marked as "read", because it is only read to calculate its own new
1447 * x and y are not detected as "not read", because multiple variables are
1450 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1452 switch (expr->kind) {
1453 case EXPR_REFERENCE: {
1454 entity_t *const entity = expr->reference.entity;
1455 if (entity->kind != ENTITY_VARIABLE
1456 && entity->kind != ENTITY_PARAMETER)
1459 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1460 if (entity->kind == ENTITY_VARIABLE) {
1461 entity->variable.read = true;
1463 entity->parameter.read = true;
1470 // TODO respect pure/const
1471 mark_vars_read(expr->call.function, NULL);
1472 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1473 mark_vars_read(arg->expression, NULL);
1477 case EXPR_CONDITIONAL:
1478 // TODO lhs_decl should depend on whether true/false have an effect
1479 mark_vars_read(expr->conditional.condition, NULL);
1480 if (expr->conditional.true_expression != NULL)
1481 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1482 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1486 if (lhs_ent == ENT_ANY
1487 && !is_type_compound(skip_typeref(expr->base.type)))
1489 mark_vars_read(expr->select.compound, lhs_ent);
1492 case EXPR_ARRAY_ACCESS: {
1493 expression_t *const ref = expr->array_access.array_ref;
1494 mark_vars_read(ref, lhs_ent);
1495 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1496 mark_vars_read(expr->array_access.index, lhs_ent);
1501 mark_vars_read(expr->va_arge.ap, lhs_ent);
1505 mark_vars_read(expr->va_copye.src, lhs_ent);
1508 case EXPR_UNARY_CAST:
1509 /* Special case: Use void cast to mark a variable as "read" */
1510 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1515 case EXPR_UNARY_THROW:
1516 if (expr->unary.value == NULL)
1519 case EXPR_UNARY_DEREFERENCE:
1520 case EXPR_UNARY_DELETE:
1521 case EXPR_UNARY_DELETE_ARRAY:
1522 if (lhs_ent == ENT_ANY)
1526 case EXPR_UNARY_NEGATE:
1527 case EXPR_UNARY_PLUS:
1528 case EXPR_UNARY_BITWISE_NEGATE:
1529 case EXPR_UNARY_NOT:
1530 case EXPR_UNARY_TAKE_ADDRESS:
1531 case EXPR_UNARY_POSTFIX_INCREMENT:
1532 case EXPR_UNARY_POSTFIX_DECREMENT:
1533 case EXPR_UNARY_PREFIX_INCREMENT:
1534 case EXPR_UNARY_PREFIX_DECREMENT:
1535 case EXPR_UNARY_CAST_IMPLICIT:
1536 case EXPR_UNARY_ASSUME:
1538 mark_vars_read(expr->unary.value, lhs_ent);
1541 case EXPR_BINARY_ADD:
1542 case EXPR_BINARY_SUB:
1543 case EXPR_BINARY_MUL:
1544 case EXPR_BINARY_DIV:
1545 case EXPR_BINARY_MOD:
1546 case EXPR_BINARY_EQUAL:
1547 case EXPR_BINARY_NOTEQUAL:
1548 case EXPR_BINARY_LESS:
1549 case EXPR_BINARY_LESSEQUAL:
1550 case EXPR_BINARY_GREATER:
1551 case EXPR_BINARY_GREATEREQUAL:
1552 case EXPR_BINARY_BITWISE_AND:
1553 case EXPR_BINARY_BITWISE_OR:
1554 case EXPR_BINARY_BITWISE_XOR:
1555 case EXPR_BINARY_LOGICAL_AND:
1556 case EXPR_BINARY_LOGICAL_OR:
1557 case EXPR_BINARY_SHIFTLEFT:
1558 case EXPR_BINARY_SHIFTRIGHT:
1559 case EXPR_BINARY_COMMA:
1560 case EXPR_BINARY_ISGREATER:
1561 case EXPR_BINARY_ISGREATEREQUAL:
1562 case EXPR_BINARY_ISLESS:
1563 case EXPR_BINARY_ISLESSEQUAL:
1564 case EXPR_BINARY_ISLESSGREATER:
1565 case EXPR_BINARY_ISUNORDERED:
1566 mark_vars_read(expr->binary.left, lhs_ent);
1567 mark_vars_read(expr->binary.right, lhs_ent);
1570 case EXPR_BINARY_ASSIGN:
1571 case EXPR_BINARY_MUL_ASSIGN:
1572 case EXPR_BINARY_DIV_ASSIGN:
1573 case EXPR_BINARY_MOD_ASSIGN:
1574 case EXPR_BINARY_ADD_ASSIGN:
1575 case EXPR_BINARY_SUB_ASSIGN:
1576 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1577 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1578 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1579 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1580 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1581 if (lhs_ent == ENT_ANY)
1583 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1584 mark_vars_read(expr->binary.right, lhs_ent);
1589 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1595 case EXPR_STRING_LITERAL:
1596 case EXPR_WIDE_STRING_LITERAL:
1597 case EXPR_COMPOUND_LITERAL: // TODO init?
1599 case EXPR_CLASSIFY_TYPE:
1602 case EXPR_BUILTIN_CONSTANT_P:
1603 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1605 case EXPR_STATEMENT: // TODO
1606 case EXPR_LABEL_ADDRESS:
1607 case EXPR_REFERENCE_ENUM_VALUE:
1611 panic("unhandled expression");
1614 static designator_t *parse_designation(void)
1616 designator_t *result = NULL;
1617 designator_t **anchor = &result;
1620 designator_t *designator;
1621 switch (token.type) {
1623 designator = allocate_ast_zero(sizeof(designator[0]));
1624 designator->source_position = token.source_position;
1626 add_anchor_token(']');
1627 designator->array_index = parse_constant_expression();
1628 rem_anchor_token(']');
1629 expect(']', end_error);
1632 designator = allocate_ast_zero(sizeof(designator[0]));
1633 designator->source_position = token.source_position;
1635 if (token.type != T_IDENTIFIER) {
1636 parse_error_expected("while parsing designator",
1637 T_IDENTIFIER, NULL);
1640 designator->symbol = token.symbol;
1644 expect('=', end_error);
1648 assert(designator != NULL);
1649 *anchor = designator;
1650 anchor = &designator->next;
1656 static initializer_t *initializer_from_string(array_type_t *const type,
1657 const string_t *const string)
1659 /* TODO: check len vs. size of array type */
1662 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1663 initializer->string.string = *string;
1668 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1669 const string_t *const string)
1671 /* TODO: check len vs. size of array type */
1674 initializer_t *const initializer =
1675 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1676 initializer->wide_string.string = *string;
1682 * Build an initializer from a given expression.
1684 static initializer_t *initializer_from_expression(type_t *orig_type,
1685 expression_t *expression)
1687 /* TODO check that expression is a constant expression */
1689 /* §6.7.8.14/15 char array may be initialized by string literals */
1690 type_t *type = skip_typeref(orig_type);
1691 type_t *expr_type_orig = expression->base.type;
1692 type_t *expr_type = skip_typeref(expr_type_orig);
1694 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1695 array_type_t *const array_type = &type->array;
1696 type_t *const element_type = skip_typeref(array_type->element_type);
1698 if (element_type->kind == TYPE_ATOMIC) {
1699 atomic_type_kind_t akind = element_type->atomic.akind;
1700 switch (expression->kind) {
1701 case EXPR_STRING_LITERAL:
1702 if (akind == ATOMIC_TYPE_CHAR
1703 || akind == ATOMIC_TYPE_SCHAR
1704 || akind == ATOMIC_TYPE_UCHAR) {
1705 return initializer_from_string(array_type,
1706 &expression->string_literal.value);
1710 case EXPR_WIDE_STRING_LITERAL: {
1711 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1712 if (get_unqualified_type(element_type) == bare_wchar_type) {
1713 return initializer_from_wide_string(array_type,
1714 &expression->string_literal.value);
1725 assign_error_t error = semantic_assign(type, expression);
1726 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1728 report_assign_error(error, type, expression, "initializer",
1729 &expression->base.source_position);
1731 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1732 result->value.value = create_implicit_cast(expression, type);
1738 * Checks if a given expression can be used as an constant initializer.
1740 static bool is_initializer_constant(const expression_t *expression)
1743 is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1744 is_address_constant(expression) != EXPR_CLASS_VARIABLE;
1748 * Parses an scalar initializer.
1750 * §6.7.8.11; eat {} without warning
1752 static initializer_t *parse_scalar_initializer(type_t *type,
1753 bool must_be_constant)
1755 /* there might be extra {} hierarchies */
1759 warningf(HERE, "extra curly braces around scalar initializer");
1762 } while (next_if('{'));
1765 expression_t *expression = parse_assignment_expression();
1766 mark_vars_read(expression, NULL);
1767 if (must_be_constant && !is_initializer_constant(expression)) {
1768 errorf(&expression->base.source_position,
1769 "initialisation expression '%E' is not constant",
1773 initializer_t *initializer = initializer_from_expression(type, expression);
1775 if (initializer == NULL) {
1776 errorf(&expression->base.source_position,
1777 "expression '%E' (type '%T') doesn't match expected type '%T'",
1778 expression, expression->base.type, type);
1783 bool additional_warning_displayed = false;
1784 while (braces > 0) {
1786 if (token.type != '}') {
1787 if (!additional_warning_displayed && warning.other) {
1788 warningf(HERE, "additional elements in scalar initializer");
1789 additional_warning_displayed = true;
1800 * An entry in the type path.
1802 typedef struct type_path_entry_t type_path_entry_t;
1803 struct type_path_entry_t {
1804 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1806 size_t index; /**< For array types: the current index. */
1807 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1812 * A type path expression a position inside compound or array types.
1814 typedef struct type_path_t type_path_t;
1815 struct type_path_t {
1816 type_path_entry_t *path; /**< An flexible array containing the current path. */
1817 type_t *top_type; /**< type of the element the path points */
1818 size_t max_index; /**< largest index in outermost array */
1822 * Prints a type path for debugging.
1824 static __attribute__((unused)) void debug_print_type_path(
1825 const type_path_t *path)
1827 size_t len = ARR_LEN(path->path);
1829 for (size_t i = 0; i < len; ++i) {
1830 const type_path_entry_t *entry = & path->path[i];
1832 type_t *type = skip_typeref(entry->type);
1833 if (is_type_compound(type)) {
1834 /* in gcc mode structs can have no members */
1835 if (entry->v.compound_entry == NULL) {
1839 fprintf(stderr, ".%s",
1840 entry->v.compound_entry->base.symbol->string);
1841 } else if (is_type_array(type)) {
1842 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1844 fprintf(stderr, "-INVALID-");
1847 if (path->top_type != NULL) {
1848 fprintf(stderr, " (");
1849 print_type(path->top_type);
1850 fprintf(stderr, ")");
1855 * Return the top type path entry, ie. in a path
1856 * (type).a.b returns the b.
1858 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1860 size_t len = ARR_LEN(path->path);
1862 return &path->path[len-1];
1866 * Enlarge the type path by an (empty) element.
1868 static type_path_entry_t *append_to_type_path(type_path_t *path)
1870 size_t len = ARR_LEN(path->path);
1871 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1873 type_path_entry_t *result = & path->path[len];
1874 memset(result, 0, sizeof(result[0]));
1879 * Descending into a sub-type. Enter the scope of the current top_type.
1881 static void descend_into_subtype(type_path_t *path)
1883 type_t *orig_top_type = path->top_type;
1884 type_t *top_type = skip_typeref(orig_top_type);
1886 type_path_entry_t *top = append_to_type_path(path);
1887 top->type = top_type;
1889 if (is_type_compound(top_type)) {
1890 compound_t *compound = top_type->compound.compound;
1891 entity_t *entry = compound->members.entities;
1893 if (entry != NULL) {
1894 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1895 top->v.compound_entry = &entry->declaration;
1896 path->top_type = entry->declaration.type;
1898 path->top_type = NULL;
1900 } else if (is_type_array(top_type)) {
1902 path->top_type = top_type->array.element_type;
1904 assert(!is_type_valid(top_type));
1909 * Pop an entry from the given type path, ie. returning from
1910 * (type).a.b to (type).a
1912 static void ascend_from_subtype(type_path_t *path)
1914 type_path_entry_t *top = get_type_path_top(path);
1916 path->top_type = top->type;
1918 size_t len = ARR_LEN(path->path);
1919 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1923 * Pop entries from the given type path until the given
1924 * path level is reached.
1926 static void ascend_to(type_path_t *path, size_t top_path_level)
1928 size_t len = ARR_LEN(path->path);
1930 while (len > top_path_level) {
1931 ascend_from_subtype(path);
1932 len = ARR_LEN(path->path);
1936 static bool walk_designator(type_path_t *path, const designator_t *designator,
1937 bool used_in_offsetof)
1939 for (; designator != NULL; designator = designator->next) {
1940 type_path_entry_t *top = get_type_path_top(path);
1941 type_t *orig_type = top->type;
1943 type_t *type = skip_typeref(orig_type);
1945 if (designator->symbol != NULL) {
1946 symbol_t *symbol = designator->symbol;
1947 if (!is_type_compound(type)) {
1948 if (is_type_valid(type)) {
1949 errorf(&designator->source_position,
1950 "'.%Y' designator used for non-compound type '%T'",
1954 top->type = type_error_type;
1955 top->v.compound_entry = NULL;
1956 orig_type = type_error_type;
1958 compound_t *compound = type->compound.compound;
1959 entity_t *iter = compound->members.entities;
1960 for (; iter != NULL; iter = iter->base.next) {
1961 if (iter->base.symbol == symbol) {
1966 errorf(&designator->source_position,
1967 "'%T' has no member named '%Y'", orig_type, symbol);
1970 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1971 if (used_in_offsetof) {
1972 type_t *real_type = skip_typeref(iter->declaration.type);
1973 if (real_type->kind == TYPE_BITFIELD) {
1974 errorf(&designator->source_position,
1975 "offsetof designator '%Y' must not specify bitfield",
1981 top->type = orig_type;
1982 top->v.compound_entry = &iter->declaration;
1983 orig_type = iter->declaration.type;
1986 expression_t *array_index = designator->array_index;
1987 assert(designator->array_index != NULL);
1989 if (!is_type_array(type)) {
1990 if (is_type_valid(type)) {
1991 errorf(&designator->source_position,
1992 "[%E] designator used for non-array type '%T'",
1993 array_index, orig_type);
1998 long index = fold_constant_to_int(array_index);
1999 if (!used_in_offsetof) {
2001 errorf(&designator->source_position,
2002 "array index [%E] must be positive", array_index);
2003 } else if (type->array.size_constant) {
2004 long array_size = type->array.size;
2005 if (index >= array_size) {
2006 errorf(&designator->source_position,
2007 "designator [%E] (%d) exceeds array size %d",
2008 array_index, index, array_size);
2013 top->type = orig_type;
2014 top->v.index = (size_t) index;
2015 orig_type = type->array.element_type;
2017 path->top_type = orig_type;
2019 if (designator->next != NULL) {
2020 descend_into_subtype(path);
2026 static void advance_current_object(type_path_t *path, size_t top_path_level)
2028 type_path_entry_t *top = get_type_path_top(path);
2030 type_t *type = skip_typeref(top->type);
2031 if (is_type_union(type)) {
2032 /* in unions only the first element is initialized */
2033 top->v.compound_entry = NULL;
2034 } else if (is_type_struct(type)) {
2035 declaration_t *entry = top->v.compound_entry;
2037 entity_t *next_entity = entry->base.next;
2038 if (next_entity != NULL) {
2039 assert(is_declaration(next_entity));
2040 entry = &next_entity->declaration;
2045 top->v.compound_entry = entry;
2046 if (entry != NULL) {
2047 path->top_type = entry->type;
2050 } else if (is_type_array(type)) {
2051 assert(is_type_array(type));
2055 if (!type->array.size_constant || top->v.index < type->array.size) {
2059 assert(!is_type_valid(type));
2063 /* we're past the last member of the current sub-aggregate, try if we
2064 * can ascend in the type hierarchy and continue with another subobject */
2065 size_t len = ARR_LEN(path->path);
2067 if (len > top_path_level) {
2068 ascend_from_subtype(path);
2069 advance_current_object(path, top_path_level);
2071 path->top_type = NULL;
2076 * skip any {...} blocks until a closing bracket is reached.
2078 static void skip_initializers(void)
2082 while (token.type != '}') {
2083 if (token.type == T_EOF)
2085 if (token.type == '{') {
2093 static initializer_t *create_empty_initializer(void)
2095 static initializer_t empty_initializer
2096 = { .list = { { INITIALIZER_LIST }, 0 } };
2097 return &empty_initializer;
2101 * Parse a part of an initialiser for a struct or union,
2103 static initializer_t *parse_sub_initializer(type_path_t *path,
2104 type_t *outer_type, size_t top_path_level,
2105 parse_initializer_env_t *env)
2107 if (token.type == '}') {
2108 /* empty initializer */
2109 return create_empty_initializer();
2112 type_t *orig_type = path->top_type;
2113 type_t *type = NULL;
2115 if (orig_type == NULL) {
2116 /* We are initializing an empty compound. */
2118 type = skip_typeref(orig_type);
2121 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2124 designator_t *designator = NULL;
2125 if (token.type == '.' || token.type == '[') {
2126 designator = parse_designation();
2127 goto finish_designator;
2128 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2129 /* GNU-style designator ("identifier: value") */
2130 designator = allocate_ast_zero(sizeof(designator[0]));
2131 designator->source_position = token.source_position;
2132 designator->symbol = token.symbol;
2137 /* reset path to toplevel, evaluate designator from there */
2138 ascend_to(path, top_path_level);
2139 if (!walk_designator(path, designator, false)) {
2140 /* can't continue after designation error */
2144 initializer_t *designator_initializer
2145 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2146 designator_initializer->designator.designator = designator;
2147 ARR_APP1(initializer_t*, initializers, designator_initializer);
2149 orig_type = path->top_type;
2150 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2155 if (token.type == '{') {
2156 if (type != NULL && is_type_scalar(type)) {
2157 sub = parse_scalar_initializer(type, env->must_be_constant);
2160 if (env->entity != NULL) {
2162 "extra brace group at end of initializer for '%Y'",
2163 env->entity->base.symbol);
2165 errorf(HERE, "extra brace group at end of initializer");
2170 descend_into_subtype(path);
2173 add_anchor_token('}');
2174 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2176 rem_anchor_token('}');
2179 ascend_from_subtype(path);
2180 expect('}', end_error);
2182 expect('}', end_error);
2183 goto error_parse_next;
2187 /* must be an expression */
2188 expression_t *expression = parse_assignment_expression();
2189 mark_vars_read(expression, NULL);
2191 if (env->must_be_constant && !is_initializer_constant(expression)) {
2192 errorf(&expression->base.source_position,
2193 "Initialisation expression '%E' is not constant",
2198 /* we are already outside, ... */
2199 if (outer_type == NULL)
2200 goto error_parse_next;
2201 type_t *const outer_type_skip = skip_typeref(outer_type);
2202 if (is_type_compound(outer_type_skip) &&
2203 !outer_type_skip->compound.compound->complete) {
2204 goto error_parse_next;
2209 /* handle { "string" } special case */
2210 if ((expression->kind == EXPR_STRING_LITERAL
2211 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2212 && outer_type != NULL) {
2213 sub = initializer_from_expression(outer_type, expression);
2216 if (token.type != '}' && warning.other) {
2217 warningf(HERE, "excessive elements in initializer for type '%T'",
2220 /* TODO: eat , ... */
2225 /* descend into subtypes until expression matches type */
2227 orig_type = path->top_type;
2228 type = skip_typeref(orig_type);
2230 sub = initializer_from_expression(orig_type, expression);
2234 if (!is_type_valid(type)) {
2237 if (is_type_scalar(type)) {
2238 errorf(&expression->base.source_position,
2239 "expression '%E' doesn't match expected type '%T'",
2240 expression, orig_type);
2244 descend_into_subtype(path);
2248 /* update largest index of top array */
2249 const type_path_entry_t *first = &path->path[0];
2250 type_t *first_type = first->type;
2251 first_type = skip_typeref(first_type);
2252 if (is_type_array(first_type)) {
2253 size_t index = first->v.index;
2254 if (index > path->max_index)
2255 path->max_index = index;
2259 /* append to initializers list */
2260 ARR_APP1(initializer_t*, initializers, sub);
2263 if (warning.other) {
2264 if (env->entity != NULL) {
2265 warningf(HERE, "excess elements in initializer for '%Y'",
2266 env->entity->base.symbol);
2268 warningf(HERE, "excess elements in initializer");
2274 if (token.type == '}') {
2277 expect(',', end_error);
2278 if (token.type == '}') {
2283 /* advance to the next declaration if we are not at the end */
2284 advance_current_object(path, top_path_level);
2285 orig_type = path->top_type;
2286 if (orig_type != NULL)
2287 type = skip_typeref(orig_type);
2293 size_t len = ARR_LEN(initializers);
2294 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2295 initializer_t *result = allocate_ast_zero(size);
2296 result->kind = INITIALIZER_LIST;
2297 result->list.len = len;
2298 memcpy(&result->list.initializers, initializers,
2299 len * sizeof(initializers[0]));
2301 DEL_ARR_F(initializers);
2302 ascend_to(path, top_path_level+1);
2307 skip_initializers();
2308 DEL_ARR_F(initializers);
2309 ascend_to(path, top_path_level+1);
2313 static expression_t *make_size_literal(size_t value)
2315 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2316 literal->base.type = type_size_t;
2319 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2320 literal->literal.value = make_string(buf);
2326 * Parses an initializer. Parsers either a compound literal
2327 * (env->declaration == NULL) or an initializer of a declaration.
2329 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2331 type_t *type = skip_typeref(env->type);
2332 size_t max_index = 0;
2333 initializer_t *result;
2335 if (is_type_scalar(type)) {
2336 result = parse_scalar_initializer(type, env->must_be_constant);
2337 } else if (token.type == '{') {
2341 memset(&path, 0, sizeof(path));
2342 path.top_type = env->type;
2343 path.path = NEW_ARR_F(type_path_entry_t, 0);
2345 descend_into_subtype(&path);
2347 add_anchor_token('}');
2348 result = parse_sub_initializer(&path, env->type, 1, env);
2349 rem_anchor_token('}');
2351 max_index = path.max_index;
2352 DEL_ARR_F(path.path);
2354 expect('}', end_error);
2356 /* parse_scalar_initializer() also works in this case: we simply
2357 * have an expression without {} around it */
2358 result = parse_scalar_initializer(type, env->must_be_constant);
2361 /* §6.7.8:22 array initializers for arrays with unknown size determine
2362 * the array type size */
2363 if (is_type_array(type) && type->array.size_expression == NULL
2364 && result != NULL) {
2366 switch (result->kind) {
2367 case INITIALIZER_LIST:
2368 assert(max_index != 0xdeadbeaf);
2369 size = max_index + 1;
2372 case INITIALIZER_STRING:
2373 size = result->string.string.size;
2376 case INITIALIZER_WIDE_STRING:
2377 size = result->wide_string.string.size;
2380 case INITIALIZER_DESIGNATOR:
2381 case INITIALIZER_VALUE:
2382 /* can happen for parse errors */
2387 internal_errorf(HERE, "invalid initializer type");
2390 type_t *new_type = duplicate_type(type);
2392 new_type->array.size_expression = make_size_literal(size);
2393 new_type->array.size_constant = true;
2394 new_type->array.has_implicit_size = true;
2395 new_type->array.size = size;
2396 env->type = new_type;
2404 static void append_entity(scope_t *scope, entity_t *entity)
2406 if (scope->last_entity != NULL) {
2407 scope->last_entity->base.next = entity;
2409 scope->entities = entity;
2411 entity->base.parent_entity = current_entity;
2412 scope->last_entity = entity;
2416 static compound_t *parse_compound_type_specifier(bool is_struct)
2418 source_position_t const pos = *HERE;
2419 eat(is_struct ? T_struct : T_union);
2421 symbol_t *symbol = NULL;
2422 entity_t *entity = NULL;
2423 attribute_t *attributes = NULL;
2425 if (token.type == T___attribute__) {
2426 attributes = parse_attributes(NULL);
2429 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2430 if (token.type == T_IDENTIFIER) {
2431 /* the compound has a name, check if we have seen it already */
2432 symbol = token.symbol;
2433 entity = get_tag(symbol, kind);
2436 if (entity != NULL) {
2437 if (entity->base.parent_scope != current_scope &&
2438 (token.type == '{' || token.type == ';')) {
2439 /* we're in an inner scope and have a definition. Shadow
2440 * existing definition in outer scope */
2442 } else if (entity->compound.complete && token.type == '{') {
2443 errorf(&pos, "multiple definitions of '%s %Y' (previous definition %P)",
2444 is_struct ? "struct" : "union", symbol,
2445 &entity->base.source_position);
2446 /* clear members in the hope to avoid further errors */
2447 entity->compound.members.entities = NULL;
2450 } else if (token.type != '{') {
2451 char const *const msg =
2452 is_struct ? "while parsing struct type specifier" :
2453 "while parsing union type specifier";
2454 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2459 if (entity == NULL) {
2460 entity = allocate_entity_zero(kind);
2462 entity->compound.alignment = 1;
2463 entity->base.namespc = NAMESPACE_TAG;
2464 entity->base.source_position = pos;
2465 entity->base.symbol = symbol;
2466 entity->base.parent_scope = current_scope;
2467 if (symbol != NULL) {
2468 environment_push(entity);
2470 append_entity(current_scope, entity);
2473 if (token.type == '{') {
2474 parse_compound_type_entries(&entity->compound);
2476 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2477 if (symbol == NULL) {
2478 assert(anonymous_entity == NULL);
2479 anonymous_entity = entity;
2483 if (attributes != NULL) {
2484 handle_entity_attributes(attributes, entity);
2487 return &entity->compound;
2490 static void parse_enum_entries(type_t *const enum_type)
2494 if (token.type == '}') {
2495 errorf(HERE, "empty enum not allowed");
2500 add_anchor_token('}');
2502 if (token.type != T_IDENTIFIER) {
2503 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2505 rem_anchor_token('}');
2509 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2510 entity->enum_value.enum_type = enum_type;
2511 entity->base.namespc = NAMESPACE_NORMAL;
2512 entity->base.symbol = token.symbol;
2513 entity->base.source_position = token.source_position;
2517 expression_t *value = parse_constant_expression();
2519 value = create_implicit_cast(value, enum_type);
2520 entity->enum_value.value = value;
2525 record_entity(entity, false);
2526 } while (next_if(',') && token.type != '}');
2527 rem_anchor_token('}');
2529 expect('}', end_error);
2535 static type_t *parse_enum_specifier(void)
2537 source_position_t const pos = *HERE;
2542 switch (token.type) {
2544 symbol = token.symbol;
2545 entity = get_tag(symbol, ENTITY_ENUM);
2548 if (entity != NULL) {
2549 if (entity->base.parent_scope != current_scope &&
2550 (token.type == '{' || token.type == ';')) {
2551 /* we're in an inner scope and have a definition. Shadow
2552 * existing definition in outer scope */
2554 } else if (entity->enume.complete && token.type == '{') {
2555 errorf(&pos, "multiple definitions of 'enum %Y' (previous definition %P)",
2556 symbol, &entity->base.source_position);
2567 parse_error_expected("while parsing enum type specifier",
2568 T_IDENTIFIER, '{', NULL);
2572 if (entity == NULL) {
2573 entity = allocate_entity_zero(ENTITY_ENUM);
2574 entity->base.namespc = NAMESPACE_TAG;
2575 entity->base.source_position = pos;
2576 entity->base.symbol = symbol;
2577 entity->base.parent_scope = current_scope;
2580 type_t *const type = allocate_type_zero(TYPE_ENUM);
2581 type->enumt.enume = &entity->enume;
2582 type->enumt.akind = ATOMIC_TYPE_INT;
2584 if (token.type == '{') {
2585 if (symbol != NULL) {
2586 environment_push(entity);
2588 append_entity(current_scope, entity);
2589 entity->enume.complete = true;
2591 parse_enum_entries(type);
2592 parse_attributes(NULL);
2594 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2595 if (symbol == NULL) {
2596 assert(anonymous_entity == NULL);
2597 anonymous_entity = entity;
2599 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2600 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2608 * if a symbol is a typedef to another type, return true
2610 static bool is_typedef_symbol(symbol_t *symbol)
2612 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2613 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2616 static type_t *parse_typeof(void)
2622 expect('(', end_error);
2623 add_anchor_token(')');
2625 expression_t *expression = NULL;
2627 bool old_type_prop = in_type_prop;
2628 bool old_gcc_extension = in_gcc_extension;
2629 in_type_prop = true;
2631 while (next_if(T___extension__)) {
2632 /* This can be a prefix to a typename or an expression. */
2633 in_gcc_extension = true;
2635 switch (token.type) {
2637 if (is_typedef_symbol(token.symbol)) {
2639 type = parse_typename();
2642 expression = parse_expression();
2643 type = revert_automatic_type_conversion(expression);
2647 in_type_prop = old_type_prop;
2648 in_gcc_extension = old_gcc_extension;
2650 rem_anchor_token(')');
2651 expect(')', end_error);
2653 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2654 typeof_type->typeoft.expression = expression;
2655 typeof_type->typeoft.typeof_type = type;
2662 typedef enum specifiers_t {
2663 SPECIFIER_SIGNED = 1 << 0,
2664 SPECIFIER_UNSIGNED = 1 << 1,
2665 SPECIFIER_LONG = 1 << 2,
2666 SPECIFIER_INT = 1 << 3,
2667 SPECIFIER_DOUBLE = 1 << 4,
2668 SPECIFIER_CHAR = 1 << 5,
2669 SPECIFIER_WCHAR_T = 1 << 6,
2670 SPECIFIER_SHORT = 1 << 7,
2671 SPECIFIER_LONG_LONG = 1 << 8,
2672 SPECIFIER_FLOAT = 1 << 9,
2673 SPECIFIER_BOOL = 1 << 10,
2674 SPECIFIER_VOID = 1 << 11,
2675 SPECIFIER_INT8 = 1 << 12,
2676 SPECIFIER_INT16 = 1 << 13,
2677 SPECIFIER_INT32 = 1 << 14,
2678 SPECIFIER_INT64 = 1 << 15,
2679 SPECIFIER_INT128 = 1 << 16,
2680 SPECIFIER_COMPLEX = 1 << 17,
2681 SPECIFIER_IMAGINARY = 1 << 18,
2684 static type_t *get_typedef_type(symbol_t *symbol)
2686 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2687 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2690 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2691 type->typedeft.typedefe = &entity->typedefe;
2696 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2698 expect('(', end_error);
2700 attribute_property_argument_t *property
2701 = allocate_ast_zero(sizeof(*property));
2704 if (token.type != T_IDENTIFIER) {
2705 parse_error_expected("while parsing property declspec",
2706 T_IDENTIFIER, NULL);
2711 symbol_t *symbol = token.symbol;
2713 if (strcmp(symbol->string, "put") == 0) {
2715 } else if (strcmp(symbol->string, "get") == 0) {
2718 errorf(HERE, "expected put or get in property declspec");
2721 expect('=', end_error);
2722 if (token.type != T_IDENTIFIER) {
2723 parse_error_expected("while parsing property declspec",
2724 T_IDENTIFIER, NULL);
2728 property->put_symbol = token.symbol;
2730 property->get_symbol = token.symbol;
2733 } while (next_if(','));
2735 attribute->a.property = property;
2737 expect(')', end_error);
2743 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2745 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2746 if (next_if(T_restrict)) {
2747 kind = ATTRIBUTE_MS_RESTRICT;
2748 } else if (token.type == T_IDENTIFIER) {
2749 const char *name = token.symbol->string;
2751 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2753 const char *attribute_name = get_attribute_name(k);
2754 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2760 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2761 warningf(HERE, "unknown __declspec '%s' ignored", name);
2764 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2768 attribute_t *attribute = allocate_attribute_zero(kind);
2770 if (kind == ATTRIBUTE_MS_PROPERTY) {
2771 return parse_attribute_ms_property(attribute);
2774 /* parse arguments */
2776 attribute->a.arguments = parse_attribute_arguments();
2781 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2785 expect('(', end_error);
2790 add_anchor_token(')');
2792 attribute_t **anchor = &first;
2794 while (*anchor != NULL)
2795 anchor = &(*anchor)->next;
2797 attribute_t *attribute
2798 = parse_microsoft_extended_decl_modifier_single();
2799 if (attribute == NULL)
2802 *anchor = attribute;
2803 anchor = &attribute->next;
2804 } while (next_if(','));
2806 rem_anchor_token(')');
2807 expect(')', end_error);
2811 rem_anchor_token(')');
2815 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2817 entity_t *entity = allocate_entity_zero(kind);
2818 entity->base.namespc = NAMESPACE_NORMAL;
2819 entity->base.source_position = *HERE;
2820 entity->base.symbol = symbol;
2821 if (is_declaration(entity)) {
2822 entity->declaration.type = type_error_type;
2823 entity->declaration.implicit = true;
2824 } else if (kind == ENTITY_TYPEDEF) {
2825 entity->typedefe.type = type_error_type;
2826 entity->typedefe.builtin = true;
2828 if (kind != ENTITY_COMPOUND_MEMBER)
2829 record_entity(entity, false);
2833 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2835 type_t *type = NULL;
2836 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2837 unsigned type_specifiers = 0;
2838 bool newtype = false;
2839 bool saw_error = false;
2840 bool old_gcc_extension = in_gcc_extension;
2842 specifiers->source_position = token.source_position;
2845 specifiers->attributes = parse_attributes(specifiers->attributes);
2847 switch (token.type) {
2849 #define MATCH_STORAGE_CLASS(token, class) \
2851 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2852 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2854 specifiers->storage_class = class; \
2855 if (specifiers->thread_local) \
2856 goto check_thread_storage_class; \
2860 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2861 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2862 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2863 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2864 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2867 specifiers->attributes
2868 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2872 if (specifiers->thread_local) {
2873 errorf(HERE, "duplicate '__thread'");
2875 specifiers->thread_local = true;
2876 check_thread_storage_class:
2877 switch (specifiers->storage_class) {
2878 case STORAGE_CLASS_EXTERN:
2879 case STORAGE_CLASS_NONE:
2880 case STORAGE_CLASS_STATIC:
2884 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2885 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2886 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2887 wrong_thread_storage_class:
2888 errorf(HERE, "'__thread' used with '%s'", wrong);
2895 /* type qualifiers */
2896 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2898 qualifiers |= qualifier; \
2902 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2903 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2904 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2905 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2906 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2907 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2908 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2909 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2911 case T___extension__:
2913 in_gcc_extension = true;
2916 /* type specifiers */
2917 #define MATCH_SPECIFIER(token, specifier, name) \
2919 if (type_specifiers & specifier) { \
2920 errorf(HERE, "multiple " name " type specifiers given"); \
2922 type_specifiers |= specifier; \
2927 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2928 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2929 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2930 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2931 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2932 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2933 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2934 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2935 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2936 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2937 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2938 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2939 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2940 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2941 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2942 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2943 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2944 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2948 specifiers->is_inline = true;
2952 case T__forceinline:
2954 specifiers->modifiers |= DM_FORCEINLINE;
2959 if (type_specifiers & SPECIFIER_LONG_LONG) {
2960 errorf(HERE, "too many long type specifiers given");
2961 } else if (type_specifiers & SPECIFIER_LONG) {
2962 type_specifiers |= SPECIFIER_LONG_LONG;
2964 type_specifiers |= SPECIFIER_LONG;
2969 #define CHECK_DOUBLE_TYPE() \
2970 if ( type != NULL) \
2971 errorf(HERE, "multiple data types in declaration specifiers");
2974 CHECK_DOUBLE_TYPE();
2975 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2977 type->compound.compound = parse_compound_type_specifier(true);
2980 CHECK_DOUBLE_TYPE();
2981 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2982 type->compound.compound = parse_compound_type_specifier(false);
2985 CHECK_DOUBLE_TYPE();
2986 type = parse_enum_specifier();
2989 CHECK_DOUBLE_TYPE();
2990 type = parse_typeof();
2992 case T___builtin_va_list:
2993 CHECK_DOUBLE_TYPE();
2994 type = duplicate_type(type_valist);
2998 case T_IDENTIFIER: {
2999 /* only parse identifier if we haven't found a type yet */
3000 if (type != NULL || type_specifiers != 0) {
3001 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3002 * declaration, so it doesn't generate errors about expecting '(' or
3004 switch (look_ahead(1)->type) {
3011 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3015 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3020 goto finish_specifiers;
3024 type_t *const typedef_type = get_typedef_type(token.symbol);
3025 if (typedef_type == NULL) {
3026 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3027 * declaration, so it doesn't generate 'implicit int' followed by more
3028 * errors later on. */
3029 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3035 errorf(HERE, "%K does not name a type", &token);
3038 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3040 type = allocate_type_zero(TYPE_TYPEDEF);
3041 type->typedeft.typedefe = &entity->typedefe;
3049 goto finish_specifiers;
3054 type = typedef_type;
3058 /* function specifier */
3060 goto finish_specifiers;
3065 specifiers->attributes = parse_attributes(specifiers->attributes);
3067 in_gcc_extension = old_gcc_extension;
3069 if (type == NULL || (saw_error && type_specifiers != 0)) {
3070 atomic_type_kind_t atomic_type;
3072 /* match valid basic types */
3073 switch (type_specifiers) {
3074 case SPECIFIER_VOID:
3075 atomic_type = ATOMIC_TYPE_VOID;
3077 case SPECIFIER_WCHAR_T:
3078 atomic_type = ATOMIC_TYPE_WCHAR_T;
3080 case SPECIFIER_CHAR:
3081 atomic_type = ATOMIC_TYPE_CHAR;
3083 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3084 atomic_type = ATOMIC_TYPE_SCHAR;
3086 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3087 atomic_type = ATOMIC_TYPE_UCHAR;
3089 case SPECIFIER_SHORT:
3090 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3091 case SPECIFIER_SHORT | SPECIFIER_INT:
3092 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3093 atomic_type = ATOMIC_TYPE_SHORT;
3095 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3096 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3097 atomic_type = ATOMIC_TYPE_USHORT;
3100 case SPECIFIER_SIGNED:
3101 case SPECIFIER_SIGNED | SPECIFIER_INT:
3102 atomic_type = ATOMIC_TYPE_INT;
3104 case SPECIFIER_UNSIGNED:
3105 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3106 atomic_type = ATOMIC_TYPE_UINT;
3108 case SPECIFIER_LONG:
3109 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3110 case SPECIFIER_LONG | SPECIFIER_INT:
3111 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3112 atomic_type = ATOMIC_TYPE_LONG;
3114 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3115 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3116 atomic_type = ATOMIC_TYPE_ULONG;
3119 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3120 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3121 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3122 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3124 atomic_type = ATOMIC_TYPE_LONGLONG;
3125 goto warn_about_long_long;
3127 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3128 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3130 atomic_type = ATOMIC_TYPE_ULONGLONG;
3131 warn_about_long_long:
3132 if (warning.long_long) {
3133 warningf(&specifiers->source_position,
3134 "ISO C90 does not support 'long long'");
3138 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3139 atomic_type = unsigned_int8_type_kind;
3142 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3143 atomic_type = unsigned_int16_type_kind;
3146 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3147 atomic_type = unsigned_int32_type_kind;
3150 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3151 atomic_type = unsigned_int64_type_kind;
3154 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3155 atomic_type = unsigned_int128_type_kind;
3158 case SPECIFIER_INT8:
3159 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3160 atomic_type = int8_type_kind;
3163 case SPECIFIER_INT16:
3164 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3165 atomic_type = int16_type_kind;
3168 case SPECIFIER_INT32:
3169 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3170 atomic_type = int32_type_kind;
3173 case SPECIFIER_INT64:
3174 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3175 atomic_type = int64_type_kind;
3178 case SPECIFIER_INT128:
3179 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3180 atomic_type = int128_type_kind;
3183 case SPECIFIER_FLOAT:
3184 atomic_type = ATOMIC_TYPE_FLOAT;
3186 case SPECIFIER_DOUBLE:
3187 atomic_type = ATOMIC_TYPE_DOUBLE;
3189 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3190 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3192 case SPECIFIER_BOOL:
3193 atomic_type = ATOMIC_TYPE_BOOL;
3195 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3196 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3197 atomic_type = ATOMIC_TYPE_FLOAT;
3199 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3200 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3201 atomic_type = ATOMIC_TYPE_DOUBLE;
3203 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3204 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3205 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3208 /* invalid specifier combination, give an error message */
3209 if (type_specifiers == 0) {
3213 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3214 if (!(c_mode & _CXX) && !strict_mode) {
3215 if (warning.implicit_int) {
3216 warningf(HERE, "no type specifiers in declaration, using 'int'");
3218 atomic_type = ATOMIC_TYPE_INT;
3221 errorf(HERE, "no type specifiers given in declaration");
3223 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3224 (type_specifiers & SPECIFIER_UNSIGNED)) {
3225 errorf(HERE, "signed and unsigned specifiers given");
3226 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3227 errorf(HERE, "only integer types can be signed or unsigned");
3229 errorf(HERE, "multiple datatypes in declaration");
3234 if (type_specifiers & SPECIFIER_COMPLEX) {
3235 type = allocate_type_zero(TYPE_COMPLEX);
3236 type->complex.akind = atomic_type;
3237 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3238 type = allocate_type_zero(TYPE_IMAGINARY);
3239 type->imaginary.akind = atomic_type;
3241 type = allocate_type_zero(TYPE_ATOMIC);
3242 type->atomic.akind = atomic_type;
3245 } else if (type_specifiers != 0) {
3246 errorf(HERE, "multiple datatypes in declaration");
3249 /* FIXME: check type qualifiers here */
3250 type->base.qualifiers = qualifiers;
3253 type = identify_new_type(type);
3255 type = typehash_insert(type);
3258 if (specifiers->attributes != NULL)
3259 type = handle_type_attributes(specifiers->attributes, type);
3260 specifiers->type = type;
3264 specifiers->type = type_error_type;
3267 static type_qualifiers_t parse_type_qualifiers(void)
3269 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3272 switch (token.type) {
3273 /* type qualifiers */
3274 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3275 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3276 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3277 /* microsoft extended type modifiers */
3278 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3279 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3280 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3281 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3282 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3291 * Parses an K&R identifier list
3293 static void parse_identifier_list(scope_t *scope)
3296 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3297 entity->base.source_position = token.source_position;
3298 entity->base.namespc = NAMESPACE_NORMAL;
3299 entity->base.symbol = token.symbol;
3300 /* a K&R parameter has no type, yet */
3304 append_entity(scope, entity);
3305 } while (next_if(',') && token.type == T_IDENTIFIER);
3308 static entity_t *parse_parameter(void)
3310 declaration_specifiers_t specifiers;
3311 memset(&specifiers, 0, sizeof(specifiers));
3313 parse_declaration_specifiers(&specifiers);
3315 entity_t *entity = parse_declarator(&specifiers,
3316 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3317 anonymous_entity = NULL;
3321 static void semantic_parameter_incomplete(const entity_t *entity)
3323 assert(entity->kind == ENTITY_PARAMETER);
3325 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3326 * list in a function declarator that is part of a
3327 * definition of that function shall not have
3328 * incomplete type. */
3329 type_t *type = skip_typeref(entity->declaration.type);
3330 if (is_type_incomplete(type)) {
3331 errorf(&entity->base.source_position,
3332 "parameter '%#T' has incomplete type",
3333 entity->declaration.type, entity->base.symbol);
3337 static bool has_parameters(void)
3339 /* func(void) is not a parameter */
3340 if (token.type == T_IDENTIFIER) {
3341 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3344 if (entity->kind != ENTITY_TYPEDEF)
3346 if (skip_typeref(entity->typedefe.type) != type_void)
3348 } else if (token.type != T_void) {
3351 if (look_ahead(1)->type != ')')
3358 * Parses function type parameters (and optionally creates variable_t entities
3359 * for them in a scope)
3361 static void parse_parameters(function_type_t *type, scope_t *scope)
3364 add_anchor_token(')');
3365 int saved_comma_state = save_and_reset_anchor_state(',');
3367 if (token.type == T_IDENTIFIER &&
3368 !is_typedef_symbol(token.symbol)) {
3369 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3370 if (la1_type == ',' || la1_type == ')') {
3371 type->kr_style_parameters = true;
3372 parse_identifier_list(scope);
3373 goto parameters_finished;
3377 if (token.type == ')') {
3378 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3379 if (!(c_mode & _CXX))
3380 type->unspecified_parameters = true;
3381 } else if (has_parameters()) {
3382 function_parameter_t **anchor = &type->parameters;
3384 switch (token.type) {
3387 type->variadic = true;
3388 goto parameters_finished;
3391 case T___extension__:
3394 entity_t *entity = parse_parameter();
3395 if (entity->kind == ENTITY_TYPEDEF) {
3396 errorf(&entity->base.source_position,
3397 "typedef not allowed as function parameter");
3400 assert(is_declaration(entity));
3402 semantic_parameter_incomplete(entity);
3404 function_parameter_t *const parameter =
3405 allocate_parameter(entity->declaration.type);
3407 if (scope != NULL) {
3408 append_entity(scope, entity);
3411 *anchor = parameter;
3412 anchor = ¶meter->next;
3417 goto parameters_finished;
3419 } while (next_if(','));
3422 parameters_finished:
3423 rem_anchor_token(')');
3424 expect(')', end_error);
3427 restore_anchor_state(',', saved_comma_state);
3430 typedef enum construct_type_kind_t {
3433 CONSTRUCT_REFERENCE,
3436 } construct_type_kind_t;
3438 typedef union construct_type_t construct_type_t;
3440 typedef struct construct_type_base_t {
3441 construct_type_kind_t kind;
3442 source_position_t pos;
3443 construct_type_t *next;
3444 } construct_type_base_t;
3446 typedef struct parsed_pointer_t {
3447 construct_type_base_t base;
3448 type_qualifiers_t type_qualifiers;
3449 variable_t *base_variable; /**< MS __based extension. */
3452 typedef struct parsed_reference_t {
3453 construct_type_base_t base;
3454 } parsed_reference_t;
3456 typedef struct construct_function_type_t {
3457 construct_type_base_t base;
3458 type_t *function_type;
3459 } construct_function_type_t;
3461 typedef struct parsed_array_t {
3462 construct_type_base_t base;
3463 type_qualifiers_t type_qualifiers;
3469 union construct_type_t {
3470 construct_type_kind_t kind;
3471 construct_type_base_t base;
3472 parsed_pointer_t pointer;
3473 parsed_reference_t reference;
3474 construct_function_type_t function;
3475 parsed_array_t array;
3478 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3480 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3481 memset(cons, 0, size);
3483 cons->base.pos = *HERE;
3488 static construct_type_t *parse_pointer_declarator(void)
3490 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3492 cons->pointer.type_qualifiers = parse_type_qualifiers();
3493 //cons->pointer.base_variable = base_variable;
3498 /* ISO/IEC 14882:1998(E) §8.3.2 */
3499 static construct_type_t *parse_reference_declarator(void)
3501 if (!(c_mode & _CXX))
3502 errorf(HERE, "references are only available for C++");
3504 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3511 static construct_type_t *parse_array_declarator(void)
3513 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3514 parsed_array_t *const array = &cons->array;
3517 add_anchor_token(']');
3519 bool is_static = next_if(T_static);
3521 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3524 is_static = next_if(T_static);
3526 array->type_qualifiers = type_qualifiers;
3527 array->is_static = is_static;
3529 expression_t *size = NULL;
3530 if (token.type == '*' && look_ahead(1)->type == ']') {
3531 array->is_variable = true;
3533 } else if (token.type != ']') {
3534 size = parse_assignment_expression();
3536 /* §6.7.5.2:1 Array size must have integer type */
3537 type_t *const orig_type = size->base.type;
3538 type_t *const type = skip_typeref(orig_type);
3539 if (!is_type_integer(type) && is_type_valid(type)) {
3540 errorf(&size->base.source_position,
3541 "array size '%E' must have integer type but has type '%T'",
3546 mark_vars_read(size, NULL);
3549 if (is_static && size == NULL)
3550 errorf(&array->base.pos, "static array parameters require a size");
3552 rem_anchor_token(']');
3553 expect(']', end_error);
3560 static construct_type_t *parse_function_declarator(scope_t *scope)
3562 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3564 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3565 function_type_t *ftype = &type->function;
3567 ftype->linkage = current_linkage;
3568 ftype->calling_convention = CC_DEFAULT;
3570 parse_parameters(ftype, scope);
3572 cons->function.function_type = type;
3577 typedef struct parse_declarator_env_t {
3578 bool may_be_abstract : 1;
3579 bool must_be_abstract : 1;
3580 decl_modifiers_t modifiers;
3582 source_position_t source_position;
3584 attribute_t *attributes;
3585 } parse_declarator_env_t;
3588 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3590 /* construct a single linked list of construct_type_t's which describe
3591 * how to construct the final declarator type */
3592 construct_type_t *first = NULL;
3593 construct_type_t **anchor = &first;
3595 env->attributes = parse_attributes(env->attributes);
3598 construct_type_t *type;
3599 //variable_t *based = NULL; /* MS __based extension */
3600 switch (token.type) {
3602 type = parse_reference_declarator();
3606 panic("based not supported anymore");
3611 type = parse_pointer_declarator();
3615 goto ptr_operator_end;
3619 anchor = &type->base.next;
3621 /* TODO: find out if this is correct */
3622 env->attributes = parse_attributes(env->attributes);
3626 construct_type_t *inner_types = NULL;
3628 switch (token.type) {
3630 if (env->must_be_abstract) {
3631 errorf(HERE, "no identifier expected in typename");
3633 env->symbol = token.symbol;
3634 env->source_position = token.source_position;
3640 /* Parenthesized declarator or function declarator? */
3641 token_t const *const la1 = look_ahead(1);
3642 switch (la1->type) {
3644 if (is_typedef_symbol(la1->symbol)) {
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. */
3650 /* Function declarator. */
3651 if (!env->may_be_abstract) {
3652 errorf(HERE, "function declarator must have a name");
3660 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3661 /* Paranthesized declarator. */
3663 add_anchor_token(')');
3664 inner_types = parse_inner_declarator(env);
3665 if (inner_types != NULL) {
3666 /* All later declarators only modify the return type */
3667 env->must_be_abstract = true;
3669 rem_anchor_token(')');
3670 expect(')', end_error);
3678 if (env->may_be_abstract)
3680 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3686 construct_type_t **const p = anchor;
3689 construct_type_t *type;
3690 switch (token.type) {
3692 scope_t *scope = NULL;
3693 if (!env->must_be_abstract) {
3694 scope = &env->parameters;
3697 type = parse_function_declarator(scope);
3701 type = parse_array_declarator();
3704 goto declarator_finished;
3707 /* insert in the middle of the list (at p) */
3708 type->base.next = *p;
3711 anchor = &type->base.next;
3714 declarator_finished:
3715 /* append inner_types at the end of the list, we don't to set anchor anymore
3716 * as it's not needed anymore */
3717 *anchor = inner_types;
3724 static type_t *construct_declarator_type(construct_type_t *construct_list,
3727 construct_type_t *iter = construct_list;
3728 for (; iter != NULL; iter = iter->base.next) {
3729 source_position_t const* const pos = &iter->base.pos;
3730 switch (iter->kind) {
3731 case CONSTRUCT_INVALID:
3733 case CONSTRUCT_FUNCTION: {
3734 construct_function_type_t *function = &iter->function;
3735 type_t *function_type = function->function_type;
3737 function_type->function.return_type = type;
3739 type_t *skipped_return_type = skip_typeref(type);
3741 if (is_type_function(skipped_return_type)) {
3742 errorf(pos, "function returning function is not allowed");
3743 } else if (is_type_array(skipped_return_type)) {
3744 errorf(pos, "function returning array is not allowed");
3746 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3747 warningf(pos, "type qualifiers in return type of function type are meaningless");
3751 /* The function type was constructed earlier. Freeing it here will
3752 * destroy other types. */
3753 type = typehash_insert(function_type);
3757 case CONSTRUCT_POINTER: {
3758 if (is_type_reference(skip_typeref(type)))
3759 errorf(pos, "cannot declare a pointer to reference");
3761 parsed_pointer_t *pointer = &iter->pointer;
3762 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3766 case CONSTRUCT_REFERENCE:
3767 if (is_type_reference(skip_typeref(type)))
3768 errorf(pos, "cannot declare a reference to reference");
3770 type = make_reference_type(type);
3773 case CONSTRUCT_ARRAY: {
3774 if (is_type_reference(skip_typeref(type)))
3775 errorf(pos, "cannot declare an array of references");
3777 parsed_array_t *array = &iter->array;
3778 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3780 expression_t *size_expression = array->size;
3781 if (size_expression != NULL) {
3783 = create_implicit_cast(size_expression, type_size_t);
3786 array_type->base.qualifiers = array->type_qualifiers;
3787 array_type->array.element_type = type;
3788 array_type->array.is_static = array->is_static;
3789 array_type->array.is_variable = array->is_variable;
3790 array_type->array.size_expression = size_expression;
3792 if (size_expression != NULL) {
3793 switch (is_constant_expression(size_expression)) {
3794 case EXPR_CLASS_CONSTANT: {
3795 long const size = fold_constant_to_int(size_expression);
3796 array_type->array.size = size;
3797 array_type->array.size_constant = true;
3798 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3799 * have a value greater than zero. */
3801 if (size < 0 || !GNU_MODE) {
3802 errorf(&size_expression->base.source_position,
3803 "size of array must be greater than zero");
3804 } else if (warning.other) {
3805 warningf(&size_expression->base.source_position,
3806 "zero length arrays are a GCC extension");
3812 case EXPR_CLASS_VARIABLE:
3813 array_type->array.is_vla = true;
3816 case EXPR_CLASS_ERROR:
3821 type_t *skipped_type = skip_typeref(type);
3823 if (is_type_incomplete(skipped_type)) {
3824 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3825 } else if (is_type_function(skipped_type)) {
3826 errorf(pos, "array of functions is not allowed");
3828 type = identify_new_type(array_type);
3832 internal_errorf(pos, "invalid type construction found");
3838 static type_t *automatic_type_conversion(type_t *orig_type);
3840 static type_t *semantic_parameter(const source_position_t *pos,
3842 const declaration_specifiers_t *specifiers,
3845 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3846 * shall be adjusted to ``qualified pointer to type'',
3848 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3849 * type'' shall be adjusted to ``pointer to function
3850 * returning type'', as in 6.3.2.1. */
3851 type = automatic_type_conversion(type);
3853 if (specifiers->is_inline && is_type_valid(type)) {
3854 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3857 /* §6.9.1:6 The declarations in the declaration list shall contain
3858 * no storage-class specifier other than register and no
3859 * initializations. */
3860 if (specifiers->thread_local || (
3861 specifiers->storage_class != STORAGE_CLASS_NONE &&
3862 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3864 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3867 /* delay test for incomplete type, because we might have (void)
3868 * which is legal but incomplete... */
3873 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3874 declarator_flags_t flags)
3876 parse_declarator_env_t env;
3877 memset(&env, 0, sizeof(env));
3878 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3880 construct_type_t *construct_type = parse_inner_declarator(&env);
3882 construct_declarator_type(construct_type, specifiers->type);
3883 type_t *type = skip_typeref(orig_type);
3885 if (construct_type != NULL) {
3886 obstack_free(&temp_obst, construct_type);
3889 attribute_t *attributes = parse_attributes(env.attributes);
3890 /* append (shared) specifier attribute behind attributes of this
3892 attribute_t **anchor = &attributes;
3893 while (*anchor != NULL)
3894 anchor = &(*anchor)->next;
3895 *anchor = specifiers->attributes;
3898 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3899 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3900 entity->base.namespc = NAMESPACE_NORMAL;
3901 entity->base.symbol = env.symbol;
3902 entity->base.source_position = env.source_position;
3903 entity->typedefe.type = orig_type;
3905 if (anonymous_entity != NULL) {
3906 if (is_type_compound(type)) {
3907 assert(anonymous_entity->compound.alias == NULL);
3908 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3909 anonymous_entity->kind == ENTITY_UNION);
3910 anonymous_entity->compound.alias = entity;
3911 anonymous_entity = NULL;
3912 } else if (is_type_enum(type)) {
3913 assert(anonymous_entity->enume.alias == NULL);
3914 assert(anonymous_entity->kind == ENTITY_ENUM);
3915 anonymous_entity->enume.alias = entity;
3916 anonymous_entity = NULL;
3920 /* create a declaration type entity */
3921 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3922 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3924 if (env.symbol != NULL) {
3925 if (specifiers->is_inline && is_type_valid(type)) {
3926 errorf(&env.source_position,
3927 "compound member '%Y' declared 'inline'", env.symbol);
3930 if (specifiers->thread_local ||
3931 specifiers->storage_class != STORAGE_CLASS_NONE) {
3932 errorf(&env.source_position,
3933 "compound member '%Y' must have no storage class",
3937 } else if (flags & DECL_IS_PARAMETER) {
3938 orig_type = semantic_parameter(&env.source_position, orig_type,
3939 specifiers, env.symbol);
3941 entity = allocate_entity_zero(ENTITY_PARAMETER);
3942 } else if (is_type_function(type)) {
3943 entity = allocate_entity_zero(ENTITY_FUNCTION);
3945 entity->function.is_inline = specifiers->is_inline;
3946 entity->function.elf_visibility = default_visibility;
3947 entity->function.parameters = env.parameters;
3949 if (env.symbol != NULL) {
3950 /* this needs fixes for C++ */
3951 bool in_function_scope = current_function != NULL;
3953 if (specifiers->thread_local || (
3954 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3955 specifiers->storage_class != STORAGE_CLASS_NONE &&
3956 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3958 errorf(&env.source_position,
3959 "invalid storage class for function '%Y'", env.symbol);
3963 entity = allocate_entity_zero(ENTITY_VARIABLE);
3965 entity->variable.elf_visibility = default_visibility;
3966 entity->variable.thread_local = specifiers->thread_local;
3968 if (env.symbol != NULL) {
3969 if (specifiers->is_inline && is_type_valid(type)) {
3970 errorf(&env.source_position,
3971 "variable '%Y' declared 'inline'", env.symbol);
3974 bool invalid_storage_class = false;
3975 if (current_scope == file_scope) {
3976 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3977 specifiers->storage_class != STORAGE_CLASS_NONE &&
3978 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3979 invalid_storage_class = true;
3982 if (specifiers->thread_local &&
3983 specifiers->storage_class == STORAGE_CLASS_NONE) {
3984 invalid_storage_class = true;
3987 if (invalid_storage_class) {
3988 errorf(&env.source_position,
3989 "invalid storage class for variable '%Y'", env.symbol);
3994 if (env.symbol != NULL) {
3995 entity->base.symbol = env.symbol;
3996 entity->base.source_position = env.source_position;
3998 entity->base.source_position = specifiers->source_position;
4000 entity->base.namespc = NAMESPACE_NORMAL;
4001 entity->declaration.type = orig_type;
4002 entity->declaration.alignment = get_type_alignment(orig_type);
4003 entity->declaration.modifiers = env.modifiers;
4004 entity->declaration.attributes = attributes;
4006 storage_class_t storage_class = specifiers->storage_class;
4007 entity->declaration.declared_storage_class = storage_class;
4009 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4010 storage_class = STORAGE_CLASS_AUTO;
4011 entity->declaration.storage_class = storage_class;
4014 if (attributes != NULL) {
4015 handle_entity_attributes(attributes, entity);
4021 static type_t *parse_abstract_declarator(type_t *base_type)
4023 parse_declarator_env_t env;
4024 memset(&env, 0, sizeof(env));
4025 env.may_be_abstract = true;
4026 env.must_be_abstract = true;
4028 construct_type_t *construct_type = parse_inner_declarator(&env);
4030 type_t *result = construct_declarator_type(construct_type, base_type);
4031 if (construct_type != NULL) {
4032 obstack_free(&temp_obst, construct_type);
4034 result = handle_type_attributes(env.attributes, result);
4040 * Check if the declaration of main is suspicious. main should be a
4041 * function with external linkage, returning int, taking either zero
4042 * arguments, two, or three arguments of appropriate types, ie.
4044 * int main([ int argc, char **argv [, char **env ] ]).
4046 * @param decl the declaration to check
4047 * @param type the function type of the declaration
4049 static void check_main(const entity_t *entity)
4051 const source_position_t *pos = &entity->base.source_position;
4052 if (entity->kind != ENTITY_FUNCTION) {
4053 warningf(pos, "'main' is not a function");
4057 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4058 warningf(pos, "'main' is normally a non-static function");
4061 type_t *type = skip_typeref(entity->declaration.type);
4062 assert(is_type_function(type));
4064 function_type_t *func_type = &type->function;
4065 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4066 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4067 func_type->return_type);
4069 const function_parameter_t *parm = func_type->parameters;
4071 type_t *const first_type = skip_typeref(parm->type);
4072 type_t *const first_type_unqual = get_unqualified_type(first_type);
4073 if (!types_compatible(first_type_unqual, type_int)) {
4075 "first argument of 'main' should be 'int', but is '%T'",
4080 type_t *const second_type = skip_typeref(parm->type);
4081 type_t *const second_type_unqual
4082 = get_unqualified_type(second_type);
4083 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4084 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'",
4089 type_t *const third_type = skip_typeref(parm->type);
4090 type_t *const third_type_unqual
4091 = get_unqualified_type(third_type);
4092 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4093 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'",
4098 goto warn_arg_count;
4102 warningf(pos, "'main' takes only zero, two or three arguments");
4108 * Check if a symbol is the equal to "main".
4110 static bool is_sym_main(const symbol_t *const sym)
4112 return strcmp(sym->string, "main") == 0;
4115 static void error_redefined_as_different_kind(const source_position_t *pos,
4116 const entity_t *old, entity_kind_t new_kind)
4118 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4119 get_entity_kind_name(old->kind), old->base.symbol,
4120 get_entity_kind_name(new_kind), &old->base.source_position);
4123 static bool is_entity_valid(entity_t *const ent)
4125 if (is_declaration(ent)) {
4126 return is_type_valid(skip_typeref(ent->declaration.type));
4127 } else if (ent->kind == ENTITY_TYPEDEF) {
4128 return is_type_valid(skip_typeref(ent->typedefe.type));
4133 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4135 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4136 if (attributes_equal(tattr, attr))
4143 * test wether new_list contains any attributes not included in old_list
4145 static bool has_new_attributes(const attribute_t *old_list,
4146 const attribute_t *new_list)
4148 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4149 if (!contains_attribute(old_list, attr))
4156 * Merge in attributes from an attribute list (probably from a previous
4157 * declaration with the same name). Warning: destroys the old structure
4158 * of the attribute list - don't reuse attributes after this call.
4160 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4163 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4165 if (contains_attribute(decl->attributes, attr))
4168 /* move attribute to new declarations attributes list */
4169 attr->next = decl->attributes;
4170 decl->attributes = attr;
4175 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4176 * for various problems that occur for multiple definitions
4178 entity_t *record_entity(entity_t *entity, const bool is_definition)
4180 const symbol_t *const symbol = entity->base.symbol;
4181 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4182 const source_position_t *pos = &entity->base.source_position;
4184 /* can happen in error cases */
4188 entity_t *const previous_entity = get_entity(symbol, namespc);
4189 /* pushing the same entity twice will break the stack structure */
4190 assert(previous_entity != entity);
4192 if (entity->kind == ENTITY_FUNCTION) {
4193 type_t *const orig_type = entity->declaration.type;
4194 type_t *const type = skip_typeref(orig_type);
4196 assert(is_type_function(type));
4197 if (type->function.unspecified_parameters &&
4198 warning.strict_prototypes &&
4199 previous_entity == NULL) {
4200 warningf(pos, "function declaration '%#T' is not a prototype",
4204 if (warning.main && current_scope == file_scope
4205 && is_sym_main(symbol)) {
4210 if (is_declaration(entity) &&
4211 warning.nested_externs &&
4212 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4213 current_scope != file_scope) {
4214 warningf(pos, "nested extern declaration of '%#T'",
4215 entity->declaration.type, symbol);
4218 if (previous_entity != NULL) {
4219 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4220 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4221 assert(previous_entity->kind == ENTITY_PARAMETER);
4223 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4224 entity->declaration.type, symbol,
4225 previous_entity->declaration.type, symbol,
4226 &previous_entity->base.source_position);
4230 if (previous_entity->base.parent_scope == current_scope) {
4231 if (previous_entity->kind != entity->kind) {
4232 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4233 error_redefined_as_different_kind(pos, previous_entity,
4238 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4239 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4240 symbol, &previous_entity->base.source_position);
4243 if (previous_entity->kind == ENTITY_TYPEDEF) {
4244 /* TODO: C++ allows this for exactly the same type */
4245 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4246 symbol, &previous_entity->base.source_position);
4250 /* at this point we should have only VARIABLES or FUNCTIONS */
4251 assert(is_declaration(previous_entity) && is_declaration(entity));
4253 declaration_t *const prev_decl = &previous_entity->declaration;
4254 declaration_t *const decl = &entity->declaration;
4256 /* can happen for K&R style declarations */
4257 if (prev_decl->type == NULL &&
4258 previous_entity->kind == ENTITY_PARAMETER &&
4259 entity->kind == ENTITY_PARAMETER) {
4260 prev_decl->type = decl->type;
4261 prev_decl->storage_class = decl->storage_class;
4262 prev_decl->declared_storage_class = decl->declared_storage_class;
4263 prev_decl->modifiers = decl->modifiers;
4264 return previous_entity;
4267 type_t *const orig_type = decl->type;
4268 assert(orig_type != NULL);
4269 type_t *const type = skip_typeref(orig_type);
4270 type_t *const prev_type = skip_typeref(prev_decl->type);
4272 if (!types_compatible(type, prev_type)) {
4274 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4275 orig_type, symbol, prev_decl->type, symbol,
4276 &previous_entity->base.source_position);
4278 unsigned old_storage_class = prev_decl->storage_class;
4280 if (warning.redundant_decls &&
4283 !(prev_decl->modifiers & DM_USED) &&
4284 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4285 warningf(&previous_entity->base.source_position,
4286 "unnecessary static forward declaration for '%#T'",
4287 prev_decl->type, symbol);
4290 storage_class_t new_storage_class = decl->storage_class;
4292 /* pretend no storage class means extern for function
4293 * declarations (except if the previous declaration is neither
4294 * none nor extern) */
4295 if (entity->kind == ENTITY_FUNCTION) {
4296 /* the previous declaration could have unspecified parameters or
4297 * be a typedef, so use the new type */
4298 if (prev_type->function.unspecified_parameters || is_definition)
4299 prev_decl->type = type;
4301 switch (old_storage_class) {
4302 case STORAGE_CLASS_NONE:
4303 old_storage_class = STORAGE_CLASS_EXTERN;
4306 case STORAGE_CLASS_EXTERN:
4307 if (is_definition) {
4308 if (warning.missing_prototypes &&
4309 prev_type->function.unspecified_parameters &&
4310 !is_sym_main(symbol)) {
4311 warningf(pos, "no previous prototype for '%#T'",
4314 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4315 new_storage_class = STORAGE_CLASS_EXTERN;
4322 } else if (is_type_incomplete(prev_type)) {
4323 prev_decl->type = type;
4326 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4327 new_storage_class == STORAGE_CLASS_EXTERN) {
4329 warn_redundant_declaration: ;
4331 = has_new_attributes(prev_decl->attributes,
4333 if (has_new_attrs) {
4334 merge_in_attributes(decl, prev_decl->attributes);
4335 } else if (!is_definition &&
4336 warning.redundant_decls &&
4337 is_type_valid(prev_type) &&
4338 strcmp(previous_entity->base.source_position.input_name,
4339 "<builtin>") != 0) {
4341 "redundant declaration for '%Y' (declared %P)",
4342 symbol, &previous_entity->base.source_position);
4344 } else if (current_function == NULL) {
4345 if (old_storage_class != STORAGE_CLASS_STATIC &&
4346 new_storage_class == STORAGE_CLASS_STATIC) {
4348 "static declaration of '%Y' follows non-static declaration (declared %P)",
4349 symbol, &previous_entity->base.source_position);
4350 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4351 prev_decl->storage_class = STORAGE_CLASS_NONE;
4352 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4354 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4356 goto error_redeclaration;
4357 goto warn_redundant_declaration;
4359 } else if (is_type_valid(prev_type)) {
4360 if (old_storage_class == new_storage_class) {
4361 error_redeclaration:
4362 errorf(pos, "redeclaration of '%Y' (declared %P)",
4363 symbol, &previous_entity->base.source_position);
4366 "redeclaration of '%Y' with different linkage (declared %P)",
4367 symbol, &previous_entity->base.source_position);
4372 prev_decl->modifiers |= decl->modifiers;
4373 if (entity->kind == ENTITY_FUNCTION) {
4374 previous_entity->function.is_inline |= entity->function.is_inline;
4376 return previous_entity;
4379 if (warning.shadow) {
4380 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4381 get_entity_kind_name(entity->kind), symbol,
4382 get_entity_kind_name(previous_entity->kind),
4383 &previous_entity->base.source_position);
4387 if (entity->kind == ENTITY_FUNCTION) {
4388 if (is_definition &&
4389 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4390 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4391 warningf(pos, "no previous prototype for '%#T'",
4392 entity->declaration.type, symbol);
4393 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4394 warningf(pos, "no previous declaration for '%#T'",
4395 entity->declaration.type, symbol);
4398 } else if (warning.missing_declarations &&
4399 entity->kind == ENTITY_VARIABLE &&
4400 current_scope == file_scope) {
4401 declaration_t *declaration = &entity->declaration;
4402 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4403 warningf(pos, "no previous declaration for '%#T'",
4404 declaration->type, symbol);
4409 assert(entity->base.parent_scope == NULL);
4410 assert(current_scope != NULL);
4412 entity->base.parent_scope = current_scope;
4413 entity->base.namespc = NAMESPACE_NORMAL;
4414 environment_push(entity);
4415 append_entity(current_scope, entity);
4420 static void parser_error_multiple_definition(entity_t *entity,
4421 const source_position_t *source_position)
4423 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4424 entity->base.symbol, &entity->base.source_position);
4427 static bool is_declaration_specifier(const token_t *token,
4428 bool only_specifiers_qualifiers)
4430 switch (token->type) {
4435 return is_typedef_symbol(token->symbol);
4437 case T___extension__:
4439 return !only_specifiers_qualifiers;
4446 static void parse_init_declarator_rest(entity_t *entity)
4448 type_t *orig_type = type_error_type;
4450 if (entity->base.kind == ENTITY_TYPEDEF) {
4451 errorf(&entity->base.source_position,
4452 "typedef '%Y' is initialized (use __typeof__ instead)",
4453 entity->base.symbol);
4455 assert(is_declaration(entity));
4456 orig_type = entity->declaration.type;
4460 type_t *type = skip_typeref(orig_type);
4462 if (entity->kind == ENTITY_VARIABLE
4463 && entity->variable.initializer != NULL) {
4464 parser_error_multiple_definition(entity, HERE);
4467 declaration_t *const declaration = &entity->declaration;
4468 bool must_be_constant = false;
4469 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4470 entity->base.parent_scope == file_scope) {
4471 must_be_constant = true;
4474 if (is_type_function(type)) {
4475 errorf(&entity->base.source_position,
4476 "function '%#T' is initialized like a variable",
4477 orig_type, entity->base.symbol);
4478 orig_type = type_error_type;
4481 parse_initializer_env_t env;
4482 env.type = orig_type;
4483 env.must_be_constant = must_be_constant;
4484 env.entity = entity;
4485 current_init_decl = entity;
4487 initializer_t *initializer = parse_initializer(&env);
4488 current_init_decl = NULL;
4490 if (entity->kind == ENTITY_VARIABLE) {
4491 /* §6.7.5:22 array initializers for arrays with unknown size
4492 * determine the array type size */
4493 declaration->type = env.type;
4494 entity->variable.initializer = initializer;
4498 /* parse rest of a declaration without any declarator */
4499 static void parse_anonymous_declaration_rest(
4500 const declaration_specifiers_t *specifiers)
4503 anonymous_entity = NULL;
4505 if (warning.other) {
4506 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4507 specifiers->thread_local) {
4508 warningf(&specifiers->source_position,
4509 "useless storage class in empty declaration");
4512 type_t *type = specifiers->type;
4513 switch (type->kind) {
4514 case TYPE_COMPOUND_STRUCT:
4515 case TYPE_COMPOUND_UNION: {
4516 if (type->compound.compound->base.symbol == NULL) {
4517 warningf(&specifiers->source_position,
4518 "unnamed struct/union that defines no instances");
4527 warningf(&specifiers->source_position, "empty declaration");
4533 static void check_variable_type_complete(entity_t *ent)
4535 if (ent->kind != ENTITY_VARIABLE)
4538 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4539 * type for the object shall be complete [...] */
4540 declaration_t *decl = &ent->declaration;
4541 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4542 decl->storage_class == STORAGE_CLASS_STATIC)
4545 type_t *const orig_type = decl->type;
4546 type_t *const type = skip_typeref(orig_type);
4547 if (!is_type_incomplete(type))
4550 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4551 * are given length one. */
4552 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4553 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4557 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4558 orig_type, ent->base.symbol);
4562 static void parse_declaration_rest(entity_t *ndeclaration,
4563 const declaration_specifiers_t *specifiers,
4564 parsed_declaration_func finished_declaration,
4565 declarator_flags_t flags)
4567 add_anchor_token(';');
4568 add_anchor_token(',');
4570 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4572 if (token.type == '=') {
4573 parse_init_declarator_rest(entity);
4574 } else if (entity->kind == ENTITY_VARIABLE) {
4575 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4576 * [...] where the extern specifier is explicitly used. */
4577 declaration_t *decl = &entity->declaration;
4578 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4579 type_t *type = decl->type;
4580 if (is_type_reference(skip_typeref(type))) {
4581 errorf(&entity->base.source_position,
4582 "reference '%#T' must be initialized",
4583 type, entity->base.symbol);
4588 check_variable_type_complete(entity);
4593 add_anchor_token('=');
4594 ndeclaration = parse_declarator(specifiers, flags);
4595 rem_anchor_token('=');
4597 expect(';', end_error);
4600 anonymous_entity = NULL;
4601 rem_anchor_token(';');
4602 rem_anchor_token(',');
4605 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4607 symbol_t *symbol = entity->base.symbol;
4608 if (symbol == NULL) {
4609 errorf(HERE, "anonymous declaration not valid as function parameter");
4613 assert(entity->base.namespc == NAMESPACE_NORMAL);
4614 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4615 if (previous_entity == NULL
4616 || previous_entity->base.parent_scope != current_scope) {
4617 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4622 if (is_definition) {
4623 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4626 return record_entity(entity, false);
4629 static void parse_declaration(parsed_declaration_func finished_declaration,
4630 declarator_flags_t flags)
4632 declaration_specifiers_t specifiers;
4633 memset(&specifiers, 0, sizeof(specifiers));
4635 add_anchor_token(';');
4636 parse_declaration_specifiers(&specifiers);
4637 rem_anchor_token(';');
4639 if (token.type == ';') {
4640 parse_anonymous_declaration_rest(&specifiers);
4642 entity_t *entity = parse_declarator(&specifiers, flags);
4643 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4648 static type_t *get_default_promoted_type(type_t *orig_type)
4650 type_t *result = orig_type;
4652 type_t *type = skip_typeref(orig_type);
4653 if (is_type_integer(type)) {
4654 result = promote_integer(type);
4655 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4656 result = type_double;
4662 static void parse_kr_declaration_list(entity_t *entity)
4664 if (entity->kind != ENTITY_FUNCTION)
4667 type_t *type = skip_typeref(entity->declaration.type);
4668 assert(is_type_function(type));
4669 if (!type->function.kr_style_parameters)
4672 add_anchor_token('{');
4674 /* push function parameters */
4675 size_t const top = environment_top();
4676 scope_t *old_scope = scope_push(&entity->function.parameters);
4678 entity_t *parameter = entity->function.parameters.entities;
4679 for ( ; parameter != NULL; parameter = parameter->base.next) {
4680 assert(parameter->base.parent_scope == NULL);
4681 parameter->base.parent_scope = current_scope;
4682 environment_push(parameter);
4685 /* parse declaration list */
4687 switch (token.type) {
4689 case T___extension__:
4690 /* This covers symbols, which are no type, too, and results in
4691 * better error messages. The typical cases are misspelled type
4692 * names and missing includes. */
4694 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4702 /* pop function parameters */
4703 assert(current_scope == &entity->function.parameters);
4704 scope_pop(old_scope);
4705 environment_pop_to(top);
4707 /* update function type */
4708 type_t *new_type = duplicate_type(type);
4710 function_parameter_t *parameters = NULL;
4711 function_parameter_t **anchor = ¶meters;
4713 /* did we have an earlier prototype? */
4714 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4715 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4718 function_parameter_t *proto_parameter = NULL;
4719 if (proto_type != NULL) {
4720 type_t *proto_type_type = proto_type->declaration.type;
4721 proto_parameter = proto_type_type->function.parameters;
4722 /* If a K&R function definition has a variadic prototype earlier, then
4723 * make the function definition variadic, too. This should conform to
4724 * §6.7.5.3:15 and §6.9.1:8. */
4725 new_type->function.variadic = proto_type_type->function.variadic;
4727 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4729 new_type->function.unspecified_parameters = true;
4732 bool need_incompatible_warning = false;
4733 parameter = entity->function.parameters.entities;
4734 for (; parameter != NULL; parameter = parameter->base.next,
4736 proto_parameter == NULL ? NULL : proto_parameter->next) {
4737 if (parameter->kind != ENTITY_PARAMETER)
4740 type_t *parameter_type = parameter->declaration.type;
4741 if (parameter_type == NULL) {
4743 errorf(HERE, "no type specified for function parameter '%Y'",
4744 parameter->base.symbol);
4745 parameter_type = type_error_type;
4747 if (warning.implicit_int) {
4748 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4749 parameter->base.symbol);
4751 parameter_type = type_int;
4753 parameter->declaration.type = parameter_type;
4756 semantic_parameter_incomplete(parameter);
4758 /* we need the default promoted types for the function type */
4759 type_t *not_promoted = parameter_type;
4760 parameter_type = get_default_promoted_type(parameter_type);
4762 /* gcc special: if the type of the prototype matches the unpromoted
4763 * type don't promote */
4764 if (!strict_mode && proto_parameter != NULL) {
4765 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4766 type_t *promo_skip = skip_typeref(parameter_type);
4767 type_t *param_skip = skip_typeref(not_promoted);
4768 if (!types_compatible(proto_p_type, promo_skip)
4769 && types_compatible(proto_p_type, param_skip)) {
4771 need_incompatible_warning = true;
4772 parameter_type = not_promoted;
4775 function_parameter_t *const parameter
4776 = allocate_parameter(parameter_type);
4778 *anchor = parameter;
4779 anchor = ¶meter->next;
4782 new_type->function.parameters = parameters;
4783 new_type = identify_new_type(new_type);
4785 if (warning.other && need_incompatible_warning) {
4786 type_t *proto_type_type = proto_type->declaration.type;
4788 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4789 proto_type_type, proto_type->base.symbol,
4790 new_type, entity->base.symbol,
4791 &proto_type->base.source_position);
4794 entity->declaration.type = new_type;
4796 rem_anchor_token('{');
4799 static bool first_err = true;
4802 * When called with first_err set, prints the name of the current function,
4805 static void print_in_function(void)
4809 diagnosticf("%s: In function '%Y':\n",
4810 current_function->base.base.source_position.input_name,
4811 current_function->base.base.symbol);
4816 * Check if all labels are defined in the current function.
4817 * Check if all labels are used in the current function.
4819 static void check_labels(void)
4821 for (const goto_statement_t *goto_statement = goto_first;
4822 goto_statement != NULL;
4823 goto_statement = goto_statement->next) {
4824 /* skip computed gotos */
4825 if (goto_statement->expression != NULL)
4828 label_t *label = goto_statement->label;
4831 if (label->base.source_position.input_name == NULL) {
4832 print_in_function();
4833 errorf(&goto_statement->base.source_position,
4834 "label '%Y' used but not defined", label->base.symbol);
4838 if (warning.unused_label) {
4839 for (const label_statement_t *label_statement = label_first;
4840 label_statement != NULL;
4841 label_statement = label_statement->next) {
4842 label_t *label = label_statement->label;
4844 if (! label->used) {
4845 print_in_function();
4846 warningf(&label_statement->base.source_position,
4847 "label '%Y' defined but not used", label->base.symbol);
4853 static void warn_unused_entity(entity_t *entity, entity_t *last)
4855 entity_t const *const end = last != NULL ? last->base.next : NULL;
4856 for (; entity != end; entity = entity->base.next) {
4857 if (!is_declaration(entity))
4860 declaration_t *declaration = &entity->declaration;
4861 if (declaration->implicit)
4864 if (!declaration->used) {
4865 print_in_function();
4866 const char *what = get_entity_kind_name(entity->kind);
4867 warningf(&entity->base.source_position, "%s '%Y' is unused",
4868 what, entity->base.symbol);
4869 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4870 print_in_function();
4871 const char *what = get_entity_kind_name(entity->kind);
4872 warningf(&entity->base.source_position, "%s '%Y' is never read",
4873 what, entity->base.symbol);
4878 static void check_unused_variables(statement_t *const stmt, void *const env)
4882 switch (stmt->kind) {
4883 case STATEMENT_DECLARATION: {
4884 declaration_statement_t const *const decls = &stmt->declaration;
4885 warn_unused_entity(decls->declarations_begin,
4886 decls->declarations_end);
4891 warn_unused_entity(stmt->fors.scope.entities, NULL);
4900 * Check declarations of current_function for unused entities.
4902 static void check_declarations(void)
4904 if (warning.unused_parameter) {
4905 const scope_t *scope = ¤t_function->parameters;
4907 /* do not issue unused warnings for main */
4908 if (!is_sym_main(current_function->base.base.symbol)) {
4909 warn_unused_entity(scope->entities, NULL);
4912 if (warning.unused_variable) {
4913 walk_statements(current_function->statement, check_unused_variables,
4918 static int determine_truth(expression_t const* const cond)
4921 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4922 fold_constant_to_bool(cond) ? 1 :
4926 static void check_reachable(statement_t *);
4927 static bool reaches_end;
4929 static bool expression_returns(expression_t const *const expr)
4931 switch (expr->kind) {
4933 expression_t const *const func = expr->call.function;
4934 if (func->kind == EXPR_REFERENCE) {
4935 entity_t *entity = func->reference.entity;
4936 if (entity->kind == ENTITY_FUNCTION
4937 && entity->declaration.modifiers & DM_NORETURN)
4941 if (!expression_returns(func))
4944 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4945 if (!expression_returns(arg->expression))
4952 case EXPR_REFERENCE:
4953 case EXPR_REFERENCE_ENUM_VALUE:
4955 case EXPR_STRING_LITERAL:
4956 case EXPR_WIDE_STRING_LITERAL:
4957 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4958 case EXPR_LABEL_ADDRESS:
4959 case EXPR_CLASSIFY_TYPE:
4960 case EXPR_SIZEOF: // TODO handle obscure VLA case
4963 case EXPR_BUILTIN_CONSTANT_P:
4964 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4969 case EXPR_STATEMENT: {
4970 bool old_reaches_end = reaches_end;
4971 reaches_end = false;
4972 check_reachable(expr->statement.statement);
4973 bool returns = reaches_end;
4974 reaches_end = old_reaches_end;
4978 case EXPR_CONDITIONAL:
4979 // TODO handle constant expression
4981 if (!expression_returns(expr->conditional.condition))
4984 if (expr->conditional.true_expression != NULL
4985 && expression_returns(expr->conditional.true_expression))
4988 return expression_returns(expr->conditional.false_expression);
4991 return expression_returns(expr->select.compound);
4993 case EXPR_ARRAY_ACCESS:
4995 expression_returns(expr->array_access.array_ref) &&
4996 expression_returns(expr->array_access.index);
4999 return expression_returns(expr->va_starte.ap);
5002 return expression_returns(expr->va_arge.ap);
5005 return expression_returns(expr->va_copye.src);
5007 EXPR_UNARY_CASES_MANDATORY
5008 return expression_returns(expr->unary.value);
5010 case EXPR_UNARY_THROW:
5014 // TODO handle constant lhs of && and ||
5016 expression_returns(expr->binary.left) &&
5017 expression_returns(expr->binary.right);
5023 panic("unhandled expression");
5026 static bool initializer_returns(initializer_t const *const init)
5028 switch (init->kind) {
5029 case INITIALIZER_VALUE:
5030 return expression_returns(init->value.value);
5032 case INITIALIZER_LIST: {
5033 initializer_t * const* i = init->list.initializers;
5034 initializer_t * const* const end = i + init->list.len;
5035 bool returns = true;
5036 for (; i != end; ++i) {
5037 if (!initializer_returns(*i))
5043 case INITIALIZER_STRING:
5044 case INITIALIZER_WIDE_STRING:
5045 case INITIALIZER_DESIGNATOR: // designators have no payload
5048 panic("unhandled initializer");
5051 static bool noreturn_candidate;
5053 static void check_reachable(statement_t *const stmt)
5055 if (stmt->base.reachable)
5057 if (stmt->kind != STATEMENT_DO_WHILE)
5058 stmt->base.reachable = true;
5060 statement_t *last = stmt;
5062 switch (stmt->kind) {
5063 case STATEMENT_INVALID:
5064 case STATEMENT_EMPTY:
5066 next = stmt->base.next;
5069 case STATEMENT_DECLARATION: {
5070 declaration_statement_t const *const decl = &stmt->declaration;
5071 entity_t const * ent = decl->declarations_begin;
5072 entity_t const *const last = decl->declarations_end;
5074 for (;; ent = ent->base.next) {
5075 if (ent->kind == ENTITY_VARIABLE &&
5076 ent->variable.initializer != NULL &&
5077 !initializer_returns(ent->variable.initializer)) {
5084 next = stmt->base.next;
5088 case STATEMENT_COMPOUND:
5089 next = stmt->compound.statements;
5091 next = stmt->base.next;
5094 case STATEMENT_RETURN: {
5095 expression_t const *const val = stmt->returns.value;
5096 if (val == NULL || expression_returns(val))
5097 noreturn_candidate = false;
5101 case STATEMENT_IF: {
5102 if_statement_t const *const ifs = &stmt->ifs;
5103 expression_t const *const cond = ifs->condition;
5105 if (!expression_returns(cond))
5108 int const val = determine_truth(cond);
5111 check_reachable(ifs->true_statement);
5116 if (ifs->false_statement != NULL) {
5117 check_reachable(ifs->false_statement);
5121 next = stmt->base.next;
5125 case STATEMENT_SWITCH: {
5126 switch_statement_t const *const switchs = &stmt->switchs;
5127 expression_t const *const expr = switchs->expression;
5129 if (!expression_returns(expr))
5132 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5133 long const val = fold_constant_to_int(expr);
5134 case_label_statement_t * defaults = NULL;
5135 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5136 if (i->expression == NULL) {
5141 if (i->first_case <= val && val <= i->last_case) {
5142 check_reachable((statement_t*)i);
5147 if (defaults != NULL) {
5148 check_reachable((statement_t*)defaults);
5152 bool has_default = false;
5153 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5154 if (i->expression == NULL)
5157 check_reachable((statement_t*)i);
5164 next = stmt->base.next;
5168 case STATEMENT_EXPRESSION: {
5169 /* Check for noreturn function call */
5170 expression_t const *const expr = stmt->expression.expression;
5171 if (!expression_returns(expr))
5174 next = stmt->base.next;
5178 case STATEMENT_CONTINUE:
5179 for (statement_t *parent = stmt;;) {
5180 parent = parent->base.parent;
5181 if (parent == NULL) /* continue not within loop */
5185 switch (parent->kind) {
5186 case STATEMENT_WHILE: goto continue_while;
5187 case STATEMENT_DO_WHILE: goto continue_do_while;
5188 case STATEMENT_FOR: goto continue_for;
5194 case STATEMENT_BREAK:
5195 for (statement_t *parent = stmt;;) {
5196 parent = parent->base.parent;
5197 if (parent == NULL) /* break not within loop/switch */
5200 switch (parent->kind) {
5201 case STATEMENT_SWITCH:
5202 case STATEMENT_WHILE:
5203 case STATEMENT_DO_WHILE:
5206 next = parent->base.next;
5207 goto found_break_parent;
5215 case STATEMENT_GOTO:
5216 if (stmt->gotos.expression) {
5217 if (!expression_returns(stmt->gotos.expression))
5220 statement_t *parent = stmt->base.parent;
5221 if (parent == NULL) /* top level goto */
5225 next = stmt->gotos.label->statement;
5226 if (next == NULL) /* missing label */
5231 case STATEMENT_LABEL:
5232 next = stmt->label.statement;
5235 case STATEMENT_CASE_LABEL:
5236 next = stmt->case_label.statement;
5239 case STATEMENT_WHILE: {
5240 while_statement_t const *const whiles = &stmt->whiles;
5241 expression_t const *const cond = whiles->condition;
5243 if (!expression_returns(cond))
5246 int const val = determine_truth(cond);
5249 check_reachable(whiles->body);
5254 next = stmt->base.next;
5258 case STATEMENT_DO_WHILE:
5259 next = stmt->do_while.body;
5262 case STATEMENT_FOR: {
5263 for_statement_t *const fors = &stmt->fors;
5265 if (fors->condition_reachable)
5267 fors->condition_reachable = true;
5269 expression_t const *const cond = fors->condition;
5274 } else if (expression_returns(cond)) {
5275 val = determine_truth(cond);
5281 check_reachable(fors->body);
5286 next = stmt->base.next;
5290 case STATEMENT_MS_TRY: {
5291 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5292 check_reachable(ms_try->try_statement);
5293 next = ms_try->final_statement;
5297 case STATEMENT_LEAVE: {
5298 statement_t *parent = stmt;
5300 parent = parent->base.parent;
5301 if (parent == NULL) /* __leave not within __try */
5304 if (parent->kind == STATEMENT_MS_TRY) {
5306 next = parent->ms_try.final_statement;
5314 panic("invalid statement kind");
5317 while (next == NULL) {
5318 next = last->base.parent;
5320 noreturn_candidate = false;
5322 type_t *const type = skip_typeref(current_function->base.type);
5323 assert(is_type_function(type));
5324 type_t *const ret = skip_typeref(type->function.return_type);
5325 if (warning.return_type &&
5326 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5327 is_type_valid(ret) &&
5328 !is_sym_main(current_function->base.base.symbol)) {
5329 warningf(&stmt->base.source_position,
5330 "control reaches end of non-void function");
5335 switch (next->kind) {
5336 case STATEMENT_INVALID:
5337 case STATEMENT_EMPTY:
5338 case STATEMENT_DECLARATION:
5339 case STATEMENT_EXPRESSION:
5341 case STATEMENT_RETURN:
5342 case STATEMENT_CONTINUE:
5343 case STATEMENT_BREAK:
5344 case STATEMENT_GOTO:
5345 case STATEMENT_LEAVE:
5346 panic("invalid control flow in function");
5348 case STATEMENT_COMPOUND:
5349 if (next->compound.stmt_expr) {
5355 case STATEMENT_SWITCH:
5356 case STATEMENT_LABEL:
5357 case STATEMENT_CASE_LABEL:
5359 next = next->base.next;
5362 case STATEMENT_WHILE: {
5364 if (next->base.reachable)
5366 next->base.reachable = true;
5368 while_statement_t const *const whiles = &next->whiles;
5369 expression_t const *const cond = whiles->condition;
5371 if (!expression_returns(cond))
5374 int const val = determine_truth(cond);
5377 check_reachable(whiles->body);
5383 next = next->base.next;
5387 case STATEMENT_DO_WHILE: {
5389 if (next->base.reachable)
5391 next->base.reachable = true;
5393 do_while_statement_t const *const dw = &next->do_while;
5394 expression_t const *const cond = dw->condition;
5396 if (!expression_returns(cond))
5399 int const val = determine_truth(cond);
5402 check_reachable(dw->body);
5408 next = next->base.next;
5412 case STATEMENT_FOR: {
5414 for_statement_t *const fors = &next->fors;
5416 fors->step_reachable = true;
5418 if (fors->condition_reachable)
5420 fors->condition_reachable = true;
5422 expression_t const *const cond = fors->condition;
5427 } else if (expression_returns(cond)) {
5428 val = determine_truth(cond);
5434 check_reachable(fors->body);
5440 next = next->base.next;
5444 case STATEMENT_MS_TRY:
5446 next = next->ms_try.final_statement;
5451 check_reachable(next);
5454 static void check_unreachable(statement_t* const stmt, void *const env)
5458 switch (stmt->kind) {
5459 case STATEMENT_DO_WHILE:
5460 if (!stmt->base.reachable) {
5461 expression_t const *const cond = stmt->do_while.condition;
5462 if (determine_truth(cond) >= 0) {
5463 warningf(&cond->base.source_position,
5464 "condition of do-while-loop is unreachable");
5469 case STATEMENT_FOR: {
5470 for_statement_t const* const fors = &stmt->fors;
5472 // if init and step are unreachable, cond is unreachable, too
5473 if (!stmt->base.reachable && !fors->step_reachable) {
5474 warningf(&stmt->base.source_position, "statement is unreachable");
5476 if (!stmt->base.reachable && fors->initialisation != NULL) {
5477 warningf(&fors->initialisation->base.source_position,
5478 "initialisation of for-statement is unreachable");
5481 if (!fors->condition_reachable && fors->condition != NULL) {
5482 warningf(&fors->condition->base.source_position,
5483 "condition of for-statement is unreachable");
5486 if (!fors->step_reachable && fors->step != NULL) {
5487 warningf(&fors->step->base.source_position,
5488 "step of for-statement is unreachable");
5494 case STATEMENT_COMPOUND:
5495 if (stmt->compound.statements != NULL)
5497 goto warn_unreachable;
5499 case STATEMENT_DECLARATION: {
5500 /* Only warn if there is at least one declarator with an initializer.
5501 * This typically occurs in switch statements. */
5502 declaration_statement_t const *const decl = &stmt->declaration;
5503 entity_t const * ent = decl->declarations_begin;
5504 entity_t const *const last = decl->declarations_end;
5506 for (;; ent = ent->base.next) {
5507 if (ent->kind == ENTITY_VARIABLE &&
5508 ent->variable.initializer != NULL) {
5509 goto warn_unreachable;
5519 if (!stmt->base.reachable)
5520 warningf(&stmt->base.source_position, "statement is unreachable");
5525 static void parse_external_declaration(void)
5527 /* function-definitions and declarations both start with declaration
5529 declaration_specifiers_t specifiers;
5530 memset(&specifiers, 0, sizeof(specifiers));
5532 add_anchor_token(';');
5533 parse_declaration_specifiers(&specifiers);
5534 rem_anchor_token(';');
5536 /* must be a declaration */
5537 if (token.type == ';') {
5538 parse_anonymous_declaration_rest(&specifiers);
5542 add_anchor_token(',');
5543 add_anchor_token('=');
5544 add_anchor_token(';');
5545 add_anchor_token('{');
5547 /* declarator is common to both function-definitions and declarations */
5548 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5550 rem_anchor_token('{');
5551 rem_anchor_token(';');
5552 rem_anchor_token('=');
5553 rem_anchor_token(',');
5555 /* must be a declaration */
5556 switch (token.type) {
5560 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5565 /* must be a function definition */
5566 parse_kr_declaration_list(ndeclaration);
5568 if (token.type != '{') {
5569 parse_error_expected("while parsing function definition", '{', NULL);
5570 eat_until_matching_token(';');
5574 assert(is_declaration(ndeclaration));
5575 type_t *const orig_type = ndeclaration->declaration.type;
5576 type_t * type = skip_typeref(orig_type);
5578 if (!is_type_function(type)) {
5579 if (is_type_valid(type)) {
5580 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5581 type, ndeclaration->base.symbol);
5585 } else if (is_typeref(orig_type)) {
5587 errorf(&ndeclaration->base.source_position,
5588 "type of function definition '%#T' is a typedef",
5589 orig_type, ndeclaration->base.symbol);
5592 if (warning.aggregate_return &&
5593 is_type_compound(skip_typeref(type->function.return_type))) {
5594 warningf(&ndeclaration->base.source_position, "function '%Y' returns an aggregate",
5595 ndeclaration->base.symbol);
5597 if (warning.traditional && !type->function.unspecified_parameters) {
5598 warningf(&ndeclaration->base.source_position, "traditional C rejects ISO C style function definition of function '%Y'",
5599 ndeclaration->base.symbol);
5601 if (warning.old_style_definition && type->function.unspecified_parameters) {
5602 warningf(&ndeclaration->base.source_position, "old-style function definition '%Y'",
5603 ndeclaration->base.symbol);
5606 /* §6.7.5.3:14 a function definition with () means no
5607 * parameters (and not unspecified parameters) */
5608 if (type->function.unspecified_parameters &&
5609 type->function.parameters == NULL) {
5610 type_t *copy = duplicate_type(type);
5611 copy->function.unspecified_parameters = false;
5612 type = identify_new_type(copy);
5614 ndeclaration->declaration.type = type;
5617 entity_t *const entity = record_entity(ndeclaration, true);
5618 assert(entity->kind == ENTITY_FUNCTION);
5619 assert(ndeclaration->kind == ENTITY_FUNCTION);
5621 function_t *const function = &entity->function;
5622 if (ndeclaration != entity) {
5623 function->parameters = ndeclaration->function.parameters;
5625 assert(is_declaration(entity));
5626 type = skip_typeref(entity->declaration.type);
5628 /* push function parameters and switch scope */
5629 size_t const top = environment_top();
5630 scope_t *old_scope = scope_push(&function->parameters);
5632 entity_t *parameter = function->parameters.entities;
5633 for (; parameter != NULL; parameter = parameter->base.next) {
5634 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5635 parameter->base.parent_scope = current_scope;
5637 assert(parameter->base.parent_scope == NULL
5638 || parameter->base.parent_scope == current_scope);
5639 parameter->base.parent_scope = current_scope;
5640 if (parameter->base.symbol == NULL) {
5641 errorf(¶meter->base.source_position, "parameter name omitted");
5644 environment_push(parameter);
5647 if (function->statement != NULL) {
5648 parser_error_multiple_definition(entity, HERE);
5651 /* parse function body */
5652 int label_stack_top = label_top();
5653 function_t *old_current_function = current_function;
5654 entity_t *old_current_entity = current_entity;
5655 current_function = function;
5656 current_entity = entity;
5657 current_parent = NULL;
5660 goto_anchor = &goto_first;
5662 label_anchor = &label_first;
5664 statement_t *const body = parse_compound_statement(false);
5665 function->statement = body;
5668 check_declarations();
5669 if (warning.return_type ||
5670 warning.unreachable_code ||
5671 (warning.missing_noreturn
5672 && !(function->base.modifiers & DM_NORETURN))) {
5673 noreturn_candidate = true;
5674 check_reachable(body);
5675 if (warning.unreachable_code)
5676 walk_statements(body, check_unreachable, NULL);
5677 if (warning.missing_noreturn &&
5678 noreturn_candidate &&
5679 !(function->base.modifiers & DM_NORETURN)) {
5680 warningf(&body->base.source_position,
5681 "function '%#T' is candidate for attribute 'noreturn'",
5682 type, entity->base.symbol);
5686 assert(current_parent == NULL);
5687 assert(current_function == function);
5688 assert(current_entity == entity);
5689 current_entity = old_current_entity;
5690 current_function = old_current_function;
5691 label_pop_to(label_stack_top);
5694 assert(current_scope == &function->parameters);
5695 scope_pop(old_scope);
5696 environment_pop_to(top);
5699 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5700 source_position_t *source_position,
5701 const symbol_t *symbol)
5703 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5705 type->bitfield.base_type = base_type;
5706 type->bitfield.size_expression = size;
5709 type_t *skipped_type = skip_typeref(base_type);
5710 if (!is_type_integer(skipped_type)) {
5711 errorf(HERE, "bitfield base type '%T' is not an integer type",
5715 bit_size = get_type_size(base_type) * 8;
5718 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5719 long v = fold_constant_to_int(size);
5720 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5723 errorf(source_position, "negative width in bit-field '%Y'",
5725 } else if (v == 0 && symbol != NULL) {
5726 errorf(source_position, "zero width for bit-field '%Y'",
5728 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5729 errorf(source_position, "width of '%Y' exceeds its type",
5732 type->bitfield.bit_size = v;
5739 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5741 entity_t *iter = compound->members.entities;
5742 for (; iter != NULL; iter = iter->base.next) {
5743 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5746 if (iter->base.symbol == symbol) {
5748 } else if (iter->base.symbol == NULL) {
5749 /* search in anonymous structs and unions */
5750 type_t *type = skip_typeref(iter->declaration.type);
5751 if (is_type_compound(type)) {
5752 if (find_compound_entry(type->compound.compound, symbol)
5763 static void check_deprecated(const source_position_t *source_position,
5764 const entity_t *entity)
5766 if (!warning.deprecated_declarations)
5768 if (!is_declaration(entity))
5770 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5773 char const *const prefix = get_entity_kind_name(entity->kind);
5774 const char *deprecated_string
5775 = get_deprecated_string(entity->declaration.attributes);
5776 if (deprecated_string != NULL) {
5777 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5778 prefix, entity->base.symbol, &entity->base.source_position,
5781 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5782 entity->base.symbol, &entity->base.source_position);
5787 static expression_t *create_select(const source_position_t *pos,
5789 type_qualifiers_t qualifiers,
5792 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5794 check_deprecated(pos, entry);
5796 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5797 select->select.compound = addr;
5798 select->select.compound_entry = entry;
5800 type_t *entry_type = entry->declaration.type;
5801 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5803 /* we always do the auto-type conversions; the & and sizeof parser contains
5804 * code to revert this! */
5805 select->base.type = automatic_type_conversion(res_type);
5806 if (res_type->kind == TYPE_BITFIELD) {
5807 select->base.type = res_type->bitfield.base_type;
5814 * Find entry with symbol in compound. Search anonymous structs and unions and
5815 * creates implicit select expressions for them.
5816 * Returns the adress for the innermost compound.
5818 static expression_t *find_create_select(const source_position_t *pos,
5820 type_qualifiers_t qualifiers,
5821 compound_t *compound, symbol_t *symbol)
5823 entity_t *iter = compound->members.entities;
5824 for (; iter != NULL; iter = iter->base.next) {
5825 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5828 symbol_t *iter_symbol = iter->base.symbol;
5829 if (iter_symbol == NULL) {
5830 type_t *type = iter->declaration.type;
5831 if (type->kind != TYPE_COMPOUND_STRUCT
5832 && type->kind != TYPE_COMPOUND_UNION)
5835 compound_t *sub_compound = type->compound.compound;
5837 if (find_compound_entry(sub_compound, symbol) == NULL)
5840 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5841 sub_addr->base.source_position = *pos;
5842 sub_addr->select.implicit = true;
5843 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5847 if (iter_symbol == symbol) {
5848 return create_select(pos, addr, qualifiers, iter);
5855 static void parse_compound_declarators(compound_t *compound,
5856 const declaration_specifiers_t *specifiers)
5861 if (token.type == ':') {
5862 source_position_t source_position = *HERE;
5865 type_t *base_type = specifiers->type;
5866 expression_t *size = parse_constant_expression();
5868 type_t *type = make_bitfield_type(base_type, size,
5869 &source_position, NULL);
5871 attribute_t *attributes = parse_attributes(NULL);
5872 attribute_t **anchor = &attributes;
5873 while (*anchor != NULL)
5874 anchor = &(*anchor)->next;
5875 *anchor = specifiers->attributes;
5877 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5878 entity->base.namespc = NAMESPACE_NORMAL;
5879 entity->base.source_position = source_position;
5880 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5881 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5882 entity->declaration.type = type;
5883 entity->declaration.attributes = attributes;
5885 if (attributes != NULL) {
5886 handle_entity_attributes(attributes, entity);
5888 append_entity(&compound->members, entity);
5890 entity = parse_declarator(specifiers,
5891 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5892 if (entity->kind == ENTITY_TYPEDEF) {
5893 errorf(&entity->base.source_position,
5894 "typedef not allowed as compound member");
5896 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5898 /* make sure we don't define a symbol multiple times */
5899 symbol_t *symbol = entity->base.symbol;
5900 if (symbol != NULL) {
5901 entity_t *prev = find_compound_entry(compound, symbol);
5903 errorf(&entity->base.source_position,
5904 "multiple declarations of symbol '%Y' (declared %P)",
5905 symbol, &prev->base.source_position);
5909 if (token.type == ':') {
5910 source_position_t source_position = *HERE;
5912 expression_t *size = parse_constant_expression();
5914 type_t *type = entity->declaration.type;
5915 type_t *bitfield_type = make_bitfield_type(type, size,
5916 &source_position, entity->base.symbol);
5918 attribute_t *attributes = parse_attributes(NULL);
5919 entity->declaration.type = bitfield_type;
5920 handle_entity_attributes(attributes, entity);
5922 type_t *orig_type = entity->declaration.type;
5923 type_t *type = skip_typeref(orig_type);
5924 if (is_type_function(type)) {
5925 errorf(&entity->base.source_position,
5926 "compound member '%Y' must not have function type '%T'",
5927 entity->base.symbol, orig_type);
5928 } else if (is_type_incomplete(type)) {
5929 /* §6.7.2.1:16 flexible array member */
5930 if (!is_type_array(type) ||
5931 token.type != ';' ||
5932 look_ahead(1)->type != '}') {
5933 errorf(&entity->base.source_position,
5934 "compound member '%Y' has incomplete type '%T'",
5935 entity->base.symbol, orig_type);
5940 append_entity(&compound->members, entity);
5943 } while (next_if(','));
5944 expect(';', end_error);
5947 anonymous_entity = NULL;
5950 static void parse_compound_type_entries(compound_t *compound)
5953 add_anchor_token('}');
5955 while (token.type != '}') {
5956 if (token.type == T_EOF) {
5957 errorf(HERE, "EOF while parsing struct");
5960 declaration_specifiers_t specifiers;
5961 memset(&specifiers, 0, sizeof(specifiers));
5962 parse_declaration_specifiers(&specifiers);
5964 parse_compound_declarators(compound, &specifiers);
5966 rem_anchor_token('}');
5970 compound->complete = true;
5973 static type_t *parse_typename(void)
5975 declaration_specifiers_t specifiers;
5976 memset(&specifiers, 0, sizeof(specifiers));
5977 parse_declaration_specifiers(&specifiers);
5978 if (specifiers.storage_class != STORAGE_CLASS_NONE
5979 || specifiers.thread_local) {
5980 /* TODO: improve error message, user does probably not know what a
5981 * storage class is...
5983 errorf(HERE, "typename must not have a storage class");
5986 type_t *result = parse_abstract_declarator(specifiers.type);
5994 typedef expression_t* (*parse_expression_function)(void);
5995 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5997 typedef struct expression_parser_function_t expression_parser_function_t;
5998 struct expression_parser_function_t {
5999 parse_expression_function parser;
6000 precedence_t infix_precedence;
6001 parse_expression_infix_function infix_parser;
6004 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6007 * Prints an error message if an expression was expected but not read
6009 static expression_t *expected_expression_error(void)
6011 /* skip the error message if the error token was read */
6012 if (token.type != T_ERROR) {
6013 errorf(HERE, "expected expression, got token %K", &token);
6017 return create_invalid_expression();
6020 static type_t *get_string_type(void)
6022 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6025 static type_t *get_wide_string_type(void)
6027 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6031 * Parse a string constant.
6033 static expression_t *parse_string_literal(void)
6035 source_position_t begin = token.source_position;
6036 string_t res = token.literal;
6037 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6040 while (token.type == T_STRING_LITERAL
6041 || token.type == T_WIDE_STRING_LITERAL) {
6042 warn_string_concat(&token.source_position);
6043 res = concat_strings(&res, &token.literal);
6045 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6048 expression_t *literal;
6050 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6051 literal->base.type = get_wide_string_type();
6053 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6054 literal->base.type = get_string_type();
6056 literal->base.source_position = begin;
6057 literal->literal.value = res;
6063 * Parse a boolean constant.
6065 static expression_t *parse_boolean_literal(bool value)
6067 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6068 literal->base.source_position = token.source_position;
6069 literal->base.type = type_bool;
6070 literal->literal.value.begin = value ? "true" : "false";
6071 literal->literal.value.size = value ? 4 : 5;
6077 static void warn_traditional_suffix(void)
6079 if (!warning.traditional)
6081 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6085 static void check_integer_suffix(void)
6087 symbol_t *suffix = token.symbol;
6091 bool not_traditional = false;
6092 const char *c = suffix->string;
6093 if (*c == 'l' || *c == 'L') {
6096 not_traditional = true;
6098 if (*c == 'u' || *c == 'U') {
6101 } else if (*c == 'u' || *c == 'U') {
6102 not_traditional = true;
6105 } else if (*c == 'u' || *c == 'U') {
6106 not_traditional = true;
6108 if (*c == 'l' || *c == 'L') {
6116 errorf(&token.source_position,
6117 "invalid suffix '%s' on integer constant", suffix->string);
6118 } else if (not_traditional) {
6119 warn_traditional_suffix();
6123 static type_t *check_floatingpoint_suffix(void)
6125 symbol_t *suffix = token.symbol;
6126 type_t *type = type_double;
6130 bool not_traditional = false;
6131 const char *c = suffix->string;
6132 if (*c == 'f' || *c == 'F') {
6135 } else if (*c == 'l' || *c == 'L') {
6137 type = type_long_double;
6140 errorf(&token.source_position,
6141 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6142 } else if (not_traditional) {
6143 warn_traditional_suffix();
6150 * Parse an integer constant.
6152 static expression_t *parse_number_literal(void)
6154 expression_kind_t kind;
6157 switch (token.type) {
6159 kind = EXPR_LITERAL_INTEGER;
6160 check_integer_suffix();
6163 case T_INTEGER_OCTAL:
6164 kind = EXPR_LITERAL_INTEGER_OCTAL;
6165 check_integer_suffix();
6168 case T_INTEGER_HEXADECIMAL:
6169 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6170 check_integer_suffix();
6173 case T_FLOATINGPOINT:
6174 kind = EXPR_LITERAL_FLOATINGPOINT;
6175 type = check_floatingpoint_suffix();
6177 case T_FLOATINGPOINT_HEXADECIMAL:
6178 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6179 type = check_floatingpoint_suffix();
6182 panic("unexpected token type in parse_number_literal");
6185 expression_t *literal = allocate_expression_zero(kind);
6186 literal->base.source_position = token.source_position;
6187 literal->base.type = type;
6188 literal->literal.value = token.literal;
6189 literal->literal.suffix = token.symbol;
6192 /* integer type depends on the size of the number and the size
6193 * representable by the types. The backend/codegeneration has to determine
6196 determine_literal_type(&literal->literal);
6201 * Parse a character constant.
6203 static expression_t *parse_character_constant(void)
6205 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6206 literal->base.source_position = token.source_position;
6207 literal->base.type = c_mode & _CXX ? type_char : type_int;
6208 literal->literal.value = token.literal;
6210 size_t len = literal->literal.value.size;
6212 if (!GNU_MODE && !(c_mode & _C99)) {
6213 errorf(HERE, "more than 1 character in character constant");
6214 } else if (warning.multichar) {
6215 literal->base.type = type_int;
6216 warningf(HERE, "multi-character character constant");
6225 * Parse a wide character constant.
6227 static expression_t *parse_wide_character_constant(void)
6229 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6230 literal->base.source_position = token.source_position;
6231 literal->base.type = type_int;
6232 literal->literal.value = token.literal;
6234 size_t len = wstrlen(&literal->literal.value);
6236 warningf(HERE, "multi-character character constant");
6243 static entity_t *create_implicit_function(symbol_t *symbol,
6244 const source_position_t *source_position)
6246 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6247 ntype->function.return_type = type_int;
6248 ntype->function.unspecified_parameters = true;
6249 ntype->function.linkage = LINKAGE_C;
6250 type_t *type = identify_new_type(ntype);
6252 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6253 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6254 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6255 entity->declaration.type = type;
6256 entity->declaration.implicit = true;
6257 entity->base.namespc = NAMESPACE_NORMAL;
6258 entity->base.symbol = symbol;
6259 entity->base.source_position = *source_position;
6261 if (current_scope != NULL) {
6262 bool strict_prototypes_old = warning.strict_prototypes;
6263 warning.strict_prototypes = false;
6264 record_entity(entity, false);
6265 warning.strict_prototypes = strict_prototypes_old;
6272 * Performs automatic type cast as described in §6.3.2.1.
6274 * @param orig_type the original type
6276 static type_t *automatic_type_conversion(type_t *orig_type)
6278 type_t *type = skip_typeref(orig_type);
6279 if (is_type_array(type)) {
6280 array_type_t *array_type = &type->array;
6281 type_t *element_type = array_type->element_type;
6282 unsigned qualifiers = array_type->base.qualifiers;
6284 return make_pointer_type(element_type, qualifiers);
6287 if (is_type_function(type)) {
6288 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6295 * reverts the automatic casts of array to pointer types and function
6296 * to function-pointer types as defined §6.3.2.1
6298 type_t *revert_automatic_type_conversion(const expression_t *expression)
6300 switch (expression->kind) {
6301 case EXPR_REFERENCE: {
6302 entity_t *entity = expression->reference.entity;
6303 if (is_declaration(entity)) {
6304 return entity->declaration.type;
6305 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6306 return entity->enum_value.enum_type;
6308 panic("no declaration or enum in reference");
6313 entity_t *entity = expression->select.compound_entry;
6314 assert(is_declaration(entity));
6315 type_t *type = entity->declaration.type;
6316 return get_qualified_type(type,
6317 expression->base.type->base.qualifiers);
6320 case EXPR_UNARY_DEREFERENCE: {
6321 const expression_t *const value = expression->unary.value;
6322 type_t *const type = skip_typeref(value->base.type);
6323 if (!is_type_pointer(type))
6324 return type_error_type;
6325 return type->pointer.points_to;
6328 case EXPR_ARRAY_ACCESS: {
6329 const expression_t *array_ref = expression->array_access.array_ref;
6330 type_t *type_left = skip_typeref(array_ref->base.type);
6331 if (!is_type_pointer(type_left))
6332 return type_error_type;
6333 return type_left->pointer.points_to;
6336 case EXPR_STRING_LITERAL: {
6337 size_t size = expression->string_literal.value.size;
6338 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6341 case EXPR_WIDE_STRING_LITERAL: {
6342 size_t size = wstrlen(&expression->string_literal.value);
6343 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6346 case EXPR_COMPOUND_LITERAL:
6347 return expression->compound_literal.type;
6352 return expression->base.type;
6356 * Find an entity matching a symbol in a scope.
6357 * Uses current scope if scope is NULL
6359 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6360 namespace_tag_t namespc)
6362 if (scope == NULL) {
6363 return get_entity(symbol, namespc);
6366 /* we should optimize here, if scope grows above a certain size we should
6367 construct a hashmap here... */
6368 entity_t *entity = scope->entities;
6369 for ( ; entity != NULL; entity = entity->base.next) {
6370 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6377 static entity_t *parse_qualified_identifier(void)
6379 /* namespace containing the symbol */
6381 source_position_t pos;
6382 const scope_t *lookup_scope = NULL;
6384 if (next_if(T_COLONCOLON))
6385 lookup_scope = &unit->scope;
6389 if (token.type != T_IDENTIFIER) {
6390 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6391 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6393 symbol = token.symbol;
6398 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6400 if (!next_if(T_COLONCOLON))
6403 switch (entity->kind) {
6404 case ENTITY_NAMESPACE:
6405 lookup_scope = &entity->namespacee.members;
6410 lookup_scope = &entity->compound.members;
6413 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6414 symbol, get_entity_kind_name(entity->kind));
6419 if (entity == NULL) {
6420 if (!strict_mode && token.type == '(') {
6421 /* an implicitly declared function */
6422 if (warning.error_implicit_function_declaration) {
6423 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6424 } else if (warning.implicit_function_declaration) {
6425 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6428 entity = create_implicit_function(symbol, &pos);
6430 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6431 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6438 /* skip further qualifications */
6439 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6441 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6444 static expression_t *parse_reference(void)
6446 source_position_t const pos = token.source_position;
6447 entity_t *const entity = parse_qualified_identifier();
6450 if (is_declaration(entity)) {
6451 orig_type = entity->declaration.type;
6452 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6453 orig_type = entity->enum_value.enum_type;
6455 panic("expected declaration or enum value in reference");
6458 /* we always do the auto-type conversions; the & and sizeof parser contains
6459 * code to revert this! */
6460 type_t *type = automatic_type_conversion(orig_type);
6462 expression_kind_t kind = EXPR_REFERENCE;
6463 if (entity->kind == ENTITY_ENUM_VALUE)
6464 kind = EXPR_REFERENCE_ENUM_VALUE;
6466 expression_t *expression = allocate_expression_zero(kind);
6467 expression->base.source_position = pos;
6468 expression->base.type = type;
6469 expression->reference.entity = entity;
6471 /* this declaration is used */
6472 if (is_declaration(entity)) {
6473 entity->declaration.used = true;
6476 if (entity->base.parent_scope != file_scope
6477 && (current_function != NULL
6478 && entity->base.parent_scope->depth < current_function->parameters.depth)
6479 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6480 if (entity->kind == ENTITY_VARIABLE) {
6481 /* access of a variable from an outer function */
6482 entity->variable.address_taken = true;
6483 } else if (entity->kind == ENTITY_PARAMETER) {
6484 entity->parameter.address_taken = true;
6486 current_function->need_closure = true;
6489 check_deprecated(HERE, entity);
6491 if (warning.init_self && entity == current_init_decl && !in_type_prop
6492 && entity->kind == ENTITY_VARIABLE) {
6493 current_init_decl = NULL;
6494 warningf(&pos, "variable '%#T' is initialized by itself",
6495 entity->declaration.type, entity->base.symbol);
6501 static bool semantic_cast(expression_t *cast)
6503 expression_t *expression = cast->unary.value;
6504 type_t *orig_dest_type = cast->base.type;
6505 type_t *orig_type_right = expression->base.type;
6506 type_t const *dst_type = skip_typeref(orig_dest_type);
6507 type_t const *src_type = skip_typeref(orig_type_right);
6508 source_position_t const *pos = &cast->base.source_position;
6510 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6511 if (dst_type == type_void)
6514 /* only integer and pointer can be casted to pointer */
6515 if (is_type_pointer(dst_type) &&
6516 !is_type_pointer(src_type) &&
6517 !is_type_integer(src_type) &&
6518 is_type_valid(src_type)) {
6519 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6523 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6524 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6528 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6529 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6533 if (warning.cast_qual &&
6534 is_type_pointer(src_type) &&
6535 is_type_pointer(dst_type)) {
6536 type_t *src = skip_typeref(src_type->pointer.points_to);
6537 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6538 unsigned missing_qualifiers =
6539 src->base.qualifiers & ~dst->base.qualifiers;
6540 if (missing_qualifiers != 0) {
6542 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6543 missing_qualifiers, orig_type_right);
6549 static expression_t *parse_compound_literal(type_t *type)
6551 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6553 parse_initializer_env_t env;
6556 env.must_be_constant = false;
6557 initializer_t *initializer = parse_initializer(&env);
6560 expression->compound_literal.initializer = initializer;
6561 expression->compound_literal.type = type;
6562 expression->base.type = automatic_type_conversion(type);
6568 * Parse a cast expression.
6570 static expression_t *parse_cast(void)
6572 source_position_t source_position = token.source_position;
6575 add_anchor_token(')');
6577 type_t *type = parse_typename();
6579 rem_anchor_token(')');
6580 expect(')', end_error);
6582 if (token.type == '{') {
6583 return parse_compound_literal(type);
6586 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6587 cast->base.source_position = source_position;
6589 expression_t *value = parse_subexpression(PREC_CAST);
6590 cast->base.type = type;
6591 cast->unary.value = value;
6593 if (! semantic_cast(cast)) {
6594 /* TODO: record the error in the AST. else it is impossible to detect it */
6599 return create_invalid_expression();
6603 * Parse a statement expression.
6605 static expression_t *parse_statement_expression(void)
6607 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6610 add_anchor_token(')');
6612 statement_t *statement = parse_compound_statement(true);
6613 statement->compound.stmt_expr = true;
6614 expression->statement.statement = statement;
6616 /* find last statement and use its type */
6617 type_t *type = type_void;
6618 const statement_t *stmt = statement->compound.statements;
6620 while (stmt->base.next != NULL)
6621 stmt = stmt->base.next;
6623 if (stmt->kind == STATEMENT_EXPRESSION) {
6624 type = stmt->expression.expression->base.type;
6626 } else if (warning.other) {
6627 warningf(&expression->base.source_position, "empty statement expression ({})");
6629 expression->base.type = type;
6631 rem_anchor_token(')');
6632 expect(')', end_error);
6639 * Parse a parenthesized expression.
6641 static expression_t *parse_parenthesized_expression(void)
6643 token_t const* const la1 = look_ahead(1);
6644 switch (la1->type) {
6646 /* gcc extension: a statement expression */
6647 return parse_statement_expression();
6650 if (is_typedef_symbol(la1->symbol)) {
6653 return parse_cast();
6658 add_anchor_token(')');
6659 expression_t *result = parse_expression();
6660 result->base.parenthesized = true;
6661 rem_anchor_token(')');
6662 expect(')', end_error);
6668 static expression_t *parse_function_keyword(void)
6672 if (current_function == NULL) {
6673 errorf(HERE, "'__func__' used outside of a function");
6676 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6677 expression->base.type = type_char_ptr;
6678 expression->funcname.kind = FUNCNAME_FUNCTION;
6685 static expression_t *parse_pretty_function_keyword(void)
6687 if (current_function == NULL) {
6688 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6691 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6692 expression->base.type = type_char_ptr;
6693 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6695 eat(T___PRETTY_FUNCTION__);
6700 static expression_t *parse_funcsig_keyword(void)
6702 if (current_function == NULL) {
6703 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6706 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6707 expression->base.type = type_char_ptr;
6708 expression->funcname.kind = FUNCNAME_FUNCSIG;
6715 static expression_t *parse_funcdname_keyword(void)
6717 if (current_function == NULL) {
6718 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6721 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6722 expression->base.type = type_char_ptr;
6723 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6725 eat(T___FUNCDNAME__);
6730 static designator_t *parse_designator(void)
6732 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6733 result->source_position = *HERE;
6735 if (token.type != T_IDENTIFIER) {
6736 parse_error_expected("while parsing member designator",
6737 T_IDENTIFIER, NULL);
6740 result->symbol = token.symbol;
6743 designator_t *last_designator = result;
6746 if (token.type != T_IDENTIFIER) {
6747 parse_error_expected("while parsing member designator",
6748 T_IDENTIFIER, NULL);
6751 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6752 designator->source_position = *HERE;
6753 designator->symbol = token.symbol;
6756 last_designator->next = designator;
6757 last_designator = designator;
6761 add_anchor_token(']');
6762 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6763 designator->source_position = *HERE;
6764 designator->array_index = parse_expression();
6765 rem_anchor_token(']');
6766 expect(']', end_error);
6767 if (designator->array_index == NULL) {
6771 last_designator->next = designator;
6772 last_designator = designator;
6784 * Parse the __builtin_offsetof() expression.
6786 static expression_t *parse_offsetof(void)
6788 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6789 expression->base.type = type_size_t;
6791 eat(T___builtin_offsetof);
6793 expect('(', end_error);
6794 add_anchor_token(',');
6795 type_t *type = parse_typename();
6796 rem_anchor_token(',');
6797 expect(',', end_error);
6798 add_anchor_token(')');
6799 designator_t *designator = parse_designator();
6800 rem_anchor_token(')');
6801 expect(')', end_error);
6803 expression->offsetofe.type = type;
6804 expression->offsetofe.designator = designator;
6807 memset(&path, 0, sizeof(path));
6808 path.top_type = type;
6809 path.path = NEW_ARR_F(type_path_entry_t, 0);
6811 descend_into_subtype(&path);
6813 if (!walk_designator(&path, designator, true)) {
6814 return create_invalid_expression();
6817 DEL_ARR_F(path.path);
6821 return create_invalid_expression();
6825 * Parses a _builtin_va_start() expression.
6827 static expression_t *parse_va_start(void)
6829 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6831 eat(T___builtin_va_start);
6833 expect('(', end_error);
6834 add_anchor_token(',');
6835 expression->va_starte.ap = parse_assignment_expression();
6836 rem_anchor_token(',');
6837 expect(',', end_error);
6838 expression_t *const expr = parse_assignment_expression();
6839 if (expr->kind == EXPR_REFERENCE) {
6840 entity_t *const entity = expr->reference.entity;
6841 if (!current_function->base.type->function.variadic) {
6842 errorf(&expr->base.source_position,
6843 "'va_start' used in non-variadic function");
6844 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6845 entity->base.next != NULL ||
6846 entity->kind != ENTITY_PARAMETER) {
6847 errorf(&expr->base.source_position,
6848 "second argument of 'va_start' must be last parameter of the current function");
6850 expression->va_starte.parameter = &entity->variable;
6852 expect(')', end_error);
6855 expect(')', end_error);
6857 return create_invalid_expression();
6861 * Parses a __builtin_va_arg() expression.
6863 static expression_t *parse_va_arg(void)
6865 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6867 eat(T___builtin_va_arg);
6869 expect('(', end_error);
6871 ap.expression = parse_assignment_expression();
6872 expression->va_arge.ap = ap.expression;
6873 check_call_argument(type_valist, &ap, 1);
6875 expect(',', end_error);
6876 expression->base.type = parse_typename();
6877 expect(')', end_error);
6881 return create_invalid_expression();
6885 * Parses a __builtin_va_copy() expression.
6887 static expression_t *parse_va_copy(void)
6889 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6891 eat(T___builtin_va_copy);
6893 expect('(', end_error);
6894 expression_t *dst = parse_assignment_expression();
6895 assign_error_t error = semantic_assign(type_valist, dst);
6896 report_assign_error(error, type_valist, dst, "call argument 1",
6897 &dst->base.source_position);
6898 expression->va_copye.dst = dst;
6900 expect(',', end_error);
6902 call_argument_t src;
6903 src.expression = parse_assignment_expression();
6904 check_call_argument(type_valist, &src, 2);
6905 expression->va_copye.src = src.expression;
6906 expect(')', end_error);
6910 return create_invalid_expression();
6914 * Parses a __builtin_constant_p() expression.
6916 static expression_t *parse_builtin_constant(void)
6918 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6920 eat(T___builtin_constant_p);
6922 expect('(', end_error);
6923 add_anchor_token(')');
6924 expression->builtin_constant.value = parse_assignment_expression();
6925 rem_anchor_token(')');
6926 expect(')', end_error);
6927 expression->base.type = type_int;
6931 return create_invalid_expression();
6935 * Parses a __builtin_types_compatible_p() expression.
6937 static expression_t *parse_builtin_types_compatible(void)
6939 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6941 eat(T___builtin_types_compatible_p);
6943 expect('(', end_error);
6944 add_anchor_token(')');
6945 add_anchor_token(',');
6946 expression->builtin_types_compatible.left = parse_typename();
6947 rem_anchor_token(',');
6948 expect(',', end_error);
6949 expression->builtin_types_compatible.right = parse_typename();
6950 rem_anchor_token(')');
6951 expect(')', end_error);
6952 expression->base.type = type_int;
6956 return create_invalid_expression();
6960 * Parses a __builtin_is_*() compare expression.
6962 static expression_t *parse_compare_builtin(void)
6964 expression_t *expression;
6966 switch (token.type) {
6967 case T___builtin_isgreater:
6968 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6970 case T___builtin_isgreaterequal:
6971 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6973 case T___builtin_isless:
6974 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6976 case T___builtin_islessequal:
6977 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6979 case T___builtin_islessgreater:
6980 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6982 case T___builtin_isunordered:
6983 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6986 internal_errorf(HERE, "invalid compare builtin found");
6988 expression->base.source_position = *HERE;
6991 expect('(', end_error);
6992 expression->binary.left = parse_assignment_expression();
6993 expect(',', end_error);
6994 expression->binary.right = parse_assignment_expression();
6995 expect(')', end_error);
6997 type_t *const orig_type_left = expression->binary.left->base.type;
6998 type_t *const orig_type_right = expression->binary.right->base.type;
7000 type_t *const type_left = skip_typeref(orig_type_left);
7001 type_t *const type_right = skip_typeref(orig_type_right);
7002 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7003 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7004 type_error_incompatible("invalid operands in comparison",
7005 &expression->base.source_position, orig_type_left, orig_type_right);
7008 semantic_comparison(&expression->binary);
7013 return create_invalid_expression();
7017 * Parses a MS assume() expression.
7019 static expression_t *parse_assume(void)
7021 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7025 expect('(', end_error);
7026 add_anchor_token(')');
7027 expression->unary.value = parse_assignment_expression();
7028 rem_anchor_token(')');
7029 expect(')', end_error);
7031 expression->base.type = type_void;
7034 return create_invalid_expression();
7038 * Return the declaration for a given label symbol or create a new one.
7040 * @param symbol the symbol of the label
7042 static label_t *get_label(symbol_t *symbol)
7045 assert(current_function != NULL);
7047 label = get_entity(symbol, NAMESPACE_LABEL);
7048 /* if we found a local label, we already created the declaration */
7049 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7050 if (label->base.parent_scope != current_scope) {
7051 assert(label->base.parent_scope->depth < current_scope->depth);
7052 current_function->goto_to_outer = true;
7054 return &label->label;
7057 label = get_entity(symbol, NAMESPACE_LABEL);
7058 /* if we found a label in the same function, then we already created the
7061 && label->base.parent_scope == ¤t_function->parameters) {
7062 return &label->label;
7065 /* otherwise we need to create a new one */
7066 label = allocate_entity_zero(ENTITY_LABEL);
7067 label->base.namespc = NAMESPACE_LABEL;
7068 label->base.symbol = symbol;
7072 return &label->label;
7076 * Parses a GNU && label address expression.
7078 static expression_t *parse_label_address(void)
7080 source_position_t source_position = token.source_position;
7082 if (token.type != T_IDENTIFIER) {
7083 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7086 symbol_t *symbol = token.symbol;
7089 label_t *label = get_label(symbol);
7091 label->address_taken = true;
7093 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7094 expression->base.source_position = source_position;
7096 /* label address is threaten as a void pointer */
7097 expression->base.type = type_void_ptr;
7098 expression->label_address.label = label;
7101 return create_invalid_expression();
7105 * Parse a microsoft __noop expression.
7107 static expression_t *parse_noop_expression(void)
7109 /* the result is a (int)0 */
7110 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7111 literal->base.type = type_int;
7112 literal->base.source_position = token.source_position;
7113 literal->literal.value.begin = "__noop";
7114 literal->literal.value.size = 6;
7118 if (token.type == '(') {
7119 /* parse arguments */
7121 add_anchor_token(')');
7122 add_anchor_token(',');
7124 if (token.type != ')') do {
7125 (void)parse_assignment_expression();
7126 } while (next_if(','));
7128 rem_anchor_token(',');
7129 rem_anchor_token(')');
7130 expect(')', end_error);
7137 * Parses a primary expression.
7139 static expression_t *parse_primary_expression(void)
7141 switch (token.type) {
7142 case T_false: return parse_boolean_literal(false);
7143 case T_true: return parse_boolean_literal(true);
7145 case T_INTEGER_OCTAL:
7146 case T_INTEGER_HEXADECIMAL:
7147 case T_FLOATINGPOINT:
7148 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7149 case T_CHARACTER_CONSTANT: return parse_character_constant();
7150 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7151 case T_STRING_LITERAL:
7152 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7153 case T___FUNCTION__:
7154 case T___func__: return parse_function_keyword();
7155 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7156 case T___FUNCSIG__: return parse_funcsig_keyword();
7157 case T___FUNCDNAME__: return parse_funcdname_keyword();
7158 case T___builtin_offsetof: return parse_offsetof();
7159 case T___builtin_va_start: return parse_va_start();
7160 case T___builtin_va_arg: return parse_va_arg();
7161 case T___builtin_va_copy: return parse_va_copy();
7162 case T___builtin_isgreater:
7163 case T___builtin_isgreaterequal:
7164 case T___builtin_isless:
7165 case T___builtin_islessequal:
7166 case T___builtin_islessgreater:
7167 case T___builtin_isunordered: return parse_compare_builtin();
7168 case T___builtin_constant_p: return parse_builtin_constant();
7169 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7170 case T__assume: return parse_assume();
7173 return parse_label_address();
7176 case '(': return parse_parenthesized_expression();
7177 case T___noop: return parse_noop_expression();
7179 /* Gracefully handle type names while parsing expressions. */
7181 return parse_reference();
7183 if (!is_typedef_symbol(token.symbol)) {
7184 return parse_reference();
7188 source_position_t const pos = *HERE;
7189 type_t const *const type = parse_typename();
7190 errorf(&pos, "encountered type '%T' while parsing expression", type);
7191 return create_invalid_expression();
7195 errorf(HERE, "unexpected token %K, expected an expression", &token);
7197 return create_invalid_expression();
7200 static expression_t *parse_array_expression(expression_t *left)
7202 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7203 array_access_expression_t *const arr = &expr->array_access;
7206 add_anchor_token(']');
7208 expression_t *const inside = parse_expression();
7210 type_t *const orig_type_left = left->base.type;
7211 type_t *const orig_type_inside = inside->base.type;
7213 type_t *const type_left = skip_typeref(orig_type_left);
7214 type_t *const type_inside = skip_typeref(orig_type_inside);
7220 if (is_type_pointer(type_left)) {
7223 idx_type = type_inside;
7224 res_type = type_left->pointer.points_to;
7226 } else if (is_type_pointer(type_inside)) {
7227 arr->flipped = true;
7230 idx_type = type_left;
7231 res_type = type_inside->pointer.points_to;
7233 res_type = automatic_type_conversion(res_type);
7234 if (!is_type_integer(idx_type)) {
7235 errorf(&idx->base.source_position, "array subscript must have integer type");
7236 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR) && warning.char_subscripts) {
7237 warningf(&idx->base.source_position, "array subscript has char type");
7240 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7242 "array access on object with non-pointer types '%T', '%T'",
7243 orig_type_left, orig_type_inside);
7245 res_type = type_error_type;
7250 arr->array_ref = ref;
7252 arr->base.type = res_type;
7254 rem_anchor_token(']');
7255 expect(']', end_error);
7260 static expression_t *parse_typeprop(expression_kind_t const kind)
7262 expression_t *tp_expression = allocate_expression_zero(kind);
7263 tp_expression->base.type = type_size_t;
7265 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7267 /* we only refer to a type property, mark this case */
7268 bool old = in_type_prop;
7269 in_type_prop = true;
7272 expression_t *expression;
7273 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7275 add_anchor_token(')');
7276 orig_type = parse_typename();
7277 rem_anchor_token(')');
7278 expect(')', end_error);
7280 if (token.type == '{') {
7281 /* It was not sizeof(type) after all. It is sizeof of an expression
7282 * starting with a compound literal */
7283 expression = parse_compound_literal(orig_type);
7284 goto typeprop_expression;
7287 expression = parse_subexpression(PREC_UNARY);
7289 typeprop_expression:
7290 tp_expression->typeprop.tp_expression = expression;
7292 orig_type = revert_automatic_type_conversion(expression);
7293 expression->base.type = orig_type;
7296 tp_expression->typeprop.type = orig_type;
7297 type_t const* const type = skip_typeref(orig_type);
7298 char const* wrong_type = NULL;
7299 if (is_type_incomplete(type)) {
7300 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7301 wrong_type = "incomplete";
7302 } else if (type->kind == TYPE_FUNCTION) {
7304 /* function types are allowed (and return 1) */
7305 if (warning.other) {
7306 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7307 warningf(&tp_expression->base.source_position,
7308 "%s expression with function argument returns invalid result", what);
7311 wrong_type = "function";
7314 if (is_type_incomplete(type))
7315 wrong_type = "incomplete";
7317 if (type->kind == TYPE_BITFIELD)
7318 wrong_type = "bitfield";
7320 if (wrong_type != NULL) {
7321 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7322 errorf(&tp_expression->base.source_position,
7323 "operand of %s expression must not be of %s type '%T'",
7324 what, wrong_type, orig_type);
7329 return tp_expression;
7332 static expression_t *parse_sizeof(void)
7334 return parse_typeprop(EXPR_SIZEOF);
7337 static expression_t *parse_alignof(void)
7339 return parse_typeprop(EXPR_ALIGNOF);
7342 static expression_t *parse_select_expression(expression_t *addr)
7344 assert(token.type == '.' || token.type == T_MINUSGREATER);
7345 bool select_left_arrow = (token.type == T_MINUSGREATER);
7346 source_position_t const pos = *HERE;
7349 if (token.type != T_IDENTIFIER) {
7350 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7351 return create_invalid_expression();
7353 symbol_t *symbol = token.symbol;
7356 type_t *const orig_type = addr->base.type;
7357 type_t *const type = skip_typeref(orig_type);
7360 bool saw_error = false;
7361 if (is_type_pointer(type)) {
7362 if (!select_left_arrow) {
7364 "request for member '%Y' in something not a struct or union, but '%T'",
7368 type_left = skip_typeref(type->pointer.points_to);
7370 if (select_left_arrow && is_type_valid(type)) {
7371 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7377 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7378 type_left->kind != TYPE_COMPOUND_UNION) {
7380 if (is_type_valid(type_left) && !saw_error) {
7382 "request for member '%Y' in something not a struct or union, but '%T'",
7385 return create_invalid_expression();
7388 compound_t *compound = type_left->compound.compound;
7389 if (!compound->complete) {
7390 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7392 return create_invalid_expression();
7395 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7396 expression_t *result =
7397 find_create_select(&pos, addr, qualifiers, compound, symbol);
7399 if (result == NULL) {
7400 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7401 return create_invalid_expression();
7407 static void check_call_argument(type_t *expected_type,
7408 call_argument_t *argument, unsigned pos)
7410 type_t *expected_type_skip = skip_typeref(expected_type);
7411 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7412 expression_t *arg_expr = argument->expression;
7413 type_t *arg_type = skip_typeref(arg_expr->base.type);
7415 /* handle transparent union gnu extension */
7416 if (is_type_union(expected_type_skip)
7417 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7418 compound_t *union_decl = expected_type_skip->compound.compound;
7419 type_t *best_type = NULL;
7420 entity_t *entry = union_decl->members.entities;
7421 for ( ; entry != NULL; entry = entry->base.next) {
7422 assert(is_declaration(entry));
7423 type_t *decl_type = entry->declaration.type;
7424 error = semantic_assign(decl_type, arg_expr);
7425 if (error == ASSIGN_ERROR_INCOMPATIBLE
7426 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7429 if (error == ASSIGN_SUCCESS) {
7430 best_type = decl_type;
7431 } else if (best_type == NULL) {
7432 best_type = decl_type;
7436 if (best_type != NULL) {
7437 expected_type = best_type;
7441 error = semantic_assign(expected_type, arg_expr);
7442 argument->expression = create_implicit_cast(arg_expr, expected_type);
7444 if (error != ASSIGN_SUCCESS) {
7445 /* report exact scope in error messages (like "in argument 3") */
7447 snprintf(buf, sizeof(buf), "call argument %u", pos);
7448 report_assign_error(error, expected_type, arg_expr, buf,
7449 &arg_expr->base.source_position);
7450 } else if (warning.traditional || warning.conversion) {
7451 type_t *const promoted_type = get_default_promoted_type(arg_type);
7452 if (!types_compatible(expected_type_skip, promoted_type) &&
7453 !types_compatible(expected_type_skip, type_void_ptr) &&
7454 !types_compatible(type_void_ptr, promoted_type)) {
7455 /* Deliberately show the skipped types in this warning */
7456 warningf(&arg_expr->base.source_position,
7457 "passing call argument %u as '%T' rather than '%T' due to prototype",
7458 pos, expected_type_skip, promoted_type);
7464 * Handle the semantic restrictions of builtin calls
7466 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7467 switch (call->function->reference.entity->function.btk) {
7468 case bk_gnu_builtin_return_address:
7469 case bk_gnu_builtin_frame_address: {
7470 /* argument must be constant */
7471 call_argument_t *argument = call->arguments;
7473 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7474 errorf(&call->base.source_position,
7475 "argument of '%Y' must be a constant expression",
7476 call->function->reference.entity->base.symbol);
7480 case bk_gnu_builtin_object_size:
7481 if (call->arguments == NULL)
7484 call_argument_t *arg = call->arguments->next;
7485 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7486 errorf(&call->base.source_position,
7487 "second argument of '%Y' must be a constant expression",
7488 call->function->reference.entity->base.symbol);
7491 case bk_gnu_builtin_prefetch:
7492 /* second and third argument must be constant if existent */
7493 if (call->arguments == NULL)
7495 call_argument_t *rw = call->arguments->next;
7496 call_argument_t *locality = NULL;
7499 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7500 errorf(&call->base.source_position,
7501 "second argument of '%Y' must be a constant expression",
7502 call->function->reference.entity->base.symbol);
7504 locality = rw->next;
7506 if (locality != NULL) {
7507 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7508 errorf(&call->base.source_position,
7509 "third argument of '%Y' must be a constant expression",
7510 call->function->reference.entity->base.symbol);
7512 locality = rw->next;
7521 * Parse a call expression, ie. expression '( ... )'.
7523 * @param expression the function address
7525 static expression_t *parse_call_expression(expression_t *expression)
7527 expression_t *result = allocate_expression_zero(EXPR_CALL);
7528 call_expression_t *call = &result->call;
7529 call->function = expression;
7531 type_t *const orig_type = expression->base.type;
7532 type_t *const type = skip_typeref(orig_type);
7534 function_type_t *function_type = NULL;
7535 if (is_type_pointer(type)) {
7536 type_t *const to_type = skip_typeref(type->pointer.points_to);
7538 if (is_type_function(to_type)) {
7539 function_type = &to_type->function;
7540 call->base.type = function_type->return_type;
7544 if (function_type == NULL && is_type_valid(type)) {
7546 "called object '%E' (type '%T') is not a pointer to a function",
7547 expression, orig_type);
7550 /* parse arguments */
7552 add_anchor_token(')');
7553 add_anchor_token(',');
7555 if (token.type != ')') {
7556 call_argument_t **anchor = &call->arguments;
7558 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7559 argument->expression = parse_assignment_expression();
7562 anchor = &argument->next;
7563 } while (next_if(','));
7565 rem_anchor_token(',');
7566 rem_anchor_token(')');
7567 expect(')', end_error);
7569 if (function_type == NULL)
7572 /* check type and count of call arguments */
7573 function_parameter_t *parameter = function_type->parameters;
7574 call_argument_t *argument = call->arguments;
7575 if (!function_type->unspecified_parameters) {
7576 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7577 parameter = parameter->next, argument = argument->next) {
7578 check_call_argument(parameter->type, argument, ++pos);
7581 if (parameter != NULL) {
7582 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7583 } else if (argument != NULL && !function_type->variadic) {
7584 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7588 /* do default promotion for other arguments */
7589 for (; argument != NULL; argument = argument->next) {
7590 type_t *type = argument->expression->base.type;
7591 if (!is_type_object(skip_typeref(type))) {
7592 errorf(&argument->expression->base.source_position,
7593 "call argument '%E' must not be void", argument->expression);
7596 type = get_default_promoted_type(type);
7598 argument->expression
7599 = create_implicit_cast(argument->expression, type);
7604 if (warning.aggregate_return &&
7605 is_type_compound(skip_typeref(function_type->return_type))) {
7606 warningf(&expression->base.source_position,
7607 "function call has aggregate value");
7610 if (expression->kind == EXPR_REFERENCE) {
7611 reference_expression_t *reference = &expression->reference;
7612 if (reference->entity->kind == ENTITY_FUNCTION &&
7613 reference->entity->function.btk != bk_none)
7614 handle_builtin_argument_restrictions(call);
7621 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7623 static bool same_compound_type(const type_t *type1, const type_t *type2)
7626 is_type_compound(type1) &&
7627 type1->kind == type2->kind &&
7628 type1->compound.compound == type2->compound.compound;
7631 static expression_t const *get_reference_address(expression_t const *expr)
7633 bool regular_take_address = true;
7635 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7636 expr = expr->unary.value;
7638 regular_take_address = false;
7641 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7644 expr = expr->unary.value;
7647 if (expr->kind != EXPR_REFERENCE)
7650 /* special case for functions which are automatically converted to a
7651 * pointer to function without an extra TAKE_ADDRESS operation */
7652 if (!regular_take_address &&
7653 expr->reference.entity->kind != ENTITY_FUNCTION) {
7660 static void warn_reference_address_as_bool(expression_t const* expr)
7662 if (!warning.address)
7665 expr = get_reference_address(expr);
7667 warningf(&expr->base.source_position,
7668 "the address of '%Y' will always evaluate as 'true'",
7669 expr->reference.entity->base.symbol);
7673 static void warn_assignment_in_condition(const expression_t *const expr)
7675 if (!warning.parentheses)
7677 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7679 if (expr->base.parenthesized)
7681 warningf(&expr->base.source_position,
7682 "suggest parentheses around assignment used as truth value");
7685 static void semantic_condition(expression_t const *const expr,
7686 char const *const context)
7688 type_t *const type = skip_typeref(expr->base.type);
7689 if (is_type_scalar(type)) {
7690 warn_reference_address_as_bool(expr);
7691 warn_assignment_in_condition(expr);
7692 } else if (is_type_valid(type)) {
7693 errorf(&expr->base.source_position,
7694 "%s must have scalar type", context);
7699 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7701 * @param expression the conditional expression
7703 static expression_t *parse_conditional_expression(expression_t *expression)
7705 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7707 conditional_expression_t *conditional = &result->conditional;
7708 conditional->condition = expression;
7711 add_anchor_token(':');
7713 /* §6.5.15:2 The first operand shall have scalar type. */
7714 semantic_condition(expression, "condition of conditional operator");
7716 expression_t *true_expression = expression;
7717 bool gnu_cond = false;
7718 if (GNU_MODE && token.type == ':') {
7721 true_expression = parse_expression();
7723 rem_anchor_token(':');
7724 expect(':', end_error);
7726 expression_t *false_expression =
7727 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7729 type_t *const orig_true_type = true_expression->base.type;
7730 type_t *const orig_false_type = false_expression->base.type;
7731 type_t *const true_type = skip_typeref(orig_true_type);
7732 type_t *const false_type = skip_typeref(orig_false_type);
7735 type_t *result_type;
7736 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7737 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7738 /* ISO/IEC 14882:1998(E) §5.16:2 */
7739 if (true_expression->kind == EXPR_UNARY_THROW) {
7740 result_type = false_type;
7741 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7742 result_type = true_type;
7744 if (warning.other && (
7745 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7746 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7748 warningf(&conditional->base.source_position,
7749 "ISO C forbids conditional expression with only one void side");
7751 result_type = type_void;
7753 } else if (is_type_arithmetic(true_type)
7754 && is_type_arithmetic(false_type)) {
7755 result_type = semantic_arithmetic(true_type, false_type);
7756 } else if (same_compound_type(true_type, false_type)) {
7757 /* just take 1 of the 2 types */
7758 result_type = true_type;
7759 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7760 type_t *pointer_type;
7762 expression_t *other_expression;
7763 if (is_type_pointer(true_type) &&
7764 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7765 pointer_type = true_type;
7766 other_type = false_type;
7767 other_expression = false_expression;
7769 pointer_type = false_type;
7770 other_type = true_type;
7771 other_expression = true_expression;
7774 if (is_null_pointer_constant(other_expression)) {
7775 result_type = pointer_type;
7776 } else if (is_type_pointer(other_type)) {
7777 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7778 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7781 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7782 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7784 } else if (types_compatible(get_unqualified_type(to1),
7785 get_unqualified_type(to2))) {
7788 if (warning.other) {
7789 warningf(&conditional->base.source_position,
7790 "pointer types '%T' and '%T' in conditional expression are incompatible",
7791 true_type, false_type);
7796 type_t *const type =
7797 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7798 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7799 } else if (is_type_integer(other_type)) {
7800 if (warning.other) {
7801 warningf(&conditional->base.source_position,
7802 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7804 result_type = pointer_type;
7806 if (is_type_valid(other_type)) {
7807 type_error_incompatible("while parsing conditional",
7808 &expression->base.source_position, true_type, false_type);
7810 result_type = type_error_type;
7813 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7814 type_error_incompatible("while parsing conditional",
7815 &conditional->base.source_position, true_type,
7818 result_type = type_error_type;
7821 conditional->true_expression
7822 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7823 conditional->false_expression
7824 = create_implicit_cast(false_expression, result_type);
7825 conditional->base.type = result_type;
7830 * Parse an extension expression.
7832 static expression_t *parse_extension(void)
7834 eat(T___extension__);
7836 bool old_gcc_extension = in_gcc_extension;
7837 in_gcc_extension = true;
7838 expression_t *expression = parse_subexpression(PREC_UNARY);
7839 in_gcc_extension = old_gcc_extension;
7844 * Parse a __builtin_classify_type() expression.
7846 static expression_t *parse_builtin_classify_type(void)
7848 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7849 result->base.type = type_int;
7851 eat(T___builtin_classify_type);
7853 expect('(', end_error);
7854 add_anchor_token(')');
7855 expression_t *expression = parse_expression();
7856 rem_anchor_token(')');
7857 expect(')', end_error);
7858 result->classify_type.type_expression = expression;
7862 return create_invalid_expression();
7866 * Parse a delete expression
7867 * ISO/IEC 14882:1998(E) §5.3.5
7869 static expression_t *parse_delete(void)
7871 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7872 result->base.type = type_void;
7877 result->kind = EXPR_UNARY_DELETE_ARRAY;
7878 expect(']', end_error);
7882 expression_t *const value = parse_subexpression(PREC_CAST);
7883 result->unary.value = value;
7885 type_t *const type = skip_typeref(value->base.type);
7886 if (!is_type_pointer(type)) {
7887 if (is_type_valid(type)) {
7888 errorf(&value->base.source_position,
7889 "operand of delete must have pointer type");
7891 } else if (warning.other &&
7892 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7893 warningf(&value->base.source_position,
7894 "deleting 'void*' is undefined");
7901 * Parse a throw expression
7902 * ISO/IEC 14882:1998(E) §15:1
7904 static expression_t *parse_throw(void)
7906 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7907 result->base.type = type_void;
7911 expression_t *value = NULL;
7912 switch (token.type) {
7914 value = parse_assignment_expression();
7915 /* ISO/IEC 14882:1998(E) §15.1:3 */
7916 type_t *const orig_type = value->base.type;
7917 type_t *const type = skip_typeref(orig_type);
7918 if (is_type_incomplete(type)) {
7919 errorf(&value->base.source_position,
7920 "cannot throw object of incomplete type '%T'", orig_type);
7921 } else if (is_type_pointer(type)) {
7922 type_t *const points_to = skip_typeref(type->pointer.points_to);
7923 if (is_type_incomplete(points_to) &&
7924 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7925 errorf(&value->base.source_position,
7926 "cannot throw pointer to incomplete type '%T'", orig_type);
7934 result->unary.value = value;
7939 static bool check_pointer_arithmetic(const source_position_t *source_position,
7940 type_t *pointer_type,
7941 type_t *orig_pointer_type)
7943 type_t *points_to = pointer_type->pointer.points_to;
7944 points_to = skip_typeref(points_to);
7946 if (is_type_incomplete(points_to)) {
7947 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7948 errorf(source_position,
7949 "arithmetic with pointer to incomplete type '%T' not allowed",
7952 } else if (warning.pointer_arith) {
7953 warningf(source_position,
7954 "pointer of type '%T' used in arithmetic",
7957 } else if (is_type_function(points_to)) {
7959 errorf(source_position,
7960 "arithmetic with pointer to function type '%T' not allowed",
7963 } else if (warning.pointer_arith) {
7964 warningf(source_position,
7965 "pointer to a function '%T' used in arithmetic",
7972 static bool is_lvalue(const expression_t *expression)
7974 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7975 switch (expression->kind) {
7976 case EXPR_ARRAY_ACCESS:
7977 case EXPR_COMPOUND_LITERAL:
7978 case EXPR_REFERENCE:
7980 case EXPR_UNARY_DEREFERENCE:
7984 type_t *type = skip_typeref(expression->base.type);
7986 /* ISO/IEC 14882:1998(E) §3.10:3 */
7987 is_type_reference(type) ||
7988 /* Claim it is an lvalue, if the type is invalid. There was a parse
7989 * error before, which maybe prevented properly recognizing it as
7991 !is_type_valid(type);
7996 static void semantic_incdec(unary_expression_t *expression)
7998 type_t *const orig_type = expression->value->base.type;
7999 type_t *const type = skip_typeref(orig_type);
8000 if (is_type_pointer(type)) {
8001 if (!check_pointer_arithmetic(&expression->base.source_position,
8005 } else if (!is_type_real(type) && is_type_valid(type)) {
8006 /* TODO: improve error message */
8007 errorf(&expression->base.source_position,
8008 "operation needs an arithmetic or pointer type");
8011 if (!is_lvalue(expression->value)) {
8012 /* TODO: improve error message */
8013 errorf(&expression->base.source_position, "lvalue required as operand");
8015 expression->base.type = orig_type;
8018 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8020 type_t *const orig_type = expression->value->base.type;
8021 type_t *const type = skip_typeref(orig_type);
8022 if (!is_type_arithmetic(type)) {
8023 if (is_type_valid(type)) {
8024 /* TODO: improve error message */
8025 errorf(&expression->base.source_position,
8026 "operation needs an arithmetic type");
8031 expression->base.type = orig_type;
8034 static void semantic_unexpr_plus(unary_expression_t *expression)
8036 semantic_unexpr_arithmetic(expression);
8037 if (warning.traditional)
8038 warningf(&expression->base.source_position,
8039 "traditional C rejects the unary plus operator");
8042 static void semantic_not(unary_expression_t *expression)
8044 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8045 semantic_condition(expression->value, "operand of !");
8046 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8049 static void semantic_unexpr_integer(unary_expression_t *expression)
8051 type_t *const orig_type = expression->value->base.type;
8052 type_t *const type = skip_typeref(orig_type);
8053 if (!is_type_integer(type)) {
8054 if (is_type_valid(type)) {
8055 errorf(&expression->base.source_position,
8056 "operand of ~ must be of integer type");
8061 expression->base.type = orig_type;
8064 static void semantic_dereference(unary_expression_t *expression)
8066 type_t *const orig_type = expression->value->base.type;
8067 type_t *const type = skip_typeref(orig_type);
8068 if (!is_type_pointer(type)) {
8069 if (is_type_valid(type)) {
8070 errorf(&expression->base.source_position,
8071 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8076 type_t *result_type = type->pointer.points_to;
8077 result_type = automatic_type_conversion(result_type);
8078 expression->base.type = result_type;
8082 * Record that an address is taken (expression represents an lvalue).
8084 * @param expression the expression
8085 * @param may_be_register if true, the expression might be an register
8087 static void set_address_taken(expression_t *expression, bool may_be_register)
8089 if (expression->kind != EXPR_REFERENCE)
8092 entity_t *const entity = expression->reference.entity;
8094 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8097 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8098 && !may_be_register) {
8099 errorf(&expression->base.source_position,
8100 "address of register %s '%Y' requested",
8101 get_entity_kind_name(entity->kind), entity->base.symbol);
8104 if (entity->kind == ENTITY_VARIABLE) {
8105 entity->variable.address_taken = true;
8107 assert(entity->kind == ENTITY_PARAMETER);
8108 entity->parameter.address_taken = true;
8113 * Check the semantic of the address taken expression.
8115 static void semantic_take_addr(unary_expression_t *expression)
8117 expression_t *value = expression->value;
8118 value->base.type = revert_automatic_type_conversion(value);
8120 type_t *orig_type = value->base.type;
8121 type_t *type = skip_typeref(orig_type);
8122 if (!is_type_valid(type))
8126 if (!is_lvalue(value)) {
8127 errorf(&expression->base.source_position, "'&' requires an lvalue");
8129 if (type->kind == TYPE_BITFIELD) {
8130 errorf(&expression->base.source_position,
8131 "'&' not allowed on object with bitfield type '%T'",
8135 set_address_taken(value, false);
8137 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8140 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8141 static expression_t *parse_##unexpression_type(void) \
8143 expression_t *unary_expression \
8144 = allocate_expression_zero(unexpression_type); \
8146 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8148 sfunc(&unary_expression->unary); \
8150 return unary_expression; \
8153 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8154 semantic_unexpr_arithmetic)
8155 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8156 semantic_unexpr_plus)
8157 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8159 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8160 semantic_dereference)
8161 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8163 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8164 semantic_unexpr_integer)
8165 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8167 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8170 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8172 static expression_t *parse_##unexpression_type(expression_t *left) \
8174 expression_t *unary_expression \
8175 = allocate_expression_zero(unexpression_type); \
8177 unary_expression->unary.value = left; \
8179 sfunc(&unary_expression->unary); \
8181 return unary_expression; \
8184 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8185 EXPR_UNARY_POSTFIX_INCREMENT,
8187 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8188 EXPR_UNARY_POSTFIX_DECREMENT,
8191 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8193 /* TODO: handle complex + imaginary types */
8195 type_left = get_unqualified_type(type_left);
8196 type_right = get_unqualified_type(type_right);
8198 /* §6.3.1.8 Usual arithmetic conversions */
8199 if (type_left == type_long_double || type_right == type_long_double) {
8200 return type_long_double;
8201 } else if (type_left == type_double || type_right == type_double) {
8203 } else if (type_left == type_float || type_right == type_float) {
8207 type_left = promote_integer(type_left);
8208 type_right = promote_integer(type_right);
8210 if (type_left == type_right)
8213 bool const signed_left = is_type_signed(type_left);
8214 bool const signed_right = is_type_signed(type_right);
8215 int const rank_left = get_rank(type_left);
8216 int const rank_right = get_rank(type_right);
8218 if (signed_left == signed_right)
8219 return rank_left >= rank_right ? type_left : type_right;
8228 u_rank = rank_right;
8229 u_type = type_right;
8231 s_rank = rank_right;
8232 s_type = type_right;
8237 if (u_rank >= s_rank)
8240 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8242 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8243 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8247 case ATOMIC_TYPE_INT: return type_unsigned_int;
8248 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8249 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8251 default: panic("invalid atomic type");
8256 * Check the semantic restrictions for a binary expression.
8258 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8260 expression_t *const left = expression->left;
8261 expression_t *const right = expression->right;
8262 type_t *const orig_type_left = left->base.type;
8263 type_t *const orig_type_right = right->base.type;
8264 type_t *const type_left = skip_typeref(orig_type_left);
8265 type_t *const type_right = skip_typeref(orig_type_right);
8267 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8268 /* TODO: improve error message */
8269 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8270 errorf(&expression->base.source_position,
8271 "operation needs arithmetic types");
8276 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8277 expression->left = create_implicit_cast(left, arithmetic_type);
8278 expression->right = create_implicit_cast(right, arithmetic_type);
8279 expression->base.type = arithmetic_type;
8282 static void semantic_binexpr_integer(binary_expression_t *const expression)
8284 expression_t *const left = expression->left;
8285 expression_t *const right = expression->right;
8286 type_t *const orig_type_left = left->base.type;
8287 type_t *const orig_type_right = right->base.type;
8288 type_t *const type_left = skip_typeref(orig_type_left);
8289 type_t *const type_right = skip_typeref(orig_type_right);
8291 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8292 /* TODO: improve error message */
8293 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8294 errorf(&expression->base.source_position,
8295 "operation needs integer types");
8300 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8301 expression->left = create_implicit_cast(left, result_type);
8302 expression->right = create_implicit_cast(right, result_type);
8303 expression->base.type = result_type;
8306 static void warn_div_by_zero(binary_expression_t const *const expression)
8308 if (!warning.div_by_zero ||
8309 !is_type_integer(expression->base.type))
8312 expression_t const *const right = expression->right;
8313 /* The type of the right operand can be different for /= */
8314 if (is_type_integer(right->base.type) &&
8315 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8316 !fold_constant_to_bool(right)) {
8317 warningf(&expression->base.source_position, "division by zero");
8322 * Check the semantic restrictions for a div/mod expression.
8324 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8326 semantic_binexpr_arithmetic(expression);
8327 warn_div_by_zero(expression);
8330 static void warn_addsub_in_shift(const expression_t *const expr)
8332 if (expr->base.parenthesized)
8336 switch (expr->kind) {
8337 case EXPR_BINARY_ADD: op = '+'; break;
8338 case EXPR_BINARY_SUB: op = '-'; break;
8342 warningf(&expr->base.source_position,
8343 "suggest parentheses around '%c' inside shift", op);
8346 static bool semantic_shift(binary_expression_t *expression)
8348 expression_t *const left = expression->left;
8349 expression_t *const right = expression->right;
8350 type_t *const orig_type_left = left->base.type;
8351 type_t *const orig_type_right = right->base.type;
8352 type_t * type_left = skip_typeref(orig_type_left);
8353 type_t * type_right = skip_typeref(orig_type_right);
8355 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8356 /* TODO: improve error message */
8357 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8358 errorf(&expression->base.source_position,
8359 "operands of shift operation must have integer types");
8364 type_left = promote_integer(type_left);
8366 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8367 long count = fold_constant_to_int(right);
8369 warningf(&right->base.source_position,
8370 "shift count must be non-negative");
8371 } else if ((unsigned long)count >=
8372 get_atomic_type_size(type_left->atomic.akind) * 8) {
8373 warningf(&right->base.source_position,
8374 "shift count must be less than type width");
8378 type_right = promote_integer(type_right);
8379 expression->right = create_implicit_cast(right, type_right);
8384 static void semantic_shift_op(binary_expression_t *expression)
8386 expression_t *const left = expression->left;
8387 expression_t *const right = expression->right;
8389 if (!semantic_shift(expression))
8392 if (warning.parentheses) {
8393 warn_addsub_in_shift(left);
8394 warn_addsub_in_shift(right);
8397 type_t *const orig_type_left = left->base.type;
8398 type_t * type_left = skip_typeref(orig_type_left);
8400 type_left = promote_integer(type_left);
8401 expression->left = create_implicit_cast(left, type_left);
8402 expression->base.type = type_left;
8405 static void semantic_add(binary_expression_t *expression)
8407 expression_t *const left = expression->left;
8408 expression_t *const right = expression->right;
8409 type_t *const orig_type_left = left->base.type;
8410 type_t *const orig_type_right = right->base.type;
8411 type_t *const type_left = skip_typeref(orig_type_left);
8412 type_t *const type_right = skip_typeref(orig_type_right);
8415 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8416 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8417 expression->left = create_implicit_cast(left, arithmetic_type);
8418 expression->right = create_implicit_cast(right, arithmetic_type);
8419 expression->base.type = arithmetic_type;
8420 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8421 check_pointer_arithmetic(&expression->base.source_position,
8422 type_left, orig_type_left);
8423 expression->base.type = type_left;
8424 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8425 check_pointer_arithmetic(&expression->base.source_position,
8426 type_right, orig_type_right);
8427 expression->base.type = type_right;
8428 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8429 errorf(&expression->base.source_position,
8430 "invalid operands to binary + ('%T', '%T')",
8431 orig_type_left, orig_type_right);
8435 static void semantic_sub(binary_expression_t *expression)
8437 expression_t *const left = expression->left;
8438 expression_t *const right = expression->right;
8439 type_t *const orig_type_left = left->base.type;
8440 type_t *const orig_type_right = right->base.type;
8441 type_t *const type_left = skip_typeref(orig_type_left);
8442 type_t *const type_right = skip_typeref(orig_type_right);
8443 source_position_t const *const pos = &expression->base.source_position;
8446 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8447 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8448 expression->left = create_implicit_cast(left, arithmetic_type);
8449 expression->right = create_implicit_cast(right, arithmetic_type);
8450 expression->base.type = arithmetic_type;
8451 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8452 check_pointer_arithmetic(&expression->base.source_position,
8453 type_left, orig_type_left);
8454 expression->base.type = type_left;
8455 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8456 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8457 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8458 if (!types_compatible(unqual_left, unqual_right)) {
8460 "subtracting pointers to incompatible types '%T' and '%T'",
8461 orig_type_left, orig_type_right);
8462 } else if (!is_type_object(unqual_left)) {
8463 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8464 errorf(pos, "subtracting pointers to non-object types '%T'",
8466 } else if (warning.other) {
8467 warningf(pos, "subtracting pointers to void");
8470 expression->base.type = type_ptrdiff_t;
8471 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8472 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8473 orig_type_left, orig_type_right);
8477 static void warn_string_literal_address(expression_t const* expr)
8479 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8480 expr = expr->unary.value;
8481 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8483 expr = expr->unary.value;
8486 if (expr->kind == EXPR_STRING_LITERAL
8487 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8488 warningf(&expr->base.source_position,
8489 "comparison with string literal results in unspecified behaviour");
8493 static void warn_comparison_in_comparison(const expression_t *const expr)
8495 if (expr->base.parenthesized)
8497 switch (expr->base.kind) {
8498 case EXPR_BINARY_LESS:
8499 case EXPR_BINARY_GREATER:
8500 case EXPR_BINARY_LESSEQUAL:
8501 case EXPR_BINARY_GREATEREQUAL:
8502 case EXPR_BINARY_NOTEQUAL:
8503 case EXPR_BINARY_EQUAL:
8504 warningf(&expr->base.source_position,
8505 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8512 static bool maybe_negative(expression_t const *const expr)
8514 switch (is_constant_expression(expr)) {
8515 case EXPR_CLASS_ERROR: return false;
8516 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8517 default: return true;
8522 * Check the semantics of comparison expressions.
8524 * @param expression The expression to check.
8526 static void semantic_comparison(binary_expression_t *expression)
8528 expression_t *left = expression->left;
8529 expression_t *right = expression->right;
8531 if (warning.address) {
8532 warn_string_literal_address(left);
8533 warn_string_literal_address(right);
8535 expression_t const* const func_left = get_reference_address(left);
8536 if (func_left != NULL && is_null_pointer_constant(right)) {
8537 warningf(&expression->base.source_position,
8538 "the address of '%Y' will never be NULL",
8539 func_left->reference.entity->base.symbol);
8542 expression_t const* const func_right = get_reference_address(right);
8543 if (func_right != NULL && is_null_pointer_constant(right)) {
8544 warningf(&expression->base.source_position,
8545 "the address of '%Y' will never be NULL",
8546 func_right->reference.entity->base.symbol);
8550 if (warning.parentheses) {
8551 warn_comparison_in_comparison(left);
8552 warn_comparison_in_comparison(right);
8555 type_t *orig_type_left = left->base.type;
8556 type_t *orig_type_right = right->base.type;
8557 type_t *type_left = skip_typeref(orig_type_left);
8558 type_t *type_right = skip_typeref(orig_type_right);
8560 /* TODO non-arithmetic types */
8561 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8562 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8564 /* test for signed vs unsigned compares */
8565 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8566 bool const signed_left = is_type_signed(type_left);
8567 bool const signed_right = is_type_signed(type_right);
8568 if (signed_left != signed_right) {
8569 /* FIXME long long needs better const folding magic */
8570 /* TODO check whether constant value can be represented by other type */
8571 if ((signed_left && maybe_negative(left)) ||
8572 (signed_right && maybe_negative(right))) {
8573 warningf(&expression->base.source_position,
8574 "comparison between signed and unsigned");
8579 expression->left = create_implicit_cast(left, arithmetic_type);
8580 expression->right = create_implicit_cast(right, arithmetic_type);
8581 expression->base.type = arithmetic_type;
8582 if (warning.float_equal &&
8583 (expression->base.kind == EXPR_BINARY_EQUAL ||
8584 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8585 is_type_float(arithmetic_type)) {
8586 warningf(&expression->base.source_position,
8587 "comparing floating point with == or != is unsafe");
8589 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8590 /* TODO check compatibility */
8591 } else if (is_type_pointer(type_left)) {
8592 expression->right = create_implicit_cast(right, type_left);
8593 } else if (is_type_pointer(type_right)) {
8594 expression->left = create_implicit_cast(left, type_right);
8595 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8596 type_error_incompatible("invalid operands in comparison",
8597 &expression->base.source_position,
8598 type_left, type_right);
8600 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8604 * Checks if a compound type has constant fields.
8606 static bool has_const_fields(const compound_type_t *type)
8608 compound_t *compound = type->compound;
8609 entity_t *entry = compound->members.entities;
8611 for (; entry != NULL; entry = entry->base.next) {
8612 if (!is_declaration(entry))
8615 const type_t *decl_type = skip_typeref(entry->declaration.type);
8616 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8623 static bool is_valid_assignment_lhs(expression_t const* const left)
8625 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8626 type_t *const type_left = skip_typeref(orig_type_left);
8628 if (!is_lvalue(left)) {
8629 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8634 if (left->kind == EXPR_REFERENCE
8635 && left->reference.entity->kind == ENTITY_FUNCTION) {
8636 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8640 if (is_type_array(type_left)) {
8641 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8644 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8645 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8649 if (is_type_incomplete(type_left)) {
8650 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8651 left, orig_type_left);
8654 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8655 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8656 left, orig_type_left);
8663 static void semantic_arithmetic_assign(binary_expression_t *expression)
8665 expression_t *left = expression->left;
8666 expression_t *right = expression->right;
8667 type_t *orig_type_left = left->base.type;
8668 type_t *orig_type_right = right->base.type;
8670 if (!is_valid_assignment_lhs(left))
8673 type_t *type_left = skip_typeref(orig_type_left);
8674 type_t *type_right = skip_typeref(orig_type_right);
8676 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8677 /* TODO: improve error message */
8678 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8679 errorf(&expression->base.source_position,
8680 "operation needs arithmetic types");
8685 /* combined instructions are tricky. We can't create an implicit cast on
8686 * the left side, because we need the uncasted form for the store.
8687 * The ast2firm pass has to know that left_type must be right_type
8688 * for the arithmetic operation and create a cast by itself */
8689 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8690 expression->right = create_implicit_cast(right, arithmetic_type);
8691 expression->base.type = type_left;
8694 static void semantic_divmod_assign(binary_expression_t *expression)
8696 semantic_arithmetic_assign(expression);
8697 warn_div_by_zero(expression);
8700 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8702 expression_t *const left = expression->left;
8703 expression_t *const right = expression->right;
8704 type_t *const orig_type_left = left->base.type;
8705 type_t *const orig_type_right = right->base.type;
8706 type_t *const type_left = skip_typeref(orig_type_left);
8707 type_t *const type_right = skip_typeref(orig_type_right);
8709 if (!is_valid_assignment_lhs(left))
8712 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8713 /* combined instructions are tricky. We can't create an implicit cast on
8714 * the left side, because we need the uncasted form for the store.
8715 * The ast2firm pass has to know that left_type must be right_type
8716 * for the arithmetic operation and create a cast by itself */
8717 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8718 expression->right = create_implicit_cast(right, arithmetic_type);
8719 expression->base.type = type_left;
8720 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8721 check_pointer_arithmetic(&expression->base.source_position,
8722 type_left, orig_type_left);
8723 expression->base.type = type_left;
8724 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8725 errorf(&expression->base.source_position,
8726 "incompatible types '%T' and '%T' in assignment",
8727 orig_type_left, orig_type_right);
8731 static void semantic_integer_assign(binary_expression_t *expression)
8733 expression_t *left = expression->left;
8734 expression_t *right = expression->right;
8735 type_t *orig_type_left = left->base.type;
8736 type_t *orig_type_right = right->base.type;
8738 if (!is_valid_assignment_lhs(left))
8741 type_t *type_left = skip_typeref(orig_type_left);
8742 type_t *type_right = skip_typeref(orig_type_right);
8744 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8745 /* TODO: improve error message */
8746 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8747 errorf(&expression->base.source_position,
8748 "operation needs integer types");
8753 /* combined instructions are tricky. We can't create an implicit cast on
8754 * the left side, because we need the uncasted form for the store.
8755 * The ast2firm pass has to know that left_type must be right_type
8756 * for the arithmetic operation and create a cast by itself */
8757 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8758 expression->right = create_implicit_cast(right, arithmetic_type);
8759 expression->base.type = type_left;
8762 static void semantic_shift_assign(binary_expression_t *expression)
8764 expression_t *left = expression->left;
8766 if (!is_valid_assignment_lhs(left))
8769 if (!semantic_shift(expression))
8772 expression->base.type = skip_typeref(left->base.type);
8775 static void warn_logical_and_within_or(const expression_t *const expr)
8777 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8779 if (expr->base.parenthesized)
8781 warningf(&expr->base.source_position,
8782 "suggest parentheses around && within ||");
8786 * Check the semantic restrictions of a logical expression.
8788 static void semantic_logical_op(binary_expression_t *expression)
8790 /* §6.5.13:2 Each of the operands shall have scalar type.
8791 * §6.5.14:2 Each of the operands shall have scalar type. */
8792 semantic_condition(expression->left, "left operand of logical operator");
8793 semantic_condition(expression->right, "right operand of logical operator");
8794 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8795 warning.parentheses) {
8796 warn_logical_and_within_or(expression->left);
8797 warn_logical_and_within_or(expression->right);
8799 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8803 * Check the semantic restrictions of a binary assign expression.
8805 static void semantic_binexpr_assign(binary_expression_t *expression)
8807 expression_t *left = expression->left;
8808 type_t *orig_type_left = left->base.type;
8810 if (!is_valid_assignment_lhs(left))
8813 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8814 report_assign_error(error, orig_type_left, expression->right,
8815 "assignment", &left->base.source_position);
8816 expression->right = create_implicit_cast(expression->right, orig_type_left);
8817 expression->base.type = orig_type_left;
8821 * Determine if the outermost operation (or parts thereof) of the given
8822 * expression has no effect in order to generate a warning about this fact.
8823 * Therefore in some cases this only examines some of the operands of the
8824 * expression (see comments in the function and examples below).
8826 * f() + 23; // warning, because + has no effect
8827 * x || f(); // no warning, because x controls execution of f()
8828 * x ? y : f(); // warning, because y has no effect
8829 * (void)x; // no warning to be able to suppress the warning
8830 * This function can NOT be used for an "expression has definitely no effect"-
8832 static bool expression_has_effect(const expression_t *const expr)
8834 switch (expr->kind) {
8835 case EXPR_UNKNOWN: break;
8836 case EXPR_INVALID: return true; /* do NOT warn */
8837 case EXPR_REFERENCE: return false;
8838 case EXPR_REFERENCE_ENUM_VALUE: return false;
8839 case EXPR_LABEL_ADDRESS: return false;
8841 /* suppress the warning for microsoft __noop operations */
8842 case EXPR_LITERAL_MS_NOOP: return true;
8843 case EXPR_LITERAL_BOOLEAN:
8844 case EXPR_LITERAL_CHARACTER:
8845 case EXPR_LITERAL_WIDE_CHARACTER:
8846 case EXPR_LITERAL_INTEGER:
8847 case EXPR_LITERAL_INTEGER_OCTAL:
8848 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8849 case EXPR_LITERAL_FLOATINGPOINT:
8850 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8851 case EXPR_STRING_LITERAL: return false;
8852 case EXPR_WIDE_STRING_LITERAL: return false;
8855 const call_expression_t *const call = &expr->call;
8856 if (call->function->kind != EXPR_REFERENCE)
8859 switch (call->function->reference.entity->function.btk) {
8860 /* FIXME: which builtins have no effect? */
8861 default: return true;
8865 /* Generate the warning if either the left or right hand side of a
8866 * conditional expression has no effect */
8867 case EXPR_CONDITIONAL: {
8868 conditional_expression_t const *const cond = &expr->conditional;
8869 expression_t const *const t = cond->true_expression;
8871 (t == NULL || expression_has_effect(t)) &&
8872 expression_has_effect(cond->false_expression);
8875 case EXPR_SELECT: return false;
8876 case EXPR_ARRAY_ACCESS: return false;
8877 case EXPR_SIZEOF: return false;
8878 case EXPR_CLASSIFY_TYPE: return false;
8879 case EXPR_ALIGNOF: return false;
8881 case EXPR_FUNCNAME: return false;
8882 case EXPR_BUILTIN_CONSTANT_P: return false;
8883 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8884 case EXPR_OFFSETOF: return false;
8885 case EXPR_VA_START: return true;
8886 case EXPR_VA_ARG: return true;
8887 case EXPR_VA_COPY: return true;
8888 case EXPR_STATEMENT: return true; // TODO
8889 case EXPR_COMPOUND_LITERAL: return false;
8891 case EXPR_UNARY_NEGATE: return false;
8892 case EXPR_UNARY_PLUS: return false;
8893 case EXPR_UNARY_BITWISE_NEGATE: return false;
8894 case EXPR_UNARY_NOT: return false;
8895 case EXPR_UNARY_DEREFERENCE: return false;
8896 case EXPR_UNARY_TAKE_ADDRESS: return false;
8897 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8898 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8899 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8900 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8902 /* Treat void casts as if they have an effect in order to being able to
8903 * suppress the warning */
8904 case EXPR_UNARY_CAST: {
8905 type_t *const type = skip_typeref(expr->base.type);
8906 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8909 case EXPR_UNARY_CAST_IMPLICIT: return true;
8910 case EXPR_UNARY_ASSUME: return true;
8911 case EXPR_UNARY_DELETE: return true;
8912 case EXPR_UNARY_DELETE_ARRAY: return true;
8913 case EXPR_UNARY_THROW: return true;
8915 case EXPR_BINARY_ADD: return false;
8916 case EXPR_BINARY_SUB: return false;
8917 case EXPR_BINARY_MUL: return false;
8918 case EXPR_BINARY_DIV: return false;
8919 case EXPR_BINARY_MOD: return false;
8920 case EXPR_BINARY_EQUAL: return false;
8921 case EXPR_BINARY_NOTEQUAL: return false;
8922 case EXPR_BINARY_LESS: return false;
8923 case EXPR_BINARY_LESSEQUAL: return false;
8924 case EXPR_BINARY_GREATER: return false;
8925 case EXPR_BINARY_GREATEREQUAL: return false;
8926 case EXPR_BINARY_BITWISE_AND: return false;
8927 case EXPR_BINARY_BITWISE_OR: return false;
8928 case EXPR_BINARY_BITWISE_XOR: return false;
8929 case EXPR_BINARY_SHIFTLEFT: return false;
8930 case EXPR_BINARY_SHIFTRIGHT: return false;
8931 case EXPR_BINARY_ASSIGN: return true;
8932 case EXPR_BINARY_MUL_ASSIGN: return true;
8933 case EXPR_BINARY_DIV_ASSIGN: return true;
8934 case EXPR_BINARY_MOD_ASSIGN: return true;
8935 case EXPR_BINARY_ADD_ASSIGN: return true;
8936 case EXPR_BINARY_SUB_ASSIGN: return true;
8937 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8938 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8939 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8940 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8941 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8943 /* Only examine the right hand side of && and ||, because the left hand
8944 * side already has the effect of controlling the execution of the right
8946 case EXPR_BINARY_LOGICAL_AND:
8947 case EXPR_BINARY_LOGICAL_OR:
8948 /* Only examine the right hand side of a comma expression, because the left
8949 * hand side has a separate warning */
8950 case EXPR_BINARY_COMMA:
8951 return expression_has_effect(expr->binary.right);
8953 case EXPR_BINARY_ISGREATER: return false;
8954 case EXPR_BINARY_ISGREATEREQUAL: return false;
8955 case EXPR_BINARY_ISLESS: return false;
8956 case EXPR_BINARY_ISLESSEQUAL: return false;
8957 case EXPR_BINARY_ISLESSGREATER: return false;
8958 case EXPR_BINARY_ISUNORDERED: return false;
8961 internal_errorf(HERE, "unexpected expression");
8964 static void semantic_comma(binary_expression_t *expression)
8966 if (warning.unused_value) {
8967 const expression_t *const left = expression->left;
8968 if (!expression_has_effect(left)) {
8969 warningf(&left->base.source_position,
8970 "left-hand operand of comma expression has no effect");
8973 expression->base.type = expression->right->base.type;
8977 * @param prec_r precedence of the right operand
8979 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8980 static expression_t *parse_##binexpression_type(expression_t *left) \
8982 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8983 binexpr->binary.left = left; \
8986 expression_t *right = parse_subexpression(prec_r); \
8988 binexpr->binary.right = right; \
8989 sfunc(&binexpr->binary); \
8994 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8995 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8996 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8997 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8998 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8999 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9000 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9001 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9002 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9003 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9004 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9005 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9006 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9007 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
9008 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
9009 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
9010 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9011 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9012 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9013 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9014 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9015 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9016 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9017 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9018 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9019 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9020 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9021 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9022 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9023 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9026 static expression_t *parse_subexpression(precedence_t precedence)
9028 if (token.type < 0) {
9029 return expected_expression_error();
9032 expression_parser_function_t *parser
9033 = &expression_parsers[token.type];
9034 source_position_t source_position = token.source_position;
9037 if (parser->parser != NULL) {
9038 left = parser->parser();
9040 left = parse_primary_expression();
9042 assert(left != NULL);
9043 left->base.source_position = source_position;
9046 if (token.type < 0) {
9047 return expected_expression_error();
9050 parser = &expression_parsers[token.type];
9051 if (parser->infix_parser == NULL)
9053 if (parser->infix_precedence < precedence)
9056 left = parser->infix_parser(left);
9058 assert(left != NULL);
9059 assert(left->kind != EXPR_UNKNOWN);
9060 left->base.source_position = source_position;
9067 * Parse an expression.
9069 static expression_t *parse_expression(void)
9071 return parse_subexpression(PREC_EXPRESSION);
9075 * Register a parser for a prefix-like operator.
9077 * @param parser the parser function
9078 * @param token_type the token type of the prefix token
9080 static void register_expression_parser(parse_expression_function parser,
9083 expression_parser_function_t *entry = &expression_parsers[token_type];
9085 if (entry->parser != NULL) {
9086 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9087 panic("trying to register multiple expression parsers for a token");
9089 entry->parser = parser;
9093 * Register a parser for an infix operator with given precedence.
9095 * @param parser the parser function
9096 * @param token_type the token type of the infix operator
9097 * @param precedence the precedence of the operator
9099 static void register_infix_parser(parse_expression_infix_function parser,
9100 int token_type, precedence_t precedence)
9102 expression_parser_function_t *entry = &expression_parsers[token_type];
9104 if (entry->infix_parser != NULL) {
9105 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9106 panic("trying to register multiple infix expression parsers for a "
9109 entry->infix_parser = parser;
9110 entry->infix_precedence = precedence;
9114 * Initialize the expression parsers.
9116 static void init_expression_parsers(void)
9118 memset(&expression_parsers, 0, sizeof(expression_parsers));
9120 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9121 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9122 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9123 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9124 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9125 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9126 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9127 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9128 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9129 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9130 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9131 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9132 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9133 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9134 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9135 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9136 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9137 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9138 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9139 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9140 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9141 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9142 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9143 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9144 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9145 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9146 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9147 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9148 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9149 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9150 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9151 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9152 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9153 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9154 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9155 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9156 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9158 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9159 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9160 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9161 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9162 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9163 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9164 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9165 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9166 register_expression_parser(parse_sizeof, T_sizeof);
9167 register_expression_parser(parse_alignof, T___alignof__);
9168 register_expression_parser(parse_extension, T___extension__);
9169 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9170 register_expression_parser(parse_delete, T_delete);
9171 register_expression_parser(parse_throw, T_throw);
9175 * Parse a asm statement arguments specification.
9177 static asm_argument_t *parse_asm_arguments(bool is_out)
9179 asm_argument_t *result = NULL;
9180 asm_argument_t **anchor = &result;
9182 while (token.type == T_STRING_LITERAL || token.type == '[') {
9183 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9184 memset(argument, 0, sizeof(argument[0]));
9187 if (token.type != T_IDENTIFIER) {
9188 parse_error_expected("while parsing asm argument",
9189 T_IDENTIFIER, NULL);
9192 argument->symbol = token.symbol;
9194 expect(']', end_error);
9197 argument->constraints = parse_string_literals();
9198 expect('(', end_error);
9199 add_anchor_token(')');
9200 expression_t *expression = parse_expression();
9201 rem_anchor_token(')');
9203 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9204 * change size or type representation (e.g. int -> long is ok, but
9205 * int -> float is not) */
9206 if (expression->kind == EXPR_UNARY_CAST) {
9207 type_t *const type = expression->base.type;
9208 type_kind_t const kind = type->kind;
9209 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9212 if (kind == TYPE_ATOMIC) {
9213 atomic_type_kind_t const akind = type->atomic.akind;
9214 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9215 size = get_atomic_type_size(akind);
9217 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9218 size = get_atomic_type_size(get_intptr_kind());
9222 expression_t *const value = expression->unary.value;
9223 type_t *const value_type = value->base.type;
9224 type_kind_t const value_kind = value_type->kind;
9226 unsigned value_flags;
9227 unsigned value_size;
9228 if (value_kind == TYPE_ATOMIC) {
9229 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9230 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9231 value_size = get_atomic_type_size(value_akind);
9232 } else if (value_kind == TYPE_POINTER) {
9233 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9234 value_size = get_atomic_type_size(get_intptr_kind());
9239 if (value_flags != flags || value_size != size)
9243 } while (expression->kind == EXPR_UNARY_CAST);
9247 if (!is_lvalue(expression)) {
9248 errorf(&expression->base.source_position,
9249 "asm output argument is not an lvalue");
9252 if (argument->constraints.begin[0] == '=')
9253 determine_lhs_ent(expression, NULL);
9255 mark_vars_read(expression, NULL);
9257 mark_vars_read(expression, NULL);
9259 argument->expression = expression;
9260 expect(')', end_error);
9262 set_address_taken(expression, true);
9265 anchor = &argument->next;
9277 * Parse a asm statement clobber specification.
9279 static asm_clobber_t *parse_asm_clobbers(void)
9281 asm_clobber_t *result = NULL;
9282 asm_clobber_t **anchor = &result;
9284 while (token.type == T_STRING_LITERAL) {
9285 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9286 clobber->clobber = parse_string_literals();
9289 anchor = &clobber->next;
9299 * Parse an asm statement.
9301 static statement_t *parse_asm_statement(void)
9303 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9304 asm_statement_t *asm_statement = &statement->asms;
9308 if (next_if(T_volatile))
9309 asm_statement->is_volatile = true;
9311 expect('(', end_error);
9312 add_anchor_token(')');
9313 if (token.type != T_STRING_LITERAL) {
9314 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9317 asm_statement->asm_text = parse_string_literals();
9319 add_anchor_token(':');
9320 if (!next_if(':')) {
9321 rem_anchor_token(':');
9325 asm_statement->outputs = parse_asm_arguments(true);
9326 if (!next_if(':')) {
9327 rem_anchor_token(':');
9331 asm_statement->inputs = parse_asm_arguments(false);
9332 if (!next_if(':')) {
9333 rem_anchor_token(':');
9336 rem_anchor_token(':');
9338 asm_statement->clobbers = parse_asm_clobbers();
9341 rem_anchor_token(')');
9342 expect(')', end_error);
9343 expect(';', end_error);
9345 if (asm_statement->outputs == NULL) {
9346 /* GCC: An 'asm' instruction without any output operands will be treated
9347 * identically to a volatile 'asm' instruction. */
9348 asm_statement->is_volatile = true;
9353 return create_invalid_statement();
9356 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9358 statement_t *inner_stmt;
9359 switch (token.type) {
9361 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9362 inner_stmt = create_invalid_statement();
9366 if (label->kind == STATEMENT_LABEL) {
9367 /* Eat an empty statement here, to avoid the warning about an empty
9368 * statement after a label. label:; is commonly used to have a label
9369 * before a closing brace. */
9370 inner_stmt = create_empty_statement();
9377 inner_stmt = parse_statement();
9378 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9379 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9380 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9388 * Parse a case statement.
9390 static statement_t *parse_case_statement(void)
9392 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9393 source_position_t *const pos = &statement->base.source_position;
9397 expression_t *const expression = parse_expression();
9398 statement->case_label.expression = expression;
9399 expression_classification_t const expr_class = is_constant_expression(expression);
9400 if (expr_class != EXPR_CLASS_CONSTANT) {
9401 if (expr_class != EXPR_CLASS_ERROR) {
9402 errorf(pos, "case label does not reduce to an integer constant");
9404 statement->case_label.is_bad = true;
9406 long const val = fold_constant_to_int(expression);
9407 statement->case_label.first_case = val;
9408 statement->case_label.last_case = val;
9412 if (next_if(T_DOTDOTDOT)) {
9413 expression_t *const end_range = parse_expression();
9414 statement->case_label.end_range = end_range;
9415 expression_classification_t const end_class = is_constant_expression(end_range);
9416 if (end_class != EXPR_CLASS_CONSTANT) {
9417 if (end_class != EXPR_CLASS_ERROR) {
9418 errorf(pos, "case range does not reduce to an integer constant");
9420 statement->case_label.is_bad = true;
9422 long const val = fold_constant_to_int(end_range);
9423 statement->case_label.last_case = val;
9425 if (warning.other && val < statement->case_label.first_case) {
9426 statement->case_label.is_empty_range = true;
9427 warningf(pos, "empty range specified");
9433 PUSH_PARENT(statement);
9435 expect(':', end_error);
9438 if (current_switch != NULL) {
9439 if (! statement->case_label.is_bad) {
9440 /* Check for duplicate case values */
9441 case_label_statement_t *c = &statement->case_label;
9442 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9443 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9446 if (c->last_case < l->first_case || c->first_case > l->last_case)
9449 errorf(pos, "duplicate case value (previously used %P)",
9450 &l->base.source_position);
9454 /* link all cases into the switch statement */
9455 if (current_switch->last_case == NULL) {
9456 current_switch->first_case = &statement->case_label;
9458 current_switch->last_case->next = &statement->case_label;
9460 current_switch->last_case = &statement->case_label;
9462 errorf(pos, "case label not within a switch statement");
9465 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9472 * Parse a default statement.
9474 static statement_t *parse_default_statement(void)
9476 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9480 PUSH_PARENT(statement);
9482 expect(':', end_error);
9485 if (current_switch != NULL) {
9486 const case_label_statement_t *def_label = current_switch->default_label;
9487 if (def_label != NULL) {
9488 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9489 &def_label->base.source_position);
9491 current_switch->default_label = &statement->case_label;
9493 /* link all cases into the switch statement */
9494 if (current_switch->last_case == NULL) {
9495 current_switch->first_case = &statement->case_label;
9497 current_switch->last_case->next = &statement->case_label;
9499 current_switch->last_case = &statement->case_label;
9502 errorf(&statement->base.source_position,
9503 "'default' label not within a switch statement");
9506 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9513 * Parse a label statement.
9515 static statement_t *parse_label_statement(void)
9517 assert(token.type == T_IDENTIFIER);
9518 symbol_t *symbol = token.symbol;
9519 label_t *label = get_label(symbol);
9521 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9522 statement->label.label = label;
9526 PUSH_PARENT(statement);
9528 /* if statement is already set then the label is defined twice,
9529 * otherwise it was just mentioned in a goto/local label declaration so far
9531 if (label->statement != NULL) {
9532 errorf(HERE, "duplicate label '%Y' (declared %P)",
9533 symbol, &label->base.source_position);
9535 label->base.source_position = token.source_position;
9536 label->statement = statement;
9541 statement->label.statement = parse_label_inner_statement(statement, "label");
9543 /* remember the labels in a list for later checking */
9544 *label_anchor = &statement->label;
9545 label_anchor = &statement->label.next;
9552 * Parse an if statement.
9554 static statement_t *parse_if(void)
9556 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9560 PUSH_PARENT(statement);
9562 add_anchor_token('{');
9564 expect('(', end_error);
9565 add_anchor_token(')');
9566 expression_t *const expr = parse_expression();
9567 statement->ifs.condition = expr;
9568 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9570 semantic_condition(expr, "condition of 'if'-statment");
9571 mark_vars_read(expr, NULL);
9572 rem_anchor_token(')');
9573 expect(')', end_error);
9576 rem_anchor_token('{');
9578 add_anchor_token(T_else);
9579 statement_t *const true_stmt = parse_statement();
9580 statement->ifs.true_statement = true_stmt;
9581 rem_anchor_token(T_else);
9583 if (next_if(T_else)) {
9584 statement->ifs.false_statement = parse_statement();
9585 } else if (warning.parentheses &&
9586 true_stmt->kind == STATEMENT_IF &&
9587 true_stmt->ifs.false_statement != NULL) {
9588 warningf(&true_stmt->base.source_position,
9589 "suggest explicit braces to avoid ambiguous 'else'");
9597 * Check that all enums are handled in a switch.
9599 * @param statement the switch statement to check
9601 static void check_enum_cases(const switch_statement_t *statement)
9603 const type_t *type = skip_typeref(statement->expression->base.type);
9604 if (! is_type_enum(type))
9606 const enum_type_t *enumt = &type->enumt;
9608 /* if we have a default, no warnings */
9609 if (statement->default_label != NULL)
9612 /* FIXME: calculation of value should be done while parsing */
9613 /* TODO: quadratic algorithm here. Change to an n log n one */
9614 long last_value = -1;
9615 const entity_t *entry = enumt->enume->base.next;
9616 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9617 entry = entry->base.next) {
9618 const expression_t *expression = entry->enum_value.value;
9619 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9621 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9622 if (l->expression == NULL)
9624 if (l->first_case <= value && value <= l->last_case) {
9630 warningf(&statement->base.source_position,
9631 "enumeration value '%Y' not handled in switch",
9632 entry->base.symbol);
9639 * Parse a switch statement.
9641 static statement_t *parse_switch(void)
9643 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9647 PUSH_PARENT(statement);
9649 expect('(', end_error);
9650 add_anchor_token(')');
9651 expression_t *const expr = parse_expression();
9652 mark_vars_read(expr, NULL);
9653 type_t * type = skip_typeref(expr->base.type);
9654 if (is_type_integer(type)) {
9655 type = promote_integer(type);
9656 if (warning.traditional) {
9657 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9658 warningf(&expr->base.source_position,
9659 "'%T' switch expression not converted to '%T' in ISO C",
9663 } else if (is_type_valid(type)) {
9664 errorf(&expr->base.source_position,
9665 "switch quantity is not an integer, but '%T'", type);
9666 type = type_error_type;
9668 statement->switchs.expression = create_implicit_cast(expr, type);
9669 expect(')', end_error);
9670 rem_anchor_token(')');
9672 switch_statement_t *rem = current_switch;
9673 current_switch = &statement->switchs;
9674 statement->switchs.body = parse_statement();
9675 current_switch = rem;
9677 if (warning.switch_default &&
9678 statement->switchs.default_label == NULL) {
9679 warningf(&statement->base.source_position, "switch has no default case");
9681 if (warning.switch_enum)
9682 check_enum_cases(&statement->switchs);
9688 return create_invalid_statement();
9691 static statement_t *parse_loop_body(statement_t *const loop)
9693 statement_t *const rem = current_loop;
9694 current_loop = loop;
9696 statement_t *const body = parse_statement();
9703 * Parse a while statement.
9705 static statement_t *parse_while(void)
9707 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9711 PUSH_PARENT(statement);
9713 expect('(', end_error);
9714 add_anchor_token(')');
9715 expression_t *const cond = parse_expression();
9716 statement->whiles.condition = cond;
9717 /* §6.8.5:2 The controlling expression of an iteration statement shall
9718 * have scalar type. */
9719 semantic_condition(cond, "condition of 'while'-statement");
9720 mark_vars_read(cond, NULL);
9721 rem_anchor_token(')');
9722 expect(')', end_error);
9724 statement->whiles.body = parse_loop_body(statement);
9730 return create_invalid_statement();
9734 * Parse a do statement.
9736 static statement_t *parse_do(void)
9738 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9742 PUSH_PARENT(statement);
9744 add_anchor_token(T_while);
9745 statement->do_while.body = parse_loop_body(statement);
9746 rem_anchor_token(T_while);
9748 expect(T_while, end_error);
9749 expect('(', end_error);
9750 add_anchor_token(')');
9751 expression_t *const cond = parse_expression();
9752 statement->do_while.condition = cond;
9753 /* §6.8.5:2 The controlling expression of an iteration statement shall
9754 * have scalar type. */
9755 semantic_condition(cond, "condition of 'do-while'-statement");
9756 mark_vars_read(cond, NULL);
9757 rem_anchor_token(')');
9758 expect(')', end_error);
9759 expect(';', end_error);
9765 return create_invalid_statement();
9769 * Parse a for statement.
9771 static statement_t *parse_for(void)
9773 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9777 expect('(', end_error1);
9778 add_anchor_token(')');
9780 PUSH_PARENT(statement);
9782 size_t const top = environment_top();
9783 scope_t *old_scope = scope_push(&statement->fors.scope);
9785 bool old_gcc_extension = in_gcc_extension;
9786 while (next_if(T___extension__)) {
9787 in_gcc_extension = true;
9791 } else if (is_declaration_specifier(&token, false)) {
9792 parse_declaration(record_entity, DECL_FLAGS_NONE);
9794 add_anchor_token(';');
9795 expression_t *const init = parse_expression();
9796 statement->fors.initialisation = init;
9797 mark_vars_read(init, ENT_ANY);
9798 if (warning.unused_value && !expression_has_effect(init)) {
9799 warningf(&init->base.source_position,
9800 "initialisation of 'for'-statement has no effect");
9802 rem_anchor_token(';');
9803 expect(';', end_error2);
9805 in_gcc_extension = old_gcc_extension;
9807 if (token.type != ';') {
9808 add_anchor_token(';');
9809 expression_t *const cond = parse_expression();
9810 statement->fors.condition = cond;
9811 /* §6.8.5:2 The controlling expression of an iteration statement
9812 * shall have scalar type. */
9813 semantic_condition(cond, "condition of 'for'-statement");
9814 mark_vars_read(cond, NULL);
9815 rem_anchor_token(';');
9817 expect(';', end_error2);
9818 if (token.type != ')') {
9819 expression_t *const step = parse_expression();
9820 statement->fors.step = step;
9821 mark_vars_read(step, ENT_ANY);
9822 if (warning.unused_value && !expression_has_effect(step)) {
9823 warningf(&step->base.source_position,
9824 "step of 'for'-statement has no effect");
9827 expect(')', end_error2);
9828 rem_anchor_token(')');
9829 statement->fors.body = parse_loop_body(statement);
9831 assert(current_scope == &statement->fors.scope);
9832 scope_pop(old_scope);
9833 environment_pop_to(top);
9840 rem_anchor_token(')');
9841 assert(current_scope == &statement->fors.scope);
9842 scope_pop(old_scope);
9843 environment_pop_to(top);
9847 return create_invalid_statement();
9851 * Parse a goto statement.
9853 static statement_t *parse_goto(void)
9855 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9858 if (GNU_MODE && next_if('*')) {
9859 expression_t *expression = parse_expression();
9860 mark_vars_read(expression, NULL);
9862 /* Argh: although documentation says the expression must be of type void*,
9863 * gcc accepts anything that can be casted into void* without error */
9864 type_t *type = expression->base.type;
9866 if (type != type_error_type) {
9867 if (!is_type_pointer(type) && !is_type_integer(type)) {
9868 errorf(&expression->base.source_position,
9869 "cannot convert to a pointer type");
9870 } else if (warning.other && type != type_void_ptr) {
9871 warningf(&expression->base.source_position,
9872 "type of computed goto expression should be 'void*' not '%T'", type);
9874 expression = create_implicit_cast(expression, type_void_ptr);
9877 statement->gotos.expression = expression;
9878 } else if (token.type == T_IDENTIFIER) {
9879 symbol_t *symbol = token.symbol;
9881 statement->gotos.label = get_label(symbol);
9884 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9886 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9888 return create_invalid_statement();
9891 /* remember the goto's in a list for later checking */
9892 *goto_anchor = &statement->gotos;
9893 goto_anchor = &statement->gotos.next;
9895 expect(';', end_error);
9902 * Parse a continue statement.
9904 static statement_t *parse_continue(void)
9906 if (current_loop == NULL) {
9907 errorf(HERE, "continue statement not within loop");
9910 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9913 expect(';', end_error);
9920 * Parse a break statement.
9922 static statement_t *parse_break(void)
9924 if (current_switch == NULL && current_loop == NULL) {
9925 errorf(HERE, "break statement not within loop or switch");
9928 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9931 expect(';', end_error);
9938 * Parse a __leave statement.
9940 static statement_t *parse_leave_statement(void)
9942 if (current_try == NULL) {
9943 errorf(HERE, "__leave statement not within __try");
9946 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9949 expect(';', end_error);
9956 * Check if a given entity represents a local variable.
9958 static bool is_local_variable(const entity_t *entity)
9960 if (entity->kind != ENTITY_VARIABLE)
9963 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9964 case STORAGE_CLASS_AUTO:
9965 case STORAGE_CLASS_REGISTER: {
9966 const type_t *type = skip_typeref(entity->declaration.type);
9967 if (is_type_function(type)) {
9979 * Check if a given expression represents a local variable.
9981 static bool expression_is_local_variable(const expression_t *expression)
9983 if (expression->base.kind != EXPR_REFERENCE) {
9986 const entity_t *entity = expression->reference.entity;
9987 return is_local_variable(entity);
9991 * Check if a given expression represents a local variable and
9992 * return its declaration then, else return NULL.
9994 entity_t *expression_is_variable(const expression_t *expression)
9996 if (expression->base.kind != EXPR_REFERENCE) {
9999 entity_t *entity = expression->reference.entity;
10000 if (entity->kind != ENTITY_VARIABLE)
10007 * Parse a return statement.
10009 static statement_t *parse_return(void)
10013 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10015 expression_t *return_value = NULL;
10016 if (token.type != ';') {
10017 return_value = parse_expression();
10018 mark_vars_read(return_value, NULL);
10021 const type_t *const func_type = skip_typeref(current_function->base.type);
10022 assert(is_type_function(func_type));
10023 type_t *const return_type = skip_typeref(func_type->function.return_type);
10025 source_position_t const *const pos = &statement->base.source_position;
10026 if (return_value != NULL) {
10027 type_t *return_value_type = skip_typeref(return_value->base.type);
10029 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10030 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10031 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10032 /* Only warn in C mode, because GCC does the same */
10033 if (c_mode & _CXX || strict_mode) {
10035 "'return' with a value, in function returning 'void'");
10036 } else if (warning.other) {
10038 "'return' with a value, in function returning 'void'");
10040 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10041 /* Only warn in C mode, because GCC does the same */
10044 "'return' with expression in function returning 'void'");
10045 } else if (warning.other) {
10047 "'return' with expression in function returning 'void'");
10051 assign_error_t error = semantic_assign(return_type, return_value);
10052 report_assign_error(error, return_type, return_value, "'return'",
10055 return_value = create_implicit_cast(return_value, return_type);
10056 /* check for returning address of a local var */
10057 if (warning.other && return_value != NULL
10058 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10059 const expression_t *expression = return_value->unary.value;
10060 if (expression_is_local_variable(expression)) {
10061 warningf(pos, "function returns address of local variable");
10064 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10065 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10066 if (c_mode & _CXX || strict_mode) {
10068 "'return' without value, in function returning non-void");
10071 "'return' without value, in function returning non-void");
10074 statement->returns.value = return_value;
10076 expect(';', end_error);
10083 * Parse a declaration statement.
10085 static statement_t *parse_declaration_statement(void)
10087 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10089 entity_t *before = current_scope->last_entity;
10091 parse_external_declaration();
10093 parse_declaration(record_entity, DECL_FLAGS_NONE);
10096 declaration_statement_t *const decl = &statement->declaration;
10097 entity_t *const begin =
10098 before != NULL ? before->base.next : current_scope->entities;
10099 decl->declarations_begin = begin;
10100 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10106 * Parse an expression statement, ie. expr ';'.
10108 static statement_t *parse_expression_statement(void)
10110 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10112 expression_t *const expr = parse_expression();
10113 statement->expression.expression = expr;
10114 mark_vars_read(expr, ENT_ANY);
10116 expect(';', end_error);
10123 * Parse a microsoft __try { } __finally { } or
10124 * __try{ } __except() { }
10126 static statement_t *parse_ms_try_statment(void)
10128 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10131 PUSH_PARENT(statement);
10133 ms_try_statement_t *rem = current_try;
10134 current_try = &statement->ms_try;
10135 statement->ms_try.try_statement = parse_compound_statement(false);
10140 if (next_if(T___except)) {
10141 expect('(', end_error);
10142 add_anchor_token(')');
10143 expression_t *const expr = parse_expression();
10144 mark_vars_read(expr, NULL);
10145 type_t * type = skip_typeref(expr->base.type);
10146 if (is_type_integer(type)) {
10147 type = promote_integer(type);
10148 } else if (is_type_valid(type)) {
10149 errorf(&expr->base.source_position,
10150 "__expect expression is not an integer, but '%T'", type);
10151 type = type_error_type;
10153 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10154 rem_anchor_token(')');
10155 expect(')', end_error);
10156 statement->ms_try.final_statement = parse_compound_statement(false);
10157 } else if (next_if(T__finally)) {
10158 statement->ms_try.final_statement = parse_compound_statement(false);
10160 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10161 return create_invalid_statement();
10165 return create_invalid_statement();
10168 static statement_t *parse_empty_statement(void)
10170 if (warning.empty_statement) {
10171 warningf(HERE, "statement is empty");
10173 statement_t *const statement = create_empty_statement();
10178 static statement_t *parse_local_label_declaration(void)
10180 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10184 entity_t *begin = NULL;
10185 entity_t *end = NULL;
10186 entity_t **anchor = &begin;
10188 if (token.type != T_IDENTIFIER) {
10189 parse_error_expected("while parsing local label declaration",
10190 T_IDENTIFIER, NULL);
10193 symbol_t *symbol = token.symbol;
10194 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10195 if (entity != NULL && entity->base.parent_scope == current_scope) {
10196 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10197 symbol, &entity->base.source_position);
10199 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10201 entity->base.parent_scope = current_scope;
10202 entity->base.namespc = NAMESPACE_LABEL;
10203 entity->base.source_position = token.source_position;
10204 entity->base.symbol = symbol;
10207 anchor = &entity->base.next;
10210 environment_push(entity);
10213 } while (next_if(','));
10214 expect(';', end_error);
10216 statement->declaration.declarations_begin = begin;
10217 statement->declaration.declarations_end = end;
10221 static void parse_namespace_definition(void)
10225 entity_t *entity = NULL;
10226 symbol_t *symbol = NULL;
10228 if (token.type == T_IDENTIFIER) {
10229 symbol = token.symbol;
10232 entity = get_entity(symbol, NAMESPACE_NORMAL);
10234 && entity->kind != ENTITY_NAMESPACE
10235 && entity->base.parent_scope == current_scope) {
10236 if (is_entity_valid(entity)) {
10237 error_redefined_as_different_kind(&token.source_position,
10238 entity, ENTITY_NAMESPACE);
10244 if (entity == NULL) {
10245 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10246 entity->base.symbol = symbol;
10247 entity->base.source_position = token.source_position;
10248 entity->base.namespc = NAMESPACE_NORMAL;
10249 entity->base.parent_scope = current_scope;
10252 if (token.type == '=') {
10253 /* TODO: parse namespace alias */
10254 panic("namespace alias definition not supported yet");
10257 environment_push(entity);
10258 append_entity(current_scope, entity);
10260 size_t const top = environment_top();
10261 scope_t *old_scope = scope_push(&entity->namespacee.members);
10263 entity_t *old_current_entity = current_entity;
10264 current_entity = entity;
10266 expect('{', end_error);
10268 expect('}', end_error);
10271 assert(current_scope == &entity->namespacee.members);
10272 assert(current_entity == entity);
10273 current_entity = old_current_entity;
10274 scope_pop(old_scope);
10275 environment_pop_to(top);
10279 * Parse a statement.
10280 * There's also parse_statement() which additionally checks for
10281 * "statement has no effect" warnings
10283 static statement_t *intern_parse_statement(void)
10285 statement_t *statement = NULL;
10287 /* declaration or statement */
10288 add_anchor_token(';');
10289 switch (token.type) {
10290 case T_IDENTIFIER: {
10291 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10292 if (la1_type == ':') {
10293 statement = parse_label_statement();
10294 } else if (is_typedef_symbol(token.symbol)) {
10295 statement = parse_declaration_statement();
10297 /* it's an identifier, the grammar says this must be an
10298 * expression statement. However it is common that users mistype
10299 * declaration types, so we guess a bit here to improve robustness
10300 * for incorrect programs */
10301 switch (la1_type) {
10304 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10306 statement = parse_expression_statement();
10310 statement = parse_declaration_statement();
10318 case T___extension__:
10319 /* This can be a prefix to a declaration or an expression statement.
10320 * We simply eat it now and parse the rest with tail recursion. */
10321 while (next_if(T___extension__)) {}
10322 bool old_gcc_extension = in_gcc_extension;
10323 in_gcc_extension = true;
10324 statement = intern_parse_statement();
10325 in_gcc_extension = old_gcc_extension;
10329 statement = parse_declaration_statement();
10333 statement = parse_local_label_declaration();
10336 case ';': statement = parse_empty_statement(); break;
10337 case '{': statement = parse_compound_statement(false); break;
10338 case T___leave: statement = parse_leave_statement(); break;
10339 case T___try: statement = parse_ms_try_statment(); break;
10340 case T_asm: statement = parse_asm_statement(); break;
10341 case T_break: statement = parse_break(); break;
10342 case T_case: statement = parse_case_statement(); break;
10343 case T_continue: statement = parse_continue(); break;
10344 case T_default: statement = parse_default_statement(); break;
10345 case T_do: statement = parse_do(); break;
10346 case T_for: statement = parse_for(); break;
10347 case T_goto: statement = parse_goto(); break;
10348 case T_if: statement = parse_if(); break;
10349 case T_return: statement = parse_return(); break;
10350 case T_switch: statement = parse_switch(); break;
10351 case T_while: statement = parse_while(); break;
10354 statement = parse_expression_statement();
10358 errorf(HERE, "unexpected token %K while parsing statement", &token);
10359 statement = create_invalid_statement();
10364 rem_anchor_token(';');
10366 assert(statement != NULL
10367 && statement->base.source_position.input_name != NULL);
10373 * parse a statement and emits "statement has no effect" warning if needed
10374 * (This is really a wrapper around intern_parse_statement with check for 1
10375 * single warning. It is needed, because for statement expressions we have
10376 * to avoid the warning on the last statement)
10378 static statement_t *parse_statement(void)
10380 statement_t *statement = intern_parse_statement();
10382 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10383 expression_t *expression = statement->expression.expression;
10384 if (!expression_has_effect(expression)) {
10385 warningf(&expression->base.source_position,
10386 "statement has no effect");
10394 * Parse a compound statement.
10396 static statement_t *parse_compound_statement(bool inside_expression_statement)
10398 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10400 PUSH_PARENT(statement);
10403 add_anchor_token('}');
10404 /* tokens, which can start a statement */
10405 /* TODO MS, __builtin_FOO */
10406 add_anchor_token('!');
10407 add_anchor_token('&');
10408 add_anchor_token('(');
10409 add_anchor_token('*');
10410 add_anchor_token('+');
10411 add_anchor_token('-');
10412 add_anchor_token('{');
10413 add_anchor_token('~');
10414 add_anchor_token(T_CHARACTER_CONSTANT);
10415 add_anchor_token(T_COLONCOLON);
10416 add_anchor_token(T_FLOATINGPOINT);
10417 add_anchor_token(T_IDENTIFIER);
10418 add_anchor_token(T_INTEGER);
10419 add_anchor_token(T_MINUSMINUS);
10420 add_anchor_token(T_PLUSPLUS);
10421 add_anchor_token(T_STRING_LITERAL);
10422 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10423 add_anchor_token(T_WIDE_STRING_LITERAL);
10424 add_anchor_token(T__Bool);
10425 add_anchor_token(T__Complex);
10426 add_anchor_token(T__Imaginary);
10427 add_anchor_token(T___FUNCTION__);
10428 add_anchor_token(T___PRETTY_FUNCTION__);
10429 add_anchor_token(T___alignof__);
10430 add_anchor_token(T___attribute__);
10431 add_anchor_token(T___builtin_va_start);
10432 add_anchor_token(T___extension__);
10433 add_anchor_token(T___func__);
10434 add_anchor_token(T___imag__);
10435 add_anchor_token(T___label__);
10436 add_anchor_token(T___real__);
10437 add_anchor_token(T___thread);
10438 add_anchor_token(T_asm);
10439 add_anchor_token(T_auto);
10440 add_anchor_token(T_bool);
10441 add_anchor_token(T_break);
10442 add_anchor_token(T_case);
10443 add_anchor_token(T_char);
10444 add_anchor_token(T_class);
10445 add_anchor_token(T_const);
10446 add_anchor_token(T_const_cast);
10447 add_anchor_token(T_continue);
10448 add_anchor_token(T_default);
10449 add_anchor_token(T_delete);
10450 add_anchor_token(T_double);
10451 add_anchor_token(T_do);
10452 add_anchor_token(T_dynamic_cast);
10453 add_anchor_token(T_enum);
10454 add_anchor_token(T_extern);
10455 add_anchor_token(T_false);
10456 add_anchor_token(T_float);
10457 add_anchor_token(T_for);
10458 add_anchor_token(T_goto);
10459 add_anchor_token(T_if);
10460 add_anchor_token(T_inline);
10461 add_anchor_token(T_int);
10462 add_anchor_token(T_long);
10463 add_anchor_token(T_new);
10464 add_anchor_token(T_operator);
10465 add_anchor_token(T_register);
10466 add_anchor_token(T_reinterpret_cast);
10467 add_anchor_token(T_restrict);
10468 add_anchor_token(T_return);
10469 add_anchor_token(T_short);
10470 add_anchor_token(T_signed);
10471 add_anchor_token(T_sizeof);
10472 add_anchor_token(T_static);
10473 add_anchor_token(T_static_cast);
10474 add_anchor_token(T_struct);
10475 add_anchor_token(T_switch);
10476 add_anchor_token(T_template);
10477 add_anchor_token(T_this);
10478 add_anchor_token(T_throw);
10479 add_anchor_token(T_true);
10480 add_anchor_token(T_try);
10481 add_anchor_token(T_typedef);
10482 add_anchor_token(T_typeid);
10483 add_anchor_token(T_typename);
10484 add_anchor_token(T_typeof);
10485 add_anchor_token(T_union);
10486 add_anchor_token(T_unsigned);
10487 add_anchor_token(T_using);
10488 add_anchor_token(T_void);
10489 add_anchor_token(T_volatile);
10490 add_anchor_token(T_wchar_t);
10491 add_anchor_token(T_while);
10493 size_t const top = environment_top();
10494 scope_t *old_scope = scope_push(&statement->compound.scope);
10496 statement_t **anchor = &statement->compound.statements;
10497 bool only_decls_so_far = true;
10498 while (token.type != '}') {
10499 if (token.type == T_EOF) {
10500 errorf(&statement->base.source_position,
10501 "EOF while parsing compound statement");
10504 statement_t *sub_statement = intern_parse_statement();
10505 if (is_invalid_statement(sub_statement)) {
10506 /* an error occurred. if we are at an anchor, return */
10512 if (warning.declaration_after_statement) {
10513 if (sub_statement->kind != STATEMENT_DECLARATION) {
10514 only_decls_so_far = false;
10515 } else if (!only_decls_so_far) {
10516 warningf(&sub_statement->base.source_position,
10517 "ISO C90 forbids mixed declarations and code");
10521 *anchor = sub_statement;
10523 while (sub_statement->base.next != NULL)
10524 sub_statement = sub_statement->base.next;
10526 anchor = &sub_statement->base.next;
10530 /* look over all statements again to produce no effect warnings */
10531 if (warning.unused_value) {
10532 statement_t *sub_statement = statement->compound.statements;
10533 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10534 if (sub_statement->kind != STATEMENT_EXPRESSION)
10536 /* don't emit a warning for the last expression in an expression
10537 * statement as it has always an effect */
10538 if (inside_expression_statement && sub_statement->base.next == NULL)
10541 expression_t *expression = sub_statement->expression.expression;
10542 if (!expression_has_effect(expression)) {
10543 warningf(&expression->base.source_position,
10544 "statement has no effect");
10550 rem_anchor_token(T_while);
10551 rem_anchor_token(T_wchar_t);
10552 rem_anchor_token(T_volatile);
10553 rem_anchor_token(T_void);
10554 rem_anchor_token(T_using);
10555 rem_anchor_token(T_unsigned);
10556 rem_anchor_token(T_union);
10557 rem_anchor_token(T_typeof);
10558 rem_anchor_token(T_typename);
10559 rem_anchor_token(T_typeid);
10560 rem_anchor_token(T_typedef);
10561 rem_anchor_token(T_try);
10562 rem_anchor_token(T_true);
10563 rem_anchor_token(T_throw);
10564 rem_anchor_token(T_this);
10565 rem_anchor_token(T_template);
10566 rem_anchor_token(T_switch);
10567 rem_anchor_token(T_struct);
10568 rem_anchor_token(T_static_cast);
10569 rem_anchor_token(T_static);
10570 rem_anchor_token(T_sizeof);
10571 rem_anchor_token(T_signed);
10572 rem_anchor_token(T_short);
10573 rem_anchor_token(T_return);
10574 rem_anchor_token(T_restrict);
10575 rem_anchor_token(T_reinterpret_cast);
10576 rem_anchor_token(T_register);
10577 rem_anchor_token(T_operator);
10578 rem_anchor_token(T_new);
10579 rem_anchor_token(T_long);
10580 rem_anchor_token(T_int);
10581 rem_anchor_token(T_inline);
10582 rem_anchor_token(T_if);
10583 rem_anchor_token(T_goto);
10584 rem_anchor_token(T_for);
10585 rem_anchor_token(T_float);
10586 rem_anchor_token(T_false);
10587 rem_anchor_token(T_extern);
10588 rem_anchor_token(T_enum);
10589 rem_anchor_token(T_dynamic_cast);
10590 rem_anchor_token(T_do);
10591 rem_anchor_token(T_double);
10592 rem_anchor_token(T_delete);
10593 rem_anchor_token(T_default);
10594 rem_anchor_token(T_continue);
10595 rem_anchor_token(T_const_cast);
10596 rem_anchor_token(T_const);
10597 rem_anchor_token(T_class);
10598 rem_anchor_token(T_char);
10599 rem_anchor_token(T_case);
10600 rem_anchor_token(T_break);
10601 rem_anchor_token(T_bool);
10602 rem_anchor_token(T_auto);
10603 rem_anchor_token(T_asm);
10604 rem_anchor_token(T___thread);
10605 rem_anchor_token(T___real__);
10606 rem_anchor_token(T___label__);
10607 rem_anchor_token(T___imag__);
10608 rem_anchor_token(T___func__);
10609 rem_anchor_token(T___extension__);
10610 rem_anchor_token(T___builtin_va_start);
10611 rem_anchor_token(T___attribute__);
10612 rem_anchor_token(T___alignof__);
10613 rem_anchor_token(T___PRETTY_FUNCTION__);
10614 rem_anchor_token(T___FUNCTION__);
10615 rem_anchor_token(T__Imaginary);
10616 rem_anchor_token(T__Complex);
10617 rem_anchor_token(T__Bool);
10618 rem_anchor_token(T_WIDE_STRING_LITERAL);
10619 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10620 rem_anchor_token(T_STRING_LITERAL);
10621 rem_anchor_token(T_PLUSPLUS);
10622 rem_anchor_token(T_MINUSMINUS);
10623 rem_anchor_token(T_INTEGER);
10624 rem_anchor_token(T_IDENTIFIER);
10625 rem_anchor_token(T_FLOATINGPOINT);
10626 rem_anchor_token(T_COLONCOLON);
10627 rem_anchor_token(T_CHARACTER_CONSTANT);
10628 rem_anchor_token('~');
10629 rem_anchor_token('{');
10630 rem_anchor_token('-');
10631 rem_anchor_token('+');
10632 rem_anchor_token('*');
10633 rem_anchor_token('(');
10634 rem_anchor_token('&');
10635 rem_anchor_token('!');
10636 rem_anchor_token('}');
10637 assert(current_scope == &statement->compound.scope);
10638 scope_pop(old_scope);
10639 environment_pop_to(top);
10646 * Check for unused global static functions and variables
10648 static void check_unused_globals(void)
10650 if (!warning.unused_function && !warning.unused_variable)
10653 for (const entity_t *entity = file_scope->entities; entity != NULL;
10654 entity = entity->base.next) {
10655 if (!is_declaration(entity))
10658 const declaration_t *declaration = &entity->declaration;
10659 if (declaration->used ||
10660 declaration->modifiers & DM_UNUSED ||
10661 declaration->modifiers & DM_USED ||
10662 declaration->storage_class != STORAGE_CLASS_STATIC)
10665 type_t *const type = declaration->type;
10667 if (entity->kind == ENTITY_FUNCTION) {
10668 /* inhibit warning for static inline functions */
10669 if (entity->function.is_inline)
10672 s = entity->function.statement != NULL ? "defined" : "declared";
10677 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10678 type, declaration->base.symbol, s);
10682 static void parse_global_asm(void)
10684 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10687 expect('(', end_error);
10689 statement->asms.asm_text = parse_string_literals();
10690 statement->base.next = unit->global_asm;
10691 unit->global_asm = statement;
10693 expect(')', end_error);
10694 expect(';', end_error);
10699 static void parse_linkage_specification(void)
10703 const char *linkage = parse_string_literals().begin;
10705 linkage_kind_t old_linkage = current_linkage;
10706 linkage_kind_t new_linkage;
10707 if (strcmp(linkage, "C") == 0) {
10708 new_linkage = LINKAGE_C;
10709 } else if (strcmp(linkage, "C++") == 0) {
10710 new_linkage = LINKAGE_CXX;
10712 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10713 new_linkage = LINKAGE_INVALID;
10715 current_linkage = new_linkage;
10717 if (next_if('{')) {
10719 expect('}', end_error);
10725 assert(current_linkage == new_linkage);
10726 current_linkage = old_linkage;
10729 static void parse_external(void)
10731 switch (token.type) {
10732 DECLARATION_START_NO_EXTERN
10734 case T___extension__:
10735 /* tokens below are for implicit int */
10736 case '&': /* & x; -> int& x; (and error later, because C++ has no
10738 case '*': /* * x; -> int* x; */
10739 case '(': /* (x); -> int (x); */
10740 parse_external_declaration();
10744 if (look_ahead(1)->type == T_STRING_LITERAL) {
10745 parse_linkage_specification();
10747 parse_external_declaration();
10752 parse_global_asm();
10756 parse_namespace_definition();
10760 if (!strict_mode) {
10762 warningf(HERE, "stray ';' outside of function");
10769 errorf(HERE, "stray %K outside of function", &token);
10770 if (token.type == '(' || token.type == '{' || token.type == '[')
10771 eat_until_matching_token(token.type);
10777 static void parse_externals(void)
10779 add_anchor_token('}');
10780 add_anchor_token(T_EOF);
10783 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10784 unsigned char token_anchor_copy[T_LAST_TOKEN];
10785 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10788 while (token.type != T_EOF && token.type != '}') {
10790 bool anchor_leak = false;
10791 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10792 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10794 /* the anchor set and its copy differs */
10795 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10796 anchor_leak = true;
10799 if (in_gcc_extension) {
10800 /* an gcc extension scope was not closed */
10801 internal_errorf(HERE, "Leaked __extension__");
10802 anchor_leak = true;
10812 rem_anchor_token(T_EOF);
10813 rem_anchor_token('}');
10817 * Parse a translation unit.
10819 static void parse_translation_unit(void)
10821 add_anchor_token(T_EOF);
10826 if (token.type == T_EOF)
10829 errorf(HERE, "stray %K outside of function", &token);
10830 if (token.type == '(' || token.type == '{' || token.type == '[')
10831 eat_until_matching_token(token.type);
10836 void set_default_visibility(elf_visibility_tag_t visibility)
10838 default_visibility = visibility;
10844 * @return the translation unit or NULL if errors occurred.
10846 void start_parsing(void)
10848 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10849 label_stack = NEW_ARR_F(stack_entry_t, 0);
10850 diagnostic_count = 0;
10854 print_to_file(stderr);
10856 assert(unit == NULL);
10857 unit = allocate_ast_zero(sizeof(unit[0]));
10859 assert(file_scope == NULL);
10860 file_scope = &unit->scope;
10862 assert(current_scope == NULL);
10863 scope_push(&unit->scope);
10865 create_gnu_builtins();
10867 create_microsoft_intrinsics();
10870 translation_unit_t *finish_parsing(void)
10872 assert(current_scope == &unit->scope);
10875 assert(file_scope == &unit->scope);
10876 check_unused_globals();
10879 DEL_ARR_F(environment_stack);
10880 DEL_ARR_F(label_stack);
10882 translation_unit_t *result = unit;
10887 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10888 * are given length one. */
10889 static void complete_incomplete_arrays(void)
10891 size_t n = ARR_LEN(incomplete_arrays);
10892 for (size_t i = 0; i != n; ++i) {
10893 declaration_t *const decl = incomplete_arrays[i];
10894 type_t *const orig_type = decl->type;
10895 type_t *const type = skip_typeref(orig_type);
10897 if (!is_type_incomplete(type))
10900 if (warning.other) {
10901 warningf(&decl->base.source_position,
10902 "array '%#T' assumed to have one element",
10903 orig_type, decl->base.symbol);
10906 type_t *const new_type = duplicate_type(type);
10907 new_type->array.size_constant = true;
10908 new_type->array.has_implicit_size = true;
10909 new_type->array.size = 1;
10911 type_t *const result = identify_new_type(new_type);
10913 decl->type = result;
10917 void prepare_main_collect2(entity_t *entity)
10919 // create call to __main
10920 symbol_t *symbol = symbol_table_insert("__main");
10921 entity_t *subsubmain_ent
10922 = create_implicit_function(symbol, &builtin_source_position);
10924 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10925 type_t *ftype = subsubmain_ent->declaration.type;
10926 ref->base.source_position = builtin_source_position;
10927 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10928 ref->reference.entity = subsubmain_ent;
10930 expression_t *call = allocate_expression_zero(EXPR_CALL);
10931 call->base.source_position = builtin_source_position;
10932 call->base.type = type_void;
10933 call->call.function = ref;
10935 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10936 expr_statement->base.source_position = builtin_source_position;
10937 expr_statement->expression.expression = call;
10939 statement_t *statement = entity->function.statement;
10940 assert(statement->kind == STATEMENT_COMPOUND);
10941 compound_statement_t *compounds = &statement->compound;
10943 expr_statement->base.next = compounds->statements;
10944 compounds->statements = expr_statement;
10949 lookahead_bufpos = 0;
10950 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10953 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10954 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10955 parse_translation_unit();
10956 complete_incomplete_arrays();
10957 DEL_ARR_F(incomplete_arrays);
10958 incomplete_arrays = NULL;
10962 * Initialize the parser.
10964 void init_parser(void)
10966 sym_anonymous = symbol_table_insert("<anonymous>");
10968 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10970 init_expression_parsers();
10971 obstack_init(&temp_obst);
10975 * Terminate the parser.
10977 void exit_parser(void)
10979 obstack_free(&temp_obst, NULL);