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 (warning.shadow_local && previous_entity->base.parent_scope != file_scope)) {
4381 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4382 get_entity_kind_name(entity->kind), symbol,
4383 get_entity_kind_name(previous_entity->kind),
4384 &previous_entity->base.source_position);
4388 if (entity->kind == ENTITY_FUNCTION) {
4389 if (is_definition &&
4390 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4391 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4392 warningf(pos, "no previous prototype for '%#T'",
4393 entity->declaration.type, symbol);
4394 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4395 warningf(pos, "no previous declaration for '%#T'",
4396 entity->declaration.type, symbol);
4399 } else if (warning.missing_declarations &&
4400 entity->kind == ENTITY_VARIABLE &&
4401 current_scope == file_scope) {
4402 declaration_t *declaration = &entity->declaration;
4403 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4404 warningf(pos, "no previous declaration for '%#T'",
4405 declaration->type, symbol);
4410 assert(entity->base.parent_scope == NULL);
4411 assert(current_scope != NULL);
4413 entity->base.parent_scope = current_scope;
4414 entity->base.namespc = NAMESPACE_NORMAL;
4415 environment_push(entity);
4416 append_entity(current_scope, entity);
4421 static void parser_error_multiple_definition(entity_t *entity,
4422 const source_position_t *source_position)
4424 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4425 entity->base.symbol, &entity->base.source_position);
4428 static bool is_declaration_specifier(const token_t *token,
4429 bool only_specifiers_qualifiers)
4431 switch (token->type) {
4436 return is_typedef_symbol(token->symbol);
4438 case T___extension__:
4440 return !only_specifiers_qualifiers;
4447 static void parse_init_declarator_rest(entity_t *entity)
4449 type_t *orig_type = type_error_type;
4451 if (entity->base.kind == ENTITY_TYPEDEF) {
4452 errorf(&entity->base.source_position,
4453 "typedef '%Y' is initialized (use __typeof__ instead)",
4454 entity->base.symbol);
4456 assert(is_declaration(entity));
4457 orig_type = entity->declaration.type;
4461 type_t *type = skip_typeref(orig_type);
4463 if (entity->kind == ENTITY_VARIABLE
4464 && entity->variable.initializer != NULL) {
4465 parser_error_multiple_definition(entity, HERE);
4468 declaration_t *const declaration = &entity->declaration;
4469 bool must_be_constant = false;
4470 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4471 entity->base.parent_scope == file_scope) {
4472 must_be_constant = true;
4475 if (is_type_function(type)) {
4476 errorf(&entity->base.source_position,
4477 "function '%#T' is initialized like a variable",
4478 orig_type, entity->base.symbol);
4479 orig_type = type_error_type;
4482 parse_initializer_env_t env;
4483 env.type = orig_type;
4484 env.must_be_constant = must_be_constant;
4485 env.entity = entity;
4486 current_init_decl = entity;
4488 initializer_t *initializer = parse_initializer(&env);
4489 current_init_decl = NULL;
4491 if (entity->kind == ENTITY_VARIABLE) {
4492 /* §6.7.5:22 array initializers for arrays with unknown size
4493 * determine the array type size */
4494 declaration->type = env.type;
4495 entity->variable.initializer = initializer;
4499 /* parse rest of a declaration without any declarator */
4500 static void parse_anonymous_declaration_rest(
4501 const declaration_specifiers_t *specifiers)
4504 anonymous_entity = NULL;
4506 if (warning.other) {
4507 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4508 specifiers->thread_local) {
4509 warningf(&specifiers->source_position,
4510 "useless storage class in empty declaration");
4513 type_t *type = specifiers->type;
4514 switch (type->kind) {
4515 case TYPE_COMPOUND_STRUCT:
4516 case TYPE_COMPOUND_UNION: {
4517 if (type->compound.compound->base.symbol == NULL) {
4518 warningf(&specifiers->source_position,
4519 "unnamed struct/union that defines no instances");
4528 warningf(&specifiers->source_position, "empty declaration");
4534 static void check_variable_type_complete(entity_t *ent)
4536 if (ent->kind != ENTITY_VARIABLE)
4539 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4540 * type for the object shall be complete [...] */
4541 declaration_t *decl = &ent->declaration;
4542 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4543 decl->storage_class == STORAGE_CLASS_STATIC)
4546 type_t *const orig_type = decl->type;
4547 type_t *const type = skip_typeref(orig_type);
4548 if (!is_type_incomplete(type))
4551 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4552 * are given length one. */
4553 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4554 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4558 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4559 orig_type, ent->base.symbol);
4563 static void parse_declaration_rest(entity_t *ndeclaration,
4564 const declaration_specifiers_t *specifiers,
4565 parsed_declaration_func finished_declaration,
4566 declarator_flags_t flags)
4568 add_anchor_token(';');
4569 add_anchor_token(',');
4571 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4573 if (token.type == '=') {
4574 parse_init_declarator_rest(entity);
4575 } else if (entity->kind == ENTITY_VARIABLE) {
4576 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4577 * [...] where the extern specifier is explicitly used. */
4578 declaration_t *decl = &entity->declaration;
4579 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4580 type_t *type = decl->type;
4581 if (is_type_reference(skip_typeref(type))) {
4582 errorf(&entity->base.source_position,
4583 "reference '%#T' must be initialized",
4584 type, entity->base.symbol);
4589 check_variable_type_complete(entity);
4594 add_anchor_token('=');
4595 ndeclaration = parse_declarator(specifiers, flags);
4596 rem_anchor_token('=');
4598 expect(';', end_error);
4601 anonymous_entity = NULL;
4602 rem_anchor_token(';');
4603 rem_anchor_token(',');
4606 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4608 symbol_t *symbol = entity->base.symbol;
4609 if (symbol == NULL) {
4610 errorf(HERE, "anonymous declaration not valid as function parameter");
4614 assert(entity->base.namespc == NAMESPACE_NORMAL);
4615 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4616 if (previous_entity == NULL
4617 || previous_entity->base.parent_scope != current_scope) {
4618 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4623 if (is_definition) {
4624 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4627 return record_entity(entity, false);
4630 static void parse_declaration(parsed_declaration_func finished_declaration,
4631 declarator_flags_t flags)
4633 declaration_specifiers_t specifiers;
4634 memset(&specifiers, 0, sizeof(specifiers));
4636 add_anchor_token(';');
4637 parse_declaration_specifiers(&specifiers);
4638 rem_anchor_token(';');
4640 if (token.type == ';') {
4641 parse_anonymous_declaration_rest(&specifiers);
4643 entity_t *entity = parse_declarator(&specifiers, flags);
4644 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4649 static type_t *get_default_promoted_type(type_t *orig_type)
4651 type_t *result = orig_type;
4653 type_t *type = skip_typeref(orig_type);
4654 if (is_type_integer(type)) {
4655 result = promote_integer(type);
4656 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4657 result = type_double;
4663 static void parse_kr_declaration_list(entity_t *entity)
4665 if (entity->kind != ENTITY_FUNCTION)
4668 type_t *type = skip_typeref(entity->declaration.type);
4669 assert(is_type_function(type));
4670 if (!type->function.kr_style_parameters)
4673 add_anchor_token('{');
4675 /* push function parameters */
4676 size_t const top = environment_top();
4677 scope_t *old_scope = scope_push(&entity->function.parameters);
4679 entity_t *parameter = entity->function.parameters.entities;
4680 for ( ; parameter != NULL; parameter = parameter->base.next) {
4681 assert(parameter->base.parent_scope == NULL);
4682 parameter->base.parent_scope = current_scope;
4683 environment_push(parameter);
4686 /* parse declaration list */
4688 switch (token.type) {
4690 case T___extension__:
4691 /* This covers symbols, which are no type, too, and results in
4692 * better error messages. The typical cases are misspelled type
4693 * names and missing includes. */
4695 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4703 /* pop function parameters */
4704 assert(current_scope == &entity->function.parameters);
4705 scope_pop(old_scope);
4706 environment_pop_to(top);
4708 /* update function type */
4709 type_t *new_type = duplicate_type(type);
4711 function_parameter_t *parameters = NULL;
4712 function_parameter_t **anchor = ¶meters;
4714 /* did we have an earlier prototype? */
4715 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4716 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4719 function_parameter_t *proto_parameter = NULL;
4720 if (proto_type != NULL) {
4721 type_t *proto_type_type = proto_type->declaration.type;
4722 proto_parameter = proto_type_type->function.parameters;
4723 /* If a K&R function definition has a variadic prototype earlier, then
4724 * make the function definition variadic, too. This should conform to
4725 * §6.7.5.3:15 and §6.9.1:8. */
4726 new_type->function.variadic = proto_type_type->function.variadic;
4728 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4730 new_type->function.unspecified_parameters = true;
4733 bool need_incompatible_warning = false;
4734 parameter = entity->function.parameters.entities;
4735 for (; parameter != NULL; parameter = parameter->base.next,
4737 proto_parameter == NULL ? NULL : proto_parameter->next) {
4738 if (parameter->kind != ENTITY_PARAMETER)
4741 type_t *parameter_type = parameter->declaration.type;
4742 if (parameter_type == NULL) {
4744 errorf(HERE, "no type specified for function parameter '%Y'",
4745 parameter->base.symbol);
4746 parameter_type = type_error_type;
4748 if (warning.implicit_int) {
4749 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4750 parameter->base.symbol);
4752 parameter_type = type_int;
4754 parameter->declaration.type = parameter_type;
4757 semantic_parameter_incomplete(parameter);
4759 /* we need the default promoted types for the function type */
4760 type_t *not_promoted = parameter_type;
4761 parameter_type = get_default_promoted_type(parameter_type);
4763 /* gcc special: if the type of the prototype matches the unpromoted
4764 * type don't promote */
4765 if (!strict_mode && proto_parameter != NULL) {
4766 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4767 type_t *promo_skip = skip_typeref(parameter_type);
4768 type_t *param_skip = skip_typeref(not_promoted);
4769 if (!types_compatible(proto_p_type, promo_skip)
4770 && types_compatible(proto_p_type, param_skip)) {
4772 need_incompatible_warning = true;
4773 parameter_type = not_promoted;
4776 function_parameter_t *const parameter
4777 = allocate_parameter(parameter_type);
4779 *anchor = parameter;
4780 anchor = ¶meter->next;
4783 new_type->function.parameters = parameters;
4784 new_type = identify_new_type(new_type);
4786 if (warning.other && need_incompatible_warning) {
4787 type_t *proto_type_type = proto_type->declaration.type;
4789 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4790 proto_type_type, proto_type->base.symbol,
4791 new_type, entity->base.symbol,
4792 &proto_type->base.source_position);
4795 entity->declaration.type = new_type;
4797 rem_anchor_token('{');
4800 static bool first_err = true;
4803 * When called with first_err set, prints the name of the current function,
4806 static void print_in_function(void)
4810 diagnosticf("%s: In function '%Y':\n",
4811 current_function->base.base.source_position.input_name,
4812 current_function->base.base.symbol);
4817 * Check if all labels are defined in the current function.
4818 * Check if all labels are used in the current function.
4820 static void check_labels(void)
4822 for (const goto_statement_t *goto_statement = goto_first;
4823 goto_statement != NULL;
4824 goto_statement = goto_statement->next) {
4825 /* skip computed gotos */
4826 if (goto_statement->expression != NULL)
4829 label_t *label = goto_statement->label;
4832 if (label->base.source_position.input_name == NULL) {
4833 print_in_function();
4834 errorf(&goto_statement->base.source_position,
4835 "label '%Y' used but not defined", label->base.symbol);
4839 if (warning.unused_label) {
4840 for (const label_statement_t *label_statement = label_first;
4841 label_statement != NULL;
4842 label_statement = label_statement->next) {
4843 label_t *label = label_statement->label;
4845 if (! label->used) {
4846 print_in_function();
4847 warningf(&label_statement->base.source_position,
4848 "label '%Y' defined but not used", label->base.symbol);
4854 static void warn_unused_entity(entity_t *entity, entity_t *last)
4856 entity_t const *const end = last != NULL ? last->base.next : NULL;
4857 for (; entity != end; entity = entity->base.next) {
4858 if (!is_declaration(entity))
4861 declaration_t *declaration = &entity->declaration;
4862 if (declaration->implicit)
4865 if (!declaration->used) {
4866 print_in_function();
4867 const char *what = get_entity_kind_name(entity->kind);
4868 warningf(&entity->base.source_position, "%s '%Y' is unused",
4869 what, entity->base.symbol);
4870 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4871 print_in_function();
4872 const char *what = get_entity_kind_name(entity->kind);
4873 warningf(&entity->base.source_position, "%s '%Y' is never read",
4874 what, entity->base.symbol);
4879 static void check_unused_variables(statement_t *const stmt, void *const env)
4883 switch (stmt->kind) {
4884 case STATEMENT_DECLARATION: {
4885 declaration_statement_t const *const decls = &stmt->declaration;
4886 warn_unused_entity(decls->declarations_begin,
4887 decls->declarations_end);
4892 warn_unused_entity(stmt->fors.scope.entities, NULL);
4901 * Check declarations of current_function for unused entities.
4903 static void check_declarations(void)
4905 if (warning.unused_parameter) {
4906 const scope_t *scope = ¤t_function->parameters;
4908 /* do not issue unused warnings for main */
4909 if (!is_sym_main(current_function->base.base.symbol)) {
4910 warn_unused_entity(scope->entities, NULL);
4913 if (warning.unused_variable) {
4914 walk_statements(current_function->statement, check_unused_variables,
4919 static int determine_truth(expression_t const* const cond)
4922 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4923 fold_constant_to_bool(cond) ? 1 :
4927 static void check_reachable(statement_t *);
4928 static bool reaches_end;
4930 static bool expression_returns(expression_t const *const expr)
4932 switch (expr->kind) {
4934 expression_t const *const func = expr->call.function;
4935 if (func->kind == EXPR_REFERENCE) {
4936 entity_t *entity = func->reference.entity;
4937 if (entity->kind == ENTITY_FUNCTION
4938 && entity->declaration.modifiers & DM_NORETURN)
4942 if (!expression_returns(func))
4945 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4946 if (!expression_returns(arg->expression))
4953 case EXPR_REFERENCE:
4954 case EXPR_REFERENCE_ENUM_VALUE:
4956 case EXPR_STRING_LITERAL:
4957 case EXPR_WIDE_STRING_LITERAL:
4958 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4959 case EXPR_LABEL_ADDRESS:
4960 case EXPR_CLASSIFY_TYPE:
4961 case EXPR_SIZEOF: // TODO handle obscure VLA case
4964 case EXPR_BUILTIN_CONSTANT_P:
4965 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4970 case EXPR_STATEMENT: {
4971 bool old_reaches_end = reaches_end;
4972 reaches_end = false;
4973 check_reachable(expr->statement.statement);
4974 bool returns = reaches_end;
4975 reaches_end = old_reaches_end;
4979 case EXPR_CONDITIONAL:
4980 // TODO handle constant expression
4982 if (!expression_returns(expr->conditional.condition))
4985 if (expr->conditional.true_expression != NULL
4986 && expression_returns(expr->conditional.true_expression))
4989 return expression_returns(expr->conditional.false_expression);
4992 return expression_returns(expr->select.compound);
4994 case EXPR_ARRAY_ACCESS:
4996 expression_returns(expr->array_access.array_ref) &&
4997 expression_returns(expr->array_access.index);
5000 return expression_returns(expr->va_starte.ap);
5003 return expression_returns(expr->va_arge.ap);
5006 return expression_returns(expr->va_copye.src);
5008 EXPR_UNARY_CASES_MANDATORY
5009 return expression_returns(expr->unary.value);
5011 case EXPR_UNARY_THROW:
5015 // TODO handle constant lhs of && and ||
5017 expression_returns(expr->binary.left) &&
5018 expression_returns(expr->binary.right);
5024 panic("unhandled expression");
5027 static bool initializer_returns(initializer_t const *const init)
5029 switch (init->kind) {
5030 case INITIALIZER_VALUE:
5031 return expression_returns(init->value.value);
5033 case INITIALIZER_LIST: {
5034 initializer_t * const* i = init->list.initializers;
5035 initializer_t * const* const end = i + init->list.len;
5036 bool returns = true;
5037 for (; i != end; ++i) {
5038 if (!initializer_returns(*i))
5044 case INITIALIZER_STRING:
5045 case INITIALIZER_WIDE_STRING:
5046 case INITIALIZER_DESIGNATOR: // designators have no payload
5049 panic("unhandled initializer");
5052 static bool noreturn_candidate;
5054 static void check_reachable(statement_t *const stmt)
5056 if (stmt->base.reachable)
5058 if (stmt->kind != STATEMENT_DO_WHILE)
5059 stmt->base.reachable = true;
5061 statement_t *last = stmt;
5063 switch (stmt->kind) {
5064 case STATEMENT_INVALID:
5065 case STATEMENT_EMPTY:
5067 next = stmt->base.next;
5070 case STATEMENT_DECLARATION: {
5071 declaration_statement_t const *const decl = &stmt->declaration;
5072 entity_t const * ent = decl->declarations_begin;
5073 entity_t const *const last = decl->declarations_end;
5075 for (;; ent = ent->base.next) {
5076 if (ent->kind == ENTITY_VARIABLE &&
5077 ent->variable.initializer != NULL &&
5078 !initializer_returns(ent->variable.initializer)) {
5085 next = stmt->base.next;
5089 case STATEMENT_COMPOUND:
5090 next = stmt->compound.statements;
5092 next = stmt->base.next;
5095 case STATEMENT_RETURN: {
5096 expression_t const *const val = stmt->returns.value;
5097 if (val == NULL || expression_returns(val))
5098 noreturn_candidate = false;
5102 case STATEMENT_IF: {
5103 if_statement_t const *const ifs = &stmt->ifs;
5104 expression_t const *const cond = ifs->condition;
5106 if (!expression_returns(cond))
5109 int const val = determine_truth(cond);
5112 check_reachable(ifs->true_statement);
5117 if (ifs->false_statement != NULL) {
5118 check_reachable(ifs->false_statement);
5122 next = stmt->base.next;
5126 case STATEMENT_SWITCH: {
5127 switch_statement_t const *const switchs = &stmt->switchs;
5128 expression_t const *const expr = switchs->expression;
5130 if (!expression_returns(expr))
5133 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5134 long const val = fold_constant_to_int(expr);
5135 case_label_statement_t * defaults = NULL;
5136 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5137 if (i->expression == NULL) {
5142 if (i->first_case <= val && val <= i->last_case) {
5143 check_reachable((statement_t*)i);
5148 if (defaults != NULL) {
5149 check_reachable((statement_t*)defaults);
5153 bool has_default = false;
5154 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5155 if (i->expression == NULL)
5158 check_reachable((statement_t*)i);
5165 next = stmt->base.next;
5169 case STATEMENT_EXPRESSION: {
5170 /* Check for noreturn function call */
5171 expression_t const *const expr = stmt->expression.expression;
5172 if (!expression_returns(expr))
5175 next = stmt->base.next;
5179 case STATEMENT_CONTINUE:
5180 for (statement_t *parent = stmt;;) {
5181 parent = parent->base.parent;
5182 if (parent == NULL) /* continue not within loop */
5186 switch (parent->kind) {
5187 case STATEMENT_WHILE: goto continue_while;
5188 case STATEMENT_DO_WHILE: goto continue_do_while;
5189 case STATEMENT_FOR: goto continue_for;
5195 case STATEMENT_BREAK:
5196 for (statement_t *parent = stmt;;) {
5197 parent = parent->base.parent;
5198 if (parent == NULL) /* break not within loop/switch */
5201 switch (parent->kind) {
5202 case STATEMENT_SWITCH:
5203 case STATEMENT_WHILE:
5204 case STATEMENT_DO_WHILE:
5207 next = parent->base.next;
5208 goto found_break_parent;
5216 case STATEMENT_GOTO:
5217 if (stmt->gotos.expression) {
5218 if (!expression_returns(stmt->gotos.expression))
5221 statement_t *parent = stmt->base.parent;
5222 if (parent == NULL) /* top level goto */
5226 next = stmt->gotos.label->statement;
5227 if (next == NULL) /* missing label */
5232 case STATEMENT_LABEL:
5233 next = stmt->label.statement;
5236 case STATEMENT_CASE_LABEL:
5237 next = stmt->case_label.statement;
5240 case STATEMENT_WHILE: {
5241 while_statement_t const *const whiles = &stmt->whiles;
5242 expression_t const *const cond = whiles->condition;
5244 if (!expression_returns(cond))
5247 int const val = determine_truth(cond);
5250 check_reachable(whiles->body);
5255 next = stmt->base.next;
5259 case STATEMENT_DO_WHILE:
5260 next = stmt->do_while.body;
5263 case STATEMENT_FOR: {
5264 for_statement_t *const fors = &stmt->fors;
5266 if (fors->condition_reachable)
5268 fors->condition_reachable = true;
5270 expression_t const *const cond = fors->condition;
5275 } else if (expression_returns(cond)) {
5276 val = determine_truth(cond);
5282 check_reachable(fors->body);
5287 next = stmt->base.next;
5291 case STATEMENT_MS_TRY: {
5292 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5293 check_reachable(ms_try->try_statement);
5294 next = ms_try->final_statement;
5298 case STATEMENT_LEAVE: {
5299 statement_t *parent = stmt;
5301 parent = parent->base.parent;
5302 if (parent == NULL) /* __leave not within __try */
5305 if (parent->kind == STATEMENT_MS_TRY) {
5307 next = parent->ms_try.final_statement;
5315 panic("invalid statement kind");
5318 while (next == NULL) {
5319 next = last->base.parent;
5321 noreturn_candidate = false;
5323 type_t *const type = skip_typeref(current_function->base.type);
5324 assert(is_type_function(type));
5325 type_t *const ret = skip_typeref(type->function.return_type);
5326 if (warning.return_type &&
5327 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5328 is_type_valid(ret) &&
5329 !is_sym_main(current_function->base.base.symbol)) {
5330 warningf(&stmt->base.source_position,
5331 "control reaches end of non-void function");
5336 switch (next->kind) {
5337 case STATEMENT_INVALID:
5338 case STATEMENT_EMPTY:
5339 case STATEMENT_DECLARATION:
5340 case STATEMENT_EXPRESSION:
5342 case STATEMENT_RETURN:
5343 case STATEMENT_CONTINUE:
5344 case STATEMENT_BREAK:
5345 case STATEMENT_GOTO:
5346 case STATEMENT_LEAVE:
5347 panic("invalid control flow in function");
5349 case STATEMENT_COMPOUND:
5350 if (next->compound.stmt_expr) {
5356 case STATEMENT_SWITCH:
5357 case STATEMENT_LABEL:
5358 case STATEMENT_CASE_LABEL:
5360 next = next->base.next;
5363 case STATEMENT_WHILE: {
5365 if (next->base.reachable)
5367 next->base.reachable = true;
5369 while_statement_t const *const whiles = &next->whiles;
5370 expression_t const *const cond = whiles->condition;
5372 if (!expression_returns(cond))
5375 int const val = determine_truth(cond);
5378 check_reachable(whiles->body);
5384 next = next->base.next;
5388 case STATEMENT_DO_WHILE: {
5390 if (next->base.reachable)
5392 next->base.reachable = true;
5394 do_while_statement_t const *const dw = &next->do_while;
5395 expression_t const *const cond = dw->condition;
5397 if (!expression_returns(cond))
5400 int const val = determine_truth(cond);
5403 check_reachable(dw->body);
5409 next = next->base.next;
5413 case STATEMENT_FOR: {
5415 for_statement_t *const fors = &next->fors;
5417 fors->step_reachable = true;
5419 if (fors->condition_reachable)
5421 fors->condition_reachable = true;
5423 expression_t const *const cond = fors->condition;
5428 } else if (expression_returns(cond)) {
5429 val = determine_truth(cond);
5435 check_reachable(fors->body);
5441 next = next->base.next;
5445 case STATEMENT_MS_TRY:
5447 next = next->ms_try.final_statement;
5452 check_reachable(next);
5455 static void check_unreachable(statement_t* const stmt, void *const env)
5459 switch (stmt->kind) {
5460 case STATEMENT_DO_WHILE:
5461 if (!stmt->base.reachable) {
5462 expression_t const *const cond = stmt->do_while.condition;
5463 if (determine_truth(cond) >= 0) {
5464 warningf(&cond->base.source_position,
5465 "condition of do-while-loop is unreachable");
5470 case STATEMENT_FOR: {
5471 for_statement_t const* const fors = &stmt->fors;
5473 // if init and step are unreachable, cond is unreachable, too
5474 if (!stmt->base.reachable && !fors->step_reachable) {
5475 warningf(&stmt->base.source_position, "statement is unreachable");
5477 if (!stmt->base.reachable && fors->initialisation != NULL) {
5478 warningf(&fors->initialisation->base.source_position,
5479 "initialisation of for-statement is unreachable");
5482 if (!fors->condition_reachable && fors->condition != NULL) {
5483 warningf(&fors->condition->base.source_position,
5484 "condition of for-statement is unreachable");
5487 if (!fors->step_reachable && fors->step != NULL) {
5488 warningf(&fors->step->base.source_position,
5489 "step of for-statement is unreachable");
5495 case STATEMENT_COMPOUND:
5496 if (stmt->compound.statements != NULL)
5498 goto warn_unreachable;
5500 case STATEMENT_DECLARATION: {
5501 /* Only warn if there is at least one declarator with an initializer.
5502 * This typically occurs in switch statements. */
5503 declaration_statement_t const *const decl = &stmt->declaration;
5504 entity_t const * ent = decl->declarations_begin;
5505 entity_t const *const last = decl->declarations_end;
5507 for (;; ent = ent->base.next) {
5508 if (ent->kind == ENTITY_VARIABLE &&
5509 ent->variable.initializer != NULL) {
5510 goto warn_unreachable;
5520 if (!stmt->base.reachable)
5521 warningf(&stmt->base.source_position, "statement is unreachable");
5526 static void parse_external_declaration(void)
5528 /* function-definitions and declarations both start with declaration
5530 declaration_specifiers_t specifiers;
5531 memset(&specifiers, 0, sizeof(specifiers));
5533 add_anchor_token(';');
5534 parse_declaration_specifiers(&specifiers);
5535 rem_anchor_token(';');
5537 /* must be a declaration */
5538 if (token.type == ';') {
5539 parse_anonymous_declaration_rest(&specifiers);
5543 add_anchor_token(',');
5544 add_anchor_token('=');
5545 add_anchor_token(';');
5546 add_anchor_token('{');
5548 /* declarator is common to both function-definitions and declarations */
5549 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5551 rem_anchor_token('{');
5552 rem_anchor_token(';');
5553 rem_anchor_token('=');
5554 rem_anchor_token(',');
5556 /* must be a declaration */
5557 switch (token.type) {
5561 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5566 /* must be a function definition */
5567 parse_kr_declaration_list(ndeclaration);
5569 if (token.type != '{') {
5570 parse_error_expected("while parsing function definition", '{', NULL);
5571 eat_until_matching_token(';');
5575 assert(is_declaration(ndeclaration));
5576 type_t *const orig_type = ndeclaration->declaration.type;
5577 type_t * type = skip_typeref(orig_type);
5579 if (!is_type_function(type)) {
5580 if (is_type_valid(type)) {
5581 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5582 type, ndeclaration->base.symbol);
5586 } else if (is_typeref(orig_type)) {
5588 errorf(&ndeclaration->base.source_position,
5589 "type of function definition '%#T' is a typedef",
5590 orig_type, ndeclaration->base.symbol);
5593 if (warning.aggregate_return &&
5594 is_type_compound(skip_typeref(type->function.return_type))) {
5595 warningf(&ndeclaration->base.source_position, "function '%Y' returns an aggregate",
5596 ndeclaration->base.symbol);
5598 if (warning.traditional && !type->function.unspecified_parameters) {
5599 warningf(&ndeclaration->base.source_position, "traditional C rejects ISO C style function definition of function '%Y'",
5600 ndeclaration->base.symbol);
5602 if (warning.old_style_definition && type->function.unspecified_parameters) {
5603 warningf(&ndeclaration->base.source_position, "old-style function definition '%Y'",
5604 ndeclaration->base.symbol);
5607 /* §6.7.5.3:14 a function definition with () means no
5608 * parameters (and not unspecified parameters) */
5609 if (type->function.unspecified_parameters &&
5610 type->function.parameters == NULL) {
5611 type_t *copy = duplicate_type(type);
5612 copy->function.unspecified_parameters = false;
5613 type = identify_new_type(copy);
5615 ndeclaration->declaration.type = type;
5618 entity_t *const entity = record_entity(ndeclaration, true);
5619 assert(entity->kind == ENTITY_FUNCTION);
5620 assert(ndeclaration->kind == ENTITY_FUNCTION);
5622 function_t *const function = &entity->function;
5623 if (ndeclaration != entity) {
5624 function->parameters = ndeclaration->function.parameters;
5626 assert(is_declaration(entity));
5627 type = skip_typeref(entity->declaration.type);
5629 /* push function parameters and switch scope */
5630 size_t const top = environment_top();
5631 scope_t *old_scope = scope_push(&function->parameters);
5633 entity_t *parameter = function->parameters.entities;
5634 for (; parameter != NULL; parameter = parameter->base.next) {
5635 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5636 parameter->base.parent_scope = current_scope;
5638 assert(parameter->base.parent_scope == NULL
5639 || parameter->base.parent_scope == current_scope);
5640 parameter->base.parent_scope = current_scope;
5641 if (parameter->base.symbol == NULL) {
5642 errorf(¶meter->base.source_position, "parameter name omitted");
5645 environment_push(parameter);
5648 if (function->statement != NULL) {
5649 parser_error_multiple_definition(entity, HERE);
5652 /* parse function body */
5653 int label_stack_top = label_top();
5654 function_t *old_current_function = current_function;
5655 entity_t *old_current_entity = current_entity;
5656 current_function = function;
5657 current_entity = entity;
5658 current_parent = NULL;
5661 goto_anchor = &goto_first;
5663 label_anchor = &label_first;
5665 statement_t *const body = parse_compound_statement(false);
5666 function->statement = body;
5669 check_declarations();
5670 if (warning.return_type ||
5671 warning.unreachable_code ||
5672 (warning.missing_noreturn
5673 && !(function->base.modifiers & DM_NORETURN))) {
5674 noreturn_candidate = true;
5675 check_reachable(body);
5676 if (warning.unreachable_code)
5677 walk_statements(body, check_unreachable, NULL);
5678 if (warning.missing_noreturn &&
5679 noreturn_candidate &&
5680 !(function->base.modifiers & DM_NORETURN)) {
5681 warningf(&body->base.source_position,
5682 "function '%#T' is candidate for attribute 'noreturn'",
5683 type, entity->base.symbol);
5687 assert(current_parent == NULL);
5688 assert(current_function == function);
5689 assert(current_entity == entity);
5690 current_entity = old_current_entity;
5691 current_function = old_current_function;
5692 label_pop_to(label_stack_top);
5695 assert(current_scope == &function->parameters);
5696 scope_pop(old_scope);
5697 environment_pop_to(top);
5700 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5701 source_position_t *source_position,
5702 const symbol_t *symbol)
5704 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5706 type->bitfield.base_type = base_type;
5707 type->bitfield.size_expression = size;
5710 type_t *skipped_type = skip_typeref(base_type);
5711 if (!is_type_integer(skipped_type)) {
5712 errorf(HERE, "bitfield base type '%T' is not an integer type",
5716 bit_size = get_type_size(base_type) * 8;
5719 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5720 long v = fold_constant_to_int(size);
5721 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5724 errorf(source_position, "negative width in bit-field '%Y'",
5726 } else if (v == 0 && symbol != NULL) {
5727 errorf(source_position, "zero width for bit-field '%Y'",
5729 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5730 errorf(source_position, "width of '%Y' exceeds its type",
5733 type->bitfield.bit_size = v;
5740 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5742 entity_t *iter = compound->members.entities;
5743 for (; iter != NULL; iter = iter->base.next) {
5744 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5747 if (iter->base.symbol == symbol) {
5749 } else if (iter->base.symbol == NULL) {
5750 /* search in anonymous structs and unions */
5751 type_t *type = skip_typeref(iter->declaration.type);
5752 if (is_type_compound(type)) {
5753 if (find_compound_entry(type->compound.compound, symbol)
5764 static void check_deprecated(const source_position_t *source_position,
5765 const entity_t *entity)
5767 if (!warning.deprecated_declarations)
5769 if (!is_declaration(entity))
5771 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5774 char const *const prefix = get_entity_kind_name(entity->kind);
5775 const char *deprecated_string
5776 = get_deprecated_string(entity->declaration.attributes);
5777 if (deprecated_string != NULL) {
5778 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5779 prefix, entity->base.symbol, &entity->base.source_position,
5782 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5783 entity->base.symbol, &entity->base.source_position);
5788 static expression_t *create_select(const source_position_t *pos,
5790 type_qualifiers_t qualifiers,
5793 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5795 check_deprecated(pos, entry);
5797 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5798 select->select.compound = addr;
5799 select->select.compound_entry = entry;
5801 type_t *entry_type = entry->declaration.type;
5802 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5804 /* we always do the auto-type conversions; the & and sizeof parser contains
5805 * code to revert this! */
5806 select->base.type = automatic_type_conversion(res_type);
5807 if (res_type->kind == TYPE_BITFIELD) {
5808 select->base.type = res_type->bitfield.base_type;
5815 * Find entry with symbol in compound. Search anonymous structs and unions and
5816 * creates implicit select expressions for them.
5817 * Returns the adress for the innermost compound.
5819 static expression_t *find_create_select(const source_position_t *pos,
5821 type_qualifiers_t qualifiers,
5822 compound_t *compound, symbol_t *symbol)
5824 entity_t *iter = compound->members.entities;
5825 for (; iter != NULL; iter = iter->base.next) {
5826 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5829 symbol_t *iter_symbol = iter->base.symbol;
5830 if (iter_symbol == NULL) {
5831 type_t *type = iter->declaration.type;
5832 if (type->kind != TYPE_COMPOUND_STRUCT
5833 && type->kind != TYPE_COMPOUND_UNION)
5836 compound_t *sub_compound = type->compound.compound;
5838 if (find_compound_entry(sub_compound, symbol) == NULL)
5841 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5842 sub_addr->base.source_position = *pos;
5843 sub_addr->select.implicit = true;
5844 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5848 if (iter_symbol == symbol) {
5849 return create_select(pos, addr, qualifiers, iter);
5856 static void parse_compound_declarators(compound_t *compound,
5857 const declaration_specifiers_t *specifiers)
5862 if (token.type == ':') {
5863 source_position_t source_position = *HERE;
5866 type_t *base_type = specifiers->type;
5867 expression_t *size = parse_constant_expression();
5869 type_t *type = make_bitfield_type(base_type, size,
5870 &source_position, NULL);
5872 attribute_t *attributes = parse_attributes(NULL);
5873 attribute_t **anchor = &attributes;
5874 while (*anchor != NULL)
5875 anchor = &(*anchor)->next;
5876 *anchor = specifiers->attributes;
5878 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5879 entity->base.namespc = NAMESPACE_NORMAL;
5880 entity->base.source_position = source_position;
5881 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5882 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5883 entity->declaration.type = type;
5884 entity->declaration.attributes = attributes;
5886 if (attributes != NULL) {
5887 handle_entity_attributes(attributes, entity);
5889 append_entity(&compound->members, entity);
5891 entity = parse_declarator(specifiers,
5892 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5893 if (entity->kind == ENTITY_TYPEDEF) {
5894 errorf(&entity->base.source_position,
5895 "typedef not allowed as compound member");
5897 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5899 /* make sure we don't define a symbol multiple times */
5900 symbol_t *symbol = entity->base.symbol;
5901 if (symbol != NULL) {
5902 entity_t *prev = find_compound_entry(compound, symbol);
5904 errorf(&entity->base.source_position,
5905 "multiple declarations of symbol '%Y' (declared %P)",
5906 symbol, &prev->base.source_position);
5910 if (token.type == ':') {
5911 source_position_t source_position = *HERE;
5913 expression_t *size = parse_constant_expression();
5915 type_t *type = entity->declaration.type;
5916 type_t *bitfield_type = make_bitfield_type(type, size,
5917 &source_position, entity->base.symbol);
5919 attribute_t *attributes = parse_attributes(NULL);
5920 entity->declaration.type = bitfield_type;
5921 handle_entity_attributes(attributes, entity);
5923 type_t *orig_type = entity->declaration.type;
5924 type_t *type = skip_typeref(orig_type);
5925 if (is_type_function(type)) {
5926 errorf(&entity->base.source_position,
5927 "compound member '%Y' must not have function type '%T'",
5928 entity->base.symbol, orig_type);
5929 } else if (is_type_incomplete(type)) {
5930 /* §6.7.2.1:16 flexible array member */
5931 if (!is_type_array(type) ||
5932 token.type != ';' ||
5933 look_ahead(1)->type != '}') {
5934 errorf(&entity->base.source_position,
5935 "compound member '%Y' has incomplete type '%T'",
5936 entity->base.symbol, orig_type);
5941 append_entity(&compound->members, entity);
5944 } while (next_if(','));
5945 expect(';', end_error);
5948 anonymous_entity = NULL;
5951 static void parse_compound_type_entries(compound_t *compound)
5954 add_anchor_token('}');
5956 while (token.type != '}') {
5957 if (token.type == T_EOF) {
5958 errorf(HERE, "EOF while parsing struct");
5961 declaration_specifiers_t specifiers;
5962 memset(&specifiers, 0, sizeof(specifiers));
5963 parse_declaration_specifiers(&specifiers);
5965 parse_compound_declarators(compound, &specifiers);
5967 rem_anchor_token('}');
5971 compound->complete = true;
5974 static type_t *parse_typename(void)
5976 declaration_specifiers_t specifiers;
5977 memset(&specifiers, 0, sizeof(specifiers));
5978 parse_declaration_specifiers(&specifiers);
5979 if (specifiers.storage_class != STORAGE_CLASS_NONE
5980 || specifiers.thread_local) {
5981 /* TODO: improve error message, user does probably not know what a
5982 * storage class is...
5984 errorf(HERE, "typename must not have a storage class");
5987 type_t *result = parse_abstract_declarator(specifiers.type);
5995 typedef expression_t* (*parse_expression_function)(void);
5996 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5998 typedef struct expression_parser_function_t expression_parser_function_t;
5999 struct expression_parser_function_t {
6000 parse_expression_function parser;
6001 precedence_t infix_precedence;
6002 parse_expression_infix_function infix_parser;
6005 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
6008 * Prints an error message if an expression was expected but not read
6010 static expression_t *expected_expression_error(void)
6012 /* skip the error message if the error token was read */
6013 if (token.type != T_ERROR) {
6014 errorf(HERE, "expected expression, got token %K", &token);
6018 return create_invalid_expression();
6021 static type_t *get_string_type(void)
6023 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6026 static type_t *get_wide_string_type(void)
6028 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6032 * Parse a string constant.
6034 static expression_t *parse_string_literal(void)
6036 source_position_t begin = token.source_position;
6037 string_t res = token.literal;
6038 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6041 while (token.type == T_STRING_LITERAL
6042 || token.type == T_WIDE_STRING_LITERAL) {
6043 warn_string_concat(&token.source_position);
6044 res = concat_strings(&res, &token.literal);
6046 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6049 expression_t *literal;
6051 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6052 literal->base.type = get_wide_string_type();
6054 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6055 literal->base.type = get_string_type();
6057 literal->base.source_position = begin;
6058 literal->literal.value = res;
6064 * Parse a boolean constant.
6066 static expression_t *parse_boolean_literal(bool value)
6068 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6069 literal->base.source_position = token.source_position;
6070 literal->base.type = type_bool;
6071 literal->literal.value.begin = value ? "true" : "false";
6072 literal->literal.value.size = value ? 4 : 5;
6078 static void warn_traditional_suffix(void)
6080 if (!warning.traditional)
6082 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6086 static void check_integer_suffix(void)
6088 symbol_t *suffix = token.symbol;
6092 bool not_traditional = false;
6093 const char *c = suffix->string;
6094 if (*c == 'l' || *c == 'L') {
6097 not_traditional = true;
6099 if (*c == 'u' || *c == 'U') {
6102 } else if (*c == 'u' || *c == 'U') {
6103 not_traditional = true;
6106 } else if (*c == 'u' || *c == 'U') {
6107 not_traditional = true;
6109 if (*c == 'l' || *c == 'L') {
6117 errorf(&token.source_position,
6118 "invalid suffix '%s' on integer constant", suffix->string);
6119 } else if (not_traditional) {
6120 warn_traditional_suffix();
6124 static type_t *check_floatingpoint_suffix(void)
6126 symbol_t *suffix = token.symbol;
6127 type_t *type = type_double;
6131 bool not_traditional = false;
6132 const char *c = suffix->string;
6133 if (*c == 'f' || *c == 'F') {
6136 } else if (*c == 'l' || *c == 'L') {
6138 type = type_long_double;
6141 errorf(&token.source_position,
6142 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6143 } else if (not_traditional) {
6144 warn_traditional_suffix();
6151 * Parse an integer constant.
6153 static expression_t *parse_number_literal(void)
6155 expression_kind_t kind;
6158 switch (token.type) {
6160 kind = EXPR_LITERAL_INTEGER;
6161 check_integer_suffix();
6164 case T_INTEGER_OCTAL:
6165 kind = EXPR_LITERAL_INTEGER_OCTAL;
6166 check_integer_suffix();
6169 case T_INTEGER_HEXADECIMAL:
6170 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6171 check_integer_suffix();
6174 case T_FLOATINGPOINT:
6175 kind = EXPR_LITERAL_FLOATINGPOINT;
6176 type = check_floatingpoint_suffix();
6178 case T_FLOATINGPOINT_HEXADECIMAL:
6179 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6180 type = check_floatingpoint_suffix();
6183 panic("unexpected token type in parse_number_literal");
6186 expression_t *literal = allocate_expression_zero(kind);
6187 literal->base.source_position = token.source_position;
6188 literal->base.type = type;
6189 literal->literal.value = token.literal;
6190 literal->literal.suffix = token.symbol;
6193 /* integer type depends on the size of the number and the size
6194 * representable by the types. The backend/codegeneration has to determine
6197 determine_literal_type(&literal->literal);
6202 * Parse a character constant.
6204 static expression_t *parse_character_constant(void)
6206 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6207 literal->base.source_position = token.source_position;
6208 literal->base.type = c_mode & _CXX ? type_char : type_int;
6209 literal->literal.value = token.literal;
6211 size_t len = literal->literal.value.size;
6213 if (!GNU_MODE && !(c_mode & _C99)) {
6214 errorf(HERE, "more than 1 character in character constant");
6215 } else if (warning.multichar) {
6216 literal->base.type = type_int;
6217 warningf(HERE, "multi-character character constant");
6226 * Parse a wide character constant.
6228 static expression_t *parse_wide_character_constant(void)
6230 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6231 literal->base.source_position = token.source_position;
6232 literal->base.type = type_int;
6233 literal->literal.value = token.literal;
6235 size_t len = wstrlen(&literal->literal.value);
6237 warningf(HERE, "multi-character character constant");
6244 static entity_t *create_implicit_function(symbol_t *symbol,
6245 const source_position_t *source_position)
6247 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6248 ntype->function.return_type = type_int;
6249 ntype->function.unspecified_parameters = true;
6250 ntype->function.linkage = LINKAGE_C;
6251 type_t *type = identify_new_type(ntype);
6253 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6254 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6255 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6256 entity->declaration.type = type;
6257 entity->declaration.implicit = true;
6258 entity->base.namespc = NAMESPACE_NORMAL;
6259 entity->base.symbol = symbol;
6260 entity->base.source_position = *source_position;
6262 if (current_scope != NULL) {
6263 bool strict_prototypes_old = warning.strict_prototypes;
6264 warning.strict_prototypes = false;
6265 record_entity(entity, false);
6266 warning.strict_prototypes = strict_prototypes_old;
6273 * Performs automatic type cast as described in §6.3.2.1.
6275 * @param orig_type the original type
6277 static type_t *automatic_type_conversion(type_t *orig_type)
6279 type_t *type = skip_typeref(orig_type);
6280 if (is_type_array(type)) {
6281 array_type_t *array_type = &type->array;
6282 type_t *element_type = array_type->element_type;
6283 unsigned qualifiers = array_type->base.qualifiers;
6285 return make_pointer_type(element_type, qualifiers);
6288 if (is_type_function(type)) {
6289 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6296 * reverts the automatic casts of array to pointer types and function
6297 * to function-pointer types as defined §6.3.2.1
6299 type_t *revert_automatic_type_conversion(const expression_t *expression)
6301 switch (expression->kind) {
6302 case EXPR_REFERENCE: {
6303 entity_t *entity = expression->reference.entity;
6304 if (is_declaration(entity)) {
6305 return entity->declaration.type;
6306 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6307 return entity->enum_value.enum_type;
6309 panic("no declaration or enum in reference");
6314 entity_t *entity = expression->select.compound_entry;
6315 assert(is_declaration(entity));
6316 type_t *type = entity->declaration.type;
6317 return get_qualified_type(type,
6318 expression->base.type->base.qualifiers);
6321 case EXPR_UNARY_DEREFERENCE: {
6322 const expression_t *const value = expression->unary.value;
6323 type_t *const type = skip_typeref(value->base.type);
6324 if (!is_type_pointer(type))
6325 return type_error_type;
6326 return type->pointer.points_to;
6329 case EXPR_ARRAY_ACCESS: {
6330 const expression_t *array_ref = expression->array_access.array_ref;
6331 type_t *type_left = skip_typeref(array_ref->base.type);
6332 if (!is_type_pointer(type_left))
6333 return type_error_type;
6334 return type_left->pointer.points_to;
6337 case EXPR_STRING_LITERAL: {
6338 size_t size = expression->string_literal.value.size;
6339 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6342 case EXPR_WIDE_STRING_LITERAL: {
6343 size_t size = wstrlen(&expression->string_literal.value);
6344 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6347 case EXPR_COMPOUND_LITERAL:
6348 return expression->compound_literal.type;
6353 return expression->base.type;
6357 * Find an entity matching a symbol in a scope.
6358 * Uses current scope if scope is NULL
6360 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6361 namespace_tag_t namespc)
6363 if (scope == NULL) {
6364 return get_entity(symbol, namespc);
6367 /* we should optimize here, if scope grows above a certain size we should
6368 construct a hashmap here... */
6369 entity_t *entity = scope->entities;
6370 for ( ; entity != NULL; entity = entity->base.next) {
6371 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6378 static entity_t *parse_qualified_identifier(void)
6380 /* namespace containing the symbol */
6382 source_position_t pos;
6383 const scope_t *lookup_scope = NULL;
6385 if (next_if(T_COLONCOLON))
6386 lookup_scope = &unit->scope;
6390 if (token.type != T_IDENTIFIER) {
6391 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6392 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6394 symbol = token.symbol;
6399 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6401 if (!next_if(T_COLONCOLON))
6404 switch (entity->kind) {
6405 case ENTITY_NAMESPACE:
6406 lookup_scope = &entity->namespacee.members;
6411 lookup_scope = &entity->compound.members;
6414 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6415 symbol, get_entity_kind_name(entity->kind));
6420 if (entity == NULL) {
6421 if (!strict_mode && token.type == '(') {
6422 /* an implicitly declared function */
6423 if (warning.error_implicit_function_declaration) {
6424 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6425 } else if (warning.implicit_function_declaration) {
6426 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6429 entity = create_implicit_function(symbol, &pos);
6431 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6432 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6439 /* skip further qualifications */
6440 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6442 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6445 static expression_t *parse_reference(void)
6447 source_position_t const pos = token.source_position;
6448 entity_t *const entity = parse_qualified_identifier();
6451 if (is_declaration(entity)) {
6452 orig_type = entity->declaration.type;
6453 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6454 orig_type = entity->enum_value.enum_type;
6456 panic("expected declaration or enum value in reference");
6459 /* we always do the auto-type conversions; the & and sizeof parser contains
6460 * code to revert this! */
6461 type_t *type = automatic_type_conversion(orig_type);
6463 expression_kind_t kind = EXPR_REFERENCE;
6464 if (entity->kind == ENTITY_ENUM_VALUE)
6465 kind = EXPR_REFERENCE_ENUM_VALUE;
6467 expression_t *expression = allocate_expression_zero(kind);
6468 expression->base.source_position = pos;
6469 expression->base.type = type;
6470 expression->reference.entity = entity;
6472 /* this declaration is used */
6473 if (is_declaration(entity)) {
6474 entity->declaration.used = true;
6477 if (entity->base.parent_scope != file_scope
6478 && (current_function != NULL
6479 && entity->base.parent_scope->depth < current_function->parameters.depth)
6480 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6481 if (entity->kind == ENTITY_VARIABLE) {
6482 /* access of a variable from an outer function */
6483 entity->variable.address_taken = true;
6484 } else if (entity->kind == ENTITY_PARAMETER) {
6485 entity->parameter.address_taken = true;
6487 current_function->need_closure = true;
6490 check_deprecated(HERE, entity);
6492 if (warning.init_self && entity == current_init_decl && !in_type_prop
6493 && entity->kind == ENTITY_VARIABLE) {
6494 current_init_decl = NULL;
6495 warningf(&pos, "variable '%#T' is initialized by itself",
6496 entity->declaration.type, entity->base.symbol);
6502 static bool semantic_cast(expression_t *cast)
6504 expression_t *expression = cast->unary.value;
6505 type_t *orig_dest_type = cast->base.type;
6506 type_t *orig_type_right = expression->base.type;
6507 type_t const *dst_type = skip_typeref(orig_dest_type);
6508 type_t const *src_type = skip_typeref(orig_type_right);
6509 source_position_t const *pos = &cast->base.source_position;
6511 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6512 if (dst_type == type_void)
6515 /* only integer and pointer can be casted to pointer */
6516 if (is_type_pointer(dst_type) &&
6517 !is_type_pointer(src_type) &&
6518 !is_type_integer(src_type) &&
6519 is_type_valid(src_type)) {
6520 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6524 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6525 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6529 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6530 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6534 if (warning.cast_qual &&
6535 is_type_pointer(src_type) &&
6536 is_type_pointer(dst_type)) {
6537 type_t *src = skip_typeref(src_type->pointer.points_to);
6538 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6539 unsigned missing_qualifiers =
6540 src->base.qualifiers & ~dst->base.qualifiers;
6541 if (missing_qualifiers != 0) {
6543 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6544 missing_qualifiers, orig_type_right);
6550 static expression_t *parse_compound_literal(type_t *type)
6552 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6554 parse_initializer_env_t env;
6557 env.must_be_constant = false;
6558 initializer_t *initializer = parse_initializer(&env);
6561 expression->compound_literal.initializer = initializer;
6562 expression->compound_literal.type = type;
6563 expression->base.type = automatic_type_conversion(type);
6569 * Parse a cast expression.
6571 static expression_t *parse_cast(void)
6573 source_position_t source_position = token.source_position;
6576 add_anchor_token(')');
6578 type_t *type = parse_typename();
6580 rem_anchor_token(')');
6581 expect(')', end_error);
6583 if (token.type == '{') {
6584 return parse_compound_literal(type);
6587 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6588 cast->base.source_position = source_position;
6590 expression_t *value = parse_subexpression(PREC_CAST);
6591 cast->base.type = type;
6592 cast->unary.value = value;
6594 if (! semantic_cast(cast)) {
6595 /* TODO: record the error in the AST. else it is impossible to detect it */
6600 return create_invalid_expression();
6604 * Parse a statement expression.
6606 static expression_t *parse_statement_expression(void)
6608 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6611 add_anchor_token(')');
6613 statement_t *statement = parse_compound_statement(true);
6614 statement->compound.stmt_expr = true;
6615 expression->statement.statement = statement;
6617 /* find last statement and use its type */
6618 type_t *type = type_void;
6619 const statement_t *stmt = statement->compound.statements;
6621 while (stmt->base.next != NULL)
6622 stmt = stmt->base.next;
6624 if (stmt->kind == STATEMENT_EXPRESSION) {
6625 type = stmt->expression.expression->base.type;
6627 } else if (warning.other) {
6628 warningf(&expression->base.source_position, "empty statement expression ({})");
6630 expression->base.type = type;
6632 rem_anchor_token(')');
6633 expect(')', end_error);
6640 * Parse a parenthesized expression.
6642 static expression_t *parse_parenthesized_expression(void)
6644 token_t const* const la1 = look_ahead(1);
6645 switch (la1->type) {
6647 /* gcc extension: a statement expression */
6648 return parse_statement_expression();
6651 if (is_typedef_symbol(la1->symbol)) {
6654 return parse_cast();
6659 add_anchor_token(')');
6660 expression_t *result = parse_expression();
6661 result->base.parenthesized = true;
6662 rem_anchor_token(')');
6663 expect(')', end_error);
6669 static expression_t *parse_function_keyword(void)
6673 if (current_function == NULL) {
6674 errorf(HERE, "'__func__' used outside of a function");
6677 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6678 expression->base.type = type_char_ptr;
6679 expression->funcname.kind = FUNCNAME_FUNCTION;
6686 static expression_t *parse_pretty_function_keyword(void)
6688 if (current_function == NULL) {
6689 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6692 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6693 expression->base.type = type_char_ptr;
6694 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6696 eat(T___PRETTY_FUNCTION__);
6701 static expression_t *parse_funcsig_keyword(void)
6703 if (current_function == NULL) {
6704 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6707 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6708 expression->base.type = type_char_ptr;
6709 expression->funcname.kind = FUNCNAME_FUNCSIG;
6716 static expression_t *parse_funcdname_keyword(void)
6718 if (current_function == NULL) {
6719 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6722 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6723 expression->base.type = type_char_ptr;
6724 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6726 eat(T___FUNCDNAME__);
6731 static designator_t *parse_designator(void)
6733 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6734 result->source_position = *HERE;
6736 if (token.type != T_IDENTIFIER) {
6737 parse_error_expected("while parsing member designator",
6738 T_IDENTIFIER, NULL);
6741 result->symbol = token.symbol;
6744 designator_t *last_designator = result;
6747 if (token.type != T_IDENTIFIER) {
6748 parse_error_expected("while parsing member designator",
6749 T_IDENTIFIER, NULL);
6752 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6753 designator->source_position = *HERE;
6754 designator->symbol = token.symbol;
6757 last_designator->next = designator;
6758 last_designator = designator;
6762 add_anchor_token(']');
6763 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6764 designator->source_position = *HERE;
6765 designator->array_index = parse_expression();
6766 rem_anchor_token(']');
6767 expect(']', end_error);
6768 if (designator->array_index == NULL) {
6772 last_designator->next = designator;
6773 last_designator = designator;
6785 * Parse the __builtin_offsetof() expression.
6787 static expression_t *parse_offsetof(void)
6789 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6790 expression->base.type = type_size_t;
6792 eat(T___builtin_offsetof);
6794 expect('(', end_error);
6795 add_anchor_token(',');
6796 type_t *type = parse_typename();
6797 rem_anchor_token(',');
6798 expect(',', end_error);
6799 add_anchor_token(')');
6800 designator_t *designator = parse_designator();
6801 rem_anchor_token(')');
6802 expect(')', end_error);
6804 expression->offsetofe.type = type;
6805 expression->offsetofe.designator = designator;
6808 memset(&path, 0, sizeof(path));
6809 path.top_type = type;
6810 path.path = NEW_ARR_F(type_path_entry_t, 0);
6812 descend_into_subtype(&path);
6814 if (!walk_designator(&path, designator, true)) {
6815 return create_invalid_expression();
6818 DEL_ARR_F(path.path);
6822 return create_invalid_expression();
6826 * Parses a _builtin_va_start() expression.
6828 static expression_t *parse_va_start(void)
6830 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6832 eat(T___builtin_va_start);
6834 expect('(', end_error);
6835 add_anchor_token(',');
6836 expression->va_starte.ap = parse_assignment_expression();
6837 rem_anchor_token(',');
6838 expect(',', end_error);
6839 expression_t *const expr = parse_assignment_expression();
6840 if (expr->kind == EXPR_REFERENCE) {
6841 entity_t *const entity = expr->reference.entity;
6842 if (!current_function->base.type->function.variadic) {
6843 errorf(&expr->base.source_position,
6844 "'va_start' used in non-variadic function");
6845 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6846 entity->base.next != NULL ||
6847 entity->kind != ENTITY_PARAMETER) {
6848 errorf(&expr->base.source_position,
6849 "second argument of 'va_start' must be last parameter of the current function");
6851 expression->va_starte.parameter = &entity->variable;
6853 expect(')', end_error);
6856 expect(')', end_error);
6858 return create_invalid_expression();
6862 * Parses a __builtin_va_arg() expression.
6864 static expression_t *parse_va_arg(void)
6866 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6868 eat(T___builtin_va_arg);
6870 expect('(', end_error);
6872 ap.expression = parse_assignment_expression();
6873 expression->va_arge.ap = ap.expression;
6874 check_call_argument(type_valist, &ap, 1);
6876 expect(',', end_error);
6877 expression->base.type = parse_typename();
6878 expect(')', end_error);
6882 return create_invalid_expression();
6886 * Parses a __builtin_va_copy() expression.
6888 static expression_t *parse_va_copy(void)
6890 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6892 eat(T___builtin_va_copy);
6894 expect('(', end_error);
6895 expression_t *dst = parse_assignment_expression();
6896 assign_error_t error = semantic_assign(type_valist, dst);
6897 report_assign_error(error, type_valist, dst, "call argument 1",
6898 &dst->base.source_position);
6899 expression->va_copye.dst = dst;
6901 expect(',', end_error);
6903 call_argument_t src;
6904 src.expression = parse_assignment_expression();
6905 check_call_argument(type_valist, &src, 2);
6906 expression->va_copye.src = src.expression;
6907 expect(')', end_error);
6911 return create_invalid_expression();
6915 * Parses a __builtin_constant_p() expression.
6917 static expression_t *parse_builtin_constant(void)
6919 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6921 eat(T___builtin_constant_p);
6923 expect('(', end_error);
6924 add_anchor_token(')');
6925 expression->builtin_constant.value = parse_assignment_expression();
6926 rem_anchor_token(')');
6927 expect(')', end_error);
6928 expression->base.type = type_int;
6932 return create_invalid_expression();
6936 * Parses a __builtin_types_compatible_p() expression.
6938 static expression_t *parse_builtin_types_compatible(void)
6940 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6942 eat(T___builtin_types_compatible_p);
6944 expect('(', end_error);
6945 add_anchor_token(')');
6946 add_anchor_token(',');
6947 expression->builtin_types_compatible.left = parse_typename();
6948 rem_anchor_token(',');
6949 expect(',', end_error);
6950 expression->builtin_types_compatible.right = parse_typename();
6951 rem_anchor_token(')');
6952 expect(')', end_error);
6953 expression->base.type = type_int;
6957 return create_invalid_expression();
6961 * Parses a __builtin_is_*() compare expression.
6963 static expression_t *parse_compare_builtin(void)
6965 expression_t *expression;
6967 switch (token.type) {
6968 case T___builtin_isgreater:
6969 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6971 case T___builtin_isgreaterequal:
6972 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6974 case T___builtin_isless:
6975 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6977 case T___builtin_islessequal:
6978 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6980 case T___builtin_islessgreater:
6981 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6983 case T___builtin_isunordered:
6984 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6987 internal_errorf(HERE, "invalid compare builtin found");
6989 expression->base.source_position = *HERE;
6992 expect('(', end_error);
6993 expression->binary.left = parse_assignment_expression();
6994 expect(',', end_error);
6995 expression->binary.right = parse_assignment_expression();
6996 expect(')', end_error);
6998 type_t *const orig_type_left = expression->binary.left->base.type;
6999 type_t *const orig_type_right = expression->binary.right->base.type;
7001 type_t *const type_left = skip_typeref(orig_type_left);
7002 type_t *const type_right = skip_typeref(orig_type_right);
7003 if (!is_type_float(type_left) && !is_type_float(type_right)) {
7004 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7005 type_error_incompatible("invalid operands in comparison",
7006 &expression->base.source_position, orig_type_left, orig_type_right);
7009 semantic_comparison(&expression->binary);
7014 return create_invalid_expression();
7018 * Parses a MS assume() expression.
7020 static expression_t *parse_assume(void)
7022 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7026 expect('(', end_error);
7027 add_anchor_token(')');
7028 expression->unary.value = parse_assignment_expression();
7029 rem_anchor_token(')');
7030 expect(')', end_error);
7032 expression->base.type = type_void;
7035 return create_invalid_expression();
7039 * Return the declaration for a given label symbol or create a new one.
7041 * @param symbol the symbol of the label
7043 static label_t *get_label(symbol_t *symbol)
7046 assert(current_function != NULL);
7048 label = get_entity(symbol, NAMESPACE_LABEL);
7049 /* if we found a local label, we already created the declaration */
7050 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7051 if (label->base.parent_scope != current_scope) {
7052 assert(label->base.parent_scope->depth < current_scope->depth);
7053 current_function->goto_to_outer = true;
7055 return &label->label;
7058 label = get_entity(symbol, NAMESPACE_LABEL);
7059 /* if we found a label in the same function, then we already created the
7062 && label->base.parent_scope == ¤t_function->parameters) {
7063 return &label->label;
7066 /* otherwise we need to create a new one */
7067 label = allocate_entity_zero(ENTITY_LABEL);
7068 label->base.namespc = NAMESPACE_LABEL;
7069 label->base.symbol = symbol;
7073 return &label->label;
7077 * Parses a GNU && label address expression.
7079 static expression_t *parse_label_address(void)
7081 source_position_t source_position = token.source_position;
7083 if (token.type != T_IDENTIFIER) {
7084 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7087 symbol_t *symbol = token.symbol;
7090 label_t *label = get_label(symbol);
7092 label->address_taken = true;
7094 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7095 expression->base.source_position = source_position;
7097 /* label address is threaten as a void pointer */
7098 expression->base.type = type_void_ptr;
7099 expression->label_address.label = label;
7102 return create_invalid_expression();
7106 * Parse a microsoft __noop expression.
7108 static expression_t *parse_noop_expression(void)
7110 /* the result is a (int)0 */
7111 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7112 literal->base.type = type_int;
7113 literal->base.source_position = token.source_position;
7114 literal->literal.value.begin = "__noop";
7115 literal->literal.value.size = 6;
7119 if (token.type == '(') {
7120 /* parse arguments */
7122 add_anchor_token(')');
7123 add_anchor_token(',');
7125 if (token.type != ')') do {
7126 (void)parse_assignment_expression();
7127 } while (next_if(','));
7129 rem_anchor_token(',');
7130 rem_anchor_token(')');
7131 expect(')', end_error);
7138 * Parses a primary expression.
7140 static expression_t *parse_primary_expression(void)
7142 switch (token.type) {
7143 case T_false: return parse_boolean_literal(false);
7144 case T_true: return parse_boolean_literal(true);
7146 case T_INTEGER_OCTAL:
7147 case T_INTEGER_HEXADECIMAL:
7148 case T_FLOATINGPOINT:
7149 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7150 case T_CHARACTER_CONSTANT: return parse_character_constant();
7151 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7152 case T_STRING_LITERAL:
7153 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7154 case T___FUNCTION__:
7155 case T___func__: return parse_function_keyword();
7156 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7157 case T___FUNCSIG__: return parse_funcsig_keyword();
7158 case T___FUNCDNAME__: return parse_funcdname_keyword();
7159 case T___builtin_offsetof: return parse_offsetof();
7160 case T___builtin_va_start: return parse_va_start();
7161 case T___builtin_va_arg: return parse_va_arg();
7162 case T___builtin_va_copy: return parse_va_copy();
7163 case T___builtin_isgreater:
7164 case T___builtin_isgreaterequal:
7165 case T___builtin_isless:
7166 case T___builtin_islessequal:
7167 case T___builtin_islessgreater:
7168 case T___builtin_isunordered: return parse_compare_builtin();
7169 case T___builtin_constant_p: return parse_builtin_constant();
7170 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7171 case T__assume: return parse_assume();
7174 return parse_label_address();
7177 case '(': return parse_parenthesized_expression();
7178 case T___noop: return parse_noop_expression();
7180 /* Gracefully handle type names while parsing expressions. */
7182 return parse_reference();
7184 if (!is_typedef_symbol(token.symbol)) {
7185 return parse_reference();
7189 source_position_t const pos = *HERE;
7190 type_t const *const type = parse_typename();
7191 errorf(&pos, "encountered type '%T' while parsing expression", type);
7192 return create_invalid_expression();
7196 errorf(HERE, "unexpected token %K, expected an expression", &token);
7198 return create_invalid_expression();
7201 static expression_t *parse_array_expression(expression_t *left)
7203 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7204 array_access_expression_t *const arr = &expr->array_access;
7207 add_anchor_token(']');
7209 expression_t *const inside = parse_expression();
7211 type_t *const orig_type_left = left->base.type;
7212 type_t *const orig_type_inside = inside->base.type;
7214 type_t *const type_left = skip_typeref(orig_type_left);
7215 type_t *const type_inside = skip_typeref(orig_type_inside);
7221 if (is_type_pointer(type_left)) {
7224 idx_type = type_inside;
7225 res_type = type_left->pointer.points_to;
7227 } else if (is_type_pointer(type_inside)) {
7228 arr->flipped = true;
7231 idx_type = type_left;
7232 res_type = type_inside->pointer.points_to;
7234 res_type = automatic_type_conversion(res_type);
7235 if (!is_type_integer(idx_type)) {
7236 errorf(&idx->base.source_position, "array subscript must have integer type");
7237 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR) && warning.char_subscripts) {
7238 warningf(&idx->base.source_position, "array subscript has char type");
7241 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7243 "array access on object with non-pointer types '%T', '%T'",
7244 orig_type_left, orig_type_inside);
7246 res_type = type_error_type;
7251 arr->array_ref = ref;
7253 arr->base.type = res_type;
7255 rem_anchor_token(']');
7256 expect(']', end_error);
7261 static expression_t *parse_typeprop(expression_kind_t const kind)
7263 expression_t *tp_expression = allocate_expression_zero(kind);
7264 tp_expression->base.type = type_size_t;
7266 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7268 /* we only refer to a type property, mark this case */
7269 bool old = in_type_prop;
7270 in_type_prop = true;
7273 expression_t *expression;
7274 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7276 add_anchor_token(')');
7277 orig_type = parse_typename();
7278 rem_anchor_token(')');
7279 expect(')', end_error);
7281 if (token.type == '{') {
7282 /* It was not sizeof(type) after all. It is sizeof of an expression
7283 * starting with a compound literal */
7284 expression = parse_compound_literal(orig_type);
7285 goto typeprop_expression;
7288 expression = parse_subexpression(PREC_UNARY);
7290 typeprop_expression:
7291 tp_expression->typeprop.tp_expression = expression;
7293 orig_type = revert_automatic_type_conversion(expression);
7294 expression->base.type = orig_type;
7297 tp_expression->typeprop.type = orig_type;
7298 type_t const* const type = skip_typeref(orig_type);
7299 char const* wrong_type = NULL;
7300 if (is_type_incomplete(type)) {
7301 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7302 wrong_type = "incomplete";
7303 } else if (type->kind == TYPE_FUNCTION) {
7305 /* function types are allowed (and return 1) */
7306 if (warning.other) {
7307 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7308 warningf(&tp_expression->base.source_position,
7309 "%s expression with function argument returns invalid result", what);
7312 wrong_type = "function";
7315 if (is_type_incomplete(type))
7316 wrong_type = "incomplete";
7318 if (type->kind == TYPE_BITFIELD)
7319 wrong_type = "bitfield";
7321 if (wrong_type != NULL) {
7322 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7323 errorf(&tp_expression->base.source_position,
7324 "operand of %s expression must not be of %s type '%T'",
7325 what, wrong_type, orig_type);
7330 return tp_expression;
7333 static expression_t *parse_sizeof(void)
7335 return parse_typeprop(EXPR_SIZEOF);
7338 static expression_t *parse_alignof(void)
7340 return parse_typeprop(EXPR_ALIGNOF);
7343 static expression_t *parse_select_expression(expression_t *addr)
7345 assert(token.type == '.' || token.type == T_MINUSGREATER);
7346 bool select_left_arrow = (token.type == T_MINUSGREATER);
7347 source_position_t const pos = *HERE;
7350 if (token.type != T_IDENTIFIER) {
7351 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7352 return create_invalid_expression();
7354 symbol_t *symbol = token.symbol;
7357 type_t *const orig_type = addr->base.type;
7358 type_t *const type = skip_typeref(orig_type);
7361 bool saw_error = false;
7362 if (is_type_pointer(type)) {
7363 if (!select_left_arrow) {
7365 "request for member '%Y' in something not a struct or union, but '%T'",
7369 type_left = skip_typeref(type->pointer.points_to);
7371 if (select_left_arrow && is_type_valid(type)) {
7372 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7378 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7379 type_left->kind != TYPE_COMPOUND_UNION) {
7381 if (is_type_valid(type_left) && !saw_error) {
7383 "request for member '%Y' in something not a struct or union, but '%T'",
7386 return create_invalid_expression();
7389 compound_t *compound = type_left->compound.compound;
7390 if (!compound->complete) {
7391 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7393 return create_invalid_expression();
7396 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7397 expression_t *result =
7398 find_create_select(&pos, addr, qualifiers, compound, symbol);
7400 if (result == NULL) {
7401 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7402 return create_invalid_expression();
7408 static void check_call_argument(type_t *expected_type,
7409 call_argument_t *argument, unsigned pos)
7411 type_t *expected_type_skip = skip_typeref(expected_type);
7412 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7413 expression_t *arg_expr = argument->expression;
7414 type_t *arg_type = skip_typeref(arg_expr->base.type);
7416 /* handle transparent union gnu extension */
7417 if (is_type_union(expected_type_skip)
7418 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7419 compound_t *union_decl = expected_type_skip->compound.compound;
7420 type_t *best_type = NULL;
7421 entity_t *entry = union_decl->members.entities;
7422 for ( ; entry != NULL; entry = entry->base.next) {
7423 assert(is_declaration(entry));
7424 type_t *decl_type = entry->declaration.type;
7425 error = semantic_assign(decl_type, arg_expr);
7426 if (error == ASSIGN_ERROR_INCOMPATIBLE
7427 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7430 if (error == ASSIGN_SUCCESS) {
7431 best_type = decl_type;
7432 } else if (best_type == NULL) {
7433 best_type = decl_type;
7437 if (best_type != NULL) {
7438 expected_type = best_type;
7442 error = semantic_assign(expected_type, arg_expr);
7443 argument->expression = create_implicit_cast(arg_expr, expected_type);
7445 if (error != ASSIGN_SUCCESS) {
7446 /* report exact scope in error messages (like "in argument 3") */
7448 snprintf(buf, sizeof(buf), "call argument %u", pos);
7449 report_assign_error(error, expected_type, arg_expr, buf,
7450 &arg_expr->base.source_position);
7451 } else if (warning.traditional || warning.conversion) {
7452 type_t *const promoted_type = get_default_promoted_type(arg_type);
7453 if (!types_compatible(expected_type_skip, promoted_type) &&
7454 !types_compatible(expected_type_skip, type_void_ptr) &&
7455 !types_compatible(type_void_ptr, promoted_type)) {
7456 /* Deliberately show the skipped types in this warning */
7457 warningf(&arg_expr->base.source_position,
7458 "passing call argument %u as '%T' rather than '%T' due to prototype",
7459 pos, expected_type_skip, promoted_type);
7465 * Handle the semantic restrictions of builtin calls
7467 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7468 switch (call->function->reference.entity->function.btk) {
7469 case bk_gnu_builtin_return_address:
7470 case bk_gnu_builtin_frame_address: {
7471 /* argument must be constant */
7472 call_argument_t *argument = call->arguments;
7474 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7475 errorf(&call->base.source_position,
7476 "argument of '%Y' must be a constant expression",
7477 call->function->reference.entity->base.symbol);
7481 case bk_gnu_builtin_object_size:
7482 if (call->arguments == NULL)
7485 call_argument_t *arg = call->arguments->next;
7486 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7487 errorf(&call->base.source_position,
7488 "second argument of '%Y' must be a constant expression",
7489 call->function->reference.entity->base.symbol);
7492 case bk_gnu_builtin_prefetch:
7493 /* second and third argument must be constant if existent */
7494 if (call->arguments == NULL)
7496 call_argument_t *rw = call->arguments->next;
7497 call_argument_t *locality = NULL;
7500 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7501 errorf(&call->base.source_position,
7502 "second argument of '%Y' must be a constant expression",
7503 call->function->reference.entity->base.symbol);
7505 locality = rw->next;
7507 if (locality != NULL) {
7508 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7509 errorf(&call->base.source_position,
7510 "third argument of '%Y' must be a constant expression",
7511 call->function->reference.entity->base.symbol);
7513 locality = rw->next;
7522 * Parse a call expression, ie. expression '( ... )'.
7524 * @param expression the function address
7526 static expression_t *parse_call_expression(expression_t *expression)
7528 expression_t *result = allocate_expression_zero(EXPR_CALL);
7529 call_expression_t *call = &result->call;
7530 call->function = expression;
7532 type_t *const orig_type = expression->base.type;
7533 type_t *const type = skip_typeref(orig_type);
7535 function_type_t *function_type = NULL;
7536 if (is_type_pointer(type)) {
7537 type_t *const to_type = skip_typeref(type->pointer.points_to);
7539 if (is_type_function(to_type)) {
7540 function_type = &to_type->function;
7541 call->base.type = function_type->return_type;
7545 if (function_type == NULL && is_type_valid(type)) {
7547 "called object '%E' (type '%T') is not a pointer to a function",
7548 expression, orig_type);
7551 /* parse arguments */
7553 add_anchor_token(')');
7554 add_anchor_token(',');
7556 if (token.type != ')') {
7557 call_argument_t **anchor = &call->arguments;
7559 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7560 argument->expression = parse_assignment_expression();
7563 anchor = &argument->next;
7564 } while (next_if(','));
7566 rem_anchor_token(',');
7567 rem_anchor_token(')');
7568 expect(')', end_error);
7570 if (function_type == NULL)
7573 /* check type and count of call arguments */
7574 function_parameter_t *parameter = function_type->parameters;
7575 call_argument_t *argument = call->arguments;
7576 if (!function_type->unspecified_parameters) {
7577 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7578 parameter = parameter->next, argument = argument->next) {
7579 check_call_argument(parameter->type, argument, ++pos);
7582 if (parameter != NULL) {
7583 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7584 } else if (argument != NULL && !function_type->variadic) {
7585 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7589 /* do default promotion for other arguments */
7590 for (; argument != NULL; argument = argument->next) {
7591 type_t *type = argument->expression->base.type;
7592 if (!is_type_object(skip_typeref(type))) {
7593 errorf(&argument->expression->base.source_position,
7594 "call argument '%E' must not be void", argument->expression);
7597 type = get_default_promoted_type(type);
7599 argument->expression
7600 = create_implicit_cast(argument->expression, type);
7605 if (warning.aggregate_return &&
7606 is_type_compound(skip_typeref(function_type->return_type))) {
7607 warningf(&expression->base.source_position,
7608 "function call has aggregate value");
7611 if (expression->kind == EXPR_REFERENCE) {
7612 reference_expression_t *reference = &expression->reference;
7613 if (reference->entity->kind == ENTITY_FUNCTION &&
7614 reference->entity->function.btk != bk_none)
7615 handle_builtin_argument_restrictions(call);
7622 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7624 static bool same_compound_type(const type_t *type1, const type_t *type2)
7627 is_type_compound(type1) &&
7628 type1->kind == type2->kind &&
7629 type1->compound.compound == type2->compound.compound;
7632 static expression_t const *get_reference_address(expression_t const *expr)
7634 bool regular_take_address = true;
7636 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7637 expr = expr->unary.value;
7639 regular_take_address = false;
7642 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7645 expr = expr->unary.value;
7648 if (expr->kind != EXPR_REFERENCE)
7651 /* special case for functions which are automatically converted to a
7652 * pointer to function without an extra TAKE_ADDRESS operation */
7653 if (!regular_take_address &&
7654 expr->reference.entity->kind != ENTITY_FUNCTION) {
7661 static void warn_reference_address_as_bool(expression_t const* expr)
7663 if (!warning.address)
7666 expr = get_reference_address(expr);
7668 warningf(&expr->base.source_position,
7669 "the address of '%Y' will always evaluate as 'true'",
7670 expr->reference.entity->base.symbol);
7674 static void warn_assignment_in_condition(const expression_t *const expr)
7676 if (!warning.parentheses)
7678 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7680 if (expr->base.parenthesized)
7682 warningf(&expr->base.source_position,
7683 "suggest parentheses around assignment used as truth value");
7686 static void semantic_condition(expression_t const *const expr,
7687 char const *const context)
7689 type_t *const type = skip_typeref(expr->base.type);
7690 if (is_type_scalar(type)) {
7691 warn_reference_address_as_bool(expr);
7692 warn_assignment_in_condition(expr);
7693 } else if (is_type_valid(type)) {
7694 errorf(&expr->base.source_position,
7695 "%s must have scalar type", context);
7700 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7702 * @param expression the conditional expression
7704 static expression_t *parse_conditional_expression(expression_t *expression)
7706 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7708 conditional_expression_t *conditional = &result->conditional;
7709 conditional->condition = expression;
7712 add_anchor_token(':');
7714 /* §6.5.15:2 The first operand shall have scalar type. */
7715 semantic_condition(expression, "condition of conditional operator");
7717 expression_t *true_expression = expression;
7718 bool gnu_cond = false;
7719 if (GNU_MODE && token.type == ':') {
7722 true_expression = parse_expression();
7724 rem_anchor_token(':');
7725 expect(':', end_error);
7727 expression_t *false_expression =
7728 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7730 type_t *const orig_true_type = true_expression->base.type;
7731 type_t *const orig_false_type = false_expression->base.type;
7732 type_t *const true_type = skip_typeref(orig_true_type);
7733 type_t *const false_type = skip_typeref(orig_false_type);
7736 type_t *result_type;
7737 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7738 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7739 /* ISO/IEC 14882:1998(E) §5.16:2 */
7740 if (true_expression->kind == EXPR_UNARY_THROW) {
7741 result_type = false_type;
7742 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7743 result_type = true_type;
7745 if (warning.other && (
7746 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7747 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7749 warningf(&conditional->base.source_position,
7750 "ISO C forbids conditional expression with only one void side");
7752 result_type = type_void;
7754 } else if (is_type_arithmetic(true_type)
7755 && is_type_arithmetic(false_type)) {
7756 result_type = semantic_arithmetic(true_type, false_type);
7757 } else if (same_compound_type(true_type, false_type)) {
7758 /* just take 1 of the 2 types */
7759 result_type = true_type;
7760 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7761 type_t *pointer_type;
7763 expression_t *other_expression;
7764 if (is_type_pointer(true_type) &&
7765 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7766 pointer_type = true_type;
7767 other_type = false_type;
7768 other_expression = false_expression;
7770 pointer_type = false_type;
7771 other_type = true_type;
7772 other_expression = true_expression;
7775 if (is_null_pointer_constant(other_expression)) {
7776 result_type = pointer_type;
7777 } else if (is_type_pointer(other_type)) {
7778 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7779 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7782 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7783 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7785 } else if (types_compatible(get_unqualified_type(to1),
7786 get_unqualified_type(to2))) {
7789 if (warning.other) {
7790 warningf(&conditional->base.source_position,
7791 "pointer types '%T' and '%T' in conditional expression are incompatible",
7792 true_type, false_type);
7797 type_t *const type =
7798 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7799 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7800 } else if (is_type_integer(other_type)) {
7801 if (warning.other) {
7802 warningf(&conditional->base.source_position,
7803 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7805 result_type = pointer_type;
7807 if (is_type_valid(other_type)) {
7808 type_error_incompatible("while parsing conditional",
7809 &expression->base.source_position, true_type, false_type);
7811 result_type = type_error_type;
7814 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7815 type_error_incompatible("while parsing conditional",
7816 &conditional->base.source_position, true_type,
7819 result_type = type_error_type;
7822 conditional->true_expression
7823 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7824 conditional->false_expression
7825 = create_implicit_cast(false_expression, result_type);
7826 conditional->base.type = result_type;
7831 * Parse an extension expression.
7833 static expression_t *parse_extension(void)
7835 eat(T___extension__);
7837 bool old_gcc_extension = in_gcc_extension;
7838 in_gcc_extension = true;
7839 expression_t *expression = parse_subexpression(PREC_UNARY);
7840 in_gcc_extension = old_gcc_extension;
7845 * Parse a __builtin_classify_type() expression.
7847 static expression_t *parse_builtin_classify_type(void)
7849 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7850 result->base.type = type_int;
7852 eat(T___builtin_classify_type);
7854 expect('(', end_error);
7855 add_anchor_token(')');
7856 expression_t *expression = parse_expression();
7857 rem_anchor_token(')');
7858 expect(')', end_error);
7859 result->classify_type.type_expression = expression;
7863 return create_invalid_expression();
7867 * Parse a delete expression
7868 * ISO/IEC 14882:1998(E) §5.3.5
7870 static expression_t *parse_delete(void)
7872 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7873 result->base.type = type_void;
7878 result->kind = EXPR_UNARY_DELETE_ARRAY;
7879 expect(']', end_error);
7883 expression_t *const value = parse_subexpression(PREC_CAST);
7884 result->unary.value = value;
7886 type_t *const type = skip_typeref(value->base.type);
7887 if (!is_type_pointer(type)) {
7888 if (is_type_valid(type)) {
7889 errorf(&value->base.source_position,
7890 "operand of delete must have pointer type");
7892 } else if (warning.other &&
7893 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7894 warningf(&value->base.source_position,
7895 "deleting 'void*' is undefined");
7902 * Parse a throw expression
7903 * ISO/IEC 14882:1998(E) §15:1
7905 static expression_t *parse_throw(void)
7907 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7908 result->base.type = type_void;
7912 expression_t *value = NULL;
7913 switch (token.type) {
7915 value = parse_assignment_expression();
7916 /* ISO/IEC 14882:1998(E) §15.1:3 */
7917 type_t *const orig_type = value->base.type;
7918 type_t *const type = skip_typeref(orig_type);
7919 if (is_type_incomplete(type)) {
7920 errorf(&value->base.source_position,
7921 "cannot throw object of incomplete type '%T'", orig_type);
7922 } else if (is_type_pointer(type)) {
7923 type_t *const points_to = skip_typeref(type->pointer.points_to);
7924 if (is_type_incomplete(points_to) &&
7925 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7926 errorf(&value->base.source_position,
7927 "cannot throw pointer to incomplete type '%T'", orig_type);
7935 result->unary.value = value;
7940 static bool check_pointer_arithmetic(const source_position_t *source_position,
7941 type_t *pointer_type,
7942 type_t *orig_pointer_type)
7944 type_t *points_to = pointer_type->pointer.points_to;
7945 points_to = skip_typeref(points_to);
7947 if (is_type_incomplete(points_to)) {
7948 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7949 errorf(source_position,
7950 "arithmetic with pointer to incomplete type '%T' not allowed",
7953 } else if (warning.pointer_arith) {
7954 warningf(source_position,
7955 "pointer of type '%T' used in arithmetic",
7958 } else if (is_type_function(points_to)) {
7960 errorf(source_position,
7961 "arithmetic with pointer to function type '%T' not allowed",
7964 } else if (warning.pointer_arith) {
7965 warningf(source_position,
7966 "pointer to a function '%T' used in arithmetic",
7973 static bool is_lvalue(const expression_t *expression)
7975 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7976 switch (expression->kind) {
7977 case EXPR_ARRAY_ACCESS:
7978 case EXPR_COMPOUND_LITERAL:
7979 case EXPR_REFERENCE:
7981 case EXPR_UNARY_DEREFERENCE:
7985 type_t *type = skip_typeref(expression->base.type);
7987 /* ISO/IEC 14882:1998(E) §3.10:3 */
7988 is_type_reference(type) ||
7989 /* Claim it is an lvalue, if the type is invalid. There was a parse
7990 * error before, which maybe prevented properly recognizing it as
7992 !is_type_valid(type);
7997 static void semantic_incdec(unary_expression_t *expression)
7999 type_t *const orig_type = expression->value->base.type;
8000 type_t *const type = skip_typeref(orig_type);
8001 if (is_type_pointer(type)) {
8002 if (!check_pointer_arithmetic(&expression->base.source_position,
8006 } else if (!is_type_real(type) && is_type_valid(type)) {
8007 /* TODO: improve error message */
8008 errorf(&expression->base.source_position,
8009 "operation needs an arithmetic or pointer type");
8012 if (!is_lvalue(expression->value)) {
8013 /* TODO: improve error message */
8014 errorf(&expression->base.source_position, "lvalue required as operand");
8016 expression->base.type = orig_type;
8019 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8021 type_t *const orig_type = expression->value->base.type;
8022 type_t *const type = skip_typeref(orig_type);
8023 if (!is_type_arithmetic(type)) {
8024 if (is_type_valid(type)) {
8025 /* TODO: improve error message */
8026 errorf(&expression->base.source_position,
8027 "operation needs an arithmetic type");
8032 expression->base.type = orig_type;
8035 static void semantic_unexpr_plus(unary_expression_t *expression)
8037 semantic_unexpr_arithmetic(expression);
8038 if (warning.traditional)
8039 warningf(&expression->base.source_position,
8040 "traditional C rejects the unary plus operator");
8043 static void semantic_not(unary_expression_t *expression)
8045 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8046 semantic_condition(expression->value, "operand of !");
8047 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8050 static void semantic_unexpr_integer(unary_expression_t *expression)
8052 type_t *const orig_type = expression->value->base.type;
8053 type_t *const type = skip_typeref(orig_type);
8054 if (!is_type_integer(type)) {
8055 if (is_type_valid(type)) {
8056 errorf(&expression->base.source_position,
8057 "operand of ~ must be of integer type");
8062 expression->base.type = orig_type;
8065 static void semantic_dereference(unary_expression_t *expression)
8067 type_t *const orig_type = expression->value->base.type;
8068 type_t *const type = skip_typeref(orig_type);
8069 if (!is_type_pointer(type)) {
8070 if (is_type_valid(type)) {
8071 errorf(&expression->base.source_position,
8072 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8077 type_t *result_type = type->pointer.points_to;
8078 result_type = automatic_type_conversion(result_type);
8079 expression->base.type = result_type;
8083 * Record that an address is taken (expression represents an lvalue).
8085 * @param expression the expression
8086 * @param may_be_register if true, the expression might be an register
8088 static void set_address_taken(expression_t *expression, bool may_be_register)
8090 if (expression->kind != EXPR_REFERENCE)
8093 entity_t *const entity = expression->reference.entity;
8095 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8098 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8099 && !may_be_register) {
8100 errorf(&expression->base.source_position,
8101 "address of register %s '%Y' requested",
8102 get_entity_kind_name(entity->kind), entity->base.symbol);
8105 if (entity->kind == ENTITY_VARIABLE) {
8106 entity->variable.address_taken = true;
8108 assert(entity->kind == ENTITY_PARAMETER);
8109 entity->parameter.address_taken = true;
8114 * Check the semantic of the address taken expression.
8116 static void semantic_take_addr(unary_expression_t *expression)
8118 expression_t *value = expression->value;
8119 value->base.type = revert_automatic_type_conversion(value);
8121 type_t *orig_type = value->base.type;
8122 type_t *type = skip_typeref(orig_type);
8123 if (!is_type_valid(type))
8127 if (!is_lvalue(value)) {
8128 errorf(&expression->base.source_position, "'&' requires an lvalue");
8130 if (type->kind == TYPE_BITFIELD) {
8131 errorf(&expression->base.source_position,
8132 "'&' not allowed on object with bitfield type '%T'",
8136 set_address_taken(value, false);
8138 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8141 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8142 static expression_t *parse_##unexpression_type(void) \
8144 expression_t *unary_expression \
8145 = allocate_expression_zero(unexpression_type); \
8147 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8149 sfunc(&unary_expression->unary); \
8151 return unary_expression; \
8154 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8155 semantic_unexpr_arithmetic)
8156 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8157 semantic_unexpr_plus)
8158 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8160 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8161 semantic_dereference)
8162 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8164 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8165 semantic_unexpr_integer)
8166 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8168 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8171 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8173 static expression_t *parse_##unexpression_type(expression_t *left) \
8175 expression_t *unary_expression \
8176 = allocate_expression_zero(unexpression_type); \
8178 unary_expression->unary.value = left; \
8180 sfunc(&unary_expression->unary); \
8182 return unary_expression; \
8185 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8186 EXPR_UNARY_POSTFIX_INCREMENT,
8188 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8189 EXPR_UNARY_POSTFIX_DECREMENT,
8192 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8194 /* TODO: handle complex + imaginary types */
8196 type_left = get_unqualified_type(type_left);
8197 type_right = get_unqualified_type(type_right);
8199 /* §6.3.1.8 Usual arithmetic conversions */
8200 if (type_left == type_long_double || type_right == type_long_double) {
8201 return type_long_double;
8202 } else if (type_left == type_double || type_right == type_double) {
8204 } else if (type_left == type_float || type_right == type_float) {
8208 type_left = promote_integer(type_left);
8209 type_right = promote_integer(type_right);
8211 if (type_left == type_right)
8214 bool const signed_left = is_type_signed(type_left);
8215 bool const signed_right = is_type_signed(type_right);
8216 int const rank_left = get_rank(type_left);
8217 int const rank_right = get_rank(type_right);
8219 if (signed_left == signed_right)
8220 return rank_left >= rank_right ? type_left : type_right;
8229 u_rank = rank_right;
8230 u_type = type_right;
8232 s_rank = rank_right;
8233 s_type = type_right;
8238 if (u_rank >= s_rank)
8241 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8243 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8244 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8248 case ATOMIC_TYPE_INT: return type_unsigned_int;
8249 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8250 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8252 default: panic("invalid atomic type");
8257 * Check the semantic restrictions for a binary expression.
8259 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8261 expression_t *const left = expression->left;
8262 expression_t *const right = expression->right;
8263 type_t *const orig_type_left = left->base.type;
8264 type_t *const orig_type_right = right->base.type;
8265 type_t *const type_left = skip_typeref(orig_type_left);
8266 type_t *const type_right = skip_typeref(orig_type_right);
8268 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8269 /* TODO: improve error message */
8270 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8271 errorf(&expression->base.source_position,
8272 "operation needs arithmetic types");
8277 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8278 expression->left = create_implicit_cast(left, arithmetic_type);
8279 expression->right = create_implicit_cast(right, arithmetic_type);
8280 expression->base.type = arithmetic_type;
8283 static void semantic_binexpr_integer(binary_expression_t *const expression)
8285 expression_t *const left = expression->left;
8286 expression_t *const right = expression->right;
8287 type_t *const orig_type_left = left->base.type;
8288 type_t *const orig_type_right = right->base.type;
8289 type_t *const type_left = skip_typeref(orig_type_left);
8290 type_t *const type_right = skip_typeref(orig_type_right);
8292 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8293 /* TODO: improve error message */
8294 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8295 errorf(&expression->base.source_position,
8296 "operation needs integer types");
8301 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8302 expression->left = create_implicit_cast(left, result_type);
8303 expression->right = create_implicit_cast(right, result_type);
8304 expression->base.type = result_type;
8307 static void warn_div_by_zero(binary_expression_t const *const expression)
8309 if (!warning.div_by_zero ||
8310 !is_type_integer(expression->base.type))
8313 expression_t const *const right = expression->right;
8314 /* The type of the right operand can be different for /= */
8315 if (is_type_integer(right->base.type) &&
8316 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8317 !fold_constant_to_bool(right)) {
8318 warningf(&expression->base.source_position, "division by zero");
8323 * Check the semantic restrictions for a div/mod expression.
8325 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8327 semantic_binexpr_arithmetic(expression);
8328 warn_div_by_zero(expression);
8331 static void warn_addsub_in_shift(const expression_t *const expr)
8333 if (expr->base.parenthesized)
8337 switch (expr->kind) {
8338 case EXPR_BINARY_ADD: op = '+'; break;
8339 case EXPR_BINARY_SUB: op = '-'; break;
8343 warningf(&expr->base.source_position,
8344 "suggest parentheses around '%c' inside shift", op);
8347 static bool semantic_shift(binary_expression_t *expression)
8349 expression_t *const left = expression->left;
8350 expression_t *const right = expression->right;
8351 type_t *const orig_type_left = left->base.type;
8352 type_t *const orig_type_right = right->base.type;
8353 type_t * type_left = skip_typeref(orig_type_left);
8354 type_t * type_right = skip_typeref(orig_type_right);
8356 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8357 /* TODO: improve error message */
8358 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8359 errorf(&expression->base.source_position,
8360 "operands of shift operation must have integer types");
8365 type_left = promote_integer(type_left);
8367 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8368 long count = fold_constant_to_int(right);
8370 warningf(&right->base.source_position,
8371 "shift count must be non-negative");
8372 } else if ((unsigned long)count >=
8373 get_atomic_type_size(type_left->atomic.akind) * 8) {
8374 warningf(&right->base.source_position,
8375 "shift count must be less than type width");
8379 type_right = promote_integer(type_right);
8380 expression->right = create_implicit_cast(right, type_right);
8385 static void semantic_shift_op(binary_expression_t *expression)
8387 expression_t *const left = expression->left;
8388 expression_t *const right = expression->right;
8390 if (!semantic_shift(expression))
8393 if (warning.parentheses) {
8394 warn_addsub_in_shift(left);
8395 warn_addsub_in_shift(right);
8398 type_t *const orig_type_left = left->base.type;
8399 type_t * type_left = skip_typeref(orig_type_left);
8401 type_left = promote_integer(type_left);
8402 expression->left = create_implicit_cast(left, type_left);
8403 expression->base.type = type_left;
8406 static void semantic_add(binary_expression_t *expression)
8408 expression_t *const left = expression->left;
8409 expression_t *const right = expression->right;
8410 type_t *const orig_type_left = left->base.type;
8411 type_t *const orig_type_right = right->base.type;
8412 type_t *const type_left = skip_typeref(orig_type_left);
8413 type_t *const type_right = skip_typeref(orig_type_right);
8416 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8417 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8418 expression->left = create_implicit_cast(left, arithmetic_type);
8419 expression->right = create_implicit_cast(right, arithmetic_type);
8420 expression->base.type = arithmetic_type;
8421 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8422 check_pointer_arithmetic(&expression->base.source_position,
8423 type_left, orig_type_left);
8424 expression->base.type = type_left;
8425 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8426 check_pointer_arithmetic(&expression->base.source_position,
8427 type_right, orig_type_right);
8428 expression->base.type = type_right;
8429 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8430 errorf(&expression->base.source_position,
8431 "invalid operands to binary + ('%T', '%T')",
8432 orig_type_left, orig_type_right);
8436 static void semantic_sub(binary_expression_t *expression)
8438 expression_t *const left = expression->left;
8439 expression_t *const right = expression->right;
8440 type_t *const orig_type_left = left->base.type;
8441 type_t *const orig_type_right = right->base.type;
8442 type_t *const type_left = skip_typeref(orig_type_left);
8443 type_t *const type_right = skip_typeref(orig_type_right);
8444 source_position_t const *const pos = &expression->base.source_position;
8447 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8448 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8449 expression->left = create_implicit_cast(left, arithmetic_type);
8450 expression->right = create_implicit_cast(right, arithmetic_type);
8451 expression->base.type = arithmetic_type;
8452 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8453 check_pointer_arithmetic(&expression->base.source_position,
8454 type_left, orig_type_left);
8455 expression->base.type = type_left;
8456 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8457 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8458 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8459 if (!types_compatible(unqual_left, unqual_right)) {
8461 "subtracting pointers to incompatible types '%T' and '%T'",
8462 orig_type_left, orig_type_right);
8463 } else if (!is_type_object(unqual_left)) {
8464 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8465 errorf(pos, "subtracting pointers to non-object types '%T'",
8467 } else if (warning.other) {
8468 warningf(pos, "subtracting pointers to void");
8471 expression->base.type = type_ptrdiff_t;
8472 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8473 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8474 orig_type_left, orig_type_right);
8478 static void warn_string_literal_address(expression_t const* expr)
8480 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8481 expr = expr->unary.value;
8482 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8484 expr = expr->unary.value;
8487 if (expr->kind == EXPR_STRING_LITERAL
8488 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8489 warningf(&expr->base.source_position,
8490 "comparison with string literal results in unspecified behaviour");
8494 static void warn_comparison_in_comparison(const expression_t *const expr)
8496 if (expr->base.parenthesized)
8498 switch (expr->base.kind) {
8499 case EXPR_BINARY_LESS:
8500 case EXPR_BINARY_GREATER:
8501 case EXPR_BINARY_LESSEQUAL:
8502 case EXPR_BINARY_GREATEREQUAL:
8503 case EXPR_BINARY_NOTEQUAL:
8504 case EXPR_BINARY_EQUAL:
8505 warningf(&expr->base.source_position,
8506 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8513 static bool maybe_negative(expression_t const *const expr)
8515 switch (is_constant_expression(expr)) {
8516 case EXPR_CLASS_ERROR: return false;
8517 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8518 default: return true;
8523 * Check the semantics of comparison expressions.
8525 * @param expression The expression to check.
8527 static void semantic_comparison(binary_expression_t *expression)
8529 expression_t *left = expression->left;
8530 expression_t *right = expression->right;
8532 if (warning.address) {
8533 warn_string_literal_address(left);
8534 warn_string_literal_address(right);
8536 expression_t const* const func_left = get_reference_address(left);
8537 if (func_left != NULL && is_null_pointer_constant(right)) {
8538 warningf(&expression->base.source_position,
8539 "the address of '%Y' will never be NULL",
8540 func_left->reference.entity->base.symbol);
8543 expression_t const* const func_right = get_reference_address(right);
8544 if (func_right != NULL && is_null_pointer_constant(right)) {
8545 warningf(&expression->base.source_position,
8546 "the address of '%Y' will never be NULL",
8547 func_right->reference.entity->base.symbol);
8551 if (warning.parentheses) {
8552 warn_comparison_in_comparison(left);
8553 warn_comparison_in_comparison(right);
8556 type_t *orig_type_left = left->base.type;
8557 type_t *orig_type_right = right->base.type;
8558 type_t *type_left = skip_typeref(orig_type_left);
8559 type_t *type_right = skip_typeref(orig_type_right);
8561 /* TODO non-arithmetic types */
8562 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8563 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8565 /* test for signed vs unsigned compares */
8566 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8567 bool const signed_left = is_type_signed(type_left);
8568 bool const signed_right = is_type_signed(type_right);
8569 if (signed_left != signed_right) {
8570 /* FIXME long long needs better const folding magic */
8571 /* TODO check whether constant value can be represented by other type */
8572 if ((signed_left && maybe_negative(left)) ||
8573 (signed_right && maybe_negative(right))) {
8574 warningf(&expression->base.source_position,
8575 "comparison between signed and unsigned");
8580 expression->left = create_implicit_cast(left, arithmetic_type);
8581 expression->right = create_implicit_cast(right, arithmetic_type);
8582 expression->base.type = arithmetic_type;
8583 if (warning.float_equal &&
8584 (expression->base.kind == EXPR_BINARY_EQUAL ||
8585 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8586 is_type_float(arithmetic_type)) {
8587 warningf(&expression->base.source_position,
8588 "comparing floating point with == or != is unsafe");
8590 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8591 /* TODO check compatibility */
8592 } else if (is_type_pointer(type_left)) {
8593 expression->right = create_implicit_cast(right, type_left);
8594 } else if (is_type_pointer(type_right)) {
8595 expression->left = create_implicit_cast(left, type_right);
8596 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8597 type_error_incompatible("invalid operands in comparison",
8598 &expression->base.source_position,
8599 type_left, type_right);
8601 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8605 * Checks if a compound type has constant fields.
8607 static bool has_const_fields(const compound_type_t *type)
8609 compound_t *compound = type->compound;
8610 entity_t *entry = compound->members.entities;
8612 for (; entry != NULL; entry = entry->base.next) {
8613 if (!is_declaration(entry))
8616 const type_t *decl_type = skip_typeref(entry->declaration.type);
8617 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8624 static bool is_valid_assignment_lhs(expression_t const* const left)
8626 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8627 type_t *const type_left = skip_typeref(orig_type_left);
8629 if (!is_lvalue(left)) {
8630 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8635 if (left->kind == EXPR_REFERENCE
8636 && left->reference.entity->kind == ENTITY_FUNCTION) {
8637 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8641 if (is_type_array(type_left)) {
8642 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8645 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8646 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8650 if (is_type_incomplete(type_left)) {
8651 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8652 left, orig_type_left);
8655 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8656 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8657 left, orig_type_left);
8664 static void semantic_arithmetic_assign(binary_expression_t *expression)
8666 expression_t *left = expression->left;
8667 expression_t *right = expression->right;
8668 type_t *orig_type_left = left->base.type;
8669 type_t *orig_type_right = right->base.type;
8671 if (!is_valid_assignment_lhs(left))
8674 type_t *type_left = skip_typeref(orig_type_left);
8675 type_t *type_right = skip_typeref(orig_type_right);
8677 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8678 /* TODO: improve error message */
8679 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8680 errorf(&expression->base.source_position,
8681 "operation needs arithmetic types");
8686 /* combined instructions are tricky. We can't create an implicit cast on
8687 * the left side, because we need the uncasted form for the store.
8688 * The ast2firm pass has to know that left_type must be right_type
8689 * for the arithmetic operation and create a cast by itself */
8690 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8691 expression->right = create_implicit_cast(right, arithmetic_type);
8692 expression->base.type = type_left;
8695 static void semantic_divmod_assign(binary_expression_t *expression)
8697 semantic_arithmetic_assign(expression);
8698 warn_div_by_zero(expression);
8701 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8703 expression_t *const left = expression->left;
8704 expression_t *const right = expression->right;
8705 type_t *const orig_type_left = left->base.type;
8706 type_t *const orig_type_right = right->base.type;
8707 type_t *const type_left = skip_typeref(orig_type_left);
8708 type_t *const type_right = skip_typeref(orig_type_right);
8710 if (!is_valid_assignment_lhs(left))
8713 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8714 /* combined instructions are tricky. We can't create an implicit cast on
8715 * the left side, because we need the uncasted form for the store.
8716 * The ast2firm pass has to know that left_type must be right_type
8717 * for the arithmetic operation and create a cast by itself */
8718 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8719 expression->right = create_implicit_cast(right, arithmetic_type);
8720 expression->base.type = type_left;
8721 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8722 check_pointer_arithmetic(&expression->base.source_position,
8723 type_left, orig_type_left);
8724 expression->base.type = type_left;
8725 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8726 errorf(&expression->base.source_position,
8727 "incompatible types '%T' and '%T' in assignment",
8728 orig_type_left, orig_type_right);
8732 static void semantic_integer_assign(binary_expression_t *expression)
8734 expression_t *left = expression->left;
8735 expression_t *right = expression->right;
8736 type_t *orig_type_left = left->base.type;
8737 type_t *orig_type_right = right->base.type;
8739 if (!is_valid_assignment_lhs(left))
8742 type_t *type_left = skip_typeref(orig_type_left);
8743 type_t *type_right = skip_typeref(orig_type_right);
8745 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8746 /* TODO: improve error message */
8747 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8748 errorf(&expression->base.source_position,
8749 "operation needs integer types");
8754 /* combined instructions are tricky. We can't create an implicit cast on
8755 * the left side, because we need the uncasted form for the store.
8756 * The ast2firm pass has to know that left_type must be right_type
8757 * for the arithmetic operation and create a cast by itself */
8758 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8759 expression->right = create_implicit_cast(right, arithmetic_type);
8760 expression->base.type = type_left;
8763 static void semantic_shift_assign(binary_expression_t *expression)
8765 expression_t *left = expression->left;
8767 if (!is_valid_assignment_lhs(left))
8770 if (!semantic_shift(expression))
8773 expression->base.type = skip_typeref(left->base.type);
8776 static void warn_logical_and_within_or(const expression_t *const expr)
8778 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8780 if (expr->base.parenthesized)
8782 warningf(&expr->base.source_position,
8783 "suggest parentheses around && within ||");
8787 * Check the semantic restrictions of a logical expression.
8789 static void semantic_logical_op(binary_expression_t *expression)
8791 /* §6.5.13:2 Each of the operands shall have scalar type.
8792 * §6.5.14:2 Each of the operands shall have scalar type. */
8793 semantic_condition(expression->left, "left operand of logical operator");
8794 semantic_condition(expression->right, "right operand of logical operator");
8795 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8796 warning.parentheses) {
8797 warn_logical_and_within_or(expression->left);
8798 warn_logical_and_within_or(expression->right);
8800 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8804 * Check the semantic restrictions of a binary assign expression.
8806 static void semantic_binexpr_assign(binary_expression_t *expression)
8808 expression_t *left = expression->left;
8809 type_t *orig_type_left = left->base.type;
8811 if (!is_valid_assignment_lhs(left))
8814 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8815 report_assign_error(error, orig_type_left, expression->right,
8816 "assignment", &left->base.source_position);
8817 expression->right = create_implicit_cast(expression->right, orig_type_left);
8818 expression->base.type = orig_type_left;
8822 * Determine if the outermost operation (or parts thereof) of the given
8823 * expression has no effect in order to generate a warning about this fact.
8824 * Therefore in some cases this only examines some of the operands of the
8825 * expression (see comments in the function and examples below).
8827 * f() + 23; // warning, because + has no effect
8828 * x || f(); // no warning, because x controls execution of f()
8829 * x ? y : f(); // warning, because y has no effect
8830 * (void)x; // no warning to be able to suppress the warning
8831 * This function can NOT be used for an "expression has definitely no effect"-
8833 static bool expression_has_effect(const expression_t *const expr)
8835 switch (expr->kind) {
8836 case EXPR_UNKNOWN: break;
8837 case EXPR_INVALID: return true; /* do NOT warn */
8838 case EXPR_REFERENCE: return false;
8839 case EXPR_REFERENCE_ENUM_VALUE: return false;
8840 case EXPR_LABEL_ADDRESS: return false;
8842 /* suppress the warning for microsoft __noop operations */
8843 case EXPR_LITERAL_MS_NOOP: return true;
8844 case EXPR_LITERAL_BOOLEAN:
8845 case EXPR_LITERAL_CHARACTER:
8846 case EXPR_LITERAL_WIDE_CHARACTER:
8847 case EXPR_LITERAL_INTEGER:
8848 case EXPR_LITERAL_INTEGER_OCTAL:
8849 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8850 case EXPR_LITERAL_FLOATINGPOINT:
8851 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8852 case EXPR_STRING_LITERAL: return false;
8853 case EXPR_WIDE_STRING_LITERAL: return false;
8856 const call_expression_t *const call = &expr->call;
8857 if (call->function->kind != EXPR_REFERENCE)
8860 switch (call->function->reference.entity->function.btk) {
8861 /* FIXME: which builtins have no effect? */
8862 default: return true;
8866 /* Generate the warning if either the left or right hand side of a
8867 * conditional expression has no effect */
8868 case EXPR_CONDITIONAL: {
8869 conditional_expression_t const *const cond = &expr->conditional;
8870 expression_t const *const t = cond->true_expression;
8872 (t == NULL || expression_has_effect(t)) &&
8873 expression_has_effect(cond->false_expression);
8876 case EXPR_SELECT: return false;
8877 case EXPR_ARRAY_ACCESS: return false;
8878 case EXPR_SIZEOF: return false;
8879 case EXPR_CLASSIFY_TYPE: return false;
8880 case EXPR_ALIGNOF: return false;
8882 case EXPR_FUNCNAME: return false;
8883 case EXPR_BUILTIN_CONSTANT_P: return false;
8884 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8885 case EXPR_OFFSETOF: return false;
8886 case EXPR_VA_START: return true;
8887 case EXPR_VA_ARG: return true;
8888 case EXPR_VA_COPY: return true;
8889 case EXPR_STATEMENT: return true; // TODO
8890 case EXPR_COMPOUND_LITERAL: return false;
8892 case EXPR_UNARY_NEGATE: return false;
8893 case EXPR_UNARY_PLUS: return false;
8894 case EXPR_UNARY_BITWISE_NEGATE: return false;
8895 case EXPR_UNARY_NOT: return false;
8896 case EXPR_UNARY_DEREFERENCE: return false;
8897 case EXPR_UNARY_TAKE_ADDRESS: return false;
8898 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8899 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8900 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8901 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8903 /* Treat void casts as if they have an effect in order to being able to
8904 * suppress the warning */
8905 case EXPR_UNARY_CAST: {
8906 type_t *const type = skip_typeref(expr->base.type);
8907 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8910 case EXPR_UNARY_CAST_IMPLICIT: return true;
8911 case EXPR_UNARY_ASSUME: return true;
8912 case EXPR_UNARY_DELETE: return true;
8913 case EXPR_UNARY_DELETE_ARRAY: return true;
8914 case EXPR_UNARY_THROW: return true;
8916 case EXPR_BINARY_ADD: return false;
8917 case EXPR_BINARY_SUB: return false;
8918 case EXPR_BINARY_MUL: return false;
8919 case EXPR_BINARY_DIV: return false;
8920 case EXPR_BINARY_MOD: return false;
8921 case EXPR_BINARY_EQUAL: return false;
8922 case EXPR_BINARY_NOTEQUAL: return false;
8923 case EXPR_BINARY_LESS: return false;
8924 case EXPR_BINARY_LESSEQUAL: return false;
8925 case EXPR_BINARY_GREATER: return false;
8926 case EXPR_BINARY_GREATEREQUAL: return false;
8927 case EXPR_BINARY_BITWISE_AND: return false;
8928 case EXPR_BINARY_BITWISE_OR: return false;
8929 case EXPR_BINARY_BITWISE_XOR: return false;
8930 case EXPR_BINARY_SHIFTLEFT: return false;
8931 case EXPR_BINARY_SHIFTRIGHT: return false;
8932 case EXPR_BINARY_ASSIGN: return true;
8933 case EXPR_BINARY_MUL_ASSIGN: return true;
8934 case EXPR_BINARY_DIV_ASSIGN: return true;
8935 case EXPR_BINARY_MOD_ASSIGN: return true;
8936 case EXPR_BINARY_ADD_ASSIGN: return true;
8937 case EXPR_BINARY_SUB_ASSIGN: return true;
8938 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8939 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8940 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8941 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8942 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8944 /* Only examine the right hand side of && and ||, because the left hand
8945 * side already has the effect of controlling the execution of the right
8947 case EXPR_BINARY_LOGICAL_AND:
8948 case EXPR_BINARY_LOGICAL_OR:
8949 /* Only examine the right hand side of a comma expression, because the left
8950 * hand side has a separate warning */
8951 case EXPR_BINARY_COMMA:
8952 return expression_has_effect(expr->binary.right);
8954 case EXPR_BINARY_ISGREATER: return false;
8955 case EXPR_BINARY_ISGREATEREQUAL: return false;
8956 case EXPR_BINARY_ISLESS: return false;
8957 case EXPR_BINARY_ISLESSEQUAL: return false;
8958 case EXPR_BINARY_ISLESSGREATER: return false;
8959 case EXPR_BINARY_ISUNORDERED: return false;
8962 internal_errorf(HERE, "unexpected expression");
8965 static void semantic_comma(binary_expression_t *expression)
8967 if (warning.unused_value) {
8968 const expression_t *const left = expression->left;
8969 if (!expression_has_effect(left)) {
8970 warningf(&left->base.source_position,
8971 "left-hand operand of comma expression has no effect");
8974 expression->base.type = expression->right->base.type;
8978 * @param prec_r precedence of the right operand
8980 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8981 static expression_t *parse_##binexpression_type(expression_t *left) \
8983 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8984 binexpr->binary.left = left; \
8987 expression_t *right = parse_subexpression(prec_r); \
8989 binexpr->binary.right = right; \
8990 sfunc(&binexpr->binary); \
8995 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8996 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8997 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8998 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8999 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
9000 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
9001 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
9002 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
9003 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
9004 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
9005 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
9006 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
9007 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
9008 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
9009 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
9010 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
9011 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9012 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9013 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9014 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9015 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9016 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9017 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9018 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9019 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9020 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9021 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9022 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9023 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9024 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9027 static expression_t *parse_subexpression(precedence_t precedence)
9029 if (token.type < 0) {
9030 return expected_expression_error();
9033 expression_parser_function_t *parser
9034 = &expression_parsers[token.type];
9035 source_position_t source_position = token.source_position;
9038 if (parser->parser != NULL) {
9039 left = parser->parser();
9041 left = parse_primary_expression();
9043 assert(left != NULL);
9044 left->base.source_position = source_position;
9047 if (token.type < 0) {
9048 return expected_expression_error();
9051 parser = &expression_parsers[token.type];
9052 if (parser->infix_parser == NULL)
9054 if (parser->infix_precedence < precedence)
9057 left = parser->infix_parser(left);
9059 assert(left != NULL);
9060 assert(left->kind != EXPR_UNKNOWN);
9061 left->base.source_position = source_position;
9068 * Parse an expression.
9070 static expression_t *parse_expression(void)
9072 return parse_subexpression(PREC_EXPRESSION);
9076 * Register a parser for a prefix-like operator.
9078 * @param parser the parser function
9079 * @param token_type the token type of the prefix token
9081 static void register_expression_parser(parse_expression_function parser,
9084 expression_parser_function_t *entry = &expression_parsers[token_type];
9086 if (entry->parser != NULL) {
9087 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9088 panic("trying to register multiple expression parsers for a token");
9090 entry->parser = parser;
9094 * Register a parser for an infix operator with given precedence.
9096 * @param parser the parser function
9097 * @param token_type the token type of the infix operator
9098 * @param precedence the precedence of the operator
9100 static void register_infix_parser(parse_expression_infix_function parser,
9101 int token_type, precedence_t precedence)
9103 expression_parser_function_t *entry = &expression_parsers[token_type];
9105 if (entry->infix_parser != NULL) {
9106 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9107 panic("trying to register multiple infix expression parsers for a "
9110 entry->infix_parser = parser;
9111 entry->infix_precedence = precedence;
9115 * Initialize the expression parsers.
9117 static void init_expression_parsers(void)
9119 memset(&expression_parsers, 0, sizeof(expression_parsers));
9121 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9122 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9123 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9124 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9125 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9126 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9127 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9128 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9129 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9130 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9131 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9132 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9133 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9134 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9135 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9136 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9137 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9138 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9139 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9140 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9141 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9142 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9143 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9144 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9145 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9146 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9147 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9148 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9149 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9150 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9151 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9152 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9153 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9154 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9155 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9156 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9157 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9159 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9160 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9161 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9162 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9163 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9164 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9165 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9166 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9167 register_expression_parser(parse_sizeof, T_sizeof);
9168 register_expression_parser(parse_alignof, T___alignof__);
9169 register_expression_parser(parse_extension, T___extension__);
9170 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9171 register_expression_parser(parse_delete, T_delete);
9172 register_expression_parser(parse_throw, T_throw);
9176 * Parse a asm statement arguments specification.
9178 static asm_argument_t *parse_asm_arguments(bool is_out)
9180 asm_argument_t *result = NULL;
9181 asm_argument_t **anchor = &result;
9183 while (token.type == T_STRING_LITERAL || token.type == '[') {
9184 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9185 memset(argument, 0, sizeof(argument[0]));
9188 if (token.type != T_IDENTIFIER) {
9189 parse_error_expected("while parsing asm argument",
9190 T_IDENTIFIER, NULL);
9193 argument->symbol = token.symbol;
9195 expect(']', end_error);
9198 argument->constraints = parse_string_literals();
9199 expect('(', end_error);
9200 add_anchor_token(')');
9201 expression_t *expression = parse_expression();
9202 rem_anchor_token(')');
9204 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9205 * change size or type representation (e.g. int -> long is ok, but
9206 * int -> float is not) */
9207 if (expression->kind == EXPR_UNARY_CAST) {
9208 type_t *const type = expression->base.type;
9209 type_kind_t const kind = type->kind;
9210 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9213 if (kind == TYPE_ATOMIC) {
9214 atomic_type_kind_t const akind = type->atomic.akind;
9215 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9216 size = get_atomic_type_size(akind);
9218 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9219 size = get_atomic_type_size(get_intptr_kind());
9223 expression_t *const value = expression->unary.value;
9224 type_t *const value_type = value->base.type;
9225 type_kind_t const value_kind = value_type->kind;
9227 unsigned value_flags;
9228 unsigned value_size;
9229 if (value_kind == TYPE_ATOMIC) {
9230 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9231 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9232 value_size = get_atomic_type_size(value_akind);
9233 } else if (value_kind == TYPE_POINTER) {
9234 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9235 value_size = get_atomic_type_size(get_intptr_kind());
9240 if (value_flags != flags || value_size != size)
9244 } while (expression->kind == EXPR_UNARY_CAST);
9248 if (!is_lvalue(expression)) {
9249 errorf(&expression->base.source_position,
9250 "asm output argument is not an lvalue");
9253 if (argument->constraints.begin[0] == '=')
9254 determine_lhs_ent(expression, NULL);
9256 mark_vars_read(expression, NULL);
9258 mark_vars_read(expression, NULL);
9260 argument->expression = expression;
9261 expect(')', end_error);
9263 set_address_taken(expression, true);
9266 anchor = &argument->next;
9278 * Parse a asm statement clobber specification.
9280 static asm_clobber_t *parse_asm_clobbers(void)
9282 asm_clobber_t *result = NULL;
9283 asm_clobber_t **anchor = &result;
9285 while (token.type == T_STRING_LITERAL) {
9286 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9287 clobber->clobber = parse_string_literals();
9290 anchor = &clobber->next;
9300 * Parse an asm statement.
9302 static statement_t *parse_asm_statement(void)
9304 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9305 asm_statement_t *asm_statement = &statement->asms;
9309 if (next_if(T_volatile))
9310 asm_statement->is_volatile = true;
9312 expect('(', end_error);
9313 add_anchor_token(')');
9314 if (token.type != T_STRING_LITERAL) {
9315 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9318 asm_statement->asm_text = parse_string_literals();
9320 add_anchor_token(':');
9321 if (!next_if(':')) {
9322 rem_anchor_token(':');
9326 asm_statement->outputs = parse_asm_arguments(true);
9327 if (!next_if(':')) {
9328 rem_anchor_token(':');
9332 asm_statement->inputs = parse_asm_arguments(false);
9333 if (!next_if(':')) {
9334 rem_anchor_token(':');
9337 rem_anchor_token(':');
9339 asm_statement->clobbers = parse_asm_clobbers();
9342 rem_anchor_token(')');
9343 expect(')', end_error);
9344 expect(';', end_error);
9346 if (asm_statement->outputs == NULL) {
9347 /* GCC: An 'asm' instruction without any output operands will be treated
9348 * identically to a volatile 'asm' instruction. */
9349 asm_statement->is_volatile = true;
9354 return create_invalid_statement();
9357 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9359 statement_t *inner_stmt;
9360 switch (token.type) {
9362 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9363 inner_stmt = create_invalid_statement();
9367 if (label->kind == STATEMENT_LABEL) {
9368 /* Eat an empty statement here, to avoid the warning about an empty
9369 * statement after a label. label:; is commonly used to have a label
9370 * before a closing brace. */
9371 inner_stmt = create_empty_statement();
9378 inner_stmt = parse_statement();
9379 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9380 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9381 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9389 * Parse a case statement.
9391 static statement_t *parse_case_statement(void)
9393 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9394 source_position_t *const pos = &statement->base.source_position;
9398 expression_t *const expression = parse_expression();
9399 statement->case_label.expression = expression;
9400 expression_classification_t const expr_class = is_constant_expression(expression);
9401 if (expr_class != EXPR_CLASS_CONSTANT) {
9402 if (expr_class != EXPR_CLASS_ERROR) {
9403 errorf(pos, "case label does not reduce to an integer constant");
9405 statement->case_label.is_bad = true;
9407 long const val = fold_constant_to_int(expression);
9408 statement->case_label.first_case = val;
9409 statement->case_label.last_case = val;
9413 if (next_if(T_DOTDOTDOT)) {
9414 expression_t *const end_range = parse_expression();
9415 statement->case_label.end_range = end_range;
9416 expression_classification_t const end_class = is_constant_expression(end_range);
9417 if (end_class != EXPR_CLASS_CONSTANT) {
9418 if (end_class != EXPR_CLASS_ERROR) {
9419 errorf(pos, "case range does not reduce to an integer constant");
9421 statement->case_label.is_bad = true;
9423 long const val = fold_constant_to_int(end_range);
9424 statement->case_label.last_case = val;
9426 if (warning.other && val < statement->case_label.first_case) {
9427 statement->case_label.is_empty_range = true;
9428 warningf(pos, "empty range specified");
9434 PUSH_PARENT(statement);
9436 expect(':', end_error);
9439 if (current_switch != NULL) {
9440 if (! statement->case_label.is_bad) {
9441 /* Check for duplicate case values */
9442 case_label_statement_t *c = &statement->case_label;
9443 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9444 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9447 if (c->last_case < l->first_case || c->first_case > l->last_case)
9450 errorf(pos, "duplicate case value (previously used %P)",
9451 &l->base.source_position);
9455 /* link all cases into the switch statement */
9456 if (current_switch->last_case == NULL) {
9457 current_switch->first_case = &statement->case_label;
9459 current_switch->last_case->next = &statement->case_label;
9461 current_switch->last_case = &statement->case_label;
9463 errorf(pos, "case label not within a switch statement");
9466 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9473 * Parse a default statement.
9475 static statement_t *parse_default_statement(void)
9477 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9481 PUSH_PARENT(statement);
9483 expect(':', end_error);
9486 if (current_switch != NULL) {
9487 const case_label_statement_t *def_label = current_switch->default_label;
9488 if (def_label != NULL) {
9489 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9490 &def_label->base.source_position);
9492 current_switch->default_label = &statement->case_label;
9494 /* link all cases into the switch statement */
9495 if (current_switch->last_case == NULL) {
9496 current_switch->first_case = &statement->case_label;
9498 current_switch->last_case->next = &statement->case_label;
9500 current_switch->last_case = &statement->case_label;
9503 errorf(&statement->base.source_position,
9504 "'default' label not within a switch statement");
9507 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9514 * Parse a label statement.
9516 static statement_t *parse_label_statement(void)
9518 assert(token.type == T_IDENTIFIER);
9519 symbol_t *symbol = token.symbol;
9520 label_t *label = get_label(symbol);
9522 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9523 statement->label.label = label;
9527 PUSH_PARENT(statement);
9529 /* if statement is already set then the label is defined twice,
9530 * otherwise it was just mentioned in a goto/local label declaration so far
9532 if (label->statement != NULL) {
9533 errorf(HERE, "duplicate label '%Y' (declared %P)",
9534 symbol, &label->base.source_position);
9536 label->base.source_position = token.source_position;
9537 label->statement = statement;
9542 statement->label.statement = parse_label_inner_statement(statement, "label");
9544 /* remember the labels in a list for later checking */
9545 *label_anchor = &statement->label;
9546 label_anchor = &statement->label.next;
9553 * Parse an if statement.
9555 static statement_t *parse_if(void)
9557 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9561 PUSH_PARENT(statement);
9563 add_anchor_token('{');
9565 expect('(', end_error);
9566 add_anchor_token(')');
9567 expression_t *const expr = parse_expression();
9568 statement->ifs.condition = expr;
9569 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9571 semantic_condition(expr, "condition of 'if'-statment");
9572 mark_vars_read(expr, NULL);
9573 rem_anchor_token(')');
9574 expect(')', end_error);
9577 rem_anchor_token('{');
9579 add_anchor_token(T_else);
9580 statement_t *const true_stmt = parse_statement();
9581 statement->ifs.true_statement = true_stmt;
9582 rem_anchor_token(T_else);
9584 if (next_if(T_else)) {
9585 statement->ifs.false_statement = parse_statement();
9586 } else if (warning.parentheses &&
9587 true_stmt->kind == STATEMENT_IF &&
9588 true_stmt->ifs.false_statement != NULL) {
9589 warningf(&true_stmt->base.source_position,
9590 "suggest explicit braces to avoid ambiguous 'else'");
9598 * Check that all enums are handled in a switch.
9600 * @param statement the switch statement to check
9602 static void check_enum_cases(const switch_statement_t *statement)
9604 const type_t *type = skip_typeref(statement->expression->base.type);
9605 if (! is_type_enum(type))
9607 const enum_type_t *enumt = &type->enumt;
9609 /* if we have a default, no warnings */
9610 if (statement->default_label != NULL)
9613 /* FIXME: calculation of value should be done while parsing */
9614 /* TODO: quadratic algorithm here. Change to an n log n one */
9615 long last_value = -1;
9616 const entity_t *entry = enumt->enume->base.next;
9617 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9618 entry = entry->base.next) {
9619 const expression_t *expression = entry->enum_value.value;
9620 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9622 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9623 if (l->expression == NULL)
9625 if (l->first_case <= value && value <= l->last_case) {
9631 warningf(&statement->base.source_position,
9632 "enumeration value '%Y' not handled in switch",
9633 entry->base.symbol);
9640 * Parse a switch statement.
9642 static statement_t *parse_switch(void)
9644 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9648 PUSH_PARENT(statement);
9650 expect('(', end_error);
9651 add_anchor_token(')');
9652 expression_t *const expr = parse_expression();
9653 mark_vars_read(expr, NULL);
9654 type_t * type = skip_typeref(expr->base.type);
9655 if (is_type_integer(type)) {
9656 type = promote_integer(type);
9657 if (warning.traditional) {
9658 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9659 warningf(&expr->base.source_position,
9660 "'%T' switch expression not converted to '%T' in ISO C",
9664 } else if (is_type_valid(type)) {
9665 errorf(&expr->base.source_position,
9666 "switch quantity is not an integer, but '%T'", type);
9667 type = type_error_type;
9669 statement->switchs.expression = create_implicit_cast(expr, type);
9670 expect(')', end_error);
9671 rem_anchor_token(')');
9673 switch_statement_t *rem = current_switch;
9674 current_switch = &statement->switchs;
9675 statement->switchs.body = parse_statement();
9676 current_switch = rem;
9678 if (warning.switch_default &&
9679 statement->switchs.default_label == NULL) {
9680 warningf(&statement->base.source_position, "switch has no default case");
9682 if (warning.switch_enum)
9683 check_enum_cases(&statement->switchs);
9689 return create_invalid_statement();
9692 static statement_t *parse_loop_body(statement_t *const loop)
9694 statement_t *const rem = current_loop;
9695 current_loop = loop;
9697 statement_t *const body = parse_statement();
9704 * Parse a while statement.
9706 static statement_t *parse_while(void)
9708 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9712 PUSH_PARENT(statement);
9714 expect('(', end_error);
9715 add_anchor_token(')');
9716 expression_t *const cond = parse_expression();
9717 statement->whiles.condition = cond;
9718 /* §6.8.5:2 The controlling expression of an iteration statement shall
9719 * have scalar type. */
9720 semantic_condition(cond, "condition of 'while'-statement");
9721 mark_vars_read(cond, NULL);
9722 rem_anchor_token(')');
9723 expect(')', end_error);
9725 statement->whiles.body = parse_loop_body(statement);
9731 return create_invalid_statement();
9735 * Parse a do statement.
9737 static statement_t *parse_do(void)
9739 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9743 PUSH_PARENT(statement);
9745 add_anchor_token(T_while);
9746 statement->do_while.body = parse_loop_body(statement);
9747 rem_anchor_token(T_while);
9749 expect(T_while, end_error);
9750 expect('(', end_error);
9751 add_anchor_token(')');
9752 expression_t *const cond = parse_expression();
9753 statement->do_while.condition = cond;
9754 /* §6.8.5:2 The controlling expression of an iteration statement shall
9755 * have scalar type. */
9756 semantic_condition(cond, "condition of 'do-while'-statement");
9757 mark_vars_read(cond, NULL);
9758 rem_anchor_token(')');
9759 expect(')', end_error);
9760 expect(';', end_error);
9766 return create_invalid_statement();
9770 * Parse a for statement.
9772 static statement_t *parse_for(void)
9774 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9778 expect('(', end_error1);
9779 add_anchor_token(')');
9781 PUSH_PARENT(statement);
9783 size_t const top = environment_top();
9784 scope_t *old_scope = scope_push(&statement->fors.scope);
9786 bool old_gcc_extension = in_gcc_extension;
9787 while (next_if(T___extension__)) {
9788 in_gcc_extension = true;
9792 } else if (is_declaration_specifier(&token, false)) {
9793 parse_declaration(record_entity, DECL_FLAGS_NONE);
9795 add_anchor_token(';');
9796 expression_t *const init = parse_expression();
9797 statement->fors.initialisation = init;
9798 mark_vars_read(init, ENT_ANY);
9799 if (warning.unused_value && !expression_has_effect(init)) {
9800 warningf(&init->base.source_position,
9801 "initialisation of 'for'-statement has no effect");
9803 rem_anchor_token(';');
9804 expect(';', end_error2);
9806 in_gcc_extension = old_gcc_extension;
9808 if (token.type != ';') {
9809 add_anchor_token(';');
9810 expression_t *const cond = parse_expression();
9811 statement->fors.condition = cond;
9812 /* §6.8.5:2 The controlling expression of an iteration statement
9813 * shall have scalar type. */
9814 semantic_condition(cond, "condition of 'for'-statement");
9815 mark_vars_read(cond, NULL);
9816 rem_anchor_token(';');
9818 expect(';', end_error2);
9819 if (token.type != ')') {
9820 expression_t *const step = parse_expression();
9821 statement->fors.step = step;
9822 mark_vars_read(step, ENT_ANY);
9823 if (warning.unused_value && !expression_has_effect(step)) {
9824 warningf(&step->base.source_position,
9825 "step of 'for'-statement has no effect");
9828 expect(')', end_error2);
9829 rem_anchor_token(')');
9830 statement->fors.body = parse_loop_body(statement);
9832 assert(current_scope == &statement->fors.scope);
9833 scope_pop(old_scope);
9834 environment_pop_to(top);
9841 rem_anchor_token(')');
9842 assert(current_scope == &statement->fors.scope);
9843 scope_pop(old_scope);
9844 environment_pop_to(top);
9848 return create_invalid_statement();
9852 * Parse a goto statement.
9854 static statement_t *parse_goto(void)
9856 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9859 if (GNU_MODE && next_if('*')) {
9860 expression_t *expression = parse_expression();
9861 mark_vars_read(expression, NULL);
9863 /* Argh: although documentation says the expression must be of type void*,
9864 * gcc accepts anything that can be casted into void* without error */
9865 type_t *type = expression->base.type;
9867 if (type != type_error_type) {
9868 if (!is_type_pointer(type) && !is_type_integer(type)) {
9869 errorf(&expression->base.source_position,
9870 "cannot convert to a pointer type");
9871 } else if (warning.other && type != type_void_ptr) {
9872 warningf(&expression->base.source_position,
9873 "type of computed goto expression should be 'void*' not '%T'", type);
9875 expression = create_implicit_cast(expression, type_void_ptr);
9878 statement->gotos.expression = expression;
9879 } else if (token.type == T_IDENTIFIER) {
9880 symbol_t *symbol = token.symbol;
9882 statement->gotos.label = get_label(symbol);
9885 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9887 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9889 return create_invalid_statement();
9892 /* remember the goto's in a list for later checking */
9893 *goto_anchor = &statement->gotos;
9894 goto_anchor = &statement->gotos.next;
9896 expect(';', end_error);
9903 * Parse a continue statement.
9905 static statement_t *parse_continue(void)
9907 if (current_loop == NULL) {
9908 errorf(HERE, "continue statement not within loop");
9911 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9914 expect(';', end_error);
9921 * Parse a break statement.
9923 static statement_t *parse_break(void)
9925 if (current_switch == NULL && current_loop == NULL) {
9926 errorf(HERE, "break statement not within loop or switch");
9929 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9932 expect(';', end_error);
9939 * Parse a __leave statement.
9941 static statement_t *parse_leave_statement(void)
9943 if (current_try == NULL) {
9944 errorf(HERE, "__leave statement not within __try");
9947 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9950 expect(';', end_error);
9957 * Check if a given entity represents a local variable.
9959 static bool is_local_variable(const entity_t *entity)
9961 if (entity->kind != ENTITY_VARIABLE)
9964 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9965 case STORAGE_CLASS_AUTO:
9966 case STORAGE_CLASS_REGISTER: {
9967 const type_t *type = skip_typeref(entity->declaration.type);
9968 if (is_type_function(type)) {
9980 * Check if a given expression represents a local variable.
9982 static bool expression_is_local_variable(const expression_t *expression)
9984 if (expression->base.kind != EXPR_REFERENCE) {
9987 const entity_t *entity = expression->reference.entity;
9988 return is_local_variable(entity);
9992 * Check if a given expression represents a local variable and
9993 * return its declaration then, else return NULL.
9995 entity_t *expression_is_variable(const expression_t *expression)
9997 if (expression->base.kind != EXPR_REFERENCE) {
10000 entity_t *entity = expression->reference.entity;
10001 if (entity->kind != ENTITY_VARIABLE)
10008 * Parse a return statement.
10010 static statement_t *parse_return(void)
10014 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10016 expression_t *return_value = NULL;
10017 if (token.type != ';') {
10018 return_value = parse_expression();
10019 mark_vars_read(return_value, NULL);
10022 const type_t *const func_type = skip_typeref(current_function->base.type);
10023 assert(is_type_function(func_type));
10024 type_t *const return_type = skip_typeref(func_type->function.return_type);
10026 source_position_t const *const pos = &statement->base.source_position;
10027 if (return_value != NULL) {
10028 type_t *return_value_type = skip_typeref(return_value->base.type);
10030 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10031 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10032 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10033 /* Only warn in C mode, because GCC does the same */
10034 if (c_mode & _CXX || strict_mode) {
10036 "'return' with a value, in function returning 'void'");
10037 } else if (warning.other) {
10039 "'return' with a value, in function returning 'void'");
10041 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10042 /* Only warn in C mode, because GCC does the same */
10045 "'return' with expression in function returning 'void'");
10046 } else if (warning.other) {
10048 "'return' with expression in function returning 'void'");
10052 assign_error_t error = semantic_assign(return_type, return_value);
10053 report_assign_error(error, return_type, return_value, "'return'",
10056 return_value = create_implicit_cast(return_value, return_type);
10057 /* check for returning address of a local var */
10058 if (warning.other && return_value != NULL
10059 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10060 const expression_t *expression = return_value->unary.value;
10061 if (expression_is_local_variable(expression)) {
10062 warningf(pos, "function returns address of local variable");
10065 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10066 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10067 if (c_mode & _CXX || strict_mode) {
10069 "'return' without value, in function returning non-void");
10072 "'return' without value, in function returning non-void");
10075 statement->returns.value = return_value;
10077 expect(';', end_error);
10084 * Parse a declaration statement.
10086 static statement_t *parse_declaration_statement(void)
10088 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10090 entity_t *before = current_scope->last_entity;
10092 parse_external_declaration();
10094 parse_declaration(record_entity, DECL_FLAGS_NONE);
10097 declaration_statement_t *const decl = &statement->declaration;
10098 entity_t *const begin =
10099 before != NULL ? before->base.next : current_scope->entities;
10100 decl->declarations_begin = begin;
10101 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10107 * Parse an expression statement, ie. expr ';'.
10109 static statement_t *parse_expression_statement(void)
10111 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10113 expression_t *const expr = parse_expression();
10114 statement->expression.expression = expr;
10115 mark_vars_read(expr, ENT_ANY);
10117 expect(';', end_error);
10124 * Parse a microsoft __try { } __finally { } or
10125 * __try{ } __except() { }
10127 static statement_t *parse_ms_try_statment(void)
10129 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10132 PUSH_PARENT(statement);
10134 ms_try_statement_t *rem = current_try;
10135 current_try = &statement->ms_try;
10136 statement->ms_try.try_statement = parse_compound_statement(false);
10141 if (next_if(T___except)) {
10142 expect('(', end_error);
10143 add_anchor_token(')');
10144 expression_t *const expr = parse_expression();
10145 mark_vars_read(expr, NULL);
10146 type_t * type = skip_typeref(expr->base.type);
10147 if (is_type_integer(type)) {
10148 type = promote_integer(type);
10149 } else if (is_type_valid(type)) {
10150 errorf(&expr->base.source_position,
10151 "__expect expression is not an integer, but '%T'", type);
10152 type = type_error_type;
10154 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10155 rem_anchor_token(')');
10156 expect(')', end_error);
10157 statement->ms_try.final_statement = parse_compound_statement(false);
10158 } else if (next_if(T__finally)) {
10159 statement->ms_try.final_statement = parse_compound_statement(false);
10161 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10162 return create_invalid_statement();
10166 return create_invalid_statement();
10169 static statement_t *parse_empty_statement(void)
10171 if (warning.empty_statement) {
10172 warningf(HERE, "statement is empty");
10174 statement_t *const statement = create_empty_statement();
10179 static statement_t *parse_local_label_declaration(void)
10181 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10185 entity_t *begin = NULL;
10186 entity_t *end = NULL;
10187 entity_t **anchor = &begin;
10189 if (token.type != T_IDENTIFIER) {
10190 parse_error_expected("while parsing local label declaration",
10191 T_IDENTIFIER, NULL);
10194 symbol_t *symbol = token.symbol;
10195 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10196 if (entity != NULL && entity->base.parent_scope == current_scope) {
10197 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10198 symbol, &entity->base.source_position);
10200 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10202 entity->base.parent_scope = current_scope;
10203 entity->base.namespc = NAMESPACE_LABEL;
10204 entity->base.source_position = token.source_position;
10205 entity->base.symbol = symbol;
10208 anchor = &entity->base.next;
10211 environment_push(entity);
10214 } while (next_if(','));
10215 expect(';', end_error);
10217 statement->declaration.declarations_begin = begin;
10218 statement->declaration.declarations_end = end;
10222 static void parse_namespace_definition(void)
10226 entity_t *entity = NULL;
10227 symbol_t *symbol = NULL;
10229 if (token.type == T_IDENTIFIER) {
10230 symbol = token.symbol;
10233 entity = get_entity(symbol, NAMESPACE_NORMAL);
10235 && entity->kind != ENTITY_NAMESPACE
10236 && entity->base.parent_scope == current_scope) {
10237 if (is_entity_valid(entity)) {
10238 error_redefined_as_different_kind(&token.source_position,
10239 entity, ENTITY_NAMESPACE);
10245 if (entity == NULL) {
10246 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10247 entity->base.symbol = symbol;
10248 entity->base.source_position = token.source_position;
10249 entity->base.namespc = NAMESPACE_NORMAL;
10250 entity->base.parent_scope = current_scope;
10253 if (token.type == '=') {
10254 /* TODO: parse namespace alias */
10255 panic("namespace alias definition not supported yet");
10258 environment_push(entity);
10259 append_entity(current_scope, entity);
10261 size_t const top = environment_top();
10262 scope_t *old_scope = scope_push(&entity->namespacee.members);
10264 entity_t *old_current_entity = current_entity;
10265 current_entity = entity;
10267 expect('{', end_error);
10269 expect('}', end_error);
10272 assert(current_scope == &entity->namespacee.members);
10273 assert(current_entity == entity);
10274 current_entity = old_current_entity;
10275 scope_pop(old_scope);
10276 environment_pop_to(top);
10280 * Parse a statement.
10281 * There's also parse_statement() which additionally checks for
10282 * "statement has no effect" warnings
10284 static statement_t *intern_parse_statement(void)
10286 statement_t *statement = NULL;
10288 /* declaration or statement */
10289 add_anchor_token(';');
10290 switch (token.type) {
10291 case T_IDENTIFIER: {
10292 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10293 if (la1_type == ':') {
10294 statement = parse_label_statement();
10295 } else if (is_typedef_symbol(token.symbol)) {
10296 statement = parse_declaration_statement();
10298 /* it's an identifier, the grammar says this must be an
10299 * expression statement. However it is common that users mistype
10300 * declaration types, so we guess a bit here to improve robustness
10301 * for incorrect programs */
10302 switch (la1_type) {
10305 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10307 statement = parse_expression_statement();
10311 statement = parse_declaration_statement();
10319 case T___extension__:
10320 /* This can be a prefix to a declaration or an expression statement.
10321 * We simply eat it now and parse the rest with tail recursion. */
10322 while (next_if(T___extension__)) {}
10323 bool old_gcc_extension = in_gcc_extension;
10324 in_gcc_extension = true;
10325 statement = intern_parse_statement();
10326 in_gcc_extension = old_gcc_extension;
10330 statement = parse_declaration_statement();
10334 statement = parse_local_label_declaration();
10337 case ';': statement = parse_empty_statement(); break;
10338 case '{': statement = parse_compound_statement(false); break;
10339 case T___leave: statement = parse_leave_statement(); break;
10340 case T___try: statement = parse_ms_try_statment(); break;
10341 case T_asm: statement = parse_asm_statement(); break;
10342 case T_break: statement = parse_break(); break;
10343 case T_case: statement = parse_case_statement(); break;
10344 case T_continue: statement = parse_continue(); break;
10345 case T_default: statement = parse_default_statement(); break;
10346 case T_do: statement = parse_do(); break;
10347 case T_for: statement = parse_for(); break;
10348 case T_goto: statement = parse_goto(); break;
10349 case T_if: statement = parse_if(); break;
10350 case T_return: statement = parse_return(); break;
10351 case T_switch: statement = parse_switch(); break;
10352 case T_while: statement = parse_while(); break;
10355 statement = parse_expression_statement();
10359 errorf(HERE, "unexpected token %K while parsing statement", &token);
10360 statement = create_invalid_statement();
10365 rem_anchor_token(';');
10367 assert(statement != NULL
10368 && statement->base.source_position.input_name != NULL);
10374 * parse a statement and emits "statement has no effect" warning if needed
10375 * (This is really a wrapper around intern_parse_statement with check for 1
10376 * single warning. It is needed, because for statement expressions we have
10377 * to avoid the warning on the last statement)
10379 static statement_t *parse_statement(void)
10381 statement_t *statement = intern_parse_statement();
10383 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10384 expression_t *expression = statement->expression.expression;
10385 if (!expression_has_effect(expression)) {
10386 warningf(&expression->base.source_position,
10387 "statement has no effect");
10395 * Parse a compound statement.
10397 static statement_t *parse_compound_statement(bool inside_expression_statement)
10399 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10401 PUSH_PARENT(statement);
10404 add_anchor_token('}');
10405 /* tokens, which can start a statement */
10406 /* TODO MS, __builtin_FOO */
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('~');
10415 add_anchor_token(T_CHARACTER_CONSTANT);
10416 add_anchor_token(T_COLONCOLON);
10417 add_anchor_token(T_FLOATINGPOINT);
10418 add_anchor_token(T_IDENTIFIER);
10419 add_anchor_token(T_INTEGER);
10420 add_anchor_token(T_MINUSMINUS);
10421 add_anchor_token(T_PLUSPLUS);
10422 add_anchor_token(T_STRING_LITERAL);
10423 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10424 add_anchor_token(T_WIDE_STRING_LITERAL);
10425 add_anchor_token(T__Bool);
10426 add_anchor_token(T__Complex);
10427 add_anchor_token(T__Imaginary);
10428 add_anchor_token(T___FUNCTION__);
10429 add_anchor_token(T___PRETTY_FUNCTION__);
10430 add_anchor_token(T___alignof__);
10431 add_anchor_token(T___attribute__);
10432 add_anchor_token(T___builtin_va_start);
10433 add_anchor_token(T___extension__);
10434 add_anchor_token(T___func__);
10435 add_anchor_token(T___imag__);
10436 add_anchor_token(T___label__);
10437 add_anchor_token(T___real__);
10438 add_anchor_token(T___thread);
10439 add_anchor_token(T_asm);
10440 add_anchor_token(T_auto);
10441 add_anchor_token(T_bool);
10442 add_anchor_token(T_break);
10443 add_anchor_token(T_case);
10444 add_anchor_token(T_char);
10445 add_anchor_token(T_class);
10446 add_anchor_token(T_const);
10447 add_anchor_token(T_const_cast);
10448 add_anchor_token(T_continue);
10449 add_anchor_token(T_default);
10450 add_anchor_token(T_delete);
10451 add_anchor_token(T_double);
10452 add_anchor_token(T_do);
10453 add_anchor_token(T_dynamic_cast);
10454 add_anchor_token(T_enum);
10455 add_anchor_token(T_extern);
10456 add_anchor_token(T_false);
10457 add_anchor_token(T_float);
10458 add_anchor_token(T_for);
10459 add_anchor_token(T_goto);
10460 add_anchor_token(T_if);
10461 add_anchor_token(T_inline);
10462 add_anchor_token(T_int);
10463 add_anchor_token(T_long);
10464 add_anchor_token(T_new);
10465 add_anchor_token(T_operator);
10466 add_anchor_token(T_register);
10467 add_anchor_token(T_reinterpret_cast);
10468 add_anchor_token(T_restrict);
10469 add_anchor_token(T_return);
10470 add_anchor_token(T_short);
10471 add_anchor_token(T_signed);
10472 add_anchor_token(T_sizeof);
10473 add_anchor_token(T_static);
10474 add_anchor_token(T_static_cast);
10475 add_anchor_token(T_struct);
10476 add_anchor_token(T_switch);
10477 add_anchor_token(T_template);
10478 add_anchor_token(T_this);
10479 add_anchor_token(T_throw);
10480 add_anchor_token(T_true);
10481 add_anchor_token(T_try);
10482 add_anchor_token(T_typedef);
10483 add_anchor_token(T_typeid);
10484 add_anchor_token(T_typename);
10485 add_anchor_token(T_typeof);
10486 add_anchor_token(T_union);
10487 add_anchor_token(T_unsigned);
10488 add_anchor_token(T_using);
10489 add_anchor_token(T_void);
10490 add_anchor_token(T_volatile);
10491 add_anchor_token(T_wchar_t);
10492 add_anchor_token(T_while);
10494 size_t const top = environment_top();
10495 scope_t *old_scope = scope_push(&statement->compound.scope);
10497 statement_t **anchor = &statement->compound.statements;
10498 bool only_decls_so_far = true;
10499 while (token.type != '}') {
10500 if (token.type == T_EOF) {
10501 errorf(&statement->base.source_position,
10502 "EOF while parsing compound statement");
10505 statement_t *sub_statement = intern_parse_statement();
10506 if (is_invalid_statement(sub_statement)) {
10507 /* an error occurred. if we are at an anchor, return */
10513 if (warning.declaration_after_statement) {
10514 if (sub_statement->kind != STATEMENT_DECLARATION) {
10515 only_decls_so_far = false;
10516 } else if (!only_decls_so_far) {
10517 warningf(&sub_statement->base.source_position,
10518 "ISO C90 forbids mixed declarations and code");
10522 *anchor = sub_statement;
10524 while (sub_statement->base.next != NULL)
10525 sub_statement = sub_statement->base.next;
10527 anchor = &sub_statement->base.next;
10531 /* look over all statements again to produce no effect warnings */
10532 if (warning.unused_value) {
10533 statement_t *sub_statement = statement->compound.statements;
10534 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10535 if (sub_statement->kind != STATEMENT_EXPRESSION)
10537 /* don't emit a warning for the last expression in an expression
10538 * statement as it has always an effect */
10539 if (inside_expression_statement && sub_statement->base.next == NULL)
10542 expression_t *expression = sub_statement->expression.expression;
10543 if (!expression_has_effect(expression)) {
10544 warningf(&expression->base.source_position,
10545 "statement has no effect");
10551 rem_anchor_token(T_while);
10552 rem_anchor_token(T_wchar_t);
10553 rem_anchor_token(T_volatile);
10554 rem_anchor_token(T_void);
10555 rem_anchor_token(T_using);
10556 rem_anchor_token(T_unsigned);
10557 rem_anchor_token(T_union);
10558 rem_anchor_token(T_typeof);
10559 rem_anchor_token(T_typename);
10560 rem_anchor_token(T_typeid);
10561 rem_anchor_token(T_typedef);
10562 rem_anchor_token(T_try);
10563 rem_anchor_token(T_true);
10564 rem_anchor_token(T_throw);
10565 rem_anchor_token(T_this);
10566 rem_anchor_token(T_template);
10567 rem_anchor_token(T_switch);
10568 rem_anchor_token(T_struct);
10569 rem_anchor_token(T_static_cast);
10570 rem_anchor_token(T_static);
10571 rem_anchor_token(T_sizeof);
10572 rem_anchor_token(T_signed);
10573 rem_anchor_token(T_short);
10574 rem_anchor_token(T_return);
10575 rem_anchor_token(T_restrict);
10576 rem_anchor_token(T_reinterpret_cast);
10577 rem_anchor_token(T_register);
10578 rem_anchor_token(T_operator);
10579 rem_anchor_token(T_new);
10580 rem_anchor_token(T_long);
10581 rem_anchor_token(T_int);
10582 rem_anchor_token(T_inline);
10583 rem_anchor_token(T_if);
10584 rem_anchor_token(T_goto);
10585 rem_anchor_token(T_for);
10586 rem_anchor_token(T_float);
10587 rem_anchor_token(T_false);
10588 rem_anchor_token(T_extern);
10589 rem_anchor_token(T_enum);
10590 rem_anchor_token(T_dynamic_cast);
10591 rem_anchor_token(T_do);
10592 rem_anchor_token(T_double);
10593 rem_anchor_token(T_delete);
10594 rem_anchor_token(T_default);
10595 rem_anchor_token(T_continue);
10596 rem_anchor_token(T_const_cast);
10597 rem_anchor_token(T_const);
10598 rem_anchor_token(T_class);
10599 rem_anchor_token(T_char);
10600 rem_anchor_token(T_case);
10601 rem_anchor_token(T_break);
10602 rem_anchor_token(T_bool);
10603 rem_anchor_token(T_auto);
10604 rem_anchor_token(T_asm);
10605 rem_anchor_token(T___thread);
10606 rem_anchor_token(T___real__);
10607 rem_anchor_token(T___label__);
10608 rem_anchor_token(T___imag__);
10609 rem_anchor_token(T___func__);
10610 rem_anchor_token(T___extension__);
10611 rem_anchor_token(T___builtin_va_start);
10612 rem_anchor_token(T___attribute__);
10613 rem_anchor_token(T___alignof__);
10614 rem_anchor_token(T___PRETTY_FUNCTION__);
10615 rem_anchor_token(T___FUNCTION__);
10616 rem_anchor_token(T__Imaginary);
10617 rem_anchor_token(T__Complex);
10618 rem_anchor_token(T__Bool);
10619 rem_anchor_token(T_WIDE_STRING_LITERAL);
10620 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10621 rem_anchor_token(T_STRING_LITERAL);
10622 rem_anchor_token(T_PLUSPLUS);
10623 rem_anchor_token(T_MINUSMINUS);
10624 rem_anchor_token(T_INTEGER);
10625 rem_anchor_token(T_IDENTIFIER);
10626 rem_anchor_token(T_FLOATINGPOINT);
10627 rem_anchor_token(T_COLONCOLON);
10628 rem_anchor_token(T_CHARACTER_CONSTANT);
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 rem_anchor_token('}');
10638 assert(current_scope == &statement->compound.scope);
10639 scope_pop(old_scope);
10640 environment_pop_to(top);
10647 * Check for unused global static functions and variables
10649 static void check_unused_globals(void)
10651 if (!warning.unused_function && !warning.unused_variable)
10654 for (const entity_t *entity = file_scope->entities; entity != NULL;
10655 entity = entity->base.next) {
10656 if (!is_declaration(entity))
10659 const declaration_t *declaration = &entity->declaration;
10660 if (declaration->used ||
10661 declaration->modifiers & DM_UNUSED ||
10662 declaration->modifiers & DM_USED ||
10663 declaration->storage_class != STORAGE_CLASS_STATIC)
10666 type_t *const type = declaration->type;
10668 if (entity->kind == ENTITY_FUNCTION) {
10669 /* inhibit warning for static inline functions */
10670 if (entity->function.is_inline)
10673 s = entity->function.statement != NULL ? "defined" : "declared";
10678 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10679 type, declaration->base.symbol, s);
10683 static void parse_global_asm(void)
10685 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10688 expect('(', end_error);
10690 statement->asms.asm_text = parse_string_literals();
10691 statement->base.next = unit->global_asm;
10692 unit->global_asm = statement;
10694 expect(')', end_error);
10695 expect(';', end_error);
10700 static void parse_linkage_specification(void)
10704 const char *linkage = parse_string_literals().begin;
10706 linkage_kind_t old_linkage = current_linkage;
10707 linkage_kind_t new_linkage;
10708 if (strcmp(linkage, "C") == 0) {
10709 new_linkage = LINKAGE_C;
10710 } else if (strcmp(linkage, "C++") == 0) {
10711 new_linkage = LINKAGE_CXX;
10713 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10714 new_linkage = LINKAGE_INVALID;
10716 current_linkage = new_linkage;
10718 if (next_if('{')) {
10720 expect('}', end_error);
10726 assert(current_linkage == new_linkage);
10727 current_linkage = old_linkage;
10730 static void parse_external(void)
10732 switch (token.type) {
10733 DECLARATION_START_NO_EXTERN
10735 case T___extension__:
10736 /* tokens below are for implicit int */
10737 case '&': /* & x; -> int& x; (and error later, because C++ has no
10739 case '*': /* * x; -> int* x; */
10740 case '(': /* (x); -> int (x); */
10741 parse_external_declaration();
10745 if (look_ahead(1)->type == T_STRING_LITERAL) {
10746 parse_linkage_specification();
10748 parse_external_declaration();
10753 parse_global_asm();
10757 parse_namespace_definition();
10761 if (!strict_mode) {
10763 warningf(HERE, "stray ';' outside of function");
10770 errorf(HERE, "stray %K outside of function", &token);
10771 if (token.type == '(' || token.type == '{' || token.type == '[')
10772 eat_until_matching_token(token.type);
10778 static void parse_externals(void)
10780 add_anchor_token('}');
10781 add_anchor_token(T_EOF);
10784 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10785 unsigned char token_anchor_copy[T_LAST_TOKEN];
10786 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10789 while (token.type != T_EOF && token.type != '}') {
10791 bool anchor_leak = false;
10792 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10793 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10795 /* the anchor set and its copy differs */
10796 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10797 anchor_leak = true;
10800 if (in_gcc_extension) {
10801 /* an gcc extension scope was not closed */
10802 internal_errorf(HERE, "Leaked __extension__");
10803 anchor_leak = true;
10813 rem_anchor_token(T_EOF);
10814 rem_anchor_token('}');
10818 * Parse a translation unit.
10820 static void parse_translation_unit(void)
10822 add_anchor_token(T_EOF);
10827 if (token.type == T_EOF)
10830 errorf(HERE, "stray %K outside of function", &token);
10831 if (token.type == '(' || token.type == '{' || token.type == '[')
10832 eat_until_matching_token(token.type);
10837 void set_default_visibility(elf_visibility_tag_t visibility)
10839 default_visibility = visibility;
10845 * @return the translation unit or NULL if errors occurred.
10847 void start_parsing(void)
10849 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10850 label_stack = NEW_ARR_F(stack_entry_t, 0);
10851 diagnostic_count = 0;
10855 print_to_file(stderr);
10857 assert(unit == NULL);
10858 unit = allocate_ast_zero(sizeof(unit[0]));
10860 assert(file_scope == NULL);
10861 file_scope = &unit->scope;
10863 assert(current_scope == NULL);
10864 scope_push(&unit->scope);
10866 create_gnu_builtins();
10868 create_microsoft_intrinsics();
10871 translation_unit_t *finish_parsing(void)
10873 assert(current_scope == &unit->scope);
10876 assert(file_scope == &unit->scope);
10877 check_unused_globals();
10880 DEL_ARR_F(environment_stack);
10881 DEL_ARR_F(label_stack);
10883 translation_unit_t *result = unit;
10888 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10889 * are given length one. */
10890 static void complete_incomplete_arrays(void)
10892 size_t n = ARR_LEN(incomplete_arrays);
10893 for (size_t i = 0; i != n; ++i) {
10894 declaration_t *const decl = incomplete_arrays[i];
10895 type_t *const orig_type = decl->type;
10896 type_t *const type = skip_typeref(orig_type);
10898 if (!is_type_incomplete(type))
10901 if (warning.other) {
10902 warningf(&decl->base.source_position,
10903 "array '%#T' assumed to have one element",
10904 orig_type, decl->base.symbol);
10907 type_t *const new_type = duplicate_type(type);
10908 new_type->array.size_constant = true;
10909 new_type->array.has_implicit_size = true;
10910 new_type->array.size = 1;
10912 type_t *const result = identify_new_type(new_type);
10914 decl->type = result;
10918 void prepare_main_collect2(entity_t *entity)
10920 // create call to __main
10921 symbol_t *symbol = symbol_table_insert("__main");
10922 entity_t *subsubmain_ent
10923 = create_implicit_function(symbol, &builtin_source_position);
10925 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10926 type_t *ftype = subsubmain_ent->declaration.type;
10927 ref->base.source_position = builtin_source_position;
10928 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10929 ref->reference.entity = subsubmain_ent;
10931 expression_t *call = allocate_expression_zero(EXPR_CALL);
10932 call->base.source_position = builtin_source_position;
10933 call->base.type = type_void;
10934 call->call.function = ref;
10936 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10937 expr_statement->base.source_position = builtin_source_position;
10938 expr_statement->expression.expression = call;
10940 statement_t *statement = entity->function.statement;
10941 assert(statement->kind == STATEMENT_COMPOUND);
10942 compound_statement_t *compounds = &statement->compound;
10944 expr_statement->base.next = compounds->statements;
10945 compounds->statements = expr_statement;
10950 lookahead_bufpos = 0;
10951 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10954 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10955 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10956 parse_translation_unit();
10957 complete_incomplete_arrays();
10958 DEL_ARR_F(incomplete_arrays);
10959 incomplete_arrays = NULL;
10963 * Initialize the parser.
10965 void init_parser(void)
10967 sym_anonymous = symbol_table_insert("<anonymous>");
10969 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10971 init_expression_parsers();
10972 obstack_init(&temp_obst);
10976 * Terminate the parser.
10978 void exit_parser(void)
10980 obstack_free(&temp_obst, NULL);