2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
113 #define PUSH_PARENT(stmt) \
114 statement_t *const prev_parent = current_parent; \
115 ((void)(current_parent = (stmt)))
116 #define POP_PARENT ((void)(current_parent = prev_parent))
118 /** special symbol used for anonymous entities. */
119 static symbol_t *sym_anonymous = NULL;
121 /** The token anchor set */
122 static unsigned char token_anchor_set[T_LAST_TOKEN];
124 /** The current source position. */
125 #define HERE (&token.source_position)
127 /** true if we are in GCC mode. */
128 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
130 static statement_t *parse_compound_statement(bool inside_expression_statement);
131 static statement_t *parse_statement(void);
133 static expression_t *parse_subexpression(precedence_t);
134 static expression_t *parse_expression(void);
135 static type_t *parse_typename(void);
136 static void parse_externals(void);
137 static void parse_external(void);
139 static void parse_compound_type_entries(compound_t *compound_declaration);
141 static void check_call_argument(type_t *expected_type,
142 call_argument_t *argument, unsigned pos);
144 typedef enum declarator_flags_t {
146 DECL_MAY_BE_ABSTRACT = 1U << 0,
147 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
148 DECL_IS_PARAMETER = 1U << 2
149 } declarator_flags_t;
151 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
152 declarator_flags_t flags);
154 static void semantic_comparison(binary_expression_t *expression);
156 #define STORAGE_CLASSES \
157 STORAGE_CLASSES_NO_EXTERN \
160 #define STORAGE_CLASSES_NO_EXTERN \
167 #define TYPE_QUALIFIERS \
172 case T__forceinline: \
173 case T___attribute__:
175 #define COMPLEX_SPECIFIERS \
177 #define IMAGINARY_SPECIFIERS \
180 #define TYPE_SPECIFIERS \
182 case T___builtin_va_list: \
207 #define DECLARATION_START \
212 #define DECLARATION_START_NO_EXTERN \
213 STORAGE_CLASSES_NO_EXTERN \
217 #define TYPENAME_START \
221 #define EXPRESSION_START \
230 case T_CHARACTER_CONSTANT: \
231 case T_FLOATINGPOINT: \
232 case T_FLOATINGPOINT_HEXADECIMAL: \
234 case T_INTEGER_HEXADECIMAL: \
235 case T_INTEGER_OCTAL: \
238 case T_STRING_LITERAL: \
239 case T_WIDE_CHARACTER_CONSTANT: \
240 case T_WIDE_STRING_LITERAL: \
241 case T___FUNCDNAME__: \
242 case T___FUNCSIG__: \
243 case T___FUNCTION__: \
244 case T___PRETTY_FUNCTION__: \
245 case T___alignof__: \
246 case T___builtin_classify_type: \
247 case T___builtin_constant_p: \
248 case T___builtin_isgreater: \
249 case T___builtin_isgreaterequal: \
250 case T___builtin_isless: \
251 case T___builtin_islessequal: \
252 case T___builtin_islessgreater: \
253 case T___builtin_isunordered: \
254 case T___builtin_offsetof: \
255 case T___builtin_va_arg: \
256 case T___builtin_va_copy: \
257 case T___builtin_va_start: \
268 * Returns the size of a statement node.
270 * @param kind the statement kind
272 static size_t get_statement_struct_size(statement_kind_t kind)
274 static const size_t sizes[] = {
275 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
276 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
277 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
278 [STATEMENT_RETURN] = sizeof(return_statement_t),
279 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
280 [STATEMENT_IF] = sizeof(if_statement_t),
281 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
282 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
283 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
284 [STATEMENT_BREAK] = sizeof(statement_base_t),
285 [STATEMENT_GOTO] = sizeof(goto_statement_t),
286 [STATEMENT_LABEL] = sizeof(label_statement_t),
287 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
288 [STATEMENT_WHILE] = sizeof(while_statement_t),
289 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
290 [STATEMENT_FOR] = sizeof(for_statement_t),
291 [STATEMENT_ASM] = sizeof(asm_statement_t),
292 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
293 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
295 assert(kind < lengthof(sizes));
296 assert(sizes[kind] != 0);
301 * Returns the size of an expression node.
303 * @param kind the expression kind
305 static size_t get_expression_struct_size(expression_kind_t kind)
307 static const size_t sizes[] = {
308 [EXPR_INVALID] = sizeof(expression_base_t),
309 [EXPR_REFERENCE] = sizeof(reference_expression_t),
310 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
311 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
312 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
314 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
316 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
317 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
318 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
319 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
320 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
321 [EXPR_CALL] = sizeof(call_expression_t),
322 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
323 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
324 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
325 [EXPR_SELECT] = sizeof(select_expression_t),
326 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
327 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
328 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
329 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
330 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
331 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
332 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
333 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
334 [EXPR_VA_START] = sizeof(va_start_expression_t),
335 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
336 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
337 [EXPR_STATEMENT] = sizeof(statement_expression_t),
338 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
340 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
341 return sizes[EXPR_UNARY_FIRST];
343 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
344 return sizes[EXPR_BINARY_FIRST];
346 assert(kind < lengthof(sizes));
347 assert(sizes[kind] != 0);
352 * Allocate a statement node of given kind and initialize all
353 * fields with zero. Sets its source position to the position
354 * of the current token.
356 static statement_t *allocate_statement_zero(statement_kind_t kind)
358 size_t size = get_statement_struct_size(kind);
359 statement_t *res = allocate_ast_zero(size);
361 res->base.kind = kind;
362 res->base.parent = current_parent;
363 res->base.source_position = token.source_position;
368 * Allocate an expression node of given kind and initialize all
371 * @param kind the kind of the expression to allocate
373 static expression_t *allocate_expression_zero(expression_kind_t kind)
375 size_t size = get_expression_struct_size(kind);
376 expression_t *res = allocate_ast_zero(size);
378 res->base.kind = kind;
379 res->base.type = type_error_type;
380 res->base.source_position = token.source_position;
385 * Creates a new invalid expression at the source position
386 * of the current token.
388 static expression_t *create_invalid_expression(void)
390 return allocate_expression_zero(EXPR_INVALID);
394 * Creates a new invalid statement.
396 static statement_t *create_invalid_statement(void)
398 return allocate_statement_zero(STATEMENT_INVALID);
402 * Allocate a new empty statement.
404 static statement_t *create_empty_statement(void)
406 return allocate_statement_zero(STATEMENT_EMPTY);
409 static function_parameter_t *allocate_parameter(type_t *const type)
411 function_parameter_t *const param
412 = obstack_alloc(type_obst, sizeof(*param));
413 memset(param, 0, sizeof(*param));
419 * Returns the size of an initializer node.
421 * @param kind the initializer kind
423 static size_t get_initializer_size(initializer_kind_t kind)
425 static const size_t sizes[] = {
426 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
427 [INITIALIZER_STRING] = sizeof(initializer_string_t),
428 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
429 [INITIALIZER_LIST] = sizeof(initializer_list_t),
430 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
432 assert(kind < lengthof(sizes));
433 assert(sizes[kind] != 0);
438 * Allocate an initializer node of given kind and initialize all
441 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
443 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
450 * Returns the index of the top element of the environment stack.
452 static size_t environment_top(void)
454 return ARR_LEN(environment_stack);
458 * Returns the index of the top element of the global label stack.
460 static size_t label_top(void)
462 return ARR_LEN(label_stack);
466 * Return the next token.
468 static inline void next_token(void)
470 token = lookahead_buffer[lookahead_bufpos];
471 lookahead_buffer[lookahead_bufpos] = lexer_token;
474 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
477 print_token(stderr, &token);
478 fprintf(stderr, "\n");
482 static inline bool next_if(int const type)
484 if (token.type == type) {
493 * Return the next token with a given lookahead.
495 static inline const token_t *look_ahead(size_t num)
497 assert(0 < num && num <= MAX_LOOKAHEAD);
498 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
499 return &lookahead_buffer[pos];
503 * Adds a token type to the token type anchor set (a multi-set).
505 static void add_anchor_token(int token_type)
507 assert(0 <= token_type && token_type < T_LAST_TOKEN);
508 ++token_anchor_set[token_type];
512 * Set the number of tokens types of the given type
513 * to zero and return the old count.
515 static int save_and_reset_anchor_state(int token_type)
517 assert(0 <= token_type && token_type < T_LAST_TOKEN);
518 int count = token_anchor_set[token_type];
519 token_anchor_set[token_type] = 0;
524 * Restore the number of token types to the given count.
526 static void restore_anchor_state(int token_type, int count)
528 assert(0 <= token_type && token_type < T_LAST_TOKEN);
529 token_anchor_set[token_type] = count;
533 * Remove a token type from the token type anchor set (a multi-set).
535 static void rem_anchor_token(int token_type)
537 assert(0 <= token_type && token_type < T_LAST_TOKEN);
538 assert(token_anchor_set[token_type] != 0);
539 --token_anchor_set[token_type];
543 * Return true if the token type of the current token is
546 static bool at_anchor(void)
550 return token_anchor_set[token.type];
554 * Eat tokens until a matching token type is found.
556 static void eat_until_matching_token(int type)
560 case '(': end_token = ')'; break;
561 case '{': end_token = '}'; break;
562 case '[': end_token = ']'; break;
563 default: end_token = type; break;
566 unsigned parenthesis_count = 0;
567 unsigned brace_count = 0;
568 unsigned bracket_count = 0;
569 while (token.type != end_token ||
570 parenthesis_count != 0 ||
572 bracket_count != 0) {
573 switch (token.type) {
575 case '(': ++parenthesis_count; break;
576 case '{': ++brace_count; break;
577 case '[': ++bracket_count; break;
580 if (parenthesis_count > 0)
590 if (bracket_count > 0)
593 if (token.type == end_token &&
594 parenthesis_count == 0 &&
608 * Eat input tokens until an anchor is found.
610 static void eat_until_anchor(void)
612 while (token_anchor_set[token.type] == 0) {
613 if (token.type == '(' || token.type == '{' || token.type == '[')
614 eat_until_matching_token(token.type);
620 * Eat a whole block from input tokens.
622 static void eat_block(void)
624 eat_until_matching_token('{');
628 #define eat(token_type) (assert(token.type == (token_type)), next_token())
631 * Report a parse error because an expected token was not found.
634 #if defined __GNUC__ && __GNUC__ >= 4
635 __attribute__((sentinel))
637 void parse_error_expected(const char *message, ...)
639 if (message != NULL) {
640 errorf(HERE, "%s", message);
643 va_start(ap, message);
644 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
649 * Report an incompatible type.
651 static void type_error_incompatible(const char *msg,
652 const source_position_t *source_position, type_t *type1, type_t *type2)
654 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
659 * Expect the current token is the expected token.
660 * If not, generate an error, eat the current statement,
661 * and goto the error_label label.
663 #define expect(expected, error_label) \
665 if (UNLIKELY(token.type != (expected))) { \
666 parse_error_expected(NULL, (expected), NULL); \
667 add_anchor_token(expected); \
668 eat_until_anchor(); \
669 next_if((expected)); \
670 rem_anchor_token(expected); \
677 * Push a given scope on the scope stack and make it the
680 static scope_t *scope_push(scope_t *new_scope)
682 if (current_scope != NULL) {
683 new_scope->depth = current_scope->depth + 1;
686 scope_t *old_scope = current_scope;
687 current_scope = new_scope;
692 * Pop the current scope from the scope stack.
694 static void scope_pop(scope_t *old_scope)
696 current_scope = old_scope;
700 * Search an entity by its symbol in a given namespace.
702 static entity_t *get_entity(const symbol_t *const symbol,
703 namespace_tag_t namespc)
705 assert(namespc != NAMESPACE_INVALID);
706 entity_t *entity = symbol->entity;
707 for (; entity != NULL; entity = entity->base.symbol_next) {
708 if (entity->base.namespc == namespc)
715 /* §6.2.3:1 24) There is only one name space for tags even though three are
717 static entity_t *get_tag(symbol_t const *const symbol,
718 entity_kind_tag_t const kind)
720 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
721 if (entity != NULL && entity->kind != kind) {
723 "'%Y' defined as wrong kind of tag (previous definition %P)",
724 symbol, &entity->base.source_position);
731 * pushs an entity on the environment stack and links the corresponding symbol
734 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
736 symbol_t *symbol = entity->base.symbol;
737 entity_namespace_t namespc = entity->base.namespc;
738 assert(namespc != NAMESPACE_INVALID);
740 /* replace/add entity into entity list of the symbol */
743 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
748 /* replace an entry? */
749 if (iter->base.namespc == namespc) {
750 entity->base.symbol_next = iter->base.symbol_next;
756 /* remember old declaration */
758 entry.symbol = symbol;
759 entry.old_entity = iter;
760 entry.namespc = namespc;
761 ARR_APP1(stack_entry_t, *stack_ptr, entry);
765 * Push an entity on the environment stack.
767 static void environment_push(entity_t *entity)
769 assert(entity->base.source_position.input_name != NULL);
770 assert(entity->base.parent_scope != NULL);
771 stack_push(&environment_stack, entity);
775 * Push a declaration on the global label stack.
777 * @param declaration the declaration
779 static void label_push(entity_t *label)
781 /* we abuse the parameters scope as parent for the labels */
782 label->base.parent_scope = ¤t_function->parameters;
783 stack_push(&label_stack, label);
787 * pops symbols from the environment stack until @p new_top is the top element
789 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
791 stack_entry_t *stack = *stack_ptr;
792 size_t top = ARR_LEN(stack);
795 assert(new_top <= top);
799 for (i = top; i > new_top; --i) {
800 stack_entry_t *entry = &stack[i - 1];
802 entity_t *old_entity = entry->old_entity;
803 symbol_t *symbol = entry->symbol;
804 entity_namespace_t namespc = entry->namespc;
806 /* replace with old_entity/remove */
809 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
811 assert(iter != NULL);
812 /* replace an entry? */
813 if (iter->base.namespc == namespc)
817 /* restore definition from outer scopes (if there was one) */
818 if (old_entity != NULL) {
819 old_entity->base.symbol_next = iter->base.symbol_next;
820 *anchor = old_entity;
822 /* remove entry from list */
823 *anchor = iter->base.symbol_next;
827 ARR_SHRINKLEN(*stack_ptr, new_top);
831 * Pop all entries from the environment stack until the new_top
834 * @param new_top the new stack top
836 static void environment_pop_to(size_t new_top)
838 stack_pop_to(&environment_stack, new_top);
842 * Pop all entries from the global label stack until the new_top
845 * @param new_top the new stack top
847 static void label_pop_to(size_t new_top)
849 stack_pop_to(&label_stack, new_top);
852 static int get_akind_rank(atomic_type_kind_t akind)
858 * Return the type rank for an atomic type.
860 static int get_rank(const type_t *type)
862 assert(!is_typeref(type));
863 if (type->kind == TYPE_ENUM)
864 return get_akind_rank(type->enumt.akind);
866 assert(type->kind == TYPE_ATOMIC);
867 return get_akind_rank(type->atomic.akind);
871 * §6.3.1.1:2 Do integer promotion for a given type.
873 * @param type the type to promote
874 * @return the promoted type
876 static type_t *promote_integer(type_t *type)
878 if (type->kind == TYPE_BITFIELD)
879 type = type->bitfield.base_type;
881 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
888 * Create a cast expression.
890 * @param expression the expression to cast
891 * @param dest_type the destination type
893 static expression_t *create_cast_expression(expression_t *expression,
896 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
898 cast->unary.value = expression;
899 cast->base.type = dest_type;
905 * Check if a given expression represents a null pointer constant.
907 * @param expression the expression to check
909 static bool is_null_pointer_constant(const expression_t *expression)
911 /* skip void* cast */
912 if (expression->kind == EXPR_UNARY_CAST ||
913 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
914 type_t *const type = skip_typeref(expression->base.type);
915 if (types_compatible(type, type_void_ptr))
916 expression = expression->unary.value;
919 type_t *const type = skip_typeref(expression->base.type);
920 if (!is_type_integer(type))
922 switch (is_constant_expression(expression)) {
923 case EXPR_CLASS_ERROR: return true;
924 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
925 default: return false;
930 * Create an implicit cast expression.
932 * @param expression the expression to cast
933 * @param dest_type the destination type
935 static expression_t *create_implicit_cast(expression_t *expression,
938 type_t *const source_type = expression->base.type;
940 if (source_type == dest_type)
943 return create_cast_expression(expression, dest_type);
946 typedef enum assign_error_t {
948 ASSIGN_ERROR_INCOMPATIBLE,
949 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
950 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
951 ASSIGN_WARNING_POINTER_FROM_INT,
952 ASSIGN_WARNING_INT_FROM_POINTER
955 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
956 const expression_t *const right,
958 const source_position_t *source_position)
960 type_t *const orig_type_right = right->base.type;
961 type_t *const type_left = skip_typeref(orig_type_left);
962 type_t *const type_right = skip_typeref(orig_type_right);
967 case ASSIGN_ERROR_INCOMPATIBLE:
968 errorf(source_position,
969 "destination type '%T' in %s is incompatible with type '%T'",
970 orig_type_left, context, orig_type_right);
973 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
975 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
976 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
978 /* the left type has all qualifiers from the right type */
979 unsigned missing_qualifiers
980 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
981 warningf(source_position,
982 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
983 orig_type_left, context, orig_type_right, missing_qualifiers);
988 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
990 warningf(source_position,
991 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
992 orig_type_left, context, right, orig_type_right);
996 case ASSIGN_WARNING_POINTER_FROM_INT:
998 warningf(source_position,
999 "%s makes pointer '%T' from integer '%T' without a cast",
1000 context, orig_type_left, orig_type_right);
1004 case ASSIGN_WARNING_INT_FROM_POINTER:
1005 if (warning.other) {
1006 warningf(source_position,
1007 "%s makes integer '%T' from pointer '%T' without a cast",
1008 context, orig_type_left, orig_type_right);
1013 panic("invalid error value");
1017 /** Implements the rules from §6.5.16.1 */
1018 static assign_error_t semantic_assign(type_t *orig_type_left,
1019 const expression_t *const right)
1021 type_t *const orig_type_right = right->base.type;
1022 type_t *const type_left = skip_typeref(orig_type_left);
1023 type_t *const type_right = skip_typeref(orig_type_right);
1025 if (is_type_pointer(type_left)) {
1026 if (is_null_pointer_constant(right)) {
1027 return ASSIGN_SUCCESS;
1028 } else if (is_type_pointer(type_right)) {
1029 type_t *points_to_left
1030 = skip_typeref(type_left->pointer.points_to);
1031 type_t *points_to_right
1032 = skip_typeref(type_right->pointer.points_to);
1033 assign_error_t res = ASSIGN_SUCCESS;
1035 /* the left type has all qualifiers from the right type */
1036 unsigned missing_qualifiers
1037 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1038 if (missing_qualifiers != 0) {
1039 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1042 points_to_left = get_unqualified_type(points_to_left);
1043 points_to_right = get_unqualified_type(points_to_right);
1045 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1048 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1049 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1050 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1053 if (!types_compatible(points_to_left, points_to_right)) {
1054 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1058 } else if (is_type_integer(type_right)) {
1059 return ASSIGN_WARNING_POINTER_FROM_INT;
1061 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1062 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1063 && is_type_pointer(type_right))) {
1064 return ASSIGN_SUCCESS;
1065 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1066 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1067 type_t *const unqual_type_left = get_unqualified_type(type_left);
1068 type_t *const unqual_type_right = get_unqualified_type(type_right);
1069 if (types_compatible(unqual_type_left, unqual_type_right)) {
1070 return ASSIGN_SUCCESS;
1072 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1073 return ASSIGN_WARNING_INT_FROM_POINTER;
1076 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1077 return ASSIGN_SUCCESS;
1079 return ASSIGN_ERROR_INCOMPATIBLE;
1082 static expression_t *parse_constant_expression(void)
1084 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1086 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1087 errorf(&result->base.source_position,
1088 "expression '%E' is not constant", result);
1094 static expression_t *parse_assignment_expression(void)
1096 return parse_subexpression(PREC_ASSIGNMENT);
1099 static void warn_string_concat(const source_position_t *pos)
1101 if (warning.traditional) {
1102 warningf(pos, "traditional C rejects string constant concatenation");
1106 static string_t parse_string_literals(void)
1108 assert(token.type == T_STRING_LITERAL);
1109 string_t result = token.literal;
1113 while (token.type == T_STRING_LITERAL) {
1114 warn_string_concat(&token.source_position);
1115 result = concat_strings(&result, &token.literal);
1123 * compare two string, ignoring double underscores on the second.
1125 static int strcmp_underscore(const char *s1, const char *s2)
1127 if (s2[0] == '_' && s2[1] == '_') {
1128 size_t len2 = strlen(s2);
1129 size_t len1 = strlen(s1);
1130 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1131 return strncmp(s1, s2+2, len2-4);
1135 return strcmp(s1, s2);
1138 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1140 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1141 attribute->kind = kind;
1146 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1149 * __attribute__ ( ( attribute-list ) )
1153 * attribute_list , attrib
1158 * any-word ( identifier )
1159 * any-word ( identifier , nonempty-expr-list )
1160 * any-word ( expr-list )
1162 * where the "identifier" must not be declared as a type, and
1163 * "any-word" may be any identifier (including one declared as a
1164 * type), a reserved word storage class specifier, type specifier or
1165 * type qualifier. ??? This still leaves out most reserved keywords
1166 * (following the old parser), shouldn't we include them, and why not
1167 * allow identifiers declared as types to start the arguments?
1169 * Matze: this all looks confusing and little systematic, so we're even less
1170 * strict and parse any list of things which are identifiers or
1171 * (assignment-)expressions.
1173 static attribute_argument_t *parse_attribute_arguments(void)
1175 attribute_argument_t *first = NULL;
1176 attribute_argument_t **anchor = &first;
1177 if (token.type != ')') do {
1178 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1180 /* is it an identifier */
1181 if (token.type == T_IDENTIFIER
1182 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1183 symbol_t *symbol = token.symbol;
1184 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1185 argument->v.symbol = symbol;
1188 /* must be an expression */
1189 expression_t *expression = parse_assignment_expression();
1191 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1192 argument->v.expression = expression;
1195 /* append argument */
1197 anchor = &argument->next;
1198 } while (next_if(','));
1199 expect(')', end_error);
1208 static attribute_t *parse_attribute_asm(void)
1212 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1214 expect('(', end_error);
1215 attribute->a.arguments = parse_attribute_arguments();
1222 static symbol_t *get_symbol_from_token(void)
1224 switch(token.type) {
1226 return token.symbol;
1255 /* maybe we need more tokens ... add them on demand */
1256 return get_token_symbol(&token);
1262 static attribute_t *parse_attribute_gnu_single(void)
1264 /* parse "any-word" */
1265 symbol_t *symbol = get_symbol_from_token();
1266 if (symbol == NULL) {
1267 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1271 const char *name = symbol->string;
1274 attribute_kind_t kind;
1275 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1276 const char *attribute_name = get_attribute_name(kind);
1277 if (attribute_name != NULL
1278 && strcmp_underscore(attribute_name, name) == 0)
1282 if (kind >= ATTRIBUTE_GNU_LAST) {
1283 if (warning.attribute) {
1284 warningf(HERE, "unknown attribute '%s' ignored", name);
1286 /* TODO: we should still save the attribute in the list... */
1287 kind = ATTRIBUTE_UNKNOWN;
1290 attribute_t *attribute = allocate_attribute_zero(kind);
1292 /* parse arguments */
1294 attribute->a.arguments = parse_attribute_arguments();
1299 static attribute_t *parse_attribute_gnu(void)
1301 attribute_t *first = NULL;
1302 attribute_t **anchor = &first;
1304 eat(T___attribute__);
1305 expect('(', end_error);
1306 expect('(', end_error);
1308 if (token.type != ')') do {
1309 attribute_t *attribute = parse_attribute_gnu_single();
1310 if (attribute == NULL)
1313 *anchor = attribute;
1314 anchor = &attribute->next;
1315 } while (next_if(','));
1316 expect(')', end_error);
1317 expect(')', end_error);
1323 /** Parse attributes. */
1324 static attribute_t *parse_attributes(attribute_t *first)
1326 attribute_t **anchor = &first;
1328 while (*anchor != NULL)
1329 anchor = &(*anchor)->next;
1331 attribute_t *attribute;
1332 switch (token.type) {
1333 case T___attribute__:
1334 attribute = parse_attribute_gnu();
1338 attribute = parse_attribute_asm();
1343 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1348 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1351 case T__forceinline:
1353 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1358 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1363 /* TODO record modifier */
1365 warningf(HERE, "Ignoring declaration modifier %K", &token);
1366 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1373 *anchor = attribute;
1374 anchor = &attribute->next;
1378 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1380 static entity_t *determine_lhs_ent(expression_t *const expr,
1383 switch (expr->kind) {
1384 case EXPR_REFERENCE: {
1385 entity_t *const entity = expr->reference.entity;
1386 /* we should only find variables as lvalues... */
1387 if (entity->base.kind != ENTITY_VARIABLE
1388 && entity->base.kind != ENTITY_PARAMETER)
1394 case EXPR_ARRAY_ACCESS: {
1395 expression_t *const ref = expr->array_access.array_ref;
1396 entity_t * ent = NULL;
1397 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1398 ent = determine_lhs_ent(ref, lhs_ent);
1401 mark_vars_read(expr->select.compound, lhs_ent);
1403 mark_vars_read(expr->array_access.index, lhs_ent);
1408 if (is_type_compound(skip_typeref(expr->base.type))) {
1409 return determine_lhs_ent(expr->select.compound, lhs_ent);
1411 mark_vars_read(expr->select.compound, lhs_ent);
1416 case EXPR_UNARY_DEREFERENCE: {
1417 expression_t *const val = expr->unary.value;
1418 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1420 return determine_lhs_ent(val->unary.value, lhs_ent);
1422 mark_vars_read(val, NULL);
1428 mark_vars_read(expr, NULL);
1433 #define ENT_ANY ((entity_t*)-1)
1436 * Mark declarations, which are read. This is used to detect variables, which
1440 * x is not marked as "read", because it is only read to calculate its own new
1444 * x and y are not detected as "not read", because multiple variables are
1447 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1449 switch (expr->kind) {
1450 case EXPR_REFERENCE: {
1451 entity_t *const entity = expr->reference.entity;
1452 if (entity->kind != ENTITY_VARIABLE
1453 && entity->kind != ENTITY_PARAMETER)
1456 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1457 if (entity->kind == ENTITY_VARIABLE) {
1458 entity->variable.read = true;
1460 entity->parameter.read = true;
1467 // TODO respect pure/const
1468 mark_vars_read(expr->call.function, NULL);
1469 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1470 mark_vars_read(arg->expression, NULL);
1474 case EXPR_CONDITIONAL:
1475 // TODO lhs_decl should depend on whether true/false have an effect
1476 mark_vars_read(expr->conditional.condition, NULL);
1477 if (expr->conditional.true_expression != NULL)
1478 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1479 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1483 if (lhs_ent == ENT_ANY
1484 && !is_type_compound(skip_typeref(expr->base.type)))
1486 mark_vars_read(expr->select.compound, lhs_ent);
1489 case EXPR_ARRAY_ACCESS: {
1490 expression_t *const ref = expr->array_access.array_ref;
1491 mark_vars_read(ref, lhs_ent);
1492 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1493 mark_vars_read(expr->array_access.index, lhs_ent);
1498 mark_vars_read(expr->va_arge.ap, lhs_ent);
1502 mark_vars_read(expr->va_copye.src, lhs_ent);
1505 case EXPR_UNARY_CAST:
1506 /* Special case: Use void cast to mark a variable as "read" */
1507 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1512 case EXPR_UNARY_THROW:
1513 if (expr->unary.value == NULL)
1516 case EXPR_UNARY_DEREFERENCE:
1517 case EXPR_UNARY_DELETE:
1518 case EXPR_UNARY_DELETE_ARRAY:
1519 if (lhs_ent == ENT_ANY)
1523 case EXPR_UNARY_NEGATE:
1524 case EXPR_UNARY_PLUS:
1525 case EXPR_UNARY_BITWISE_NEGATE:
1526 case EXPR_UNARY_NOT:
1527 case EXPR_UNARY_TAKE_ADDRESS:
1528 case EXPR_UNARY_POSTFIX_INCREMENT:
1529 case EXPR_UNARY_POSTFIX_DECREMENT:
1530 case EXPR_UNARY_PREFIX_INCREMENT:
1531 case EXPR_UNARY_PREFIX_DECREMENT:
1532 case EXPR_UNARY_CAST_IMPLICIT:
1533 case EXPR_UNARY_ASSUME:
1535 mark_vars_read(expr->unary.value, lhs_ent);
1538 case EXPR_BINARY_ADD:
1539 case EXPR_BINARY_SUB:
1540 case EXPR_BINARY_MUL:
1541 case EXPR_BINARY_DIV:
1542 case EXPR_BINARY_MOD:
1543 case EXPR_BINARY_EQUAL:
1544 case EXPR_BINARY_NOTEQUAL:
1545 case EXPR_BINARY_LESS:
1546 case EXPR_BINARY_LESSEQUAL:
1547 case EXPR_BINARY_GREATER:
1548 case EXPR_BINARY_GREATEREQUAL:
1549 case EXPR_BINARY_BITWISE_AND:
1550 case EXPR_BINARY_BITWISE_OR:
1551 case EXPR_BINARY_BITWISE_XOR:
1552 case EXPR_BINARY_LOGICAL_AND:
1553 case EXPR_BINARY_LOGICAL_OR:
1554 case EXPR_BINARY_SHIFTLEFT:
1555 case EXPR_BINARY_SHIFTRIGHT:
1556 case EXPR_BINARY_COMMA:
1557 case EXPR_BINARY_ISGREATER:
1558 case EXPR_BINARY_ISGREATEREQUAL:
1559 case EXPR_BINARY_ISLESS:
1560 case EXPR_BINARY_ISLESSEQUAL:
1561 case EXPR_BINARY_ISLESSGREATER:
1562 case EXPR_BINARY_ISUNORDERED:
1563 mark_vars_read(expr->binary.left, lhs_ent);
1564 mark_vars_read(expr->binary.right, lhs_ent);
1567 case EXPR_BINARY_ASSIGN:
1568 case EXPR_BINARY_MUL_ASSIGN:
1569 case EXPR_BINARY_DIV_ASSIGN:
1570 case EXPR_BINARY_MOD_ASSIGN:
1571 case EXPR_BINARY_ADD_ASSIGN:
1572 case EXPR_BINARY_SUB_ASSIGN:
1573 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1574 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1575 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1576 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1577 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1578 if (lhs_ent == ENT_ANY)
1580 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1581 mark_vars_read(expr->binary.right, lhs_ent);
1586 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1592 case EXPR_STRING_LITERAL:
1593 case EXPR_WIDE_STRING_LITERAL:
1594 case EXPR_COMPOUND_LITERAL: // TODO init?
1596 case EXPR_CLASSIFY_TYPE:
1599 case EXPR_BUILTIN_CONSTANT_P:
1600 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1602 case EXPR_STATEMENT: // TODO
1603 case EXPR_LABEL_ADDRESS:
1604 case EXPR_REFERENCE_ENUM_VALUE:
1608 panic("unhandled expression");
1611 static designator_t *parse_designation(void)
1613 designator_t *result = NULL;
1614 designator_t **anchor = &result;
1617 designator_t *designator;
1618 switch (token.type) {
1620 designator = allocate_ast_zero(sizeof(designator[0]));
1621 designator->source_position = token.source_position;
1623 add_anchor_token(']');
1624 designator->array_index = parse_constant_expression();
1625 rem_anchor_token(']');
1626 expect(']', end_error);
1629 designator = allocate_ast_zero(sizeof(designator[0]));
1630 designator->source_position = token.source_position;
1632 if (token.type != T_IDENTIFIER) {
1633 parse_error_expected("while parsing designator",
1634 T_IDENTIFIER, NULL);
1637 designator->symbol = token.symbol;
1641 expect('=', end_error);
1645 assert(designator != NULL);
1646 *anchor = designator;
1647 anchor = &designator->next;
1653 static initializer_t *initializer_from_string(array_type_t *const type,
1654 const string_t *const string)
1656 /* TODO: check len vs. size of array type */
1659 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1660 initializer->string.string = *string;
1665 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1666 const string_t *const string)
1668 /* TODO: check len vs. size of array type */
1671 initializer_t *const initializer =
1672 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1673 initializer->wide_string.string = *string;
1679 * Build an initializer from a given expression.
1681 static initializer_t *initializer_from_expression(type_t *orig_type,
1682 expression_t *expression)
1684 /* TODO check that expression is a constant expression */
1686 /* §6.7.8.14/15 char array may be initialized by string literals */
1687 type_t *type = skip_typeref(orig_type);
1688 type_t *expr_type_orig = expression->base.type;
1689 type_t *expr_type = skip_typeref(expr_type_orig);
1691 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1692 array_type_t *const array_type = &type->array;
1693 type_t *const element_type = skip_typeref(array_type->element_type);
1695 if (element_type->kind == TYPE_ATOMIC) {
1696 atomic_type_kind_t akind = element_type->atomic.akind;
1697 switch (expression->kind) {
1698 case EXPR_STRING_LITERAL:
1699 if (akind == ATOMIC_TYPE_CHAR
1700 || akind == ATOMIC_TYPE_SCHAR
1701 || akind == ATOMIC_TYPE_UCHAR) {
1702 return initializer_from_string(array_type,
1703 &expression->string_literal.value);
1707 case EXPR_WIDE_STRING_LITERAL: {
1708 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1709 if (get_unqualified_type(element_type) == bare_wchar_type) {
1710 return initializer_from_wide_string(array_type,
1711 &expression->string_literal.value);
1722 assign_error_t error = semantic_assign(type, expression);
1723 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1725 report_assign_error(error, type, expression, "initializer",
1726 &expression->base.source_position);
1728 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1729 result->value.value = create_implicit_cast(expression, type);
1735 * Checks if a given expression can be used as an constant initializer.
1737 static bool is_initializer_constant(const expression_t *expression)
1740 is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1741 is_address_constant(expression) != EXPR_CLASS_VARIABLE;
1745 * Parses an scalar initializer.
1747 * §6.7.8.11; eat {} without warning
1749 static initializer_t *parse_scalar_initializer(type_t *type,
1750 bool must_be_constant)
1752 /* there might be extra {} hierarchies */
1756 warningf(HERE, "extra curly braces around scalar initializer");
1759 } while (next_if('{'));
1762 expression_t *expression = parse_assignment_expression();
1763 mark_vars_read(expression, NULL);
1764 if (must_be_constant && !is_initializer_constant(expression)) {
1765 errorf(&expression->base.source_position,
1766 "initialisation expression '%E' is not constant",
1770 initializer_t *initializer = initializer_from_expression(type, expression);
1772 if (initializer == NULL) {
1773 errorf(&expression->base.source_position,
1774 "expression '%E' (type '%T') doesn't match expected type '%T'",
1775 expression, expression->base.type, type);
1780 bool additional_warning_displayed = false;
1781 while (braces > 0) {
1783 if (token.type != '}') {
1784 if (!additional_warning_displayed && warning.other) {
1785 warningf(HERE, "additional elements in scalar initializer");
1786 additional_warning_displayed = true;
1797 * An entry in the type path.
1799 typedef struct type_path_entry_t type_path_entry_t;
1800 struct type_path_entry_t {
1801 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1803 size_t index; /**< For array types: the current index. */
1804 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1809 * A type path expression a position inside compound or array types.
1811 typedef struct type_path_t type_path_t;
1812 struct type_path_t {
1813 type_path_entry_t *path; /**< An flexible array containing the current path. */
1814 type_t *top_type; /**< type of the element the path points */
1815 size_t max_index; /**< largest index in outermost array */
1819 * Prints a type path for debugging.
1821 static __attribute__((unused)) void debug_print_type_path(
1822 const type_path_t *path)
1824 size_t len = ARR_LEN(path->path);
1826 for (size_t i = 0; i < len; ++i) {
1827 const type_path_entry_t *entry = & path->path[i];
1829 type_t *type = skip_typeref(entry->type);
1830 if (is_type_compound(type)) {
1831 /* in gcc mode structs can have no members */
1832 if (entry->v.compound_entry == NULL) {
1836 fprintf(stderr, ".%s",
1837 entry->v.compound_entry->base.symbol->string);
1838 } else if (is_type_array(type)) {
1839 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1841 fprintf(stderr, "-INVALID-");
1844 if (path->top_type != NULL) {
1845 fprintf(stderr, " (");
1846 print_type(path->top_type);
1847 fprintf(stderr, ")");
1852 * Return the top type path entry, ie. in a path
1853 * (type).a.b returns the b.
1855 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1857 size_t len = ARR_LEN(path->path);
1859 return &path->path[len-1];
1863 * Enlarge the type path by an (empty) element.
1865 static type_path_entry_t *append_to_type_path(type_path_t *path)
1867 size_t len = ARR_LEN(path->path);
1868 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1870 type_path_entry_t *result = & path->path[len];
1871 memset(result, 0, sizeof(result[0]));
1876 * Descending into a sub-type. Enter the scope of the current top_type.
1878 static void descend_into_subtype(type_path_t *path)
1880 type_t *orig_top_type = path->top_type;
1881 type_t *top_type = skip_typeref(orig_top_type);
1883 type_path_entry_t *top = append_to_type_path(path);
1884 top->type = top_type;
1886 if (is_type_compound(top_type)) {
1887 compound_t *compound = top_type->compound.compound;
1888 entity_t *entry = compound->members.entities;
1890 if (entry != NULL) {
1891 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1892 top->v.compound_entry = &entry->declaration;
1893 path->top_type = entry->declaration.type;
1895 path->top_type = NULL;
1897 } else if (is_type_array(top_type)) {
1899 path->top_type = top_type->array.element_type;
1901 assert(!is_type_valid(top_type));
1906 * Pop an entry from the given type path, ie. returning from
1907 * (type).a.b to (type).a
1909 static void ascend_from_subtype(type_path_t *path)
1911 type_path_entry_t *top = get_type_path_top(path);
1913 path->top_type = top->type;
1915 size_t len = ARR_LEN(path->path);
1916 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1920 * Pop entries from the given type path until the given
1921 * path level is reached.
1923 static void ascend_to(type_path_t *path, size_t top_path_level)
1925 size_t len = ARR_LEN(path->path);
1927 while (len > top_path_level) {
1928 ascend_from_subtype(path);
1929 len = ARR_LEN(path->path);
1933 static bool walk_designator(type_path_t *path, const designator_t *designator,
1934 bool used_in_offsetof)
1936 for (; designator != NULL; designator = designator->next) {
1937 type_path_entry_t *top = get_type_path_top(path);
1938 type_t *orig_type = top->type;
1940 type_t *type = skip_typeref(orig_type);
1942 if (designator->symbol != NULL) {
1943 symbol_t *symbol = designator->symbol;
1944 if (!is_type_compound(type)) {
1945 if (is_type_valid(type)) {
1946 errorf(&designator->source_position,
1947 "'.%Y' designator used for non-compound type '%T'",
1951 top->type = type_error_type;
1952 top->v.compound_entry = NULL;
1953 orig_type = type_error_type;
1955 compound_t *compound = type->compound.compound;
1956 entity_t *iter = compound->members.entities;
1957 for (; iter != NULL; iter = iter->base.next) {
1958 if (iter->base.symbol == symbol) {
1963 errorf(&designator->source_position,
1964 "'%T' has no member named '%Y'", orig_type, symbol);
1967 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1968 if (used_in_offsetof) {
1969 type_t *real_type = skip_typeref(iter->declaration.type);
1970 if (real_type->kind == TYPE_BITFIELD) {
1971 errorf(&designator->source_position,
1972 "offsetof designator '%Y' must not specify bitfield",
1978 top->type = orig_type;
1979 top->v.compound_entry = &iter->declaration;
1980 orig_type = iter->declaration.type;
1983 expression_t *array_index = designator->array_index;
1984 assert(designator->array_index != NULL);
1986 if (!is_type_array(type)) {
1987 if (is_type_valid(type)) {
1988 errorf(&designator->source_position,
1989 "[%E] designator used for non-array type '%T'",
1990 array_index, orig_type);
1995 long index = fold_constant_to_int(array_index);
1996 if (!used_in_offsetof) {
1998 errorf(&designator->source_position,
1999 "array index [%E] must be positive", array_index);
2000 } else if (type->array.size_constant) {
2001 long array_size = type->array.size;
2002 if (index >= array_size) {
2003 errorf(&designator->source_position,
2004 "designator [%E] (%d) exceeds array size %d",
2005 array_index, index, array_size);
2010 top->type = orig_type;
2011 top->v.index = (size_t) index;
2012 orig_type = type->array.element_type;
2014 path->top_type = orig_type;
2016 if (designator->next != NULL) {
2017 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);
2161 if (env->entity != NULL) {
2163 "extra brace group at end of initializer for '%Y'",
2164 env->entity->base.symbol);
2166 errorf(HERE, "extra brace group at end of initializer");
2169 descend_into_subtype(path);
2171 add_anchor_token('}');
2172 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2174 rem_anchor_token('}');
2177 ascend_from_subtype(path);
2178 expect('}', end_error);
2180 expect('}', end_error);
2181 goto error_parse_next;
2185 /* must be an expression */
2186 expression_t *expression = parse_assignment_expression();
2187 mark_vars_read(expression, NULL);
2189 if (env->must_be_constant && !is_initializer_constant(expression)) {
2190 errorf(&expression->base.source_position,
2191 "Initialisation expression '%E' is not constant",
2196 /* we are already outside, ... */
2197 if (outer_type == NULL)
2198 goto error_parse_next;
2199 type_t *const outer_type_skip = skip_typeref(outer_type);
2200 if (is_type_compound(outer_type_skip) &&
2201 !outer_type_skip->compound.compound->complete) {
2202 goto error_parse_next;
2207 /* handle { "string" } special case */
2208 if ((expression->kind == EXPR_STRING_LITERAL
2209 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2210 && outer_type != NULL) {
2211 sub = initializer_from_expression(outer_type, expression);
2214 if (token.type != '}' && warning.other) {
2215 warningf(HERE, "excessive elements in initializer for type '%T'",
2218 /* TODO: eat , ... */
2223 /* descend into subtypes until expression matches type */
2225 orig_type = path->top_type;
2226 type = skip_typeref(orig_type);
2228 sub = initializer_from_expression(orig_type, expression);
2232 if (!is_type_valid(type)) {
2235 if (is_type_scalar(type)) {
2236 errorf(&expression->base.source_position,
2237 "expression '%E' doesn't match expected type '%T'",
2238 expression, orig_type);
2242 descend_into_subtype(path);
2246 /* update largest index of top array */
2247 const type_path_entry_t *first = &path->path[0];
2248 type_t *first_type = first->type;
2249 first_type = skip_typeref(first_type);
2250 if (is_type_array(first_type)) {
2251 size_t index = first->v.index;
2252 if (index > path->max_index)
2253 path->max_index = index;
2257 /* append to initializers list */
2258 ARR_APP1(initializer_t*, initializers, sub);
2261 if (warning.other) {
2262 if (env->entity != NULL) {
2263 warningf(HERE, "excess elements in initializer for '%Y'",
2264 env->entity->base.symbol);
2266 warningf(HERE, "excess elements in initializer");
2272 if (token.type == '}') {
2275 expect(',', end_error);
2276 if (token.type == '}') {
2281 /* advance to the next declaration if we are not at the end */
2282 advance_current_object(path, top_path_level);
2283 orig_type = path->top_type;
2284 if (orig_type != NULL)
2285 type = skip_typeref(orig_type);
2291 size_t len = ARR_LEN(initializers);
2292 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2293 initializer_t *result = allocate_ast_zero(size);
2294 result->kind = INITIALIZER_LIST;
2295 result->list.len = len;
2296 memcpy(&result->list.initializers, initializers,
2297 len * sizeof(initializers[0]));
2299 DEL_ARR_F(initializers);
2300 ascend_to(path, top_path_level+1);
2305 skip_initializers();
2306 DEL_ARR_F(initializers);
2307 ascend_to(path, top_path_level+1);
2311 static expression_t *make_size_literal(size_t value)
2313 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2314 literal->base.type = type_size_t;
2317 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2318 literal->literal.value = make_string(buf);
2324 * Parses an initializer. Parsers either a compound literal
2325 * (env->declaration == NULL) or an initializer of a declaration.
2327 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2329 type_t *type = skip_typeref(env->type);
2330 size_t max_index = 0;
2331 initializer_t *result;
2333 if (is_type_scalar(type)) {
2334 result = parse_scalar_initializer(type, env->must_be_constant);
2335 } else if (token.type == '{') {
2339 memset(&path, 0, sizeof(path));
2340 path.top_type = env->type;
2341 path.path = NEW_ARR_F(type_path_entry_t, 0);
2343 descend_into_subtype(&path);
2345 add_anchor_token('}');
2346 result = parse_sub_initializer(&path, env->type, 1, env);
2347 rem_anchor_token('}');
2349 max_index = path.max_index;
2350 DEL_ARR_F(path.path);
2352 expect('}', end_error);
2354 /* parse_scalar_initializer() also works in this case: we simply
2355 * have an expression without {} around it */
2356 result = parse_scalar_initializer(type, env->must_be_constant);
2359 /* §6.7.8:22 array initializers for arrays with unknown size determine
2360 * the array type size */
2361 if (is_type_array(type) && type->array.size_expression == NULL
2362 && result != NULL) {
2364 switch (result->kind) {
2365 case INITIALIZER_LIST:
2366 assert(max_index != 0xdeadbeaf);
2367 size = max_index + 1;
2370 case INITIALIZER_STRING:
2371 size = result->string.string.size;
2374 case INITIALIZER_WIDE_STRING:
2375 size = result->wide_string.string.size;
2378 case INITIALIZER_DESIGNATOR:
2379 case INITIALIZER_VALUE:
2380 /* can happen for parse errors */
2385 internal_errorf(HERE, "invalid initializer type");
2388 type_t *new_type = duplicate_type(type);
2390 new_type->array.size_expression = make_size_literal(size);
2391 new_type->array.size_constant = true;
2392 new_type->array.has_implicit_size = true;
2393 new_type->array.size = size;
2394 env->type = new_type;
2402 static void append_entity(scope_t *scope, entity_t *entity)
2404 if (scope->last_entity != NULL) {
2405 scope->last_entity->base.next = entity;
2407 scope->entities = entity;
2409 entity->base.parent_entity = current_entity;
2410 scope->last_entity = entity;
2414 static compound_t *parse_compound_type_specifier(bool is_struct)
2416 eat(is_struct ? T_struct : T_union);
2418 symbol_t *symbol = NULL;
2419 compound_t *compound = NULL;
2420 attribute_t *attributes = NULL;
2422 if (token.type == T___attribute__) {
2423 attributes = parse_attributes(NULL);
2426 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2427 if (token.type == T_IDENTIFIER) {
2428 /* the compound has a name, check if we have seen it already */
2429 symbol = token.symbol;
2432 entity_t *entity = get_tag(symbol, kind);
2433 if (entity != NULL) {
2434 compound = &entity->compound;
2435 if (compound->base.parent_scope != current_scope &&
2436 (token.type == '{' || token.type == ';')) {
2437 /* we're in an inner scope and have a definition. Shadow
2438 * existing definition in outer scope */
2440 } else if (compound->complete && token.type == '{') {
2441 assert(symbol != NULL);
2442 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2443 is_struct ? "struct" : "union", symbol,
2444 &compound->base.source_position);
2445 /* clear members in the hope to avoid further errors */
2446 compound->members.entities = NULL;
2449 } else if (token.type != '{') {
2451 parse_error_expected("while parsing struct type specifier",
2452 T_IDENTIFIER, '{', NULL);
2454 parse_error_expected("while parsing union type specifier",
2455 T_IDENTIFIER, '{', NULL);
2461 if (compound == NULL) {
2462 entity_t *entity = allocate_entity_zero(kind);
2463 compound = &entity->compound;
2465 compound->alignment = 1;
2466 compound->base.namespc = NAMESPACE_TAG;
2467 compound->base.source_position = token.source_position;
2468 compound->base.symbol = symbol;
2469 compound->base.parent_scope = current_scope;
2470 if (symbol != NULL) {
2471 environment_push(entity);
2473 append_entity(current_scope, entity);
2476 if (token.type == '{') {
2477 parse_compound_type_entries(compound);
2479 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2480 if (symbol == NULL) {
2481 assert(anonymous_entity == NULL);
2482 anonymous_entity = (entity_t*)compound;
2486 if (attributes != NULL) {
2487 handle_entity_attributes(attributes, (entity_t*) compound);
2493 static void parse_enum_entries(type_t *const enum_type)
2497 if (token.type == '}') {
2498 errorf(HERE, "empty enum not allowed");
2503 add_anchor_token('}');
2505 if (token.type != T_IDENTIFIER) {
2506 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2508 rem_anchor_token('}');
2512 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2513 entity->enum_value.enum_type = enum_type;
2514 entity->base.namespc = NAMESPACE_NORMAL;
2515 entity->base.symbol = token.symbol;
2516 entity->base.source_position = token.source_position;
2520 expression_t *value = parse_constant_expression();
2522 value = create_implicit_cast(value, enum_type);
2523 entity->enum_value.value = value;
2528 record_entity(entity, false);
2529 } while (next_if(',') && token.type != '}');
2530 rem_anchor_token('}');
2532 expect('}', end_error);
2538 static type_t *parse_enum_specifier(void)
2544 switch (token.type) {
2546 symbol = token.symbol;
2549 entity = get_tag(symbol, ENTITY_ENUM);
2550 if (entity != NULL) {
2551 if (entity->base.parent_scope != current_scope &&
2552 (token.type == '{' || token.type == ';')) {
2553 /* we're in an inner scope and have a definition. Shadow
2554 * existing definition in outer scope */
2556 } else if (entity->enume.complete && token.type == '{') {
2557 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2558 symbol, &entity->base.source_position);
2569 parse_error_expected("while parsing enum type specifier",
2570 T_IDENTIFIER, '{', NULL);
2574 if (entity == NULL) {
2575 entity = allocate_entity_zero(ENTITY_ENUM);
2576 entity->base.namespc = NAMESPACE_TAG;
2577 entity->base.source_position = token.source_position;
2578 entity->base.symbol = symbol;
2579 entity->base.parent_scope = current_scope;
2582 type_t *const type = allocate_type_zero(TYPE_ENUM);
2583 type->enumt.enume = &entity->enume;
2584 type->enumt.akind = ATOMIC_TYPE_INT;
2586 if (token.type == '{') {
2587 if (symbol != NULL) {
2588 environment_push(entity);
2590 append_entity(current_scope, entity);
2591 entity->enume.complete = true;
2593 parse_enum_entries(type);
2594 parse_attributes(NULL);
2596 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2597 if (symbol == NULL) {
2598 assert(anonymous_entity == NULL);
2599 anonymous_entity = entity;
2601 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2602 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2610 * if a symbol is a typedef to another type, return true
2612 static bool is_typedef_symbol(symbol_t *symbol)
2614 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2615 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2618 static type_t *parse_typeof(void)
2624 expect('(', end_error);
2625 add_anchor_token(')');
2627 expression_t *expression = NULL;
2629 bool old_type_prop = in_type_prop;
2630 bool old_gcc_extension = in_gcc_extension;
2631 in_type_prop = true;
2633 while (next_if(T___extension__)) {
2634 /* This can be a prefix to a typename or an expression. */
2635 in_gcc_extension = true;
2637 switch (token.type) {
2639 if (is_typedef_symbol(token.symbol)) {
2641 type = parse_typename();
2644 expression = parse_expression();
2645 type = revert_automatic_type_conversion(expression);
2649 in_type_prop = old_type_prop;
2650 in_gcc_extension = old_gcc_extension;
2652 rem_anchor_token(')');
2653 expect(')', end_error);
2655 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2656 typeof_type->typeoft.expression = expression;
2657 typeof_type->typeoft.typeof_type = type;
2664 typedef enum specifiers_t {
2665 SPECIFIER_SIGNED = 1 << 0,
2666 SPECIFIER_UNSIGNED = 1 << 1,
2667 SPECIFIER_LONG = 1 << 2,
2668 SPECIFIER_INT = 1 << 3,
2669 SPECIFIER_DOUBLE = 1 << 4,
2670 SPECIFIER_CHAR = 1 << 5,
2671 SPECIFIER_WCHAR_T = 1 << 6,
2672 SPECIFIER_SHORT = 1 << 7,
2673 SPECIFIER_LONG_LONG = 1 << 8,
2674 SPECIFIER_FLOAT = 1 << 9,
2675 SPECIFIER_BOOL = 1 << 10,
2676 SPECIFIER_VOID = 1 << 11,
2677 SPECIFIER_INT8 = 1 << 12,
2678 SPECIFIER_INT16 = 1 << 13,
2679 SPECIFIER_INT32 = 1 << 14,
2680 SPECIFIER_INT64 = 1 << 15,
2681 SPECIFIER_INT128 = 1 << 16,
2682 SPECIFIER_COMPLEX = 1 << 17,
2683 SPECIFIER_IMAGINARY = 1 << 18,
2686 static type_t *create_builtin_type(symbol_t *const symbol,
2687 type_t *const real_type)
2689 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2690 type->builtin.symbol = symbol;
2691 type->builtin.real_type = real_type;
2692 return identify_new_type(type);
2695 static type_t *get_typedef_type(symbol_t *symbol)
2697 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2698 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2701 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2702 type->typedeft.typedefe = &entity->typedefe;
2707 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2709 expect('(', end_error);
2711 attribute_property_argument_t *property
2712 = allocate_ast_zero(sizeof(*property));
2715 if (token.type != T_IDENTIFIER) {
2716 parse_error_expected("while parsing property declspec",
2717 T_IDENTIFIER, NULL);
2722 symbol_t *symbol = token.symbol;
2724 if (strcmp(symbol->string, "put") == 0) {
2726 } else if (strcmp(symbol->string, "get") == 0) {
2729 errorf(HERE, "expected put or get in property declspec");
2732 expect('=', end_error);
2733 if (token.type != T_IDENTIFIER) {
2734 parse_error_expected("while parsing property declspec",
2735 T_IDENTIFIER, NULL);
2739 property->put_symbol = token.symbol;
2741 property->get_symbol = token.symbol;
2744 } while (next_if(','));
2746 attribute->a.property = property;
2748 expect(')', end_error);
2754 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2756 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2757 if (next_if(T_restrict)) {
2758 kind = ATTRIBUTE_MS_RESTRICT;
2759 } else if (token.type == T_IDENTIFIER) {
2760 const char *name = token.symbol->string;
2762 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2764 const char *attribute_name = get_attribute_name(k);
2765 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2771 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2772 warningf(HERE, "unknown __declspec '%s' ignored", name);
2775 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2779 attribute_t *attribute = allocate_attribute_zero(kind);
2781 if (kind == ATTRIBUTE_MS_PROPERTY) {
2782 return parse_attribute_ms_property(attribute);
2785 /* parse arguments */
2787 attribute->a.arguments = parse_attribute_arguments();
2792 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2796 expect('(', end_error);
2801 add_anchor_token(')');
2803 attribute_t **anchor = &first;
2805 while (*anchor != NULL)
2806 anchor = &(*anchor)->next;
2808 attribute_t *attribute
2809 = parse_microsoft_extended_decl_modifier_single();
2810 if (attribute == NULL)
2813 *anchor = attribute;
2814 anchor = &attribute->next;
2815 } while (next_if(','));
2817 rem_anchor_token(')');
2818 expect(')', end_error);
2822 rem_anchor_token(')');
2826 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2828 entity_t *entity = allocate_entity_zero(kind);
2829 entity->base.namespc = NAMESPACE_NORMAL;
2830 entity->base.source_position = *HERE;
2831 entity->base.symbol = symbol;
2832 if (is_declaration(entity)) {
2833 entity->declaration.type = type_error_type;
2834 entity->declaration.implicit = true;
2835 } else if (kind == ENTITY_TYPEDEF) {
2836 entity->typedefe.type = type_error_type;
2837 entity->typedefe.builtin = true;
2839 if (kind != ENTITY_COMPOUND_MEMBER)
2840 record_entity(entity, false);
2844 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2846 type_t *type = NULL;
2847 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2848 unsigned type_specifiers = 0;
2849 bool newtype = false;
2850 bool saw_error = false;
2851 bool old_gcc_extension = in_gcc_extension;
2853 specifiers->source_position = token.source_position;
2856 specifiers->attributes = parse_attributes(specifiers->attributes);
2858 switch (token.type) {
2860 #define MATCH_STORAGE_CLASS(token, class) \
2862 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2863 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2865 specifiers->storage_class = class; \
2866 if (specifiers->thread_local) \
2867 goto check_thread_storage_class; \
2871 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2872 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2873 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2874 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2875 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2878 specifiers->attributes
2879 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2883 if (specifiers->thread_local) {
2884 errorf(HERE, "duplicate '__thread'");
2886 specifiers->thread_local = true;
2887 check_thread_storage_class:
2888 switch (specifiers->storage_class) {
2889 case STORAGE_CLASS_EXTERN:
2890 case STORAGE_CLASS_NONE:
2891 case STORAGE_CLASS_STATIC:
2895 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2896 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2897 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2898 wrong_thread_storage_class:
2899 errorf(HERE, "'__thread' used with '%s'", wrong);
2906 /* type qualifiers */
2907 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2909 qualifiers |= qualifier; \
2913 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2914 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2915 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2916 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2917 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2918 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2919 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2920 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2922 case T___extension__:
2924 in_gcc_extension = true;
2927 /* type specifiers */
2928 #define MATCH_SPECIFIER(token, specifier, name) \
2930 if (type_specifiers & specifier) { \
2931 errorf(HERE, "multiple " name " type specifiers given"); \
2933 type_specifiers |= specifier; \
2938 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2939 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2940 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2941 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2942 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2943 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2944 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2945 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2946 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2947 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2948 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2949 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2950 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2951 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2952 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2953 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2954 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2955 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2959 specifiers->is_inline = true;
2963 case T__forceinline:
2965 specifiers->modifiers |= DM_FORCEINLINE;
2970 if (type_specifiers & SPECIFIER_LONG_LONG) {
2971 errorf(HERE, "multiple type specifiers given");
2972 } else if (type_specifiers & SPECIFIER_LONG) {
2973 type_specifiers |= SPECIFIER_LONG_LONG;
2975 type_specifiers |= SPECIFIER_LONG;
2980 #define CHECK_DOUBLE_TYPE() \
2981 if ( type != NULL) \
2982 errorf(HERE, "multiple data types in declaration specifiers");
2985 CHECK_DOUBLE_TYPE();
2986 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2988 type->compound.compound = parse_compound_type_specifier(true);
2991 CHECK_DOUBLE_TYPE();
2992 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2993 type->compound.compound = parse_compound_type_specifier(false);
2996 CHECK_DOUBLE_TYPE();
2997 type = parse_enum_specifier();
3000 CHECK_DOUBLE_TYPE();
3001 type = parse_typeof();
3003 case T___builtin_va_list:
3004 CHECK_DOUBLE_TYPE();
3005 type = duplicate_type(type_valist);
3009 case T_IDENTIFIER: {
3010 /* only parse identifier if we haven't found a type yet */
3011 if (type != NULL || type_specifiers != 0) {
3012 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3013 * declaration, so it doesn't generate errors about expecting '(' or
3015 switch (look_ahead(1)->type) {
3022 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3026 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3031 goto finish_specifiers;
3035 type_t *const typedef_type = get_typedef_type(token.symbol);
3036 if (typedef_type == NULL) {
3037 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3038 * declaration, so it doesn't generate 'implicit int' followed by more
3039 * errors later on. */
3040 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3046 errorf(HERE, "%K does not name a type", &token);
3049 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3051 type = allocate_type_zero(TYPE_TYPEDEF);
3052 type->typedeft.typedefe = &entity->typedefe;
3056 if (la1_type == '&' || la1_type == '*')
3057 goto finish_specifiers;
3062 goto finish_specifiers;
3067 type = typedef_type;
3071 /* function specifier */
3073 goto finish_specifiers;
3078 specifiers->attributes = parse_attributes(specifiers->attributes);
3080 in_gcc_extension = old_gcc_extension;
3082 if (type == NULL || (saw_error && type_specifiers != 0)) {
3083 atomic_type_kind_t atomic_type;
3085 /* match valid basic types */
3086 switch (type_specifiers) {
3087 case SPECIFIER_VOID:
3088 atomic_type = ATOMIC_TYPE_VOID;
3090 case SPECIFIER_WCHAR_T:
3091 atomic_type = ATOMIC_TYPE_WCHAR_T;
3093 case SPECIFIER_CHAR:
3094 atomic_type = ATOMIC_TYPE_CHAR;
3096 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3097 atomic_type = ATOMIC_TYPE_SCHAR;
3099 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3100 atomic_type = ATOMIC_TYPE_UCHAR;
3102 case SPECIFIER_SHORT:
3103 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3104 case SPECIFIER_SHORT | SPECIFIER_INT:
3105 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3106 atomic_type = ATOMIC_TYPE_SHORT;
3108 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3109 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3110 atomic_type = ATOMIC_TYPE_USHORT;
3113 case SPECIFIER_SIGNED:
3114 case SPECIFIER_SIGNED | SPECIFIER_INT:
3115 atomic_type = ATOMIC_TYPE_INT;
3117 case SPECIFIER_UNSIGNED:
3118 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3119 atomic_type = ATOMIC_TYPE_UINT;
3121 case SPECIFIER_LONG:
3122 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3123 case SPECIFIER_LONG | SPECIFIER_INT:
3124 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3125 atomic_type = ATOMIC_TYPE_LONG;
3127 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3128 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3129 atomic_type = ATOMIC_TYPE_ULONG;
3132 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3133 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3134 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3135 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3137 atomic_type = ATOMIC_TYPE_LONGLONG;
3138 goto warn_about_long_long;
3140 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3141 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3143 atomic_type = ATOMIC_TYPE_ULONGLONG;
3144 warn_about_long_long:
3145 if (warning.long_long) {
3146 warningf(&specifiers->source_position,
3147 "ISO C90 does not support 'long long'");
3151 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3152 atomic_type = unsigned_int8_type_kind;
3155 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3156 atomic_type = unsigned_int16_type_kind;
3159 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3160 atomic_type = unsigned_int32_type_kind;
3163 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3164 atomic_type = unsigned_int64_type_kind;
3167 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3168 atomic_type = unsigned_int128_type_kind;
3171 case SPECIFIER_INT8:
3172 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3173 atomic_type = int8_type_kind;
3176 case SPECIFIER_INT16:
3177 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3178 atomic_type = int16_type_kind;
3181 case SPECIFIER_INT32:
3182 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3183 atomic_type = int32_type_kind;
3186 case SPECIFIER_INT64:
3187 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3188 atomic_type = int64_type_kind;
3191 case SPECIFIER_INT128:
3192 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3193 atomic_type = int128_type_kind;
3196 case SPECIFIER_FLOAT:
3197 atomic_type = ATOMIC_TYPE_FLOAT;
3199 case SPECIFIER_DOUBLE:
3200 atomic_type = ATOMIC_TYPE_DOUBLE;
3202 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3203 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3205 case SPECIFIER_BOOL:
3206 atomic_type = ATOMIC_TYPE_BOOL;
3208 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3209 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3210 atomic_type = ATOMIC_TYPE_FLOAT;
3212 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3213 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3214 atomic_type = ATOMIC_TYPE_DOUBLE;
3216 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3217 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3218 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3221 /* invalid specifier combination, give an error message */
3222 if (type_specifiers == 0) {
3226 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3227 if (!(c_mode & _CXX) && !strict_mode) {
3228 if (warning.implicit_int) {
3229 warningf(HERE, "no type specifiers in declaration, using 'int'");
3231 atomic_type = ATOMIC_TYPE_INT;
3234 errorf(HERE, "no type specifiers given in declaration");
3236 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3237 (type_specifiers & SPECIFIER_UNSIGNED)) {
3238 errorf(HERE, "signed and unsigned specifiers given");
3239 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3240 errorf(HERE, "only integer types can be signed or unsigned");
3242 errorf(HERE, "multiple datatypes in declaration");
3247 if (type_specifiers & SPECIFIER_COMPLEX) {
3248 type = allocate_type_zero(TYPE_COMPLEX);
3249 type->complex.akind = atomic_type;
3250 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3251 type = allocate_type_zero(TYPE_IMAGINARY);
3252 type->imaginary.akind = atomic_type;
3254 type = allocate_type_zero(TYPE_ATOMIC);
3255 type->atomic.akind = atomic_type;
3258 } else if (type_specifiers != 0) {
3259 errorf(HERE, "multiple datatypes in declaration");
3262 /* FIXME: check type qualifiers here */
3263 type->base.qualifiers = qualifiers;
3266 type = identify_new_type(type);
3268 type = typehash_insert(type);
3271 if (specifiers->attributes != NULL)
3272 type = handle_type_attributes(specifiers->attributes, type);
3273 specifiers->type = type;
3277 specifiers->type = type_error_type;
3280 static type_qualifiers_t parse_type_qualifiers(void)
3282 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3285 switch (token.type) {
3286 /* type qualifiers */
3287 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3288 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3289 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3290 /* microsoft extended type modifiers */
3291 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3292 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3293 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3294 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3295 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3304 * Parses an K&R identifier list
3306 static void parse_identifier_list(scope_t *scope)
3309 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3310 entity->base.source_position = token.source_position;
3311 entity->base.namespc = NAMESPACE_NORMAL;
3312 entity->base.symbol = token.symbol;
3313 /* a K&R parameter has no type, yet */
3317 append_entity(scope, entity);
3318 } while (next_if(',') && token.type == T_IDENTIFIER);
3321 static entity_t *parse_parameter(void)
3323 declaration_specifiers_t specifiers;
3324 memset(&specifiers, 0, sizeof(specifiers));
3326 parse_declaration_specifiers(&specifiers);
3328 entity_t *entity = parse_declarator(&specifiers,
3329 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3330 anonymous_entity = NULL;
3334 static void semantic_parameter_incomplete(const entity_t *entity)
3336 assert(entity->kind == ENTITY_PARAMETER);
3338 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3339 * list in a function declarator that is part of a
3340 * definition of that function shall not have
3341 * incomplete type. */
3342 type_t *type = skip_typeref(entity->declaration.type);
3343 if (is_type_incomplete(type)) {
3344 errorf(&entity->base.source_position,
3345 "parameter '%#T' has incomplete type",
3346 entity->declaration.type, entity->base.symbol);
3350 static bool has_parameters(void)
3352 /* func(void) is not a parameter */
3353 if (token.type == T_IDENTIFIER) {
3354 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3357 if (entity->kind != ENTITY_TYPEDEF)
3359 if (skip_typeref(entity->typedefe.type) != type_void)
3361 } else if (token.type != T_void) {
3364 if (look_ahead(1)->type != ')')
3371 * Parses function type parameters (and optionally creates variable_t entities
3372 * for them in a scope)
3374 static void parse_parameters(function_type_t *type, scope_t *scope)
3377 add_anchor_token(')');
3378 int saved_comma_state = save_and_reset_anchor_state(',');
3380 if (token.type == T_IDENTIFIER &&
3381 !is_typedef_symbol(token.symbol)) {
3382 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3383 if (la1_type == ',' || la1_type == ')') {
3384 type->kr_style_parameters = true;
3385 parse_identifier_list(scope);
3386 goto parameters_finished;
3390 if (token.type == ')') {
3391 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3392 if (!(c_mode & _CXX))
3393 type->unspecified_parameters = true;
3394 goto parameters_finished;
3397 if (has_parameters()) {
3398 function_parameter_t **anchor = &type->parameters;
3400 switch (token.type) {
3403 type->variadic = true;
3404 goto parameters_finished;
3407 case T___extension__:
3410 entity_t *entity = parse_parameter();
3411 if (entity->kind == ENTITY_TYPEDEF) {
3412 errorf(&entity->base.source_position,
3413 "typedef not allowed as function parameter");
3416 assert(is_declaration(entity));
3418 semantic_parameter_incomplete(entity);
3420 function_parameter_t *const parameter =
3421 allocate_parameter(entity->declaration.type);
3423 if (scope != NULL) {
3424 append_entity(scope, entity);
3427 *anchor = parameter;
3428 anchor = ¶meter->next;
3433 goto parameters_finished;
3435 } while (next_if(','));
3439 parameters_finished:
3440 rem_anchor_token(')');
3441 expect(')', end_error);
3444 restore_anchor_state(',', saved_comma_state);
3447 typedef enum construct_type_kind_t {
3450 CONSTRUCT_REFERENCE,
3453 } construct_type_kind_t;
3455 typedef union construct_type_t construct_type_t;
3457 typedef struct construct_type_base_t {
3458 construct_type_kind_t kind;
3459 construct_type_t *next;
3460 } construct_type_base_t;
3462 typedef struct parsed_pointer_t {
3463 construct_type_base_t base;
3464 type_qualifiers_t type_qualifiers;
3465 variable_t *base_variable; /**< MS __based extension. */
3468 typedef struct parsed_reference_t {
3469 construct_type_base_t base;
3470 } parsed_reference_t;
3472 typedef struct construct_function_type_t {
3473 construct_type_base_t base;
3474 type_t *function_type;
3475 } construct_function_type_t;
3477 typedef struct parsed_array_t {
3478 construct_type_base_t base;
3479 type_qualifiers_t type_qualifiers;
3485 union construct_type_t {
3486 construct_type_kind_t kind;
3487 construct_type_base_t base;
3488 parsed_pointer_t pointer;
3489 parsed_reference_t reference;
3490 construct_function_type_t function;
3491 parsed_array_t array;
3494 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3496 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3497 memset(cons, 0, size);
3503 static construct_type_t *parse_pointer_declarator(void)
3507 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3508 cons->pointer.type_qualifiers = parse_type_qualifiers();
3509 //cons->pointer.base_variable = base_variable;
3514 /* ISO/IEC 14882:1998(E) §8.3.2 */
3515 static construct_type_t *parse_reference_declarator(void)
3519 if (!(c_mode & _CXX))
3520 errorf(HERE, "references are only available for C++");
3522 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3528 static construct_type_t *parse_array_declarator(void)
3531 add_anchor_token(']');
3533 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3534 parsed_array_t *const array = &cons->array;
3536 bool is_static = next_if(T_static);
3538 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3541 is_static = next_if(T_static);
3543 array->type_qualifiers = type_qualifiers;
3544 array->is_static = is_static;
3546 expression_t *size = NULL;
3547 if (token.type == '*' && look_ahead(1)->type == ']') {
3548 array->is_variable = true;
3550 } else if (token.type != ']') {
3551 size = parse_assignment_expression();
3553 /* §6.7.5.2:1 Array size must have integer type */
3554 type_t *const orig_type = size->base.type;
3555 type_t *const type = skip_typeref(orig_type);
3556 if (!is_type_integer(type) && is_type_valid(type)) {
3557 errorf(&size->base.source_position,
3558 "array size '%E' must have integer type but has type '%T'",
3563 mark_vars_read(size, NULL);
3566 if (is_static && size == NULL)
3567 errorf(HERE, "static array parameters require a size");
3569 rem_anchor_token(']');
3570 expect(']', end_error);
3577 static construct_type_t *parse_function_declarator(scope_t *scope)
3579 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3580 function_type_t *ftype = &type->function;
3582 ftype->linkage = current_linkage;
3583 ftype->calling_convention = CC_DEFAULT;
3585 parse_parameters(ftype, scope);
3587 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3588 cons->function.function_type = type;
3593 typedef struct parse_declarator_env_t {
3594 bool may_be_abstract : 1;
3595 bool must_be_abstract : 1;
3596 decl_modifiers_t modifiers;
3598 source_position_t source_position;
3600 attribute_t *attributes;
3601 } parse_declarator_env_t;
3604 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3606 /* construct a single linked list of construct_type_t's which describe
3607 * how to construct the final declarator type */
3608 construct_type_t *first = NULL;
3609 construct_type_t **anchor = &first;
3611 env->attributes = parse_attributes(env->attributes);
3614 construct_type_t *type;
3615 //variable_t *based = NULL; /* MS __based extension */
3616 switch (token.type) {
3618 type = parse_reference_declarator();
3622 panic("based not supported anymore");
3627 type = parse_pointer_declarator();
3631 goto ptr_operator_end;
3635 anchor = &type->base.next;
3637 /* TODO: find out if this is correct */
3638 env->attributes = parse_attributes(env->attributes);
3642 construct_type_t *inner_types = NULL;
3644 switch (token.type) {
3646 if (env->must_be_abstract) {
3647 errorf(HERE, "no identifier expected in typename");
3649 env->symbol = token.symbol;
3650 env->source_position = token.source_position;
3655 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3656 * interpreted as ``function with no parameter specification'', rather
3657 * than redundant parentheses around the omitted identifier. */
3658 if (look_ahead(1)->type != ')') {
3660 add_anchor_token(')');
3661 inner_types = parse_inner_declarator(env);
3662 if (inner_types != NULL) {
3663 /* All later declarators only modify the return type */
3664 env->must_be_abstract = true;
3666 rem_anchor_token(')');
3667 expect(')', end_error);
3668 } else if (!env->may_be_abstract) {
3669 errorf(HERE, "declarator must have a name");
3674 if (env->may_be_abstract)
3676 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3682 construct_type_t **const p = anchor;
3685 construct_type_t *type;
3686 switch (token.type) {
3688 scope_t *scope = NULL;
3689 if (!env->must_be_abstract) {
3690 scope = &env->parameters;
3693 type = parse_function_declarator(scope);
3697 type = parse_array_declarator();
3700 goto declarator_finished;
3703 /* insert in the middle of the list (at p) */
3704 type->base.next = *p;
3707 anchor = &type->base.next;
3710 declarator_finished:
3711 /* append inner_types at the end of the list, we don't to set anchor anymore
3712 * as it's not needed anymore */
3713 *anchor = inner_types;
3720 static type_t *construct_declarator_type(construct_type_t *construct_list,
3723 construct_type_t *iter = construct_list;
3724 for (; iter != NULL; iter = iter->base.next) {
3725 switch (iter->kind) {
3726 case CONSTRUCT_INVALID:
3728 case CONSTRUCT_FUNCTION: {
3729 construct_function_type_t *function = &iter->function;
3730 type_t *function_type = function->function_type;
3732 function_type->function.return_type = type;
3734 type_t *skipped_return_type = skip_typeref(type);
3736 if (is_type_function(skipped_return_type)) {
3737 errorf(HERE, "function returning function is not allowed");
3738 } else if (is_type_array(skipped_return_type)) {
3739 errorf(HERE, "function returning array is not allowed");
3741 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3743 "type qualifiers in return type of function type are meaningless");
3747 /* The function type was constructed earlier. Freeing it here will
3748 * destroy other types. */
3749 type = typehash_insert(function_type);
3753 case CONSTRUCT_POINTER: {
3754 if (is_type_reference(skip_typeref(type)))
3755 errorf(HERE, "cannot declare a pointer to reference");
3757 parsed_pointer_t *pointer = &iter->pointer;
3758 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3762 case CONSTRUCT_REFERENCE:
3763 if (is_type_reference(skip_typeref(type)))
3764 errorf(HERE, "cannot declare a reference to reference");
3766 type = make_reference_type(type);
3769 case CONSTRUCT_ARRAY: {
3770 if (is_type_reference(skip_typeref(type)))
3771 errorf(HERE, "cannot declare an array of references");
3773 parsed_array_t *array = &iter->array;
3774 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3776 expression_t *size_expression = array->size;
3777 if (size_expression != NULL) {
3779 = create_implicit_cast(size_expression, type_size_t);
3782 array_type->base.qualifiers = array->type_qualifiers;
3783 array_type->array.element_type = type;
3784 array_type->array.is_static = array->is_static;
3785 array_type->array.is_variable = array->is_variable;
3786 array_type->array.size_expression = size_expression;
3788 if (size_expression != NULL) {
3789 switch (is_constant_expression(size_expression)) {
3790 case EXPR_CLASS_CONSTANT: {
3791 long const size = fold_constant_to_int(size_expression);
3792 array_type->array.size = size;
3793 array_type->array.size_constant = true;
3794 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3795 * have a value greater than zero. */
3797 if (size < 0 || !GNU_MODE) {
3798 errorf(&size_expression->base.source_position,
3799 "size of array must be greater than zero");
3800 } else if (warning.other) {
3801 warningf(&size_expression->base.source_position,
3802 "zero length arrays are a GCC extension");
3808 case EXPR_CLASS_VARIABLE:
3809 array_type->array.is_vla = true;
3812 case EXPR_CLASS_ERROR:
3817 type_t *skipped_type = skip_typeref(type);
3819 if (is_type_incomplete(skipped_type)) {
3820 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3821 } else if (is_type_function(skipped_type)) {
3822 errorf(HERE, "array of functions is not allowed");
3824 type = identify_new_type(array_type);
3828 internal_errorf(HERE, "invalid type construction found");
3834 static type_t *automatic_type_conversion(type_t *orig_type);
3836 static type_t *semantic_parameter(const source_position_t *pos,
3838 const declaration_specifiers_t *specifiers,
3841 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3842 * shall be adjusted to ``qualified pointer to type'',
3844 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3845 * type'' shall be adjusted to ``pointer to function
3846 * returning type'', as in 6.3.2.1. */
3847 type = automatic_type_conversion(type);
3849 if (specifiers->is_inline && is_type_valid(type)) {
3850 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3853 /* §6.9.1:6 The declarations in the declaration list shall contain
3854 * no storage-class specifier other than register and no
3855 * initializations. */
3856 if (specifiers->thread_local || (
3857 specifiers->storage_class != STORAGE_CLASS_NONE &&
3858 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3860 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3863 /* delay test for incomplete type, because we might have (void)
3864 * which is legal but incomplete... */
3869 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3870 declarator_flags_t flags)
3872 parse_declarator_env_t env;
3873 memset(&env, 0, sizeof(env));
3874 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3876 construct_type_t *construct_type = parse_inner_declarator(&env);
3878 construct_declarator_type(construct_type, specifiers->type);
3879 type_t *type = skip_typeref(orig_type);
3881 if (construct_type != NULL) {
3882 obstack_free(&temp_obst, construct_type);
3885 attribute_t *attributes = parse_attributes(env.attributes);
3886 /* append (shared) specifier attribute behind attributes of this
3888 attribute_t **anchor = &attributes;
3889 while (*anchor != NULL)
3890 anchor = &(*anchor)->next;
3891 *anchor = specifiers->attributes;
3894 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3895 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3896 entity->base.namespc = NAMESPACE_NORMAL;
3897 entity->base.symbol = env.symbol;
3898 entity->base.source_position = env.source_position;
3899 entity->typedefe.type = orig_type;
3901 if (anonymous_entity != NULL) {
3902 if (is_type_compound(type)) {
3903 assert(anonymous_entity->compound.alias == NULL);
3904 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3905 anonymous_entity->kind == ENTITY_UNION);
3906 anonymous_entity->compound.alias = entity;
3907 anonymous_entity = NULL;
3908 } else if (is_type_enum(type)) {
3909 assert(anonymous_entity->enume.alias == NULL);
3910 assert(anonymous_entity->kind == ENTITY_ENUM);
3911 anonymous_entity->enume.alias = entity;
3912 anonymous_entity = NULL;
3916 /* create a declaration type entity */
3917 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3918 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3920 if (env.symbol != NULL) {
3921 if (specifiers->is_inline && is_type_valid(type)) {
3922 errorf(&env.source_position,
3923 "compound member '%Y' declared 'inline'", env.symbol);
3926 if (specifiers->thread_local ||
3927 specifiers->storage_class != STORAGE_CLASS_NONE) {
3928 errorf(&env.source_position,
3929 "compound member '%Y' must have no storage class",
3933 } else if (flags & DECL_IS_PARAMETER) {
3934 orig_type = semantic_parameter(&env.source_position, orig_type,
3935 specifiers, env.symbol);
3937 entity = allocate_entity_zero(ENTITY_PARAMETER);
3938 } else if (is_type_function(type)) {
3939 entity = allocate_entity_zero(ENTITY_FUNCTION);
3941 entity->function.is_inline = specifiers->is_inline;
3942 entity->function.parameters = env.parameters;
3944 if (env.symbol != NULL) {
3945 /* this needs fixes for C++ */
3946 bool in_function_scope = current_function != NULL;
3948 if (specifiers->thread_local || (
3949 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3950 specifiers->storage_class != STORAGE_CLASS_NONE &&
3951 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3953 errorf(&env.source_position,
3954 "invalid storage class for function '%Y'", env.symbol);
3958 entity = allocate_entity_zero(ENTITY_VARIABLE);
3960 entity->variable.thread_local = specifiers->thread_local;
3962 if (env.symbol != NULL) {
3963 if (specifiers->is_inline && is_type_valid(type)) {
3964 errorf(&env.source_position,
3965 "variable '%Y' declared 'inline'", env.symbol);
3968 bool invalid_storage_class = false;
3969 if (current_scope == file_scope) {
3970 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3971 specifiers->storage_class != STORAGE_CLASS_NONE &&
3972 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3973 invalid_storage_class = true;
3976 if (specifiers->thread_local &&
3977 specifiers->storage_class == STORAGE_CLASS_NONE) {
3978 invalid_storage_class = true;
3981 if (invalid_storage_class) {
3982 errorf(&env.source_position,
3983 "invalid storage class for variable '%Y'", env.symbol);
3988 if (env.symbol != NULL) {
3989 entity->base.symbol = env.symbol;
3990 entity->base.source_position = env.source_position;
3992 entity->base.source_position = specifiers->source_position;
3994 entity->base.namespc = NAMESPACE_NORMAL;
3995 entity->declaration.type = orig_type;
3996 entity->declaration.alignment = get_type_alignment(orig_type);
3997 entity->declaration.modifiers = env.modifiers;
3998 entity->declaration.attributes = attributes;
4000 storage_class_t storage_class = specifiers->storage_class;
4001 entity->declaration.declared_storage_class = storage_class;
4003 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4004 storage_class = STORAGE_CLASS_AUTO;
4005 entity->declaration.storage_class = storage_class;
4008 if (attributes != NULL) {
4009 handle_entity_attributes(attributes, entity);
4015 static type_t *parse_abstract_declarator(type_t *base_type)
4017 parse_declarator_env_t env;
4018 memset(&env, 0, sizeof(env));
4019 env.may_be_abstract = true;
4020 env.must_be_abstract = true;
4022 construct_type_t *construct_type = parse_inner_declarator(&env);
4024 type_t *result = construct_declarator_type(construct_type, base_type);
4025 if (construct_type != NULL) {
4026 obstack_free(&temp_obst, construct_type);
4028 result = handle_type_attributes(env.attributes, result);
4034 * Check if the declaration of main is suspicious. main should be a
4035 * function with external linkage, returning int, taking either zero
4036 * arguments, two, or three arguments of appropriate types, ie.
4038 * int main([ int argc, char **argv [, char **env ] ]).
4040 * @param decl the declaration to check
4041 * @param type the function type of the declaration
4043 static void check_main(const entity_t *entity)
4045 const source_position_t *pos = &entity->base.source_position;
4046 if (entity->kind != ENTITY_FUNCTION) {
4047 warningf(pos, "'main' is not a function");
4051 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4052 warningf(pos, "'main' is normally a non-static function");
4055 type_t *type = skip_typeref(entity->declaration.type);
4056 assert(is_type_function(type));
4058 function_type_t *func_type = &type->function;
4059 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4060 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4061 func_type->return_type);
4063 const function_parameter_t *parm = func_type->parameters;
4065 type_t *const first_type = parm->type;
4066 if (!types_compatible(skip_typeref(first_type), type_int)) {
4068 "first argument of 'main' should be 'int', but is '%T'",
4073 type_t *const second_type = parm->type;
4074 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4075 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4079 type_t *const third_type = parm->type;
4080 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4081 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4085 goto warn_arg_count;
4089 warningf(pos, "'main' takes only zero, two or three arguments");
4095 * Check if a symbol is the equal to "main".
4097 static bool is_sym_main(const symbol_t *const sym)
4099 return strcmp(sym->string, "main") == 0;
4102 static void error_redefined_as_different_kind(const source_position_t *pos,
4103 const entity_t *old, entity_kind_t new_kind)
4105 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4106 get_entity_kind_name(old->kind), old->base.symbol,
4107 get_entity_kind_name(new_kind), &old->base.source_position);
4110 static bool is_entity_valid(entity_t *const ent)
4112 if (is_declaration(ent)) {
4113 return is_type_valid(skip_typeref(ent->declaration.type));
4114 } else if (ent->kind == ENTITY_TYPEDEF) {
4115 return is_type_valid(skip_typeref(ent->typedefe.type));
4120 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4122 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4123 if (attributes_equal(tattr, attr))
4130 * test wether new_list contains any attributes not included in old_list
4132 static bool has_new_attributes(const attribute_t *old_list,
4133 const attribute_t *new_list)
4135 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4136 if (!contains_attribute(old_list, attr))
4143 * Merge in attributes from an attribute list (probably from a previous
4144 * declaration with the same name). Warning: destroys the old structure
4145 * of the attribute list - don't reuse attributes after this call.
4147 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4150 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4152 if (contains_attribute(decl->attributes, attr))
4155 /* move attribute to new declarations attributes list */
4156 attr->next = decl->attributes;
4157 decl->attributes = attr;
4162 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4163 * for various problems that occur for multiple definitions
4165 entity_t *record_entity(entity_t *entity, const bool is_definition)
4167 const symbol_t *const symbol = entity->base.symbol;
4168 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4169 const source_position_t *pos = &entity->base.source_position;
4171 /* can happen in error cases */
4175 entity_t *const previous_entity = get_entity(symbol, namespc);
4176 /* pushing the same entity twice will break the stack structure */
4177 assert(previous_entity != entity);
4179 if (entity->kind == ENTITY_FUNCTION) {
4180 type_t *const orig_type = entity->declaration.type;
4181 type_t *const type = skip_typeref(orig_type);
4183 assert(is_type_function(type));
4184 if (type->function.unspecified_parameters &&
4185 warning.strict_prototypes &&
4186 previous_entity == NULL) {
4187 warningf(pos, "function declaration '%#T' is not a prototype",
4191 if (warning.main && current_scope == file_scope
4192 && is_sym_main(symbol)) {
4197 if (is_declaration(entity) &&
4198 warning.nested_externs &&
4199 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4200 current_scope != file_scope) {
4201 warningf(pos, "nested extern declaration of '%#T'",
4202 entity->declaration.type, symbol);
4205 if (previous_entity != NULL) {
4206 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4207 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4208 assert(previous_entity->kind == ENTITY_PARAMETER);
4210 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4211 entity->declaration.type, symbol,
4212 previous_entity->declaration.type, symbol,
4213 &previous_entity->base.source_position);
4217 if (previous_entity->base.parent_scope == current_scope) {
4218 if (previous_entity->kind != entity->kind) {
4219 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4220 error_redefined_as_different_kind(pos, previous_entity,
4225 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4226 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4227 symbol, &previous_entity->base.source_position);
4230 if (previous_entity->kind == ENTITY_TYPEDEF) {
4231 /* TODO: C++ allows this for exactly the same type */
4232 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4233 symbol, &previous_entity->base.source_position);
4237 /* at this point we should have only VARIABLES or FUNCTIONS */
4238 assert(is_declaration(previous_entity) && is_declaration(entity));
4240 declaration_t *const prev_decl = &previous_entity->declaration;
4241 declaration_t *const decl = &entity->declaration;
4243 /* can happen for K&R style declarations */
4244 if (prev_decl->type == NULL &&
4245 previous_entity->kind == ENTITY_PARAMETER &&
4246 entity->kind == ENTITY_PARAMETER) {
4247 prev_decl->type = decl->type;
4248 prev_decl->storage_class = decl->storage_class;
4249 prev_decl->declared_storage_class = decl->declared_storage_class;
4250 prev_decl->modifiers = decl->modifiers;
4251 return previous_entity;
4254 type_t *const orig_type = decl->type;
4255 assert(orig_type != NULL);
4256 type_t *const type = skip_typeref(orig_type);
4257 type_t *const prev_type = skip_typeref(prev_decl->type);
4259 if (!types_compatible(type, prev_type)) {
4261 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4262 orig_type, symbol, prev_decl->type, symbol,
4263 &previous_entity->base.source_position);
4265 unsigned old_storage_class = prev_decl->storage_class;
4267 if (warning.redundant_decls &&
4270 !(prev_decl->modifiers & DM_USED) &&
4271 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4272 warningf(&previous_entity->base.source_position,
4273 "unnecessary static forward declaration for '%#T'",
4274 prev_decl->type, symbol);
4277 storage_class_t new_storage_class = decl->storage_class;
4279 /* pretend no storage class means extern for function
4280 * declarations (except if the previous declaration is neither
4281 * none nor extern) */
4282 if (entity->kind == ENTITY_FUNCTION) {
4283 /* the previous declaration could have unspecified parameters or
4284 * be a typedef, so use the new type */
4285 if (prev_type->function.unspecified_parameters || is_definition)
4286 prev_decl->type = type;
4288 switch (old_storage_class) {
4289 case STORAGE_CLASS_NONE:
4290 old_storage_class = STORAGE_CLASS_EXTERN;
4293 case STORAGE_CLASS_EXTERN:
4294 if (is_definition) {
4295 if (warning.missing_prototypes &&
4296 prev_type->function.unspecified_parameters &&
4297 !is_sym_main(symbol)) {
4298 warningf(pos, "no previous prototype for '%#T'",
4301 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4302 new_storage_class = STORAGE_CLASS_EXTERN;
4309 } else if (is_type_incomplete(prev_type)) {
4310 prev_decl->type = type;
4313 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4314 new_storage_class == STORAGE_CLASS_EXTERN) {
4316 warn_redundant_declaration: ;
4318 = has_new_attributes(prev_decl->attributes,
4320 if (has_new_attrs) {
4321 merge_in_attributes(decl, prev_decl->attributes);
4322 } else if (!is_definition &&
4323 warning.redundant_decls &&
4324 is_type_valid(prev_type) &&
4325 strcmp(previous_entity->base.source_position.input_name,
4326 "<builtin>") != 0) {
4328 "redundant declaration for '%Y' (declared %P)",
4329 symbol, &previous_entity->base.source_position);
4331 } else if (current_function == NULL) {
4332 if (old_storage_class != STORAGE_CLASS_STATIC &&
4333 new_storage_class == STORAGE_CLASS_STATIC) {
4335 "static declaration of '%Y' follows non-static declaration (declared %P)",
4336 symbol, &previous_entity->base.source_position);
4337 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4338 prev_decl->storage_class = STORAGE_CLASS_NONE;
4339 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4341 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4343 goto error_redeclaration;
4344 goto warn_redundant_declaration;
4346 } else if (is_type_valid(prev_type)) {
4347 if (old_storage_class == new_storage_class) {
4348 error_redeclaration:
4349 errorf(pos, "redeclaration of '%Y' (declared %P)",
4350 symbol, &previous_entity->base.source_position);
4353 "redeclaration of '%Y' with different linkage (declared %P)",
4354 symbol, &previous_entity->base.source_position);
4359 prev_decl->modifiers |= decl->modifiers;
4360 if (entity->kind == ENTITY_FUNCTION) {
4361 previous_entity->function.is_inline |= entity->function.is_inline;
4363 return previous_entity;
4366 if (warning.shadow) {
4367 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4368 get_entity_kind_name(entity->kind), symbol,
4369 get_entity_kind_name(previous_entity->kind),
4370 &previous_entity->base.source_position);
4374 if (entity->kind == ENTITY_FUNCTION) {
4375 if (is_definition &&
4376 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4377 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4378 warningf(pos, "no previous prototype for '%#T'",
4379 entity->declaration.type, symbol);
4380 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4381 warningf(pos, "no previous declaration for '%#T'",
4382 entity->declaration.type, symbol);
4385 } else if (warning.missing_declarations &&
4386 entity->kind == ENTITY_VARIABLE &&
4387 current_scope == file_scope) {
4388 declaration_t *declaration = &entity->declaration;
4389 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4390 warningf(pos, "no previous declaration for '%#T'",
4391 declaration->type, symbol);
4396 assert(entity->base.parent_scope == NULL);
4397 assert(current_scope != NULL);
4399 entity->base.parent_scope = current_scope;
4400 entity->base.namespc = NAMESPACE_NORMAL;
4401 environment_push(entity);
4402 append_entity(current_scope, entity);
4407 static void parser_error_multiple_definition(entity_t *entity,
4408 const source_position_t *source_position)
4410 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4411 entity->base.symbol, &entity->base.source_position);
4414 static bool is_declaration_specifier(const token_t *token,
4415 bool only_specifiers_qualifiers)
4417 switch (token->type) {
4422 return is_typedef_symbol(token->symbol);
4424 case T___extension__:
4426 return !only_specifiers_qualifiers;
4433 static void parse_init_declarator_rest(entity_t *entity)
4435 type_t *orig_type = type_error_type;
4437 if (entity->base.kind == ENTITY_TYPEDEF) {
4438 errorf(&entity->base.source_position,
4439 "typedef '%Y' is initialized (use __typeof__ instead)",
4440 entity->base.symbol);
4442 assert(is_declaration(entity));
4443 orig_type = entity->declaration.type;
4447 type_t *type = skip_typeref(orig_type);
4449 if (entity->kind == ENTITY_VARIABLE
4450 && entity->variable.initializer != NULL) {
4451 parser_error_multiple_definition(entity, HERE);
4454 declaration_t *const declaration = &entity->declaration;
4455 bool must_be_constant = false;
4456 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4457 entity->base.parent_scope == file_scope) {
4458 must_be_constant = true;
4461 if (is_type_function(type)) {
4462 errorf(&entity->base.source_position,
4463 "function '%#T' is initialized like a variable",
4464 orig_type, entity->base.symbol);
4465 orig_type = type_error_type;
4468 parse_initializer_env_t env;
4469 env.type = orig_type;
4470 env.must_be_constant = must_be_constant;
4471 env.entity = entity;
4472 current_init_decl = entity;
4474 initializer_t *initializer = parse_initializer(&env);
4475 current_init_decl = NULL;
4477 if (entity->kind == ENTITY_VARIABLE) {
4478 /* §6.7.5:22 array initializers for arrays with unknown size
4479 * determine the array type size */
4480 declaration->type = env.type;
4481 entity->variable.initializer = initializer;
4485 /* parse rest of a declaration without any declarator */
4486 static void parse_anonymous_declaration_rest(
4487 const declaration_specifiers_t *specifiers)
4490 anonymous_entity = NULL;
4492 if (warning.other) {
4493 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4494 specifiers->thread_local) {
4495 warningf(&specifiers->source_position,
4496 "useless storage class in empty declaration");
4499 type_t *type = specifiers->type;
4500 switch (type->kind) {
4501 case TYPE_COMPOUND_STRUCT:
4502 case TYPE_COMPOUND_UNION: {
4503 if (type->compound.compound->base.symbol == NULL) {
4504 warningf(&specifiers->source_position,
4505 "unnamed struct/union that defines no instances");
4514 warningf(&specifiers->source_position, "empty declaration");
4520 static void check_variable_type_complete(entity_t *ent)
4522 if (ent->kind != ENTITY_VARIABLE)
4525 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4526 * type for the object shall be complete [...] */
4527 declaration_t *decl = &ent->declaration;
4528 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4529 decl->storage_class == STORAGE_CLASS_STATIC)
4532 type_t *const orig_type = decl->type;
4533 type_t *const type = skip_typeref(orig_type);
4534 if (!is_type_incomplete(type))
4537 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4538 * are given length one. */
4539 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4540 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4544 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4545 orig_type, ent->base.symbol);
4549 static void parse_declaration_rest(entity_t *ndeclaration,
4550 const declaration_specifiers_t *specifiers,
4551 parsed_declaration_func finished_declaration,
4552 declarator_flags_t flags)
4554 add_anchor_token(';');
4555 add_anchor_token(',');
4557 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4559 if (token.type == '=') {
4560 parse_init_declarator_rest(entity);
4561 } else if (entity->kind == ENTITY_VARIABLE) {
4562 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4563 * [...] where the extern specifier is explicitly used. */
4564 declaration_t *decl = &entity->declaration;
4565 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4566 type_t *type = decl->type;
4567 if (is_type_reference(skip_typeref(type))) {
4568 errorf(&entity->base.source_position,
4569 "reference '%#T' must be initialized",
4570 type, entity->base.symbol);
4575 check_variable_type_complete(entity);
4580 add_anchor_token('=');
4581 ndeclaration = parse_declarator(specifiers, flags);
4582 rem_anchor_token('=');
4584 expect(';', end_error);
4587 anonymous_entity = NULL;
4588 rem_anchor_token(';');
4589 rem_anchor_token(',');
4592 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4594 symbol_t *symbol = entity->base.symbol;
4595 if (symbol == NULL) {
4596 errorf(HERE, "anonymous declaration not valid as function parameter");
4600 assert(entity->base.namespc == NAMESPACE_NORMAL);
4601 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4602 if (previous_entity == NULL
4603 || previous_entity->base.parent_scope != current_scope) {
4604 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4609 if (is_definition) {
4610 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4613 return record_entity(entity, false);
4616 static void parse_declaration(parsed_declaration_func finished_declaration,
4617 declarator_flags_t flags)
4619 declaration_specifiers_t specifiers;
4620 memset(&specifiers, 0, sizeof(specifiers));
4622 add_anchor_token(';');
4623 parse_declaration_specifiers(&specifiers);
4624 rem_anchor_token(';');
4626 if (token.type == ';') {
4627 parse_anonymous_declaration_rest(&specifiers);
4629 entity_t *entity = parse_declarator(&specifiers, flags);
4630 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4635 static type_t *get_default_promoted_type(type_t *orig_type)
4637 type_t *result = orig_type;
4639 type_t *type = skip_typeref(orig_type);
4640 if (is_type_integer(type)) {
4641 result = promote_integer(type);
4642 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4643 result = type_double;
4649 static void parse_kr_declaration_list(entity_t *entity)
4651 if (entity->kind != ENTITY_FUNCTION)
4654 type_t *type = skip_typeref(entity->declaration.type);
4655 assert(is_type_function(type));
4656 if (!type->function.kr_style_parameters)
4659 add_anchor_token('{');
4661 /* push function parameters */
4662 size_t const top = environment_top();
4663 scope_t *old_scope = scope_push(&entity->function.parameters);
4665 entity_t *parameter = entity->function.parameters.entities;
4666 for ( ; parameter != NULL; parameter = parameter->base.next) {
4667 assert(parameter->base.parent_scope == NULL);
4668 parameter->base.parent_scope = current_scope;
4669 environment_push(parameter);
4672 /* parse declaration list */
4674 switch (token.type) {
4676 case T___extension__:
4677 /* This covers symbols, which are no type, too, and results in
4678 * better error messages. The typical cases are misspelled type
4679 * names and missing includes. */
4681 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4689 /* pop function parameters */
4690 assert(current_scope == &entity->function.parameters);
4691 scope_pop(old_scope);
4692 environment_pop_to(top);
4694 /* update function type */
4695 type_t *new_type = duplicate_type(type);
4697 function_parameter_t *parameters = NULL;
4698 function_parameter_t **anchor = ¶meters;
4700 /* did we have an earlier prototype? */
4701 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4702 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4705 function_parameter_t *proto_parameter = NULL;
4706 if (proto_type != NULL) {
4707 type_t *proto_type_type = proto_type->declaration.type;
4708 proto_parameter = proto_type_type->function.parameters;
4709 /* If a K&R function definition has a variadic prototype earlier, then
4710 * make the function definition variadic, too. This should conform to
4711 * §6.7.5.3:15 and §6.9.1:8. */
4712 new_type->function.variadic = proto_type_type->function.variadic;
4714 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4716 new_type->function.unspecified_parameters = true;
4719 bool need_incompatible_warning = false;
4720 parameter = entity->function.parameters.entities;
4721 for (; parameter != NULL; parameter = parameter->base.next,
4723 proto_parameter == NULL ? NULL : proto_parameter->next) {
4724 if (parameter->kind != ENTITY_PARAMETER)
4727 type_t *parameter_type = parameter->declaration.type;
4728 if (parameter_type == NULL) {
4730 errorf(HERE, "no type specified for function parameter '%Y'",
4731 parameter->base.symbol);
4732 parameter_type = type_error_type;
4734 if (warning.implicit_int) {
4735 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4736 parameter->base.symbol);
4738 parameter_type = type_int;
4740 parameter->declaration.type = parameter_type;
4743 semantic_parameter_incomplete(parameter);
4745 /* we need the default promoted types for the function type */
4746 type_t *not_promoted = parameter_type;
4747 parameter_type = get_default_promoted_type(parameter_type);
4749 /* gcc special: if the type of the prototype matches the unpromoted
4750 * type don't promote */
4751 if (!strict_mode && proto_parameter != NULL) {
4752 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4753 type_t *promo_skip = skip_typeref(parameter_type);
4754 type_t *param_skip = skip_typeref(not_promoted);
4755 if (!types_compatible(proto_p_type, promo_skip)
4756 && types_compatible(proto_p_type, param_skip)) {
4758 need_incompatible_warning = true;
4759 parameter_type = not_promoted;
4762 function_parameter_t *const parameter
4763 = allocate_parameter(parameter_type);
4765 *anchor = parameter;
4766 anchor = ¶meter->next;
4769 new_type->function.parameters = parameters;
4770 new_type = identify_new_type(new_type);
4772 if (warning.other && need_incompatible_warning) {
4773 type_t *proto_type_type = proto_type->declaration.type;
4775 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4776 proto_type_type, proto_type->base.symbol,
4777 new_type, entity->base.symbol,
4778 &proto_type->base.source_position);
4781 entity->declaration.type = new_type;
4783 rem_anchor_token('{');
4786 static bool first_err = true;
4789 * When called with first_err set, prints the name of the current function,
4792 static void print_in_function(void)
4796 diagnosticf("%s: In function '%Y':\n",
4797 current_function->base.base.source_position.input_name,
4798 current_function->base.base.symbol);
4803 * Check if all labels are defined in the current function.
4804 * Check if all labels are used in the current function.
4806 static void check_labels(void)
4808 for (const goto_statement_t *goto_statement = goto_first;
4809 goto_statement != NULL;
4810 goto_statement = goto_statement->next) {
4811 /* skip computed gotos */
4812 if (goto_statement->expression != NULL)
4815 label_t *label = goto_statement->label;
4818 if (label->base.source_position.input_name == NULL) {
4819 print_in_function();
4820 errorf(&goto_statement->base.source_position,
4821 "label '%Y' used but not defined", label->base.symbol);
4825 if (warning.unused_label) {
4826 for (const label_statement_t *label_statement = label_first;
4827 label_statement != NULL;
4828 label_statement = label_statement->next) {
4829 label_t *label = label_statement->label;
4831 if (! label->used) {
4832 print_in_function();
4833 warningf(&label_statement->base.source_position,
4834 "label '%Y' defined but not used", label->base.symbol);
4840 static void warn_unused_entity(entity_t *entity, entity_t *last)
4842 entity_t const *const end = last != NULL ? last->base.next : NULL;
4843 for (; entity != end; entity = entity->base.next) {
4844 if (!is_declaration(entity))
4847 declaration_t *declaration = &entity->declaration;
4848 if (declaration->implicit)
4851 if (!declaration->used) {
4852 print_in_function();
4853 const char *what = get_entity_kind_name(entity->kind);
4854 warningf(&entity->base.source_position, "%s '%Y' is unused",
4855 what, entity->base.symbol);
4856 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4857 print_in_function();
4858 const char *what = get_entity_kind_name(entity->kind);
4859 warningf(&entity->base.source_position, "%s '%Y' is never read",
4860 what, entity->base.symbol);
4865 static void check_unused_variables(statement_t *const stmt, void *const env)
4869 switch (stmt->kind) {
4870 case STATEMENT_DECLARATION: {
4871 declaration_statement_t const *const decls = &stmt->declaration;
4872 warn_unused_entity(decls->declarations_begin,
4873 decls->declarations_end);
4878 warn_unused_entity(stmt->fors.scope.entities, NULL);
4887 * Check declarations of current_function for unused entities.
4889 static void check_declarations(void)
4891 if (warning.unused_parameter) {
4892 const scope_t *scope = ¤t_function->parameters;
4894 /* do not issue unused warnings for main */
4895 if (!is_sym_main(current_function->base.base.symbol)) {
4896 warn_unused_entity(scope->entities, NULL);
4899 if (warning.unused_variable) {
4900 walk_statements(current_function->statement, check_unused_variables,
4905 static int determine_truth(expression_t const* const cond)
4908 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4909 fold_constant_to_bool(cond) ? 1 :
4913 static void check_reachable(statement_t *);
4914 static bool reaches_end;
4916 static bool expression_returns(expression_t const *const expr)
4918 switch (expr->kind) {
4920 expression_t const *const func = expr->call.function;
4921 if (func->kind == EXPR_REFERENCE) {
4922 entity_t *entity = func->reference.entity;
4923 if (entity->kind == ENTITY_FUNCTION
4924 && entity->declaration.modifiers & DM_NORETURN)
4928 if (!expression_returns(func))
4931 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4932 if (!expression_returns(arg->expression))
4939 case EXPR_REFERENCE:
4940 case EXPR_REFERENCE_ENUM_VALUE:
4942 case EXPR_STRING_LITERAL:
4943 case EXPR_WIDE_STRING_LITERAL:
4944 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4945 case EXPR_LABEL_ADDRESS:
4946 case EXPR_CLASSIFY_TYPE:
4947 case EXPR_SIZEOF: // TODO handle obscure VLA case
4950 case EXPR_BUILTIN_CONSTANT_P:
4951 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4956 case EXPR_STATEMENT: {
4957 bool old_reaches_end = reaches_end;
4958 reaches_end = false;
4959 check_reachable(expr->statement.statement);
4960 bool returns = reaches_end;
4961 reaches_end = old_reaches_end;
4965 case EXPR_CONDITIONAL:
4966 // TODO handle constant expression
4968 if (!expression_returns(expr->conditional.condition))
4971 if (expr->conditional.true_expression != NULL
4972 && expression_returns(expr->conditional.true_expression))
4975 return expression_returns(expr->conditional.false_expression);
4978 return expression_returns(expr->select.compound);
4980 case EXPR_ARRAY_ACCESS:
4982 expression_returns(expr->array_access.array_ref) &&
4983 expression_returns(expr->array_access.index);
4986 return expression_returns(expr->va_starte.ap);
4989 return expression_returns(expr->va_arge.ap);
4992 return expression_returns(expr->va_copye.src);
4994 EXPR_UNARY_CASES_MANDATORY
4995 return expression_returns(expr->unary.value);
4997 case EXPR_UNARY_THROW:
5001 // TODO handle constant lhs of && and ||
5003 expression_returns(expr->binary.left) &&
5004 expression_returns(expr->binary.right);
5010 panic("unhandled expression");
5013 static bool initializer_returns(initializer_t const *const init)
5015 switch (init->kind) {
5016 case INITIALIZER_VALUE:
5017 return expression_returns(init->value.value);
5019 case INITIALIZER_LIST: {
5020 initializer_t * const* i = init->list.initializers;
5021 initializer_t * const* const end = i + init->list.len;
5022 bool returns = true;
5023 for (; i != end; ++i) {
5024 if (!initializer_returns(*i))
5030 case INITIALIZER_STRING:
5031 case INITIALIZER_WIDE_STRING:
5032 case INITIALIZER_DESIGNATOR: // designators have no payload
5035 panic("unhandled initializer");
5038 static bool noreturn_candidate;
5040 static void check_reachable(statement_t *const stmt)
5042 if (stmt->base.reachable)
5044 if (stmt->kind != STATEMENT_DO_WHILE)
5045 stmt->base.reachable = true;
5047 statement_t *last = stmt;
5049 switch (stmt->kind) {
5050 case STATEMENT_INVALID:
5051 case STATEMENT_EMPTY:
5053 next = stmt->base.next;
5056 case STATEMENT_DECLARATION: {
5057 declaration_statement_t const *const decl = &stmt->declaration;
5058 entity_t const * ent = decl->declarations_begin;
5059 entity_t const *const last = decl->declarations_end;
5061 for (;; ent = ent->base.next) {
5062 if (ent->kind == ENTITY_VARIABLE &&
5063 ent->variable.initializer != NULL &&
5064 !initializer_returns(ent->variable.initializer)) {
5071 next = stmt->base.next;
5075 case STATEMENT_COMPOUND:
5076 next = stmt->compound.statements;
5078 next = stmt->base.next;
5081 case STATEMENT_RETURN: {
5082 expression_t const *const val = stmt->returns.value;
5083 if (val == NULL || expression_returns(val))
5084 noreturn_candidate = false;
5088 case STATEMENT_IF: {
5089 if_statement_t const *const ifs = &stmt->ifs;
5090 expression_t const *const cond = ifs->condition;
5092 if (!expression_returns(cond))
5095 int const val = determine_truth(cond);
5098 check_reachable(ifs->true_statement);
5103 if (ifs->false_statement != NULL) {
5104 check_reachable(ifs->false_statement);
5108 next = stmt->base.next;
5112 case STATEMENT_SWITCH: {
5113 switch_statement_t const *const switchs = &stmt->switchs;
5114 expression_t const *const expr = switchs->expression;
5116 if (!expression_returns(expr))
5119 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5120 long const val = fold_constant_to_int(expr);
5121 case_label_statement_t * defaults = NULL;
5122 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5123 if (i->expression == NULL) {
5128 if (i->first_case <= val && val <= i->last_case) {
5129 check_reachable((statement_t*)i);
5134 if (defaults != NULL) {
5135 check_reachable((statement_t*)defaults);
5139 bool has_default = false;
5140 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5141 if (i->expression == NULL)
5144 check_reachable((statement_t*)i);
5151 next = stmt->base.next;
5155 case STATEMENT_EXPRESSION: {
5156 /* Check for noreturn function call */
5157 expression_t const *const expr = stmt->expression.expression;
5158 if (!expression_returns(expr))
5161 next = stmt->base.next;
5165 case STATEMENT_CONTINUE:
5166 for (statement_t *parent = stmt;;) {
5167 parent = parent->base.parent;
5168 if (parent == NULL) /* continue not within loop */
5172 switch (parent->kind) {
5173 case STATEMENT_WHILE: goto continue_while;
5174 case STATEMENT_DO_WHILE: goto continue_do_while;
5175 case STATEMENT_FOR: goto continue_for;
5181 case STATEMENT_BREAK:
5182 for (statement_t *parent = stmt;;) {
5183 parent = parent->base.parent;
5184 if (parent == NULL) /* break not within loop/switch */
5187 switch (parent->kind) {
5188 case STATEMENT_SWITCH:
5189 case STATEMENT_WHILE:
5190 case STATEMENT_DO_WHILE:
5193 next = parent->base.next;
5194 goto found_break_parent;
5202 case STATEMENT_GOTO:
5203 if (stmt->gotos.expression) {
5204 if (!expression_returns(stmt->gotos.expression))
5207 statement_t *parent = stmt->base.parent;
5208 if (parent == NULL) /* top level goto */
5212 next = stmt->gotos.label->statement;
5213 if (next == NULL) /* missing label */
5218 case STATEMENT_LABEL:
5219 next = stmt->label.statement;
5222 case STATEMENT_CASE_LABEL:
5223 next = stmt->case_label.statement;
5226 case STATEMENT_WHILE: {
5227 while_statement_t const *const whiles = &stmt->whiles;
5228 expression_t const *const cond = whiles->condition;
5230 if (!expression_returns(cond))
5233 int const val = determine_truth(cond);
5236 check_reachable(whiles->body);
5241 next = stmt->base.next;
5245 case STATEMENT_DO_WHILE:
5246 next = stmt->do_while.body;
5249 case STATEMENT_FOR: {
5250 for_statement_t *const fors = &stmt->fors;
5252 if (fors->condition_reachable)
5254 fors->condition_reachable = true;
5256 expression_t const *const cond = fors->condition;
5261 } else if (expression_returns(cond)) {
5262 val = determine_truth(cond);
5268 check_reachable(fors->body);
5273 next = stmt->base.next;
5277 case STATEMENT_MS_TRY: {
5278 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5279 check_reachable(ms_try->try_statement);
5280 next = ms_try->final_statement;
5284 case STATEMENT_LEAVE: {
5285 statement_t *parent = stmt;
5287 parent = parent->base.parent;
5288 if (parent == NULL) /* __leave not within __try */
5291 if (parent->kind == STATEMENT_MS_TRY) {
5293 next = parent->ms_try.final_statement;
5301 panic("invalid statement kind");
5304 while (next == NULL) {
5305 next = last->base.parent;
5307 noreturn_candidate = false;
5309 type_t *const type = skip_typeref(current_function->base.type);
5310 assert(is_type_function(type));
5311 type_t *const ret = skip_typeref(type->function.return_type);
5312 if (warning.return_type &&
5313 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5314 is_type_valid(ret) &&
5315 !is_sym_main(current_function->base.base.symbol)) {
5316 warningf(&stmt->base.source_position,
5317 "control reaches end of non-void function");
5322 switch (next->kind) {
5323 case STATEMENT_INVALID:
5324 case STATEMENT_EMPTY:
5325 case STATEMENT_DECLARATION:
5326 case STATEMENT_EXPRESSION:
5328 case STATEMENT_RETURN:
5329 case STATEMENT_CONTINUE:
5330 case STATEMENT_BREAK:
5331 case STATEMENT_GOTO:
5332 case STATEMENT_LEAVE:
5333 panic("invalid control flow in function");
5335 case STATEMENT_COMPOUND:
5336 if (next->compound.stmt_expr) {
5342 case STATEMENT_SWITCH:
5343 case STATEMENT_LABEL:
5344 case STATEMENT_CASE_LABEL:
5346 next = next->base.next;
5349 case STATEMENT_WHILE: {
5351 if (next->base.reachable)
5353 next->base.reachable = true;
5355 while_statement_t const *const whiles = &next->whiles;
5356 expression_t const *const cond = whiles->condition;
5358 if (!expression_returns(cond))
5361 int const val = determine_truth(cond);
5364 check_reachable(whiles->body);
5370 next = next->base.next;
5374 case STATEMENT_DO_WHILE: {
5376 if (next->base.reachable)
5378 next->base.reachable = true;
5380 do_while_statement_t const *const dw = &next->do_while;
5381 expression_t const *const cond = dw->condition;
5383 if (!expression_returns(cond))
5386 int const val = determine_truth(cond);
5389 check_reachable(dw->body);
5395 next = next->base.next;
5399 case STATEMENT_FOR: {
5401 for_statement_t *const fors = &next->fors;
5403 fors->step_reachable = true;
5405 if (fors->condition_reachable)
5407 fors->condition_reachable = true;
5409 expression_t const *const cond = fors->condition;
5414 } else if (expression_returns(cond)) {
5415 val = determine_truth(cond);
5421 check_reachable(fors->body);
5427 next = next->base.next;
5431 case STATEMENT_MS_TRY:
5433 next = next->ms_try.final_statement;
5438 check_reachable(next);
5441 static void check_unreachable(statement_t* const stmt, void *const env)
5445 switch (stmt->kind) {
5446 case STATEMENT_DO_WHILE:
5447 if (!stmt->base.reachable) {
5448 expression_t const *const cond = stmt->do_while.condition;
5449 if (determine_truth(cond) >= 0) {
5450 warningf(&cond->base.source_position,
5451 "condition of do-while-loop is unreachable");
5456 case STATEMENT_FOR: {
5457 for_statement_t const* const fors = &stmt->fors;
5459 // if init and step are unreachable, cond is unreachable, too
5460 if (!stmt->base.reachable && !fors->step_reachable) {
5461 warningf(&stmt->base.source_position, "statement is unreachable");
5463 if (!stmt->base.reachable && fors->initialisation != NULL) {
5464 warningf(&fors->initialisation->base.source_position,
5465 "initialisation of for-statement is unreachable");
5468 if (!fors->condition_reachable && fors->condition != NULL) {
5469 warningf(&fors->condition->base.source_position,
5470 "condition of for-statement is unreachable");
5473 if (!fors->step_reachable && fors->step != NULL) {
5474 warningf(&fors->step->base.source_position,
5475 "step of for-statement is unreachable");
5481 case STATEMENT_COMPOUND:
5482 if (stmt->compound.statements != NULL)
5484 goto warn_unreachable;
5486 case STATEMENT_DECLARATION: {
5487 /* Only warn if there is at least one declarator with an initializer.
5488 * This typically occurs in switch statements. */
5489 declaration_statement_t const *const decl = &stmt->declaration;
5490 entity_t const * ent = decl->declarations_begin;
5491 entity_t const *const last = decl->declarations_end;
5493 for (;; ent = ent->base.next) {
5494 if (ent->kind == ENTITY_VARIABLE &&
5495 ent->variable.initializer != NULL) {
5496 goto warn_unreachable;
5506 if (!stmt->base.reachable)
5507 warningf(&stmt->base.source_position, "statement is unreachable");
5512 static void parse_external_declaration(void)
5514 /* function-definitions and declarations both start with declaration
5516 declaration_specifiers_t specifiers;
5517 memset(&specifiers, 0, sizeof(specifiers));
5519 add_anchor_token(';');
5520 parse_declaration_specifiers(&specifiers);
5521 rem_anchor_token(';');
5523 /* must be a declaration */
5524 if (token.type == ';') {
5525 parse_anonymous_declaration_rest(&specifiers);
5529 add_anchor_token(',');
5530 add_anchor_token('=');
5531 add_anchor_token(';');
5532 add_anchor_token('{');
5534 /* declarator is common to both function-definitions and declarations */
5535 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5537 rem_anchor_token('{');
5538 rem_anchor_token(';');
5539 rem_anchor_token('=');
5540 rem_anchor_token(',');
5542 /* must be a declaration */
5543 switch (token.type) {
5547 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5552 /* must be a function definition */
5553 parse_kr_declaration_list(ndeclaration);
5555 if (token.type != '{') {
5556 parse_error_expected("while parsing function definition", '{', NULL);
5557 eat_until_matching_token(';');
5561 assert(is_declaration(ndeclaration));
5562 type_t *const orig_type = ndeclaration->declaration.type;
5563 type_t * type = skip_typeref(orig_type);
5565 if (!is_type_function(type)) {
5566 if (is_type_valid(type)) {
5567 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5568 type, ndeclaration->base.symbol);
5572 } else if (is_typeref(orig_type)) {
5574 errorf(&ndeclaration->base.source_position,
5575 "type of function definition '%#T' is a typedef",
5576 orig_type, ndeclaration->base.symbol);
5579 if (warning.aggregate_return &&
5580 is_type_compound(skip_typeref(type->function.return_type))) {
5581 warningf(HERE, "function '%Y' returns an aggregate",
5582 ndeclaration->base.symbol);
5584 if (warning.traditional && !type->function.unspecified_parameters) {
5585 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5586 ndeclaration->base.symbol);
5588 if (warning.old_style_definition && type->function.unspecified_parameters) {
5589 warningf(HERE, "old-style function definition '%Y'",
5590 ndeclaration->base.symbol);
5593 /* §6.7.5.3:14 a function definition with () means no
5594 * parameters (and not unspecified parameters) */
5595 if (type->function.unspecified_parameters &&
5596 type->function.parameters == NULL) {
5597 type_t *copy = duplicate_type(type);
5598 copy->function.unspecified_parameters = false;
5599 type = identify_new_type(copy);
5601 ndeclaration->declaration.type = type;
5604 entity_t *const entity = record_entity(ndeclaration, true);
5605 assert(entity->kind == ENTITY_FUNCTION);
5606 assert(ndeclaration->kind == ENTITY_FUNCTION);
5608 function_t *function = &entity->function;
5609 if (ndeclaration != entity) {
5610 function->parameters = ndeclaration->function.parameters;
5612 assert(is_declaration(entity));
5613 type = skip_typeref(entity->declaration.type);
5615 /* push function parameters and switch scope */
5616 size_t const top = environment_top();
5617 scope_t *old_scope = scope_push(&function->parameters);
5619 entity_t *parameter = function->parameters.entities;
5620 for (; parameter != NULL; parameter = parameter->base.next) {
5621 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5622 parameter->base.parent_scope = current_scope;
5624 assert(parameter->base.parent_scope == NULL
5625 || parameter->base.parent_scope == current_scope);
5626 parameter->base.parent_scope = current_scope;
5627 if (parameter->base.symbol == NULL) {
5628 errorf(¶meter->base.source_position, "parameter name omitted");
5631 environment_push(parameter);
5634 if (function->statement != NULL) {
5635 parser_error_multiple_definition(entity, HERE);
5638 /* parse function body */
5639 int label_stack_top = label_top();
5640 function_t *old_current_function = current_function;
5641 entity_t *old_current_entity = current_entity;
5642 current_function = function;
5643 current_entity = (entity_t*) function;
5644 current_parent = NULL;
5647 goto_anchor = &goto_first;
5649 label_anchor = &label_first;
5651 statement_t *const body = parse_compound_statement(false);
5652 function->statement = body;
5655 check_declarations();
5656 if (warning.return_type ||
5657 warning.unreachable_code ||
5658 (warning.missing_noreturn
5659 && !(function->base.modifiers & DM_NORETURN))) {
5660 noreturn_candidate = true;
5661 check_reachable(body);
5662 if (warning.unreachable_code)
5663 walk_statements(body, check_unreachable, NULL);
5664 if (warning.missing_noreturn &&
5665 noreturn_candidate &&
5666 !(function->base.modifiers & DM_NORETURN)) {
5667 warningf(&body->base.source_position,
5668 "function '%#T' is candidate for attribute 'noreturn'",
5669 type, entity->base.symbol);
5673 assert(current_parent == NULL);
5674 assert(current_function == function);
5675 assert(current_entity == (entity_t*) function);
5676 current_entity = old_current_entity;
5677 current_function = old_current_function;
5678 label_pop_to(label_stack_top);
5681 assert(current_scope == &function->parameters);
5682 scope_pop(old_scope);
5683 environment_pop_to(top);
5686 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5687 source_position_t *source_position,
5688 const symbol_t *symbol)
5690 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5692 type->bitfield.base_type = base_type;
5693 type->bitfield.size_expression = size;
5696 type_t *skipped_type = skip_typeref(base_type);
5697 if (!is_type_integer(skipped_type)) {
5698 errorf(HERE, "bitfield base type '%T' is not an integer type",
5702 bit_size = get_type_size(base_type) * 8;
5705 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5706 long v = fold_constant_to_int(size);
5707 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5710 errorf(source_position, "negative width in bit-field '%Y'",
5712 } else if (v == 0 && symbol != NULL) {
5713 errorf(source_position, "zero width for bit-field '%Y'",
5715 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5716 errorf(source_position, "width of '%Y' exceeds its type",
5719 type->bitfield.bit_size = v;
5726 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5728 entity_t *iter = compound->members.entities;
5729 for (; iter != NULL; iter = iter->base.next) {
5730 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5733 if (iter->base.symbol == symbol) {
5735 } else if (iter->base.symbol == NULL) {
5736 /* search in anonymous structs and unions */
5737 type_t *type = skip_typeref(iter->declaration.type);
5738 if (is_type_compound(type)) {
5739 if (find_compound_entry(type->compound.compound, symbol)
5750 static void check_deprecated(const source_position_t *source_position,
5751 const entity_t *entity)
5753 if (!warning.deprecated_declarations)
5755 if (!is_declaration(entity))
5757 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5760 char const *const prefix = get_entity_kind_name(entity->kind);
5761 const char *deprecated_string
5762 = get_deprecated_string(entity->declaration.attributes);
5763 if (deprecated_string != NULL) {
5764 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5765 prefix, entity->base.symbol, &entity->base.source_position,
5768 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5769 entity->base.symbol, &entity->base.source_position);
5774 static expression_t *create_select(const source_position_t *pos,
5776 type_qualifiers_t qualifiers,
5779 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5781 check_deprecated(pos, entry);
5783 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5784 select->select.compound = addr;
5785 select->select.compound_entry = entry;
5787 type_t *entry_type = entry->declaration.type;
5788 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5790 /* we always do the auto-type conversions; the & and sizeof parser contains
5791 * code to revert this! */
5792 select->base.type = automatic_type_conversion(res_type);
5793 if (res_type->kind == TYPE_BITFIELD) {
5794 select->base.type = res_type->bitfield.base_type;
5801 * Find entry with symbol in compound. Search anonymous structs and unions and
5802 * creates implicit select expressions for them.
5803 * Returns the adress for the innermost compound.
5805 static expression_t *find_create_select(const source_position_t *pos,
5807 type_qualifiers_t qualifiers,
5808 compound_t *compound, symbol_t *symbol)
5810 entity_t *iter = compound->members.entities;
5811 for (; iter != NULL; iter = iter->base.next) {
5812 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5815 symbol_t *iter_symbol = iter->base.symbol;
5816 if (iter_symbol == NULL) {
5817 type_t *type = iter->declaration.type;
5818 if (type->kind != TYPE_COMPOUND_STRUCT
5819 && type->kind != TYPE_COMPOUND_UNION)
5822 compound_t *sub_compound = type->compound.compound;
5824 if (find_compound_entry(sub_compound, symbol) == NULL)
5827 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5828 sub_addr->base.source_position = *pos;
5829 sub_addr->select.implicit = true;
5830 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5834 if (iter_symbol == symbol) {
5835 return create_select(pos, addr, qualifiers, iter);
5842 static void parse_compound_declarators(compound_t *compound,
5843 const declaration_specifiers_t *specifiers)
5848 if (token.type == ':') {
5849 source_position_t source_position = *HERE;
5852 type_t *base_type = specifiers->type;
5853 expression_t *size = parse_constant_expression();
5855 type_t *type = make_bitfield_type(base_type, size,
5856 &source_position, NULL);
5858 attribute_t *attributes = parse_attributes(NULL);
5859 attribute_t **anchor = &attributes;
5860 while (*anchor != NULL)
5861 anchor = &(*anchor)->next;
5862 *anchor = specifiers->attributes;
5864 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5865 entity->base.namespc = NAMESPACE_NORMAL;
5866 entity->base.source_position = source_position;
5867 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5868 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5869 entity->declaration.type = type;
5870 entity->declaration.attributes = attributes;
5872 if (attributes != NULL) {
5873 handle_entity_attributes(attributes, entity);
5875 append_entity(&compound->members, entity);
5877 entity = parse_declarator(specifiers,
5878 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5879 if (entity->kind == ENTITY_TYPEDEF) {
5880 errorf(&entity->base.source_position,
5881 "typedef not allowed as compound member");
5883 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5885 /* make sure we don't define a symbol multiple times */
5886 symbol_t *symbol = entity->base.symbol;
5887 if (symbol != NULL) {
5888 entity_t *prev = find_compound_entry(compound, symbol);
5890 errorf(&entity->base.source_position,
5891 "multiple declarations of symbol '%Y' (declared %P)",
5892 symbol, &prev->base.source_position);
5896 if (token.type == ':') {
5897 source_position_t source_position = *HERE;
5899 expression_t *size = parse_constant_expression();
5901 type_t *type = entity->declaration.type;
5902 type_t *bitfield_type = make_bitfield_type(type, size,
5903 &source_position, entity->base.symbol);
5905 attribute_t *attributes = parse_attributes(NULL);
5906 entity->declaration.type = bitfield_type;
5907 handle_entity_attributes(attributes, entity);
5909 type_t *orig_type = entity->declaration.type;
5910 type_t *type = skip_typeref(orig_type);
5911 if (is_type_function(type)) {
5912 errorf(&entity->base.source_position,
5913 "compound member '%Y' must not have function type '%T'",
5914 entity->base.symbol, orig_type);
5915 } else if (is_type_incomplete(type)) {
5916 /* §6.7.2.1:16 flexible array member */
5917 if (!is_type_array(type) ||
5918 token.type != ';' ||
5919 look_ahead(1)->type != '}') {
5920 errorf(&entity->base.source_position,
5921 "compound member '%Y' has incomplete type '%T'",
5922 entity->base.symbol, orig_type);
5927 append_entity(&compound->members, entity);
5930 } while (next_if(','));
5931 expect(';', end_error);
5934 anonymous_entity = NULL;
5937 static void parse_compound_type_entries(compound_t *compound)
5940 add_anchor_token('}');
5942 while (token.type != '}') {
5943 if (token.type == T_EOF) {
5944 errorf(HERE, "EOF while parsing struct");
5947 declaration_specifiers_t specifiers;
5948 memset(&specifiers, 0, sizeof(specifiers));
5949 parse_declaration_specifiers(&specifiers);
5951 parse_compound_declarators(compound, &specifiers);
5953 rem_anchor_token('}');
5957 compound->complete = true;
5960 static type_t *parse_typename(void)
5962 declaration_specifiers_t specifiers;
5963 memset(&specifiers, 0, sizeof(specifiers));
5964 parse_declaration_specifiers(&specifiers);
5965 if (specifiers.storage_class != STORAGE_CLASS_NONE
5966 || specifiers.thread_local) {
5967 /* TODO: improve error message, user does probably not know what a
5968 * storage class is...
5970 errorf(HERE, "typename must not have a storage class");
5973 type_t *result = parse_abstract_declarator(specifiers.type);
5981 typedef expression_t* (*parse_expression_function)(void);
5982 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5984 typedef struct expression_parser_function_t expression_parser_function_t;
5985 struct expression_parser_function_t {
5986 parse_expression_function parser;
5987 precedence_t infix_precedence;
5988 parse_expression_infix_function infix_parser;
5991 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5994 * Prints an error message if an expression was expected but not read
5996 static expression_t *expected_expression_error(void)
5998 /* skip the error message if the error token was read */
5999 if (token.type != T_ERROR) {
6000 errorf(HERE, "expected expression, got token %K", &token);
6004 return create_invalid_expression();
6007 static type_t *get_string_type(void)
6009 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6012 static type_t *get_wide_string_type(void)
6014 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6018 * Parse a string constant.
6020 static expression_t *parse_string_literal(void)
6022 source_position_t begin = token.source_position;
6023 string_t res = token.literal;
6024 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6027 while (token.type == T_STRING_LITERAL
6028 || token.type == T_WIDE_STRING_LITERAL) {
6029 warn_string_concat(&token.source_position);
6030 res = concat_strings(&res, &token.literal);
6032 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6035 expression_t *literal;
6037 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6038 literal->base.type = get_wide_string_type();
6040 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6041 literal->base.type = get_string_type();
6043 literal->base.source_position = begin;
6044 literal->literal.value = res;
6050 * Parse a boolean constant.
6052 static expression_t *parse_boolean_literal(bool value)
6054 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6055 literal->base.source_position = token.source_position;
6056 literal->base.type = type_bool;
6057 literal->literal.value.begin = value ? "true" : "false";
6058 literal->literal.value.size = value ? 4 : 5;
6064 static void warn_traditional_suffix(void)
6066 if (!warning.traditional)
6068 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6072 static void check_integer_suffix(void)
6074 symbol_t *suffix = token.symbol;
6078 bool not_traditional = false;
6079 const char *c = suffix->string;
6080 if (*c == 'l' || *c == 'L') {
6083 not_traditional = true;
6085 if (*c == 'u' || *c == 'U') {
6088 } else if (*c == 'u' || *c == 'U') {
6089 not_traditional = true;
6092 } else if (*c == 'u' || *c == 'U') {
6093 not_traditional = true;
6095 if (*c == 'l' || *c == 'L') {
6103 errorf(&token.source_position,
6104 "invalid suffix '%s' on integer constant", suffix->string);
6105 } else if (not_traditional) {
6106 warn_traditional_suffix();
6110 static type_t *check_floatingpoint_suffix(void)
6112 symbol_t *suffix = token.symbol;
6113 type_t *type = type_double;
6117 bool not_traditional = false;
6118 const char *c = suffix->string;
6119 if (*c == 'f' || *c == 'F') {
6122 } else if (*c == 'l' || *c == 'L') {
6124 type = type_long_double;
6127 errorf(&token.source_position,
6128 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6129 } else if (not_traditional) {
6130 warn_traditional_suffix();
6137 * Parse an integer constant.
6139 static expression_t *parse_number_literal(void)
6141 expression_kind_t kind;
6144 switch (token.type) {
6146 kind = EXPR_LITERAL_INTEGER;
6147 check_integer_suffix();
6150 case T_INTEGER_OCTAL:
6151 kind = EXPR_LITERAL_INTEGER_OCTAL;
6152 check_integer_suffix();
6155 case T_INTEGER_HEXADECIMAL:
6156 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6157 check_integer_suffix();
6160 case T_FLOATINGPOINT:
6161 kind = EXPR_LITERAL_FLOATINGPOINT;
6162 type = check_floatingpoint_suffix();
6164 case T_FLOATINGPOINT_HEXADECIMAL:
6165 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6166 type = check_floatingpoint_suffix();
6169 panic("unexpected token type in parse_number_literal");
6172 expression_t *literal = allocate_expression_zero(kind);
6173 literal->base.source_position = token.source_position;
6174 literal->base.type = type;
6175 literal->literal.value = token.literal;
6176 literal->literal.suffix = token.symbol;
6179 /* integer type depends on the size of the number and the size
6180 * representable by the types. The backend/codegeneration has to determine
6183 determine_literal_type(&literal->literal);
6188 * Parse a character constant.
6190 static expression_t *parse_character_constant(void)
6192 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6193 literal->base.source_position = token.source_position;
6194 literal->base.type = c_mode & _CXX ? type_char : type_int;
6195 literal->literal.value = token.literal;
6197 size_t len = literal->literal.value.size;
6199 if (!GNU_MODE && !(c_mode & _C99)) {
6200 errorf(HERE, "more than 1 character in character constant");
6201 } else if (warning.multichar) {
6202 literal->base.type = type_int;
6203 warningf(HERE, "multi-character character constant");
6212 * Parse a wide character constant.
6214 static expression_t *parse_wide_character_constant(void)
6216 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6217 literal->base.source_position = token.source_position;
6218 literal->base.type = type_int;
6219 literal->literal.value = token.literal;
6221 size_t len = wstrlen(&literal->literal.value);
6223 warningf(HERE, "multi-character character constant");
6230 static entity_t *create_implicit_function(symbol_t *symbol,
6231 const source_position_t *source_position)
6233 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6234 ntype->function.return_type = type_int;
6235 ntype->function.unspecified_parameters = true;
6236 ntype->function.linkage = LINKAGE_C;
6237 type_t *type = identify_new_type(ntype);
6239 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6240 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6241 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6242 entity->declaration.type = type;
6243 entity->declaration.implicit = true;
6244 entity->base.namespc = NAMESPACE_NORMAL;
6245 entity->base.symbol = symbol;
6246 entity->base.source_position = *source_position;
6248 if (current_scope != NULL) {
6249 bool strict_prototypes_old = warning.strict_prototypes;
6250 warning.strict_prototypes = false;
6251 record_entity(entity, false);
6252 warning.strict_prototypes = strict_prototypes_old;
6259 * Performs automatic type cast as described in §6.3.2.1.
6261 * @param orig_type the original type
6263 static type_t *automatic_type_conversion(type_t *orig_type)
6265 type_t *type = skip_typeref(orig_type);
6266 if (is_type_array(type)) {
6267 array_type_t *array_type = &type->array;
6268 type_t *element_type = array_type->element_type;
6269 unsigned qualifiers = array_type->base.qualifiers;
6271 return make_pointer_type(element_type, qualifiers);
6274 if (is_type_function(type)) {
6275 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6282 * reverts the automatic casts of array to pointer types and function
6283 * to function-pointer types as defined §6.3.2.1
6285 type_t *revert_automatic_type_conversion(const expression_t *expression)
6287 switch (expression->kind) {
6288 case EXPR_REFERENCE: {
6289 entity_t *entity = expression->reference.entity;
6290 if (is_declaration(entity)) {
6291 return entity->declaration.type;
6292 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6293 return entity->enum_value.enum_type;
6295 panic("no declaration or enum in reference");
6300 entity_t *entity = expression->select.compound_entry;
6301 assert(is_declaration(entity));
6302 type_t *type = entity->declaration.type;
6303 return get_qualified_type(type,
6304 expression->base.type->base.qualifiers);
6307 case EXPR_UNARY_DEREFERENCE: {
6308 const expression_t *const value = expression->unary.value;
6309 type_t *const type = skip_typeref(value->base.type);
6310 if (!is_type_pointer(type))
6311 return type_error_type;
6312 return type->pointer.points_to;
6315 case EXPR_ARRAY_ACCESS: {
6316 const expression_t *array_ref = expression->array_access.array_ref;
6317 type_t *type_left = skip_typeref(array_ref->base.type);
6318 if (!is_type_pointer(type_left))
6319 return type_error_type;
6320 return type_left->pointer.points_to;
6323 case EXPR_STRING_LITERAL: {
6324 size_t size = expression->string_literal.value.size;
6325 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6328 case EXPR_WIDE_STRING_LITERAL: {
6329 size_t size = wstrlen(&expression->string_literal.value);
6330 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6333 case EXPR_COMPOUND_LITERAL:
6334 return expression->compound_literal.type;
6339 return expression->base.type;
6343 * Find an entity matching a symbol in a scope.
6344 * Uses current scope if scope is NULL
6346 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6347 namespace_tag_t namespc)
6349 if (scope == NULL) {
6350 return get_entity(symbol, namespc);
6353 /* we should optimize here, if scope grows above a certain size we should
6354 construct a hashmap here... */
6355 entity_t *entity = scope->entities;
6356 for ( ; entity != NULL; entity = entity->base.next) {
6357 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6364 static entity_t *parse_qualified_identifier(void)
6366 /* namespace containing the symbol */
6368 source_position_t pos;
6369 const scope_t *lookup_scope = NULL;
6371 if (next_if(T_COLONCOLON))
6372 lookup_scope = &unit->scope;
6376 if (token.type != T_IDENTIFIER) {
6377 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6378 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6380 symbol = token.symbol;
6385 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6387 if (!next_if(T_COLONCOLON))
6390 switch (entity->kind) {
6391 case ENTITY_NAMESPACE:
6392 lookup_scope = &entity->namespacee.members;
6397 lookup_scope = &entity->compound.members;
6400 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6401 symbol, get_entity_kind_name(entity->kind));
6406 if (entity == NULL) {
6407 if (!strict_mode && token.type == '(') {
6408 /* an implicitly declared function */
6409 if (warning.error_implicit_function_declaration) {
6410 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6411 } else if (warning.implicit_function_declaration) {
6412 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6415 entity = create_implicit_function(symbol, &pos);
6417 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6418 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6425 /* skip further qualifications */
6426 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6428 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6431 static expression_t *parse_reference(void)
6433 entity_t *entity = parse_qualified_identifier();
6436 if (is_declaration(entity)) {
6437 orig_type = entity->declaration.type;
6438 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6439 orig_type = entity->enum_value.enum_type;
6441 panic("expected declaration or enum value in reference");
6444 /* we always do the auto-type conversions; the & and sizeof parser contains
6445 * code to revert this! */
6446 type_t *type = automatic_type_conversion(orig_type);
6448 expression_kind_t kind = EXPR_REFERENCE;
6449 if (entity->kind == ENTITY_ENUM_VALUE)
6450 kind = EXPR_REFERENCE_ENUM_VALUE;
6452 expression_t *expression = allocate_expression_zero(kind);
6453 expression->reference.entity = entity;
6454 expression->base.type = type;
6456 /* this declaration is used */
6457 if (is_declaration(entity)) {
6458 entity->declaration.used = true;
6461 if (entity->base.parent_scope != file_scope
6462 && (current_function != NULL
6463 && entity->base.parent_scope->depth < current_function->parameters.depth)
6464 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6465 if (entity->kind == ENTITY_VARIABLE) {
6466 /* access of a variable from an outer function */
6467 entity->variable.address_taken = true;
6468 } else if (entity->kind == ENTITY_PARAMETER) {
6469 entity->parameter.address_taken = true;
6471 current_function->need_closure = true;
6474 check_deprecated(HERE, entity);
6476 if (warning.init_self && entity == current_init_decl && !in_type_prop
6477 && entity->kind == ENTITY_VARIABLE) {
6478 current_init_decl = NULL;
6479 warningf(HERE, "variable '%#T' is initialized by itself",
6480 entity->declaration.type, entity->base.symbol);
6486 static bool semantic_cast(expression_t *cast)
6488 expression_t *expression = cast->unary.value;
6489 type_t *orig_dest_type = cast->base.type;
6490 type_t *orig_type_right = expression->base.type;
6491 type_t const *dst_type = skip_typeref(orig_dest_type);
6492 type_t const *src_type = skip_typeref(orig_type_right);
6493 source_position_t const *pos = &cast->base.source_position;
6495 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6496 if (dst_type == type_void)
6499 /* only integer and pointer can be casted to pointer */
6500 if (is_type_pointer(dst_type) &&
6501 !is_type_pointer(src_type) &&
6502 !is_type_integer(src_type) &&
6503 is_type_valid(src_type)) {
6504 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6508 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6509 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6513 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6514 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6518 if (warning.cast_qual &&
6519 is_type_pointer(src_type) &&
6520 is_type_pointer(dst_type)) {
6521 type_t *src = skip_typeref(src_type->pointer.points_to);
6522 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6523 unsigned missing_qualifiers =
6524 src->base.qualifiers & ~dst->base.qualifiers;
6525 if (missing_qualifiers != 0) {
6527 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6528 missing_qualifiers, orig_type_right);
6534 static expression_t *parse_compound_literal(type_t *type)
6536 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6538 parse_initializer_env_t env;
6541 env.must_be_constant = false;
6542 initializer_t *initializer = parse_initializer(&env);
6545 expression->compound_literal.initializer = initializer;
6546 expression->compound_literal.type = type;
6547 expression->base.type = automatic_type_conversion(type);
6553 * Parse a cast expression.
6555 static expression_t *parse_cast(void)
6557 add_anchor_token(')');
6559 source_position_t source_position = token.source_position;
6561 type_t *type = parse_typename();
6563 rem_anchor_token(')');
6564 expect(')', end_error);
6566 if (token.type == '{') {
6567 return parse_compound_literal(type);
6570 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6571 cast->base.source_position = source_position;
6573 expression_t *value = parse_subexpression(PREC_CAST);
6574 cast->base.type = type;
6575 cast->unary.value = value;
6577 if (! semantic_cast(cast)) {
6578 /* TODO: record the error in the AST. else it is impossible to detect it */
6583 return create_invalid_expression();
6587 * Parse a statement expression.
6589 static expression_t *parse_statement_expression(void)
6591 add_anchor_token(')');
6593 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6595 statement_t *statement = parse_compound_statement(true);
6596 statement->compound.stmt_expr = true;
6597 expression->statement.statement = statement;
6599 /* find last statement and use its type */
6600 type_t *type = type_void;
6601 const statement_t *stmt = statement->compound.statements;
6603 while (stmt->base.next != NULL)
6604 stmt = stmt->base.next;
6606 if (stmt->kind == STATEMENT_EXPRESSION) {
6607 type = stmt->expression.expression->base.type;
6609 } else if (warning.other) {
6610 warningf(&expression->base.source_position, "empty statement expression ({})");
6612 expression->base.type = type;
6614 rem_anchor_token(')');
6615 expect(')', end_error);
6622 * Parse a parenthesized expression.
6624 static expression_t *parse_parenthesized_expression(void)
6628 switch (token.type) {
6630 /* gcc extension: a statement expression */
6631 return parse_statement_expression();
6635 return parse_cast();
6637 if (is_typedef_symbol(token.symbol)) {
6638 return parse_cast();
6642 add_anchor_token(')');
6643 expression_t *result = parse_expression();
6644 result->base.parenthesized = true;
6645 rem_anchor_token(')');
6646 expect(')', end_error);
6652 static expression_t *parse_function_keyword(void)
6656 if (current_function == NULL) {
6657 errorf(HERE, "'__func__' used outside of a function");
6660 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6661 expression->base.type = type_char_ptr;
6662 expression->funcname.kind = FUNCNAME_FUNCTION;
6669 static expression_t *parse_pretty_function_keyword(void)
6671 if (current_function == NULL) {
6672 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6675 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6676 expression->base.type = type_char_ptr;
6677 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6679 eat(T___PRETTY_FUNCTION__);
6684 static expression_t *parse_funcsig_keyword(void)
6686 if (current_function == NULL) {
6687 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6690 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6691 expression->base.type = type_char_ptr;
6692 expression->funcname.kind = FUNCNAME_FUNCSIG;
6699 static expression_t *parse_funcdname_keyword(void)
6701 if (current_function == NULL) {
6702 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6705 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6706 expression->base.type = type_char_ptr;
6707 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6709 eat(T___FUNCDNAME__);
6714 static designator_t *parse_designator(void)
6716 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6717 result->source_position = *HERE;
6719 if (token.type != T_IDENTIFIER) {
6720 parse_error_expected("while parsing member designator",
6721 T_IDENTIFIER, NULL);
6724 result->symbol = token.symbol;
6727 designator_t *last_designator = result;
6730 if (token.type != T_IDENTIFIER) {
6731 parse_error_expected("while parsing member designator",
6732 T_IDENTIFIER, NULL);
6735 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6736 designator->source_position = *HERE;
6737 designator->symbol = token.symbol;
6740 last_designator->next = designator;
6741 last_designator = designator;
6745 add_anchor_token(']');
6746 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6747 designator->source_position = *HERE;
6748 designator->array_index = parse_expression();
6749 rem_anchor_token(']');
6750 expect(']', end_error);
6751 if (designator->array_index == NULL) {
6755 last_designator->next = designator;
6756 last_designator = designator;
6768 * Parse the __builtin_offsetof() expression.
6770 static expression_t *parse_offsetof(void)
6772 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6773 expression->base.type = type_size_t;
6775 eat(T___builtin_offsetof);
6777 expect('(', end_error);
6778 add_anchor_token(',');
6779 type_t *type = parse_typename();
6780 rem_anchor_token(',');
6781 expect(',', end_error);
6782 add_anchor_token(')');
6783 designator_t *designator = parse_designator();
6784 rem_anchor_token(')');
6785 expect(')', end_error);
6787 expression->offsetofe.type = type;
6788 expression->offsetofe.designator = designator;
6791 memset(&path, 0, sizeof(path));
6792 path.top_type = type;
6793 path.path = NEW_ARR_F(type_path_entry_t, 0);
6795 descend_into_subtype(&path);
6797 if (!walk_designator(&path, designator, true)) {
6798 return create_invalid_expression();
6801 DEL_ARR_F(path.path);
6805 return create_invalid_expression();
6809 * Parses a _builtin_va_start() expression.
6811 static expression_t *parse_va_start(void)
6813 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6815 eat(T___builtin_va_start);
6817 expect('(', end_error);
6818 add_anchor_token(',');
6819 expression->va_starte.ap = parse_assignment_expression();
6820 rem_anchor_token(',');
6821 expect(',', end_error);
6822 expression_t *const expr = parse_assignment_expression();
6823 if (expr->kind == EXPR_REFERENCE) {
6824 entity_t *const entity = expr->reference.entity;
6825 if (!current_function->base.type->function.variadic) {
6826 errorf(&expr->base.source_position,
6827 "'va_start' used in non-variadic function");
6828 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6829 entity->base.next != NULL ||
6830 entity->kind != ENTITY_PARAMETER) {
6831 errorf(&expr->base.source_position,
6832 "second argument of 'va_start' must be last parameter of the current function");
6834 expression->va_starte.parameter = &entity->variable;
6836 expect(')', end_error);
6839 expect(')', end_error);
6841 return create_invalid_expression();
6845 * Parses a __builtin_va_arg() expression.
6847 static expression_t *parse_va_arg(void)
6849 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6851 eat(T___builtin_va_arg);
6853 expect('(', end_error);
6855 ap.expression = parse_assignment_expression();
6856 expression->va_arge.ap = ap.expression;
6857 check_call_argument(type_valist, &ap, 1);
6859 expect(',', end_error);
6860 expression->base.type = parse_typename();
6861 expect(')', end_error);
6865 return create_invalid_expression();
6869 * Parses a __builtin_va_copy() expression.
6871 static expression_t *parse_va_copy(void)
6873 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6875 eat(T___builtin_va_copy);
6877 expect('(', end_error);
6878 expression_t *dst = parse_assignment_expression();
6879 assign_error_t error = semantic_assign(type_valist, dst);
6880 report_assign_error(error, type_valist, dst, "call argument 1",
6881 &dst->base.source_position);
6882 expression->va_copye.dst = dst;
6884 expect(',', end_error);
6886 call_argument_t src;
6887 src.expression = parse_assignment_expression();
6888 check_call_argument(type_valist, &src, 2);
6889 expression->va_copye.src = src.expression;
6890 expect(')', end_error);
6894 return create_invalid_expression();
6898 * Parses a __builtin_constant_p() expression.
6900 static expression_t *parse_builtin_constant(void)
6902 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6904 eat(T___builtin_constant_p);
6906 expect('(', end_error);
6907 add_anchor_token(')');
6908 expression->builtin_constant.value = parse_assignment_expression();
6909 rem_anchor_token(')');
6910 expect(')', end_error);
6911 expression->base.type = type_int;
6915 return create_invalid_expression();
6919 * Parses a __builtin_types_compatible_p() expression.
6921 static expression_t *parse_builtin_types_compatible(void)
6923 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6925 eat(T___builtin_types_compatible_p);
6927 expect('(', end_error);
6928 add_anchor_token(')');
6929 add_anchor_token(',');
6930 expression->builtin_types_compatible.left = parse_typename();
6931 rem_anchor_token(',');
6932 expect(',', end_error);
6933 expression->builtin_types_compatible.right = parse_typename();
6934 rem_anchor_token(')');
6935 expect(')', end_error);
6936 expression->base.type = type_int;
6940 return create_invalid_expression();
6944 * Parses a __builtin_is_*() compare expression.
6946 static expression_t *parse_compare_builtin(void)
6948 expression_t *expression;
6950 switch (token.type) {
6951 case T___builtin_isgreater:
6952 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6954 case T___builtin_isgreaterequal:
6955 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6957 case T___builtin_isless:
6958 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6960 case T___builtin_islessequal:
6961 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6963 case T___builtin_islessgreater:
6964 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6966 case T___builtin_isunordered:
6967 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6970 internal_errorf(HERE, "invalid compare builtin found");
6972 expression->base.source_position = *HERE;
6975 expect('(', end_error);
6976 expression->binary.left = parse_assignment_expression();
6977 expect(',', end_error);
6978 expression->binary.right = parse_assignment_expression();
6979 expect(')', end_error);
6981 type_t *const orig_type_left = expression->binary.left->base.type;
6982 type_t *const orig_type_right = expression->binary.right->base.type;
6984 type_t *const type_left = skip_typeref(orig_type_left);
6985 type_t *const type_right = skip_typeref(orig_type_right);
6986 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6987 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6988 type_error_incompatible("invalid operands in comparison",
6989 &expression->base.source_position, orig_type_left, orig_type_right);
6992 semantic_comparison(&expression->binary);
6997 return create_invalid_expression();
7001 * Parses a MS assume() expression.
7003 static expression_t *parse_assume(void)
7005 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7009 expect('(', end_error);
7010 add_anchor_token(')');
7011 expression->unary.value = parse_assignment_expression();
7012 rem_anchor_token(')');
7013 expect(')', end_error);
7015 expression->base.type = type_void;
7018 return create_invalid_expression();
7022 * Return the declaration for a given label symbol or create a new one.
7024 * @param symbol the symbol of the label
7026 static label_t *get_label(symbol_t *symbol)
7029 assert(current_function != NULL);
7031 label = get_entity(symbol, NAMESPACE_LABEL);
7032 /* if we found a local label, we already created the declaration */
7033 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7034 if (label->base.parent_scope != current_scope) {
7035 assert(label->base.parent_scope->depth < current_scope->depth);
7036 current_function->goto_to_outer = true;
7038 return &label->label;
7041 label = get_entity(symbol, NAMESPACE_LABEL);
7042 /* if we found a label in the same function, then we already created the
7045 && label->base.parent_scope == ¤t_function->parameters) {
7046 return &label->label;
7049 /* otherwise we need to create a new one */
7050 label = allocate_entity_zero(ENTITY_LABEL);
7051 label->base.namespc = NAMESPACE_LABEL;
7052 label->base.symbol = symbol;
7056 return &label->label;
7060 * Parses a GNU && label address expression.
7062 static expression_t *parse_label_address(void)
7064 source_position_t source_position = token.source_position;
7066 if (token.type != T_IDENTIFIER) {
7067 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7070 symbol_t *symbol = token.symbol;
7073 label_t *label = get_label(symbol);
7075 label->address_taken = true;
7077 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7078 expression->base.source_position = source_position;
7080 /* label address is threaten as a void pointer */
7081 expression->base.type = type_void_ptr;
7082 expression->label_address.label = label;
7085 return create_invalid_expression();
7089 * Parse a microsoft __noop expression.
7091 static expression_t *parse_noop_expression(void)
7093 /* the result is a (int)0 */
7094 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7095 literal->base.type = type_int;
7096 literal->base.source_position = token.source_position;
7097 literal->literal.value.begin = "__noop";
7098 literal->literal.value.size = 6;
7102 if (token.type == '(') {
7103 /* parse arguments */
7105 add_anchor_token(')');
7106 add_anchor_token(',');
7108 if (token.type != ')') do {
7109 (void)parse_assignment_expression();
7110 } while (next_if(','));
7112 rem_anchor_token(',');
7113 rem_anchor_token(')');
7114 expect(')', end_error);
7121 * Parses a primary expression.
7123 static expression_t *parse_primary_expression(void)
7125 switch (token.type) {
7126 case T_false: return parse_boolean_literal(false);
7127 case T_true: return parse_boolean_literal(true);
7129 case T_INTEGER_OCTAL:
7130 case T_INTEGER_HEXADECIMAL:
7131 case T_FLOATINGPOINT:
7132 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7133 case T_CHARACTER_CONSTANT: return parse_character_constant();
7134 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7135 case T_STRING_LITERAL:
7136 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7137 case T___FUNCTION__:
7138 case T___func__: return parse_function_keyword();
7139 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7140 case T___FUNCSIG__: return parse_funcsig_keyword();
7141 case T___FUNCDNAME__: return parse_funcdname_keyword();
7142 case T___builtin_offsetof: return parse_offsetof();
7143 case T___builtin_va_start: return parse_va_start();
7144 case T___builtin_va_arg: return parse_va_arg();
7145 case T___builtin_va_copy: return parse_va_copy();
7146 case T___builtin_isgreater:
7147 case T___builtin_isgreaterequal:
7148 case T___builtin_isless:
7149 case T___builtin_islessequal:
7150 case T___builtin_islessgreater:
7151 case T___builtin_isunordered: return parse_compare_builtin();
7152 case T___builtin_constant_p: return parse_builtin_constant();
7153 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7154 case T__assume: return parse_assume();
7157 return parse_label_address();
7160 case '(': return parse_parenthesized_expression();
7161 case T___noop: return parse_noop_expression();
7163 /* Gracefully handle type names while parsing expressions. */
7165 return parse_reference();
7167 if (!is_typedef_symbol(token.symbol)) {
7168 return parse_reference();
7172 source_position_t const pos = *HERE;
7173 type_t const *const type = parse_typename();
7174 errorf(&pos, "encountered type '%T' while parsing expression", type);
7175 return create_invalid_expression();
7179 errorf(HERE, "unexpected token %K, expected an expression", &token);
7181 return create_invalid_expression();
7185 * Check if the expression has the character type and issue a warning then.
7187 static void check_for_char_index_type(const expression_t *expression)
7189 type_t *const type = expression->base.type;
7190 const type_t *const base_type = skip_typeref(type);
7192 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7193 warning.char_subscripts) {
7194 warningf(&expression->base.source_position,
7195 "array subscript has type '%T'", type);
7199 static expression_t *parse_array_expression(expression_t *left)
7201 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7204 add_anchor_token(']');
7206 expression_t *inside = parse_expression();
7208 type_t *const orig_type_left = left->base.type;
7209 type_t *const orig_type_inside = inside->base.type;
7211 type_t *const type_left = skip_typeref(orig_type_left);
7212 type_t *const type_inside = skip_typeref(orig_type_inside);
7214 type_t *return_type;
7215 array_access_expression_t *array_access = &expression->array_access;
7216 if (is_type_pointer(type_left)) {
7217 return_type = type_left->pointer.points_to;
7218 array_access->array_ref = left;
7219 array_access->index = inside;
7220 check_for_char_index_type(inside);
7221 } else if (is_type_pointer(type_inside)) {
7222 return_type = type_inside->pointer.points_to;
7223 array_access->array_ref = inside;
7224 array_access->index = left;
7225 array_access->flipped = true;
7226 check_for_char_index_type(left);
7228 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7230 "array access on object with non-pointer types '%T', '%T'",
7231 orig_type_left, orig_type_inside);
7233 return_type = type_error_type;
7234 array_access->array_ref = left;
7235 array_access->index = inside;
7238 expression->base.type = automatic_type_conversion(return_type);
7240 rem_anchor_token(']');
7241 expect(']', end_error);
7246 static expression_t *parse_typeprop(expression_kind_t const kind)
7248 expression_t *tp_expression = allocate_expression_zero(kind);
7249 tp_expression->base.type = type_size_t;
7251 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7253 /* we only refer to a type property, mark this case */
7254 bool old = in_type_prop;
7255 in_type_prop = true;
7258 expression_t *expression;
7259 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7261 add_anchor_token(')');
7262 orig_type = parse_typename();
7263 rem_anchor_token(')');
7264 expect(')', end_error);
7266 if (token.type == '{') {
7267 /* It was not sizeof(type) after all. It is sizeof of an expression
7268 * starting with a compound literal */
7269 expression = parse_compound_literal(orig_type);
7270 goto typeprop_expression;
7273 expression = parse_subexpression(PREC_UNARY);
7275 typeprop_expression:
7276 tp_expression->typeprop.tp_expression = expression;
7278 orig_type = revert_automatic_type_conversion(expression);
7279 expression->base.type = orig_type;
7282 tp_expression->typeprop.type = orig_type;
7283 type_t const* const type = skip_typeref(orig_type);
7284 char const* wrong_type = NULL;
7285 if (is_type_incomplete(type)) {
7286 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7287 wrong_type = "incomplete";
7288 } else if (type->kind == TYPE_FUNCTION) {
7290 /* function types are allowed (and return 1) */
7291 if (warning.other) {
7292 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7293 warningf(&tp_expression->base.source_position,
7294 "%s expression with function argument returns invalid result", what);
7297 wrong_type = "function";
7300 if (is_type_incomplete(type))
7301 wrong_type = "incomplete";
7303 if (type->kind == TYPE_BITFIELD)
7304 wrong_type = "bitfield";
7306 if (wrong_type != NULL) {
7307 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7308 errorf(&tp_expression->base.source_position,
7309 "operand of %s expression must not be of %s type '%T'",
7310 what, wrong_type, orig_type);
7315 return tp_expression;
7318 static expression_t *parse_sizeof(void)
7320 return parse_typeprop(EXPR_SIZEOF);
7323 static expression_t *parse_alignof(void)
7325 return parse_typeprop(EXPR_ALIGNOF);
7328 static expression_t *parse_select_expression(expression_t *addr)
7330 assert(token.type == '.' || token.type == T_MINUSGREATER);
7331 bool select_left_arrow = (token.type == T_MINUSGREATER);
7332 source_position_t const pos = *HERE;
7335 if (token.type != T_IDENTIFIER) {
7336 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7337 return create_invalid_expression();
7339 symbol_t *symbol = token.symbol;
7342 type_t *const orig_type = addr->base.type;
7343 type_t *const type = skip_typeref(orig_type);
7346 bool saw_error = false;
7347 if (is_type_pointer(type)) {
7348 if (!select_left_arrow) {
7350 "request for member '%Y' in something not a struct or union, but '%T'",
7354 type_left = skip_typeref(type->pointer.points_to);
7356 if (select_left_arrow && is_type_valid(type)) {
7357 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7363 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7364 type_left->kind != TYPE_COMPOUND_UNION) {
7366 if (is_type_valid(type_left) && !saw_error) {
7368 "request for member '%Y' in something not a struct or union, but '%T'",
7371 return create_invalid_expression();
7374 compound_t *compound = type_left->compound.compound;
7375 if (!compound->complete) {
7376 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7378 return create_invalid_expression();
7381 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7382 expression_t *result =
7383 find_create_select(&pos, addr, qualifiers, compound, symbol);
7385 if (result == NULL) {
7386 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7387 return create_invalid_expression();
7393 static void check_call_argument(type_t *expected_type,
7394 call_argument_t *argument, unsigned pos)
7396 type_t *expected_type_skip = skip_typeref(expected_type);
7397 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7398 expression_t *arg_expr = argument->expression;
7399 type_t *arg_type = skip_typeref(arg_expr->base.type);
7401 /* handle transparent union gnu extension */
7402 if (is_type_union(expected_type_skip)
7403 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7404 compound_t *union_decl = expected_type_skip->compound.compound;
7405 type_t *best_type = NULL;
7406 entity_t *entry = union_decl->members.entities;
7407 for ( ; entry != NULL; entry = entry->base.next) {
7408 assert(is_declaration(entry));
7409 type_t *decl_type = entry->declaration.type;
7410 error = semantic_assign(decl_type, arg_expr);
7411 if (error == ASSIGN_ERROR_INCOMPATIBLE
7412 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7415 if (error == ASSIGN_SUCCESS) {
7416 best_type = decl_type;
7417 } else if (best_type == NULL) {
7418 best_type = decl_type;
7422 if (best_type != NULL) {
7423 expected_type = best_type;
7427 error = semantic_assign(expected_type, arg_expr);
7428 argument->expression = create_implicit_cast(arg_expr, expected_type);
7430 if (error != ASSIGN_SUCCESS) {
7431 /* report exact scope in error messages (like "in argument 3") */
7433 snprintf(buf, sizeof(buf), "call argument %u", pos);
7434 report_assign_error(error, expected_type, arg_expr, buf,
7435 &arg_expr->base.source_position);
7436 } else if (warning.traditional || warning.conversion) {
7437 type_t *const promoted_type = get_default_promoted_type(arg_type);
7438 if (!types_compatible(expected_type_skip, promoted_type) &&
7439 !types_compatible(expected_type_skip, type_void_ptr) &&
7440 !types_compatible(type_void_ptr, promoted_type)) {
7441 /* Deliberately show the skipped types in this warning */
7442 warningf(&arg_expr->base.source_position,
7443 "passing call argument %u as '%T' rather than '%T' due to prototype",
7444 pos, expected_type_skip, promoted_type);
7450 * Handle the semantic restrictions of builtin calls
7452 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7453 switch (call->function->reference.entity->function.btk) {
7454 case bk_gnu_builtin_return_address:
7455 case bk_gnu_builtin_frame_address: {
7456 /* argument must be constant */
7457 call_argument_t *argument = call->arguments;
7459 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7460 errorf(&call->base.source_position,
7461 "argument of '%Y' must be a constant expression",
7462 call->function->reference.entity->base.symbol);
7466 case bk_gnu_builtin_object_size:
7467 if (call->arguments == NULL)
7470 call_argument_t *arg = call->arguments->next;
7471 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7472 errorf(&call->base.source_position,
7473 "second argument of '%Y' must be a constant expression",
7474 call->function->reference.entity->base.symbol);
7477 case bk_gnu_builtin_prefetch:
7478 /* second and third argument must be constant if existent */
7479 if (call->arguments == NULL)
7481 call_argument_t *rw = call->arguments->next;
7482 call_argument_t *locality = NULL;
7485 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7486 errorf(&call->base.source_position,
7487 "second argument of '%Y' must be a constant expression",
7488 call->function->reference.entity->base.symbol);
7490 locality = rw->next;
7492 if (locality != NULL) {
7493 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7494 errorf(&call->base.source_position,
7495 "third argument of '%Y' must be a constant expression",
7496 call->function->reference.entity->base.symbol);
7498 locality = rw->next;
7507 * Parse a call expression, ie. expression '( ... )'.
7509 * @param expression the function address
7511 static expression_t *parse_call_expression(expression_t *expression)
7513 expression_t *result = allocate_expression_zero(EXPR_CALL);
7514 call_expression_t *call = &result->call;
7515 call->function = expression;
7517 type_t *const orig_type = expression->base.type;
7518 type_t *const type = skip_typeref(orig_type);
7520 function_type_t *function_type = NULL;
7521 if (is_type_pointer(type)) {
7522 type_t *const to_type = skip_typeref(type->pointer.points_to);
7524 if (is_type_function(to_type)) {
7525 function_type = &to_type->function;
7526 call->base.type = function_type->return_type;
7530 if (function_type == NULL && is_type_valid(type)) {
7532 "called object '%E' (type '%T') is not a pointer to a function",
7533 expression, orig_type);
7536 /* parse arguments */
7538 add_anchor_token(')');
7539 add_anchor_token(',');
7541 if (token.type != ')') {
7542 call_argument_t **anchor = &call->arguments;
7544 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7545 argument->expression = parse_assignment_expression();
7548 anchor = &argument->next;
7549 } while (next_if(','));
7551 rem_anchor_token(',');
7552 rem_anchor_token(')');
7553 expect(')', end_error);
7555 if (function_type == NULL)
7558 /* check type and count of call arguments */
7559 function_parameter_t *parameter = function_type->parameters;
7560 call_argument_t *argument = call->arguments;
7561 if (!function_type->unspecified_parameters) {
7562 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7563 parameter = parameter->next, argument = argument->next) {
7564 check_call_argument(parameter->type, argument, ++pos);
7567 if (parameter != NULL) {
7568 errorf(HERE, "too few arguments to function '%E'", expression);
7569 } else if (argument != NULL && !function_type->variadic) {
7570 errorf(HERE, "too many arguments to function '%E'", expression);
7574 /* do default promotion for other arguments */
7575 for (; argument != NULL; argument = argument->next) {
7576 type_t *type = argument->expression->base.type;
7577 if (!is_type_object(skip_typeref(type))) {
7578 errorf(&argument->expression->base.source_position,
7579 "call argument '%E' must not be void", argument->expression);
7582 type = get_default_promoted_type(type);
7584 argument->expression
7585 = create_implicit_cast(argument->expression, type);
7588 check_format(&result->call);
7590 if (warning.aggregate_return &&
7591 is_type_compound(skip_typeref(function_type->return_type))) {
7592 warningf(&result->base.source_position,
7593 "function call has aggregate value");
7596 if (call->function->kind == EXPR_REFERENCE) {
7597 reference_expression_t *reference = &call->function->reference;
7598 if (reference->entity->kind == ENTITY_FUNCTION &&
7599 reference->entity->function.btk != bk_none)
7600 handle_builtin_argument_restrictions(call);
7607 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7609 static bool same_compound_type(const type_t *type1, const type_t *type2)
7612 is_type_compound(type1) &&
7613 type1->kind == type2->kind &&
7614 type1->compound.compound == type2->compound.compound;
7617 static expression_t const *get_reference_address(expression_t const *expr)
7619 bool regular_take_address = true;
7621 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7622 expr = expr->unary.value;
7624 regular_take_address = false;
7627 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7630 expr = expr->unary.value;
7633 if (expr->kind != EXPR_REFERENCE)
7636 /* special case for functions which are automatically converted to a
7637 * pointer to function without an extra TAKE_ADDRESS operation */
7638 if (!regular_take_address &&
7639 expr->reference.entity->kind != ENTITY_FUNCTION) {
7646 static void warn_reference_address_as_bool(expression_t const* expr)
7648 if (!warning.address)
7651 expr = get_reference_address(expr);
7653 warningf(&expr->base.source_position,
7654 "the address of '%Y' will always evaluate as 'true'",
7655 expr->reference.entity->base.symbol);
7659 static void warn_assignment_in_condition(const expression_t *const expr)
7661 if (!warning.parentheses)
7663 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7665 if (expr->base.parenthesized)
7667 warningf(&expr->base.source_position,
7668 "suggest parentheses around assignment used as truth value");
7671 static void semantic_condition(expression_t const *const expr,
7672 char const *const context)
7674 type_t *const type = skip_typeref(expr->base.type);
7675 if (is_type_scalar(type)) {
7676 warn_reference_address_as_bool(expr);
7677 warn_assignment_in_condition(expr);
7678 } else if (is_type_valid(type)) {
7679 errorf(&expr->base.source_position,
7680 "%s must have scalar type", context);
7685 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7687 * @param expression the conditional expression
7689 static expression_t *parse_conditional_expression(expression_t *expression)
7691 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7693 conditional_expression_t *conditional = &result->conditional;
7694 conditional->condition = expression;
7697 add_anchor_token(':');
7699 /* §6.5.15:2 The first operand shall have scalar type. */
7700 semantic_condition(expression, "condition of conditional operator");
7702 expression_t *true_expression = expression;
7703 bool gnu_cond = false;
7704 if (GNU_MODE && token.type == ':') {
7707 true_expression = parse_expression();
7709 rem_anchor_token(':');
7710 expect(':', end_error);
7712 expression_t *false_expression =
7713 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7715 type_t *const orig_true_type = true_expression->base.type;
7716 type_t *const orig_false_type = false_expression->base.type;
7717 type_t *const true_type = skip_typeref(orig_true_type);
7718 type_t *const false_type = skip_typeref(orig_false_type);
7721 type_t *result_type;
7722 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7723 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7724 /* ISO/IEC 14882:1998(E) §5.16:2 */
7725 if (true_expression->kind == EXPR_UNARY_THROW) {
7726 result_type = false_type;
7727 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7728 result_type = true_type;
7730 if (warning.other && (
7731 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7732 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7734 warningf(&conditional->base.source_position,
7735 "ISO C forbids conditional expression with only one void side");
7737 result_type = type_void;
7739 } else if (is_type_arithmetic(true_type)
7740 && is_type_arithmetic(false_type)) {
7741 result_type = semantic_arithmetic(true_type, false_type);
7742 } else if (same_compound_type(true_type, false_type)) {
7743 /* just take 1 of the 2 types */
7744 result_type = true_type;
7745 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7746 type_t *pointer_type;
7748 expression_t *other_expression;
7749 if (is_type_pointer(true_type) &&
7750 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7751 pointer_type = true_type;
7752 other_type = false_type;
7753 other_expression = false_expression;
7755 pointer_type = false_type;
7756 other_type = true_type;
7757 other_expression = true_expression;
7760 if (is_null_pointer_constant(other_expression)) {
7761 result_type = pointer_type;
7762 } else if (is_type_pointer(other_type)) {
7763 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7764 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7767 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7768 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7770 } else if (types_compatible(get_unqualified_type(to1),
7771 get_unqualified_type(to2))) {
7774 if (warning.other) {
7775 warningf(&conditional->base.source_position,
7776 "pointer types '%T' and '%T' in conditional expression are incompatible",
7777 true_type, false_type);
7782 type_t *const type =
7783 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7784 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7785 } else if (is_type_integer(other_type)) {
7786 if (warning.other) {
7787 warningf(&conditional->base.source_position,
7788 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7790 result_type = pointer_type;
7792 if (is_type_valid(other_type)) {
7793 type_error_incompatible("while parsing conditional",
7794 &expression->base.source_position, true_type, false_type);
7796 result_type = type_error_type;
7799 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7800 type_error_incompatible("while parsing conditional",
7801 &conditional->base.source_position, true_type,
7804 result_type = type_error_type;
7807 conditional->true_expression
7808 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7809 conditional->false_expression
7810 = create_implicit_cast(false_expression, result_type);
7811 conditional->base.type = result_type;
7816 * Parse an extension expression.
7818 static expression_t *parse_extension(void)
7820 eat(T___extension__);
7822 bool old_gcc_extension = in_gcc_extension;
7823 in_gcc_extension = true;
7824 expression_t *expression = parse_subexpression(PREC_UNARY);
7825 in_gcc_extension = old_gcc_extension;
7830 * Parse a __builtin_classify_type() expression.
7832 static expression_t *parse_builtin_classify_type(void)
7834 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7835 result->base.type = type_int;
7837 eat(T___builtin_classify_type);
7839 expect('(', end_error);
7840 add_anchor_token(')');
7841 expression_t *expression = parse_expression();
7842 rem_anchor_token(')');
7843 expect(')', end_error);
7844 result->classify_type.type_expression = expression;
7848 return create_invalid_expression();
7852 * Parse a delete expression
7853 * ISO/IEC 14882:1998(E) §5.3.5
7855 static expression_t *parse_delete(void)
7857 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7858 result->base.type = type_void;
7863 result->kind = EXPR_UNARY_DELETE_ARRAY;
7864 expect(']', end_error);
7868 expression_t *const value = parse_subexpression(PREC_CAST);
7869 result->unary.value = value;
7871 type_t *const type = skip_typeref(value->base.type);
7872 if (!is_type_pointer(type)) {
7873 if (is_type_valid(type)) {
7874 errorf(&value->base.source_position,
7875 "operand of delete must have pointer type");
7877 } else if (warning.other &&
7878 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7879 warningf(&value->base.source_position,
7880 "deleting 'void*' is undefined");
7887 * Parse a throw expression
7888 * ISO/IEC 14882:1998(E) §15:1
7890 static expression_t *parse_throw(void)
7892 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7893 result->base.type = type_void;
7897 expression_t *value = NULL;
7898 switch (token.type) {
7900 value = parse_assignment_expression();
7901 /* ISO/IEC 14882:1998(E) §15.1:3 */
7902 type_t *const orig_type = value->base.type;
7903 type_t *const type = skip_typeref(orig_type);
7904 if (is_type_incomplete(type)) {
7905 errorf(&value->base.source_position,
7906 "cannot throw object of incomplete type '%T'", orig_type);
7907 } else if (is_type_pointer(type)) {
7908 type_t *const points_to = skip_typeref(type->pointer.points_to);
7909 if (is_type_incomplete(points_to) &&
7910 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7911 errorf(&value->base.source_position,
7912 "cannot throw pointer to incomplete type '%T'", orig_type);
7920 result->unary.value = value;
7925 static bool check_pointer_arithmetic(const source_position_t *source_position,
7926 type_t *pointer_type,
7927 type_t *orig_pointer_type)
7929 type_t *points_to = pointer_type->pointer.points_to;
7930 points_to = skip_typeref(points_to);
7932 if (is_type_incomplete(points_to)) {
7933 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7934 errorf(source_position,
7935 "arithmetic with pointer to incomplete type '%T' not allowed",
7938 } else if (warning.pointer_arith) {
7939 warningf(source_position,
7940 "pointer of type '%T' used in arithmetic",
7943 } else if (is_type_function(points_to)) {
7945 errorf(source_position,
7946 "arithmetic with pointer to function type '%T' not allowed",
7949 } else if (warning.pointer_arith) {
7950 warningf(source_position,
7951 "pointer to a function '%T' used in arithmetic",
7958 static bool is_lvalue(const expression_t *expression)
7960 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7961 switch (expression->kind) {
7962 case EXPR_ARRAY_ACCESS:
7963 case EXPR_COMPOUND_LITERAL:
7964 case EXPR_REFERENCE:
7966 case EXPR_UNARY_DEREFERENCE:
7970 type_t *type = skip_typeref(expression->base.type);
7972 /* ISO/IEC 14882:1998(E) §3.10:3 */
7973 is_type_reference(type) ||
7974 /* Claim it is an lvalue, if the type is invalid. There was a parse
7975 * error before, which maybe prevented properly recognizing it as
7977 !is_type_valid(type);
7982 static void semantic_incdec(unary_expression_t *expression)
7984 type_t *const orig_type = expression->value->base.type;
7985 type_t *const type = skip_typeref(orig_type);
7986 if (is_type_pointer(type)) {
7987 if (!check_pointer_arithmetic(&expression->base.source_position,
7991 } else if (!is_type_real(type) && is_type_valid(type)) {
7992 /* TODO: improve error message */
7993 errorf(&expression->base.source_position,
7994 "operation needs an arithmetic or pointer type");
7997 if (!is_lvalue(expression->value)) {
7998 /* TODO: improve error message */
7999 errorf(&expression->base.source_position, "lvalue required as operand");
8001 expression->base.type = orig_type;
8004 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8006 type_t *const orig_type = expression->value->base.type;
8007 type_t *const type = skip_typeref(orig_type);
8008 if (!is_type_arithmetic(type)) {
8009 if (is_type_valid(type)) {
8010 /* TODO: improve error message */
8011 errorf(&expression->base.source_position,
8012 "operation needs an arithmetic type");
8017 expression->base.type = orig_type;
8020 static void semantic_unexpr_plus(unary_expression_t *expression)
8022 semantic_unexpr_arithmetic(expression);
8023 if (warning.traditional)
8024 warningf(&expression->base.source_position,
8025 "traditional C rejects the unary plus operator");
8028 static void semantic_not(unary_expression_t *expression)
8030 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8031 semantic_condition(expression->value, "operand of !");
8032 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8035 static void semantic_unexpr_integer(unary_expression_t *expression)
8037 type_t *const orig_type = expression->value->base.type;
8038 type_t *const type = skip_typeref(orig_type);
8039 if (!is_type_integer(type)) {
8040 if (is_type_valid(type)) {
8041 errorf(&expression->base.source_position,
8042 "operand of ~ must be of integer type");
8047 expression->base.type = orig_type;
8050 static void semantic_dereference(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_pointer(type)) {
8055 if (is_type_valid(type)) {
8056 errorf(&expression->base.source_position,
8057 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8062 type_t *result_type = type->pointer.points_to;
8063 result_type = automatic_type_conversion(result_type);
8064 expression->base.type = result_type;
8068 * Record that an address is taken (expression represents an lvalue).
8070 * @param expression the expression
8071 * @param may_be_register if true, the expression might be an register
8073 static void set_address_taken(expression_t *expression, bool may_be_register)
8075 if (expression->kind != EXPR_REFERENCE)
8078 entity_t *const entity = expression->reference.entity;
8080 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8083 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8084 && !may_be_register) {
8085 errorf(&expression->base.source_position,
8086 "address of register %s '%Y' requested",
8087 get_entity_kind_name(entity->kind), entity->base.symbol);
8090 if (entity->kind == ENTITY_VARIABLE) {
8091 entity->variable.address_taken = true;
8093 assert(entity->kind == ENTITY_PARAMETER);
8094 entity->parameter.address_taken = true;
8099 * Check the semantic of the address taken expression.
8101 static void semantic_take_addr(unary_expression_t *expression)
8103 expression_t *value = expression->value;
8104 value->base.type = revert_automatic_type_conversion(value);
8106 type_t *orig_type = value->base.type;
8107 type_t *type = skip_typeref(orig_type);
8108 if (!is_type_valid(type))
8112 if (!is_lvalue(value)) {
8113 errorf(&expression->base.source_position, "'&' requires an lvalue");
8115 if (type->kind == TYPE_BITFIELD) {
8116 errorf(&expression->base.source_position,
8117 "'&' not allowed on object with bitfield type '%T'",
8121 set_address_taken(value, false);
8123 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8126 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8127 static expression_t *parse_##unexpression_type(void) \
8129 expression_t *unary_expression \
8130 = allocate_expression_zero(unexpression_type); \
8132 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8134 sfunc(&unary_expression->unary); \
8136 return unary_expression; \
8139 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8140 semantic_unexpr_arithmetic)
8141 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8142 semantic_unexpr_plus)
8143 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8145 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8146 semantic_dereference)
8147 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8149 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8150 semantic_unexpr_integer)
8151 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8153 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8156 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8158 static expression_t *parse_##unexpression_type(expression_t *left) \
8160 expression_t *unary_expression \
8161 = allocate_expression_zero(unexpression_type); \
8163 unary_expression->unary.value = left; \
8165 sfunc(&unary_expression->unary); \
8167 return unary_expression; \
8170 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8171 EXPR_UNARY_POSTFIX_INCREMENT,
8173 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8174 EXPR_UNARY_POSTFIX_DECREMENT,
8177 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8179 /* TODO: handle complex + imaginary types */
8181 type_left = get_unqualified_type(type_left);
8182 type_right = get_unqualified_type(type_right);
8184 /* §6.3.1.8 Usual arithmetic conversions */
8185 if (type_left == type_long_double || type_right == type_long_double) {
8186 return type_long_double;
8187 } else if (type_left == type_double || type_right == type_double) {
8189 } else if (type_left == type_float || type_right == type_float) {
8193 type_left = promote_integer(type_left);
8194 type_right = promote_integer(type_right);
8196 if (type_left == type_right)
8199 bool const signed_left = is_type_signed(type_left);
8200 bool const signed_right = is_type_signed(type_right);
8201 int const rank_left = get_rank(type_left);
8202 int const rank_right = get_rank(type_right);
8204 if (signed_left == signed_right)
8205 return rank_left >= rank_right ? type_left : type_right;
8214 u_rank = rank_right;
8215 u_type = type_right;
8217 s_rank = rank_right;
8218 s_type = type_right;
8223 if (u_rank >= s_rank)
8226 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8228 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8229 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8233 case ATOMIC_TYPE_INT: return type_unsigned_int;
8234 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8235 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8237 default: panic("invalid atomic type");
8242 * Check the semantic restrictions for a binary expression.
8244 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8246 expression_t *const left = expression->left;
8247 expression_t *const right = expression->right;
8248 type_t *const orig_type_left = left->base.type;
8249 type_t *const orig_type_right = right->base.type;
8250 type_t *const type_left = skip_typeref(orig_type_left);
8251 type_t *const type_right = skip_typeref(orig_type_right);
8253 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8254 /* TODO: improve error message */
8255 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8256 errorf(&expression->base.source_position,
8257 "operation needs arithmetic types");
8262 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8263 expression->left = create_implicit_cast(left, arithmetic_type);
8264 expression->right = create_implicit_cast(right, arithmetic_type);
8265 expression->base.type = arithmetic_type;
8268 static void semantic_binexpr_integer(binary_expression_t *const expression)
8270 expression_t *const left = expression->left;
8271 expression_t *const right = expression->right;
8272 type_t *const orig_type_left = left->base.type;
8273 type_t *const orig_type_right = right->base.type;
8274 type_t *const type_left = skip_typeref(orig_type_left);
8275 type_t *const type_right = skip_typeref(orig_type_right);
8277 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8278 /* TODO: improve error message */
8279 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8280 errorf(&expression->base.source_position,
8281 "operation needs integer types");
8286 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8287 expression->left = create_implicit_cast(left, result_type);
8288 expression->right = create_implicit_cast(right, result_type);
8289 expression->base.type = result_type;
8292 static void warn_div_by_zero(binary_expression_t const *const expression)
8294 if (!warning.div_by_zero ||
8295 !is_type_integer(expression->base.type))
8298 expression_t const *const right = expression->right;
8299 /* The type of the right operand can be different for /= */
8300 if (is_type_integer(right->base.type) &&
8301 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8302 !fold_constant_to_bool(right)) {
8303 warningf(&expression->base.source_position, "division by zero");
8308 * Check the semantic restrictions for a div/mod expression.
8310 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8312 semantic_binexpr_arithmetic(expression);
8313 warn_div_by_zero(expression);
8316 static void warn_addsub_in_shift(const expression_t *const expr)
8318 if (expr->base.parenthesized)
8322 switch (expr->kind) {
8323 case EXPR_BINARY_ADD: op = '+'; break;
8324 case EXPR_BINARY_SUB: op = '-'; break;
8328 warningf(&expr->base.source_position,
8329 "suggest parentheses around '%c' inside shift", op);
8332 static bool semantic_shift(binary_expression_t *expression)
8334 expression_t *const left = expression->left;
8335 expression_t *const right = expression->right;
8336 type_t *const orig_type_left = left->base.type;
8337 type_t *const orig_type_right = right->base.type;
8338 type_t * type_left = skip_typeref(orig_type_left);
8339 type_t * type_right = skip_typeref(orig_type_right);
8341 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8342 /* TODO: improve error message */
8343 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8344 errorf(&expression->base.source_position,
8345 "operands of shift operation must have integer types");
8350 type_left = promote_integer(type_left);
8352 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8353 long count = fold_constant_to_int(right);
8355 warningf(&right->base.source_position,
8356 "shift count must be non-negative");
8357 } else if ((unsigned long)count >=
8358 get_atomic_type_size(type_left->atomic.akind) * 8) {
8359 warningf(&right->base.source_position,
8360 "shift count must be less than type width");
8364 type_right = promote_integer(type_right);
8365 expression->right = create_implicit_cast(right, type_right);
8370 static void semantic_shift_op(binary_expression_t *expression)
8372 expression_t *const left = expression->left;
8373 expression_t *const right = expression->right;
8375 if (!semantic_shift(expression))
8378 if (warning.parentheses) {
8379 warn_addsub_in_shift(left);
8380 warn_addsub_in_shift(right);
8383 type_t *const orig_type_left = left->base.type;
8384 type_t * type_left = skip_typeref(orig_type_left);
8386 type_left = promote_integer(type_left);
8387 expression->left = create_implicit_cast(left, type_left);
8388 expression->base.type = type_left;
8391 static void semantic_add(binary_expression_t *expression)
8393 expression_t *const left = expression->left;
8394 expression_t *const right = expression->right;
8395 type_t *const orig_type_left = left->base.type;
8396 type_t *const orig_type_right = right->base.type;
8397 type_t *const type_left = skip_typeref(orig_type_left);
8398 type_t *const type_right = skip_typeref(orig_type_right);
8401 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8402 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8403 expression->left = create_implicit_cast(left, arithmetic_type);
8404 expression->right = create_implicit_cast(right, arithmetic_type);
8405 expression->base.type = arithmetic_type;
8406 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8407 check_pointer_arithmetic(&expression->base.source_position,
8408 type_left, orig_type_left);
8409 expression->base.type = type_left;
8410 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8411 check_pointer_arithmetic(&expression->base.source_position,
8412 type_right, orig_type_right);
8413 expression->base.type = type_right;
8414 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8415 errorf(&expression->base.source_position,
8416 "invalid operands to binary + ('%T', '%T')",
8417 orig_type_left, orig_type_right);
8421 static void semantic_sub(binary_expression_t *expression)
8423 expression_t *const left = expression->left;
8424 expression_t *const right = expression->right;
8425 type_t *const orig_type_left = left->base.type;
8426 type_t *const orig_type_right = right->base.type;
8427 type_t *const type_left = skip_typeref(orig_type_left);
8428 type_t *const type_right = skip_typeref(orig_type_right);
8429 source_position_t const *const pos = &expression->base.source_position;
8432 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8433 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8434 expression->left = create_implicit_cast(left, arithmetic_type);
8435 expression->right = create_implicit_cast(right, arithmetic_type);
8436 expression->base.type = arithmetic_type;
8437 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8438 check_pointer_arithmetic(&expression->base.source_position,
8439 type_left, orig_type_left);
8440 expression->base.type = type_left;
8441 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8442 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8443 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8444 if (!types_compatible(unqual_left, unqual_right)) {
8446 "subtracting pointers to incompatible types '%T' and '%T'",
8447 orig_type_left, orig_type_right);
8448 } else if (!is_type_object(unqual_left)) {
8449 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8450 errorf(pos, "subtracting pointers to non-object types '%T'",
8452 } else if (warning.other) {
8453 warningf(pos, "subtracting pointers to void");
8456 expression->base.type = type_ptrdiff_t;
8457 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8458 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8459 orig_type_left, orig_type_right);
8463 static void warn_string_literal_address(expression_t const* expr)
8465 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8466 expr = expr->unary.value;
8467 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8469 expr = expr->unary.value;
8472 if (expr->kind == EXPR_STRING_LITERAL
8473 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8474 warningf(&expr->base.source_position,
8475 "comparison with string literal results in unspecified behaviour");
8479 static void warn_comparison_in_comparison(const expression_t *const expr)
8481 if (expr->base.parenthesized)
8483 switch (expr->base.kind) {
8484 case EXPR_BINARY_LESS:
8485 case EXPR_BINARY_GREATER:
8486 case EXPR_BINARY_LESSEQUAL:
8487 case EXPR_BINARY_GREATEREQUAL:
8488 case EXPR_BINARY_NOTEQUAL:
8489 case EXPR_BINARY_EQUAL:
8490 warningf(&expr->base.source_position,
8491 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8498 static bool maybe_negative(expression_t const *const expr)
8500 switch (is_constant_expression(expr)) {
8501 case EXPR_CLASS_ERROR: return false;
8502 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8503 default: return true;
8508 * Check the semantics of comparison expressions.
8510 * @param expression The expression to check.
8512 static void semantic_comparison(binary_expression_t *expression)
8514 expression_t *left = expression->left;
8515 expression_t *right = expression->right;
8517 if (warning.address) {
8518 warn_string_literal_address(left);
8519 warn_string_literal_address(right);
8521 expression_t const* const func_left = get_reference_address(left);
8522 if (func_left != NULL && is_null_pointer_constant(right)) {
8523 warningf(&expression->base.source_position,
8524 "the address of '%Y' will never be NULL",
8525 func_left->reference.entity->base.symbol);
8528 expression_t const* const func_right = get_reference_address(right);
8529 if (func_right != NULL && is_null_pointer_constant(right)) {
8530 warningf(&expression->base.source_position,
8531 "the address of '%Y' will never be NULL",
8532 func_right->reference.entity->base.symbol);
8536 if (warning.parentheses) {
8537 warn_comparison_in_comparison(left);
8538 warn_comparison_in_comparison(right);
8541 type_t *orig_type_left = left->base.type;
8542 type_t *orig_type_right = right->base.type;
8543 type_t *type_left = skip_typeref(orig_type_left);
8544 type_t *type_right = skip_typeref(orig_type_right);
8546 /* TODO non-arithmetic types */
8547 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8548 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8550 /* test for signed vs unsigned compares */
8551 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8552 bool const signed_left = is_type_signed(type_left);
8553 bool const signed_right = is_type_signed(type_right);
8554 if (signed_left != signed_right) {
8555 /* FIXME long long needs better const folding magic */
8556 /* TODO check whether constant value can be represented by other type */
8557 if ((signed_left && maybe_negative(left)) ||
8558 (signed_right && maybe_negative(right))) {
8559 warningf(&expression->base.source_position,
8560 "comparison between signed and unsigned");
8565 expression->left = create_implicit_cast(left, arithmetic_type);
8566 expression->right = create_implicit_cast(right, arithmetic_type);
8567 expression->base.type = arithmetic_type;
8568 if (warning.float_equal &&
8569 (expression->base.kind == EXPR_BINARY_EQUAL ||
8570 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8571 is_type_float(arithmetic_type)) {
8572 warningf(&expression->base.source_position,
8573 "comparing floating point with == or != is unsafe");
8575 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8576 /* TODO check compatibility */
8577 } else if (is_type_pointer(type_left)) {
8578 expression->right = create_implicit_cast(right, type_left);
8579 } else if (is_type_pointer(type_right)) {
8580 expression->left = create_implicit_cast(left, type_right);
8581 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8582 type_error_incompatible("invalid operands in comparison",
8583 &expression->base.source_position,
8584 type_left, type_right);
8586 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8590 * Checks if a compound type has constant fields.
8592 static bool has_const_fields(const compound_type_t *type)
8594 compound_t *compound = type->compound;
8595 entity_t *entry = compound->members.entities;
8597 for (; entry != NULL; entry = entry->base.next) {
8598 if (!is_declaration(entry))
8601 const type_t *decl_type = skip_typeref(entry->declaration.type);
8602 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8609 static bool is_valid_assignment_lhs(expression_t const* const left)
8611 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8612 type_t *const type_left = skip_typeref(orig_type_left);
8614 if (!is_lvalue(left)) {
8615 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8620 if (left->kind == EXPR_REFERENCE
8621 && left->reference.entity->kind == ENTITY_FUNCTION) {
8622 errorf(HERE, "cannot assign to function '%E'", left);
8626 if (is_type_array(type_left)) {
8627 errorf(HERE, "cannot assign to array '%E'", left);
8630 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8631 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8635 if (is_type_incomplete(type_left)) {
8636 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8637 left, orig_type_left);
8640 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8641 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8642 left, orig_type_left);
8649 static void semantic_arithmetic_assign(binary_expression_t *expression)
8651 expression_t *left = expression->left;
8652 expression_t *right = expression->right;
8653 type_t *orig_type_left = left->base.type;
8654 type_t *orig_type_right = right->base.type;
8656 if (!is_valid_assignment_lhs(left))
8659 type_t *type_left = skip_typeref(orig_type_left);
8660 type_t *type_right = skip_typeref(orig_type_right);
8662 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8663 /* TODO: improve error message */
8664 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8665 errorf(&expression->base.source_position,
8666 "operation needs arithmetic types");
8671 /* combined instructions are tricky. We can't create an implicit cast on
8672 * the left side, because we need the uncasted form for the store.
8673 * The ast2firm pass has to know that left_type must be right_type
8674 * for the arithmetic operation and create a cast by itself */
8675 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8676 expression->right = create_implicit_cast(right, arithmetic_type);
8677 expression->base.type = type_left;
8680 static void semantic_divmod_assign(binary_expression_t *expression)
8682 semantic_arithmetic_assign(expression);
8683 warn_div_by_zero(expression);
8686 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8688 expression_t *const left = expression->left;
8689 expression_t *const right = expression->right;
8690 type_t *const orig_type_left = left->base.type;
8691 type_t *const orig_type_right = right->base.type;
8692 type_t *const type_left = skip_typeref(orig_type_left);
8693 type_t *const type_right = skip_typeref(orig_type_right);
8695 if (!is_valid_assignment_lhs(left))
8698 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8699 /* combined instructions are tricky. We can't create an implicit cast on
8700 * the left side, because we need the uncasted form for the store.
8701 * The ast2firm pass has to know that left_type must be right_type
8702 * for the arithmetic operation and create a cast by itself */
8703 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8704 expression->right = create_implicit_cast(right, arithmetic_type);
8705 expression->base.type = type_left;
8706 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8707 check_pointer_arithmetic(&expression->base.source_position,
8708 type_left, orig_type_left);
8709 expression->base.type = type_left;
8710 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8711 errorf(&expression->base.source_position,
8712 "incompatible types '%T' and '%T' in assignment",
8713 orig_type_left, orig_type_right);
8717 static void semantic_integer_assign(binary_expression_t *expression)
8719 expression_t *left = expression->left;
8720 expression_t *right = expression->right;
8721 type_t *orig_type_left = left->base.type;
8722 type_t *orig_type_right = right->base.type;
8724 if (!is_valid_assignment_lhs(left))
8727 type_t *type_left = skip_typeref(orig_type_left);
8728 type_t *type_right = skip_typeref(orig_type_right);
8730 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8731 /* TODO: improve error message */
8732 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8733 errorf(&expression->base.source_position,
8734 "operation needs integer types");
8739 /* combined instructions are tricky. We can't create an implicit cast on
8740 * the left side, because we need the uncasted form for the store.
8741 * The ast2firm pass has to know that left_type must be right_type
8742 * for the arithmetic operation and create a cast by itself */
8743 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8744 expression->right = create_implicit_cast(right, arithmetic_type);
8745 expression->base.type = type_left;
8748 static void semantic_shift_assign(binary_expression_t *expression)
8750 expression_t *left = expression->left;
8752 if (!is_valid_assignment_lhs(left))
8755 if (!semantic_shift(expression))
8758 expression->base.type = skip_typeref(left->base.type);
8761 static void warn_logical_and_within_or(const expression_t *const expr)
8763 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8765 if (expr->base.parenthesized)
8767 warningf(&expr->base.source_position,
8768 "suggest parentheses around && within ||");
8772 * Check the semantic restrictions of a logical expression.
8774 static void semantic_logical_op(binary_expression_t *expression)
8776 /* §6.5.13:2 Each of the operands shall have scalar type.
8777 * §6.5.14:2 Each of the operands shall have scalar type. */
8778 semantic_condition(expression->left, "left operand of logical operator");
8779 semantic_condition(expression->right, "right operand of logical operator");
8780 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8781 warning.parentheses) {
8782 warn_logical_and_within_or(expression->left);
8783 warn_logical_and_within_or(expression->right);
8785 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8789 * Check the semantic restrictions of a binary assign expression.
8791 static void semantic_binexpr_assign(binary_expression_t *expression)
8793 expression_t *left = expression->left;
8794 type_t *orig_type_left = left->base.type;
8796 if (!is_valid_assignment_lhs(left))
8799 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8800 report_assign_error(error, orig_type_left, expression->right,
8801 "assignment", &left->base.source_position);
8802 expression->right = create_implicit_cast(expression->right, orig_type_left);
8803 expression->base.type = orig_type_left;
8807 * Determine if the outermost operation (or parts thereof) of the given
8808 * expression has no effect in order to generate a warning about this fact.
8809 * Therefore in some cases this only examines some of the operands of the
8810 * expression (see comments in the function and examples below).
8812 * f() + 23; // warning, because + has no effect
8813 * x || f(); // no warning, because x controls execution of f()
8814 * x ? y : f(); // warning, because y has no effect
8815 * (void)x; // no warning to be able to suppress the warning
8816 * This function can NOT be used for an "expression has definitely no effect"-
8818 static bool expression_has_effect(const expression_t *const expr)
8820 switch (expr->kind) {
8821 case EXPR_UNKNOWN: break;
8822 case EXPR_INVALID: return true; /* do NOT warn */
8823 case EXPR_REFERENCE: return false;
8824 case EXPR_REFERENCE_ENUM_VALUE: return false;
8825 case EXPR_LABEL_ADDRESS: return false;
8827 /* suppress the warning for microsoft __noop operations */
8828 case EXPR_LITERAL_MS_NOOP: return true;
8829 case EXPR_LITERAL_BOOLEAN:
8830 case EXPR_LITERAL_CHARACTER:
8831 case EXPR_LITERAL_WIDE_CHARACTER:
8832 case EXPR_LITERAL_INTEGER:
8833 case EXPR_LITERAL_INTEGER_OCTAL:
8834 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8835 case EXPR_LITERAL_FLOATINGPOINT:
8836 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8837 case EXPR_STRING_LITERAL: return false;
8838 case EXPR_WIDE_STRING_LITERAL: return false;
8841 const call_expression_t *const call = &expr->call;
8842 if (call->function->kind != EXPR_REFERENCE)
8845 switch (call->function->reference.entity->function.btk) {
8846 /* FIXME: which builtins have no effect? */
8847 default: return true;
8851 /* Generate the warning if either the left or right hand side of a
8852 * conditional expression has no effect */
8853 case EXPR_CONDITIONAL: {
8854 conditional_expression_t const *const cond = &expr->conditional;
8855 expression_t const *const t = cond->true_expression;
8857 (t == NULL || expression_has_effect(t)) &&
8858 expression_has_effect(cond->false_expression);
8861 case EXPR_SELECT: return false;
8862 case EXPR_ARRAY_ACCESS: return false;
8863 case EXPR_SIZEOF: return false;
8864 case EXPR_CLASSIFY_TYPE: return false;
8865 case EXPR_ALIGNOF: return false;
8867 case EXPR_FUNCNAME: return false;
8868 case EXPR_BUILTIN_CONSTANT_P: return false;
8869 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8870 case EXPR_OFFSETOF: return false;
8871 case EXPR_VA_START: return true;
8872 case EXPR_VA_ARG: return true;
8873 case EXPR_VA_COPY: return true;
8874 case EXPR_STATEMENT: return true; // TODO
8875 case EXPR_COMPOUND_LITERAL: return false;
8877 case EXPR_UNARY_NEGATE: return false;
8878 case EXPR_UNARY_PLUS: return false;
8879 case EXPR_UNARY_BITWISE_NEGATE: return false;
8880 case EXPR_UNARY_NOT: return false;
8881 case EXPR_UNARY_DEREFERENCE: return false;
8882 case EXPR_UNARY_TAKE_ADDRESS: return false;
8883 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8884 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8885 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8886 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8888 /* Treat void casts as if they have an effect in order to being able to
8889 * suppress the warning */
8890 case EXPR_UNARY_CAST: {
8891 type_t *const type = skip_typeref(expr->base.type);
8892 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8895 case EXPR_UNARY_CAST_IMPLICIT: return true;
8896 case EXPR_UNARY_ASSUME: return true;
8897 case EXPR_UNARY_DELETE: return true;
8898 case EXPR_UNARY_DELETE_ARRAY: return true;
8899 case EXPR_UNARY_THROW: return true;
8901 case EXPR_BINARY_ADD: return false;
8902 case EXPR_BINARY_SUB: return false;
8903 case EXPR_BINARY_MUL: return false;
8904 case EXPR_BINARY_DIV: return false;
8905 case EXPR_BINARY_MOD: return false;
8906 case EXPR_BINARY_EQUAL: return false;
8907 case EXPR_BINARY_NOTEQUAL: return false;
8908 case EXPR_BINARY_LESS: return false;
8909 case EXPR_BINARY_LESSEQUAL: return false;
8910 case EXPR_BINARY_GREATER: return false;
8911 case EXPR_BINARY_GREATEREQUAL: return false;
8912 case EXPR_BINARY_BITWISE_AND: return false;
8913 case EXPR_BINARY_BITWISE_OR: return false;
8914 case EXPR_BINARY_BITWISE_XOR: return false;
8915 case EXPR_BINARY_SHIFTLEFT: return false;
8916 case EXPR_BINARY_SHIFTRIGHT: return false;
8917 case EXPR_BINARY_ASSIGN: return true;
8918 case EXPR_BINARY_MUL_ASSIGN: return true;
8919 case EXPR_BINARY_DIV_ASSIGN: return true;
8920 case EXPR_BINARY_MOD_ASSIGN: return true;
8921 case EXPR_BINARY_ADD_ASSIGN: return true;
8922 case EXPR_BINARY_SUB_ASSIGN: return true;
8923 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8924 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8925 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8926 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8927 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8929 /* Only examine the right hand side of && and ||, because the left hand
8930 * side already has the effect of controlling the execution of the right
8932 case EXPR_BINARY_LOGICAL_AND:
8933 case EXPR_BINARY_LOGICAL_OR:
8934 /* Only examine the right hand side of a comma expression, because the left
8935 * hand side has a separate warning */
8936 case EXPR_BINARY_COMMA:
8937 return expression_has_effect(expr->binary.right);
8939 case EXPR_BINARY_ISGREATER: return false;
8940 case EXPR_BINARY_ISGREATEREQUAL: return false;
8941 case EXPR_BINARY_ISLESS: return false;
8942 case EXPR_BINARY_ISLESSEQUAL: return false;
8943 case EXPR_BINARY_ISLESSGREATER: return false;
8944 case EXPR_BINARY_ISUNORDERED: return false;
8947 internal_errorf(HERE, "unexpected expression");
8950 static void semantic_comma(binary_expression_t *expression)
8952 if (warning.unused_value) {
8953 const expression_t *const left = expression->left;
8954 if (!expression_has_effect(left)) {
8955 warningf(&left->base.source_position,
8956 "left-hand operand of comma expression has no effect");
8959 expression->base.type = expression->right->base.type;
8963 * @param prec_r precedence of the right operand
8965 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8966 static expression_t *parse_##binexpression_type(expression_t *left) \
8968 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8969 binexpr->binary.left = left; \
8972 expression_t *right = parse_subexpression(prec_r); \
8974 binexpr->binary.right = right; \
8975 sfunc(&binexpr->binary); \
8980 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8981 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8982 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8983 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8984 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8985 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8986 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8987 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8988 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8989 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8990 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8991 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8992 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8993 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8994 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8995 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8996 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8997 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8998 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8999 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9000 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9001 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9002 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9003 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9004 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9005 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9006 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9007 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9008 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9009 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9012 static expression_t *parse_subexpression(precedence_t precedence)
9014 if (token.type < 0) {
9015 return expected_expression_error();
9018 expression_parser_function_t *parser
9019 = &expression_parsers[token.type];
9020 source_position_t source_position = token.source_position;
9023 if (parser->parser != NULL) {
9024 left = parser->parser();
9026 left = parse_primary_expression();
9028 assert(left != NULL);
9029 left->base.source_position = source_position;
9032 if (token.type < 0) {
9033 return expected_expression_error();
9036 parser = &expression_parsers[token.type];
9037 if (parser->infix_parser == NULL)
9039 if (parser->infix_precedence < precedence)
9042 left = parser->infix_parser(left);
9044 assert(left != NULL);
9045 assert(left->kind != EXPR_UNKNOWN);
9046 left->base.source_position = source_position;
9053 * Parse an expression.
9055 static expression_t *parse_expression(void)
9057 return parse_subexpression(PREC_EXPRESSION);
9061 * Register a parser for a prefix-like operator.
9063 * @param parser the parser function
9064 * @param token_type the token type of the prefix token
9066 static void register_expression_parser(parse_expression_function parser,
9069 expression_parser_function_t *entry = &expression_parsers[token_type];
9071 if (entry->parser != NULL) {
9072 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9073 panic("trying to register multiple expression parsers for a token");
9075 entry->parser = parser;
9079 * Register a parser for an infix operator with given precedence.
9081 * @param parser the parser function
9082 * @param token_type the token type of the infix operator
9083 * @param precedence the precedence of the operator
9085 static void register_infix_parser(parse_expression_infix_function parser,
9086 int token_type, precedence_t precedence)
9088 expression_parser_function_t *entry = &expression_parsers[token_type];
9090 if (entry->infix_parser != NULL) {
9091 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9092 panic("trying to register multiple infix expression parsers for a "
9095 entry->infix_parser = parser;
9096 entry->infix_precedence = precedence;
9100 * Initialize the expression parsers.
9102 static void init_expression_parsers(void)
9104 memset(&expression_parsers, 0, sizeof(expression_parsers));
9106 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9107 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9108 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9109 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9110 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9111 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9112 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9113 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9114 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9115 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9116 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9117 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9118 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9119 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9120 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9121 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9122 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9123 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9124 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9125 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9126 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9127 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9128 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9129 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9130 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9131 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9132 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9133 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9134 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9135 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9136 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9137 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9138 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9139 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9140 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9141 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9142 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9144 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9145 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9146 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9147 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9148 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9149 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9150 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9151 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9152 register_expression_parser(parse_sizeof, T_sizeof);
9153 register_expression_parser(parse_alignof, T___alignof__);
9154 register_expression_parser(parse_extension, T___extension__);
9155 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9156 register_expression_parser(parse_delete, T_delete);
9157 register_expression_parser(parse_throw, T_throw);
9161 * Parse a asm statement arguments specification.
9163 static asm_argument_t *parse_asm_arguments(bool is_out)
9165 asm_argument_t *result = NULL;
9166 asm_argument_t **anchor = &result;
9168 while (token.type == T_STRING_LITERAL || token.type == '[') {
9169 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9170 memset(argument, 0, sizeof(argument[0]));
9173 if (token.type != T_IDENTIFIER) {
9174 parse_error_expected("while parsing asm argument",
9175 T_IDENTIFIER, NULL);
9178 argument->symbol = token.symbol;
9180 expect(']', end_error);
9183 argument->constraints = parse_string_literals();
9184 expect('(', end_error);
9185 add_anchor_token(')');
9186 expression_t *expression = parse_expression();
9187 rem_anchor_token(')');
9189 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9190 * change size or type representation (e.g. int -> long is ok, but
9191 * int -> float is not) */
9192 if (expression->kind == EXPR_UNARY_CAST) {
9193 type_t *const type = expression->base.type;
9194 type_kind_t const kind = type->kind;
9195 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9198 if (kind == TYPE_ATOMIC) {
9199 atomic_type_kind_t const akind = type->atomic.akind;
9200 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9201 size = get_atomic_type_size(akind);
9203 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9204 size = get_atomic_type_size(get_intptr_kind());
9208 expression_t *const value = expression->unary.value;
9209 type_t *const value_type = value->base.type;
9210 type_kind_t const value_kind = value_type->kind;
9212 unsigned value_flags;
9213 unsigned value_size;
9214 if (value_kind == TYPE_ATOMIC) {
9215 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9216 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9217 value_size = get_atomic_type_size(value_akind);
9218 } else if (value_kind == TYPE_POINTER) {
9219 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9220 value_size = get_atomic_type_size(get_intptr_kind());
9225 if (value_flags != flags || value_size != size)
9229 } while (expression->kind == EXPR_UNARY_CAST);
9233 if (!is_lvalue(expression)) {
9234 errorf(&expression->base.source_position,
9235 "asm output argument is not an lvalue");
9238 if (argument->constraints.begin[0] == '=')
9239 determine_lhs_ent(expression, NULL);
9241 mark_vars_read(expression, NULL);
9243 mark_vars_read(expression, NULL);
9245 argument->expression = expression;
9246 expect(')', end_error);
9248 set_address_taken(expression, true);
9251 anchor = &argument->next;
9263 * Parse a asm statement clobber specification.
9265 static asm_clobber_t *parse_asm_clobbers(void)
9267 asm_clobber_t *result = NULL;
9268 asm_clobber_t **anchor = &result;
9270 while (token.type == T_STRING_LITERAL) {
9271 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9272 clobber->clobber = parse_string_literals();
9275 anchor = &clobber->next;
9285 * Parse an asm statement.
9287 static statement_t *parse_asm_statement(void)
9289 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9290 asm_statement_t *asm_statement = &statement->asms;
9294 if (next_if(T_volatile))
9295 asm_statement->is_volatile = true;
9297 expect('(', end_error);
9298 add_anchor_token(')');
9299 if (token.type != T_STRING_LITERAL) {
9300 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9303 asm_statement->asm_text = parse_string_literals();
9305 add_anchor_token(':');
9306 if (!next_if(':')) {
9307 rem_anchor_token(':');
9311 asm_statement->outputs = parse_asm_arguments(true);
9312 if (!next_if(':')) {
9313 rem_anchor_token(':');
9317 asm_statement->inputs = parse_asm_arguments(false);
9318 if (!next_if(':')) {
9319 rem_anchor_token(':');
9322 rem_anchor_token(':');
9324 asm_statement->clobbers = parse_asm_clobbers();
9327 rem_anchor_token(')');
9328 expect(')', end_error);
9329 expect(';', end_error);
9331 if (asm_statement->outputs == NULL) {
9332 /* GCC: An 'asm' instruction without any output operands will be treated
9333 * identically to a volatile 'asm' instruction. */
9334 asm_statement->is_volatile = true;
9339 return create_invalid_statement();
9342 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9344 statement_t *inner_stmt;
9345 switch (token.type) {
9347 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9348 inner_stmt = create_invalid_statement();
9352 if (label->kind == STATEMENT_LABEL) {
9353 /* Eat an empty statement here, to avoid the warning about an empty
9354 * statement after a label. label:; is commonly used to have a label
9355 * before a closing brace. */
9356 inner_stmt = create_empty_statement();
9363 inner_stmt = parse_statement();
9364 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9365 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9366 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9374 * Parse a case statement.
9376 static statement_t *parse_case_statement(void)
9378 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9379 source_position_t *const pos = &statement->base.source_position;
9383 expression_t *const expression = parse_expression();
9384 statement->case_label.expression = expression;
9385 expression_classification_t const expr_class = is_constant_expression(expression);
9386 if (expr_class != EXPR_CLASS_CONSTANT) {
9387 if (expr_class != EXPR_CLASS_ERROR) {
9388 errorf(pos, "case label does not reduce to an integer constant");
9390 statement->case_label.is_bad = true;
9392 long const val = fold_constant_to_int(expression);
9393 statement->case_label.first_case = val;
9394 statement->case_label.last_case = val;
9398 if (next_if(T_DOTDOTDOT)) {
9399 expression_t *const end_range = parse_expression();
9400 statement->case_label.end_range = end_range;
9401 expression_classification_t const end_class = is_constant_expression(end_range);
9402 if (end_class != EXPR_CLASS_CONSTANT) {
9403 if (end_class != EXPR_CLASS_ERROR) {
9404 errorf(pos, "case range does not reduce to an integer constant");
9406 statement->case_label.is_bad = true;
9408 long const val = fold_constant_to_int(end_range);
9409 statement->case_label.last_case = val;
9411 if (warning.other && val < statement->case_label.first_case) {
9412 statement->case_label.is_empty_range = true;
9413 warningf(pos, "empty range specified");
9419 PUSH_PARENT(statement);
9421 expect(':', end_error);
9424 if (current_switch != NULL) {
9425 if (! statement->case_label.is_bad) {
9426 /* Check for duplicate case values */
9427 case_label_statement_t *c = &statement->case_label;
9428 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9429 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9432 if (c->last_case < l->first_case || c->first_case > l->last_case)
9435 errorf(pos, "duplicate case value (previously used %P)",
9436 &l->base.source_position);
9440 /* link all cases into the switch statement */
9441 if (current_switch->last_case == NULL) {
9442 current_switch->first_case = &statement->case_label;
9444 current_switch->last_case->next = &statement->case_label;
9446 current_switch->last_case = &statement->case_label;
9448 errorf(pos, "case label not within a switch statement");
9451 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9458 * Parse a default statement.
9460 static statement_t *parse_default_statement(void)
9462 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9466 PUSH_PARENT(statement);
9468 expect(':', end_error);
9471 if (current_switch != NULL) {
9472 const case_label_statement_t *def_label = current_switch->default_label;
9473 if (def_label != NULL) {
9474 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9475 &def_label->base.source_position);
9477 current_switch->default_label = &statement->case_label;
9479 /* link all cases into the switch statement */
9480 if (current_switch->last_case == NULL) {
9481 current_switch->first_case = &statement->case_label;
9483 current_switch->last_case->next = &statement->case_label;
9485 current_switch->last_case = &statement->case_label;
9488 errorf(&statement->base.source_position,
9489 "'default' label not within a switch statement");
9492 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9499 * Parse a label statement.
9501 static statement_t *parse_label_statement(void)
9503 assert(token.type == T_IDENTIFIER);
9504 symbol_t *symbol = token.symbol;
9505 label_t *label = get_label(symbol);
9507 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9508 statement->label.label = label;
9512 PUSH_PARENT(statement);
9514 /* if statement is already set then the label is defined twice,
9515 * otherwise it was just mentioned in a goto/local label declaration so far
9517 if (label->statement != NULL) {
9518 errorf(HERE, "duplicate label '%Y' (declared %P)",
9519 symbol, &label->base.source_position);
9521 label->base.source_position = token.source_position;
9522 label->statement = statement;
9527 statement->label.statement = parse_label_inner_statement(statement, "label");
9529 /* remember the labels in a list for later checking */
9530 *label_anchor = &statement->label;
9531 label_anchor = &statement->label.next;
9538 * Parse an if statement.
9540 static statement_t *parse_if(void)
9542 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9546 PUSH_PARENT(statement);
9548 add_anchor_token('{');
9550 expect('(', end_error);
9551 add_anchor_token(')');
9552 expression_t *const expr = parse_expression();
9553 statement->ifs.condition = expr;
9554 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9556 semantic_condition(expr, "condition of 'if'-statment");
9557 mark_vars_read(expr, NULL);
9558 rem_anchor_token(')');
9559 expect(')', end_error);
9562 rem_anchor_token('{');
9564 add_anchor_token(T_else);
9565 statement_t *const true_stmt = parse_statement();
9566 statement->ifs.true_statement = true_stmt;
9567 rem_anchor_token(T_else);
9569 if (next_if(T_else)) {
9570 statement->ifs.false_statement = parse_statement();
9571 } else if (warning.parentheses &&
9572 true_stmt->kind == STATEMENT_IF &&
9573 true_stmt->ifs.false_statement != NULL) {
9574 warningf(&true_stmt->base.source_position,
9575 "suggest explicit braces to avoid ambiguous 'else'");
9583 * Check that all enums are handled in a switch.
9585 * @param statement the switch statement to check
9587 static void check_enum_cases(const switch_statement_t *statement)
9589 const type_t *type = skip_typeref(statement->expression->base.type);
9590 if (! is_type_enum(type))
9592 const enum_type_t *enumt = &type->enumt;
9594 /* if we have a default, no warnings */
9595 if (statement->default_label != NULL)
9598 /* FIXME: calculation of value should be done while parsing */
9599 /* TODO: quadratic algorithm here. Change to an n log n one */
9600 long last_value = -1;
9601 const entity_t *entry = enumt->enume->base.next;
9602 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9603 entry = entry->base.next) {
9604 const expression_t *expression = entry->enum_value.value;
9605 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9607 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9608 if (l->expression == NULL)
9610 if (l->first_case <= value && value <= l->last_case) {
9616 warningf(&statement->base.source_position,
9617 "enumeration value '%Y' not handled in switch",
9618 entry->base.symbol);
9625 * Parse a switch statement.
9627 static statement_t *parse_switch(void)
9629 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9633 PUSH_PARENT(statement);
9635 expect('(', end_error);
9636 add_anchor_token(')');
9637 expression_t *const expr = parse_expression();
9638 mark_vars_read(expr, NULL);
9639 type_t * type = skip_typeref(expr->base.type);
9640 if (is_type_integer(type)) {
9641 type = promote_integer(type);
9642 if (warning.traditional) {
9643 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9644 warningf(&expr->base.source_position,
9645 "'%T' switch expression not converted to '%T' in ISO C",
9649 } else if (is_type_valid(type)) {
9650 errorf(&expr->base.source_position,
9651 "switch quantity is not an integer, but '%T'", type);
9652 type = type_error_type;
9654 statement->switchs.expression = create_implicit_cast(expr, type);
9655 expect(')', end_error);
9656 rem_anchor_token(')');
9658 switch_statement_t *rem = current_switch;
9659 current_switch = &statement->switchs;
9660 statement->switchs.body = parse_statement();
9661 current_switch = rem;
9663 if (warning.switch_default &&
9664 statement->switchs.default_label == NULL) {
9665 warningf(&statement->base.source_position, "switch has no default case");
9667 if (warning.switch_enum)
9668 check_enum_cases(&statement->switchs);
9674 return create_invalid_statement();
9677 static statement_t *parse_loop_body(statement_t *const loop)
9679 statement_t *const rem = current_loop;
9680 current_loop = loop;
9682 statement_t *const body = parse_statement();
9689 * Parse a while statement.
9691 static statement_t *parse_while(void)
9693 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9697 PUSH_PARENT(statement);
9699 expect('(', end_error);
9700 add_anchor_token(')');
9701 expression_t *const cond = parse_expression();
9702 statement->whiles.condition = cond;
9703 /* §6.8.5:2 The controlling expression of an iteration statement shall
9704 * have scalar type. */
9705 semantic_condition(cond, "condition of 'while'-statement");
9706 mark_vars_read(cond, NULL);
9707 rem_anchor_token(')');
9708 expect(')', end_error);
9710 statement->whiles.body = parse_loop_body(statement);
9716 return create_invalid_statement();
9720 * Parse a do statement.
9722 static statement_t *parse_do(void)
9724 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9728 PUSH_PARENT(statement);
9730 add_anchor_token(T_while);
9731 statement->do_while.body = parse_loop_body(statement);
9732 rem_anchor_token(T_while);
9734 expect(T_while, end_error);
9735 expect('(', end_error);
9736 add_anchor_token(')');
9737 expression_t *const cond = parse_expression();
9738 statement->do_while.condition = cond;
9739 /* §6.8.5:2 The controlling expression of an iteration statement shall
9740 * have scalar type. */
9741 semantic_condition(cond, "condition of 'do-while'-statement");
9742 mark_vars_read(cond, NULL);
9743 rem_anchor_token(')');
9744 expect(')', end_error);
9745 expect(';', end_error);
9751 return create_invalid_statement();
9755 * Parse a for statement.
9757 static statement_t *parse_for(void)
9759 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9763 expect('(', end_error1);
9764 add_anchor_token(')');
9766 PUSH_PARENT(statement);
9768 size_t const top = environment_top();
9769 scope_t *old_scope = scope_push(&statement->fors.scope);
9771 bool old_gcc_extension = in_gcc_extension;
9772 while (next_if(T___extension__)) {
9773 in_gcc_extension = true;
9777 } else if (is_declaration_specifier(&token, false)) {
9778 parse_declaration(record_entity, DECL_FLAGS_NONE);
9780 add_anchor_token(';');
9781 expression_t *const init = parse_expression();
9782 statement->fors.initialisation = init;
9783 mark_vars_read(init, ENT_ANY);
9784 if (warning.unused_value && !expression_has_effect(init)) {
9785 warningf(&init->base.source_position,
9786 "initialisation of 'for'-statement has no effect");
9788 rem_anchor_token(';');
9789 expect(';', end_error2);
9791 in_gcc_extension = old_gcc_extension;
9793 if (token.type != ';') {
9794 add_anchor_token(';');
9795 expression_t *const cond = parse_expression();
9796 statement->fors.condition = cond;
9797 /* §6.8.5:2 The controlling expression of an iteration statement
9798 * shall have scalar type. */
9799 semantic_condition(cond, "condition of 'for'-statement");
9800 mark_vars_read(cond, NULL);
9801 rem_anchor_token(';');
9803 expect(';', end_error2);
9804 if (token.type != ')') {
9805 expression_t *const step = parse_expression();
9806 statement->fors.step = step;
9807 mark_vars_read(step, ENT_ANY);
9808 if (warning.unused_value && !expression_has_effect(step)) {
9809 warningf(&step->base.source_position,
9810 "step of 'for'-statement has no effect");
9813 expect(')', end_error2);
9814 rem_anchor_token(')');
9815 statement->fors.body = parse_loop_body(statement);
9817 assert(current_scope == &statement->fors.scope);
9818 scope_pop(old_scope);
9819 environment_pop_to(top);
9826 rem_anchor_token(')');
9827 assert(current_scope == &statement->fors.scope);
9828 scope_pop(old_scope);
9829 environment_pop_to(top);
9833 return create_invalid_statement();
9837 * Parse a goto statement.
9839 static statement_t *parse_goto(void)
9841 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9844 if (GNU_MODE && next_if('*')) {
9845 expression_t *expression = parse_expression();
9846 mark_vars_read(expression, NULL);
9848 /* Argh: although documentation says the expression must be of type void*,
9849 * gcc accepts anything that can be casted into void* without error */
9850 type_t *type = expression->base.type;
9852 if (type != type_error_type) {
9853 if (!is_type_pointer(type) && !is_type_integer(type)) {
9854 errorf(&expression->base.source_position,
9855 "cannot convert to a pointer type");
9856 } else if (warning.other && type != type_void_ptr) {
9857 warningf(&expression->base.source_position,
9858 "type of computed goto expression should be 'void*' not '%T'", type);
9860 expression = create_implicit_cast(expression, type_void_ptr);
9863 statement->gotos.expression = expression;
9864 } else if (token.type == T_IDENTIFIER) {
9865 symbol_t *symbol = token.symbol;
9867 statement->gotos.label = get_label(symbol);
9870 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9872 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9874 return create_invalid_statement();
9877 /* remember the goto's in a list for later checking */
9878 *goto_anchor = &statement->gotos;
9879 goto_anchor = &statement->gotos.next;
9881 expect(';', end_error);
9888 * Parse a continue statement.
9890 static statement_t *parse_continue(void)
9892 if (current_loop == NULL) {
9893 errorf(HERE, "continue statement not within loop");
9896 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9899 expect(';', end_error);
9906 * Parse a break statement.
9908 static statement_t *parse_break(void)
9910 if (current_switch == NULL && current_loop == NULL) {
9911 errorf(HERE, "break statement not within loop or switch");
9914 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9917 expect(';', end_error);
9924 * Parse a __leave statement.
9926 static statement_t *parse_leave_statement(void)
9928 if (current_try == NULL) {
9929 errorf(HERE, "__leave statement not within __try");
9932 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9935 expect(';', end_error);
9942 * Check if a given entity represents a local variable.
9944 static bool is_local_variable(const entity_t *entity)
9946 if (entity->kind != ENTITY_VARIABLE)
9949 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9950 case STORAGE_CLASS_AUTO:
9951 case STORAGE_CLASS_REGISTER: {
9952 const type_t *type = skip_typeref(entity->declaration.type);
9953 if (is_type_function(type)) {
9965 * Check if a given expression represents a local variable.
9967 static bool expression_is_local_variable(const expression_t *expression)
9969 if (expression->base.kind != EXPR_REFERENCE) {
9972 const entity_t *entity = expression->reference.entity;
9973 return is_local_variable(entity);
9977 * Check if a given expression represents a local variable and
9978 * return its declaration then, else return NULL.
9980 entity_t *expression_is_variable(const expression_t *expression)
9982 if (expression->base.kind != EXPR_REFERENCE) {
9985 entity_t *entity = expression->reference.entity;
9986 if (entity->kind != ENTITY_VARIABLE)
9993 * Parse a return statement.
9995 static statement_t *parse_return(void)
9999 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10001 expression_t *return_value = NULL;
10002 if (token.type != ';') {
10003 return_value = parse_expression();
10004 mark_vars_read(return_value, NULL);
10007 const type_t *const func_type = skip_typeref(current_function->base.type);
10008 assert(is_type_function(func_type));
10009 type_t *const return_type = skip_typeref(func_type->function.return_type);
10011 source_position_t const *const pos = &statement->base.source_position;
10012 if (return_value != NULL) {
10013 type_t *return_value_type = skip_typeref(return_value->base.type);
10015 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10016 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10017 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10018 /* Only warn in C mode, because GCC does the same */
10019 if (c_mode & _CXX || strict_mode) {
10021 "'return' with a value, in function returning 'void'");
10022 } else if (warning.other) {
10024 "'return' with a value, in function returning 'void'");
10026 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10027 /* Only warn in C mode, because GCC does the same */
10030 "'return' with expression in function returning 'void'");
10031 } else if (warning.other) {
10033 "'return' with expression in function returning 'void'");
10037 assign_error_t error = semantic_assign(return_type, return_value);
10038 report_assign_error(error, return_type, return_value, "'return'",
10041 return_value = create_implicit_cast(return_value, return_type);
10042 /* check for returning address of a local var */
10043 if (warning.other && return_value != NULL
10044 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10045 const expression_t *expression = return_value->unary.value;
10046 if (expression_is_local_variable(expression)) {
10047 warningf(pos, "function returns address of local variable");
10050 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10051 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10052 if (c_mode & _CXX || strict_mode) {
10054 "'return' without value, in function returning non-void");
10057 "'return' without value, in function returning non-void");
10060 statement->returns.value = return_value;
10062 expect(';', end_error);
10069 * Parse a declaration statement.
10071 static statement_t *parse_declaration_statement(void)
10073 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10075 entity_t *before = current_scope->last_entity;
10077 parse_external_declaration();
10079 parse_declaration(record_entity, DECL_FLAGS_NONE);
10082 declaration_statement_t *const decl = &statement->declaration;
10083 entity_t *const begin =
10084 before != NULL ? before->base.next : current_scope->entities;
10085 decl->declarations_begin = begin;
10086 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10092 * Parse an expression statement, ie. expr ';'.
10094 static statement_t *parse_expression_statement(void)
10096 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10098 expression_t *const expr = parse_expression();
10099 statement->expression.expression = expr;
10100 mark_vars_read(expr, ENT_ANY);
10102 expect(';', end_error);
10109 * Parse a microsoft __try { } __finally { } or
10110 * __try{ } __except() { }
10112 static statement_t *parse_ms_try_statment(void)
10114 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10117 PUSH_PARENT(statement);
10119 ms_try_statement_t *rem = current_try;
10120 current_try = &statement->ms_try;
10121 statement->ms_try.try_statement = parse_compound_statement(false);
10126 if (next_if(T___except)) {
10127 expect('(', end_error);
10128 add_anchor_token(')');
10129 expression_t *const expr = parse_expression();
10130 mark_vars_read(expr, NULL);
10131 type_t * type = skip_typeref(expr->base.type);
10132 if (is_type_integer(type)) {
10133 type = promote_integer(type);
10134 } else if (is_type_valid(type)) {
10135 errorf(&expr->base.source_position,
10136 "__expect expression is not an integer, but '%T'", type);
10137 type = type_error_type;
10139 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10140 rem_anchor_token(')');
10141 expect(')', end_error);
10142 statement->ms_try.final_statement = parse_compound_statement(false);
10143 } else if (next_if(T__finally)) {
10144 statement->ms_try.final_statement = parse_compound_statement(false);
10146 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10147 return create_invalid_statement();
10151 return create_invalid_statement();
10154 static statement_t *parse_empty_statement(void)
10156 if (warning.empty_statement) {
10157 warningf(HERE, "statement is empty");
10159 statement_t *const statement = create_empty_statement();
10164 static statement_t *parse_local_label_declaration(void)
10166 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10170 entity_t *begin = NULL;
10171 entity_t *end = NULL;
10172 entity_t **anchor = &begin;
10174 if (token.type != T_IDENTIFIER) {
10175 parse_error_expected("while parsing local label declaration",
10176 T_IDENTIFIER, NULL);
10179 symbol_t *symbol = token.symbol;
10180 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10181 if (entity != NULL && entity->base.parent_scope == current_scope) {
10182 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10183 symbol, &entity->base.source_position);
10185 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10187 entity->base.parent_scope = current_scope;
10188 entity->base.namespc = NAMESPACE_LABEL;
10189 entity->base.source_position = token.source_position;
10190 entity->base.symbol = symbol;
10193 anchor = &entity->base.next;
10196 environment_push(entity);
10199 } while (next_if(','));
10200 expect(';', end_error);
10202 statement->declaration.declarations_begin = begin;
10203 statement->declaration.declarations_end = end;
10207 static void parse_namespace_definition(void)
10211 entity_t *entity = NULL;
10212 symbol_t *symbol = NULL;
10214 if (token.type == T_IDENTIFIER) {
10215 symbol = token.symbol;
10218 entity = get_entity(symbol, NAMESPACE_NORMAL);
10220 && entity->kind != ENTITY_NAMESPACE
10221 && entity->base.parent_scope == current_scope) {
10222 if (is_entity_valid(entity)) {
10223 error_redefined_as_different_kind(&token.source_position,
10224 entity, ENTITY_NAMESPACE);
10230 if (entity == NULL) {
10231 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10232 entity->base.symbol = symbol;
10233 entity->base.source_position = token.source_position;
10234 entity->base.namespc = NAMESPACE_NORMAL;
10235 entity->base.parent_scope = current_scope;
10238 if (token.type == '=') {
10239 /* TODO: parse namespace alias */
10240 panic("namespace alias definition not supported yet");
10243 environment_push(entity);
10244 append_entity(current_scope, entity);
10246 size_t const top = environment_top();
10247 scope_t *old_scope = scope_push(&entity->namespacee.members);
10249 entity_t *old_current_entity = current_entity;
10250 current_entity = entity;
10252 expect('{', end_error);
10254 expect('}', end_error);
10257 assert(current_scope == &entity->namespacee.members);
10258 assert(current_entity == entity);
10259 current_entity = old_current_entity;
10260 scope_pop(old_scope);
10261 environment_pop_to(top);
10265 * Parse a statement.
10266 * There's also parse_statement() which additionally checks for
10267 * "statement has no effect" warnings
10269 static statement_t *intern_parse_statement(void)
10271 statement_t *statement = NULL;
10273 /* declaration or statement */
10274 add_anchor_token(';');
10275 switch (token.type) {
10276 case T_IDENTIFIER: {
10277 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10278 if (la1_type == ':') {
10279 statement = parse_label_statement();
10280 } else if (is_typedef_symbol(token.symbol)) {
10281 statement = parse_declaration_statement();
10283 /* it's an identifier, the grammar says this must be an
10284 * expression statement. However it is common that users mistype
10285 * declaration types, so we guess a bit here to improve robustness
10286 * for incorrect programs */
10287 switch (la1_type) {
10290 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10292 statement = parse_expression_statement();
10296 statement = parse_declaration_statement();
10304 case T___extension__:
10305 /* This can be a prefix to a declaration or an expression statement.
10306 * We simply eat it now and parse the rest with tail recursion. */
10307 while (next_if(T___extension__)) {}
10308 bool old_gcc_extension = in_gcc_extension;
10309 in_gcc_extension = true;
10310 statement = intern_parse_statement();
10311 in_gcc_extension = old_gcc_extension;
10315 statement = parse_declaration_statement();
10319 statement = parse_local_label_declaration();
10322 case ';': statement = parse_empty_statement(); break;
10323 case '{': statement = parse_compound_statement(false); break;
10324 case T___leave: statement = parse_leave_statement(); break;
10325 case T___try: statement = parse_ms_try_statment(); break;
10326 case T_asm: statement = parse_asm_statement(); break;
10327 case T_break: statement = parse_break(); break;
10328 case T_case: statement = parse_case_statement(); break;
10329 case T_continue: statement = parse_continue(); break;
10330 case T_default: statement = parse_default_statement(); break;
10331 case T_do: statement = parse_do(); break;
10332 case T_for: statement = parse_for(); break;
10333 case T_goto: statement = parse_goto(); break;
10334 case T_if: statement = parse_if(); break;
10335 case T_return: statement = parse_return(); break;
10336 case T_switch: statement = parse_switch(); break;
10337 case T_while: statement = parse_while(); break;
10340 statement = parse_expression_statement();
10344 errorf(HERE, "unexpected token %K while parsing statement", &token);
10345 statement = create_invalid_statement();
10350 rem_anchor_token(';');
10352 assert(statement != NULL
10353 && statement->base.source_position.input_name != NULL);
10359 * parse a statement and emits "statement has no effect" warning if needed
10360 * (This is really a wrapper around intern_parse_statement with check for 1
10361 * single warning. It is needed, because for statement expressions we have
10362 * to avoid the warning on the last statement)
10364 static statement_t *parse_statement(void)
10366 statement_t *statement = intern_parse_statement();
10368 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10369 expression_t *expression = statement->expression.expression;
10370 if (!expression_has_effect(expression)) {
10371 warningf(&expression->base.source_position,
10372 "statement has no effect");
10380 * Parse a compound statement.
10382 static statement_t *parse_compound_statement(bool inside_expression_statement)
10384 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10386 PUSH_PARENT(statement);
10389 add_anchor_token('}');
10390 /* tokens, which can start a statement */
10391 /* TODO MS, __builtin_FOO */
10392 add_anchor_token('!');
10393 add_anchor_token('&');
10394 add_anchor_token('(');
10395 add_anchor_token('*');
10396 add_anchor_token('+');
10397 add_anchor_token('-');
10398 add_anchor_token('{');
10399 add_anchor_token('~');
10400 add_anchor_token(T_CHARACTER_CONSTANT);
10401 add_anchor_token(T_COLONCOLON);
10402 add_anchor_token(T_FLOATINGPOINT);
10403 add_anchor_token(T_IDENTIFIER);
10404 add_anchor_token(T_INTEGER);
10405 add_anchor_token(T_MINUSMINUS);
10406 add_anchor_token(T_PLUSPLUS);
10407 add_anchor_token(T_STRING_LITERAL);
10408 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10409 add_anchor_token(T_WIDE_STRING_LITERAL);
10410 add_anchor_token(T__Bool);
10411 add_anchor_token(T__Complex);
10412 add_anchor_token(T__Imaginary);
10413 add_anchor_token(T___FUNCTION__);
10414 add_anchor_token(T___PRETTY_FUNCTION__);
10415 add_anchor_token(T___alignof__);
10416 add_anchor_token(T___attribute__);
10417 add_anchor_token(T___builtin_va_start);
10418 add_anchor_token(T___extension__);
10419 add_anchor_token(T___func__);
10420 add_anchor_token(T___imag__);
10421 add_anchor_token(T___label__);
10422 add_anchor_token(T___real__);
10423 add_anchor_token(T___thread);
10424 add_anchor_token(T_asm);
10425 add_anchor_token(T_auto);
10426 add_anchor_token(T_bool);
10427 add_anchor_token(T_break);
10428 add_anchor_token(T_case);
10429 add_anchor_token(T_char);
10430 add_anchor_token(T_class);
10431 add_anchor_token(T_const);
10432 add_anchor_token(T_const_cast);
10433 add_anchor_token(T_continue);
10434 add_anchor_token(T_default);
10435 add_anchor_token(T_delete);
10436 add_anchor_token(T_double);
10437 add_anchor_token(T_do);
10438 add_anchor_token(T_dynamic_cast);
10439 add_anchor_token(T_enum);
10440 add_anchor_token(T_extern);
10441 add_anchor_token(T_false);
10442 add_anchor_token(T_float);
10443 add_anchor_token(T_for);
10444 add_anchor_token(T_goto);
10445 add_anchor_token(T_if);
10446 add_anchor_token(T_inline);
10447 add_anchor_token(T_int);
10448 add_anchor_token(T_long);
10449 add_anchor_token(T_new);
10450 add_anchor_token(T_operator);
10451 add_anchor_token(T_register);
10452 add_anchor_token(T_reinterpret_cast);
10453 add_anchor_token(T_restrict);
10454 add_anchor_token(T_return);
10455 add_anchor_token(T_short);
10456 add_anchor_token(T_signed);
10457 add_anchor_token(T_sizeof);
10458 add_anchor_token(T_static);
10459 add_anchor_token(T_static_cast);
10460 add_anchor_token(T_struct);
10461 add_anchor_token(T_switch);
10462 add_anchor_token(T_template);
10463 add_anchor_token(T_this);
10464 add_anchor_token(T_throw);
10465 add_anchor_token(T_true);
10466 add_anchor_token(T_try);
10467 add_anchor_token(T_typedef);
10468 add_anchor_token(T_typeid);
10469 add_anchor_token(T_typename);
10470 add_anchor_token(T_typeof);
10471 add_anchor_token(T_union);
10472 add_anchor_token(T_unsigned);
10473 add_anchor_token(T_using);
10474 add_anchor_token(T_void);
10475 add_anchor_token(T_volatile);
10476 add_anchor_token(T_wchar_t);
10477 add_anchor_token(T_while);
10479 size_t const top = environment_top();
10480 scope_t *old_scope = scope_push(&statement->compound.scope);
10482 statement_t **anchor = &statement->compound.statements;
10483 bool only_decls_so_far = true;
10484 while (token.type != '}') {
10485 if (token.type == T_EOF) {
10486 errorf(&statement->base.source_position,
10487 "EOF while parsing compound statement");
10490 statement_t *sub_statement = intern_parse_statement();
10491 if (is_invalid_statement(sub_statement)) {
10492 /* an error occurred. if we are at an anchor, return */
10498 if (warning.declaration_after_statement) {
10499 if (sub_statement->kind != STATEMENT_DECLARATION) {
10500 only_decls_so_far = false;
10501 } else if (!only_decls_so_far) {
10502 warningf(&sub_statement->base.source_position,
10503 "ISO C90 forbids mixed declarations and code");
10507 *anchor = sub_statement;
10509 while (sub_statement->base.next != NULL)
10510 sub_statement = sub_statement->base.next;
10512 anchor = &sub_statement->base.next;
10516 /* look over all statements again to produce no effect warnings */
10517 if (warning.unused_value) {
10518 statement_t *sub_statement = statement->compound.statements;
10519 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10520 if (sub_statement->kind != STATEMENT_EXPRESSION)
10522 /* don't emit a warning for the last expression in an expression
10523 * statement as it has always an effect */
10524 if (inside_expression_statement && sub_statement->base.next == NULL)
10527 expression_t *expression = sub_statement->expression.expression;
10528 if (!expression_has_effect(expression)) {
10529 warningf(&expression->base.source_position,
10530 "statement has no effect");
10536 rem_anchor_token(T_while);
10537 rem_anchor_token(T_wchar_t);
10538 rem_anchor_token(T_volatile);
10539 rem_anchor_token(T_void);
10540 rem_anchor_token(T_using);
10541 rem_anchor_token(T_unsigned);
10542 rem_anchor_token(T_union);
10543 rem_anchor_token(T_typeof);
10544 rem_anchor_token(T_typename);
10545 rem_anchor_token(T_typeid);
10546 rem_anchor_token(T_typedef);
10547 rem_anchor_token(T_try);
10548 rem_anchor_token(T_true);
10549 rem_anchor_token(T_throw);
10550 rem_anchor_token(T_this);
10551 rem_anchor_token(T_template);
10552 rem_anchor_token(T_switch);
10553 rem_anchor_token(T_struct);
10554 rem_anchor_token(T_static_cast);
10555 rem_anchor_token(T_static);
10556 rem_anchor_token(T_sizeof);
10557 rem_anchor_token(T_signed);
10558 rem_anchor_token(T_short);
10559 rem_anchor_token(T_return);
10560 rem_anchor_token(T_restrict);
10561 rem_anchor_token(T_reinterpret_cast);
10562 rem_anchor_token(T_register);
10563 rem_anchor_token(T_operator);
10564 rem_anchor_token(T_new);
10565 rem_anchor_token(T_long);
10566 rem_anchor_token(T_int);
10567 rem_anchor_token(T_inline);
10568 rem_anchor_token(T_if);
10569 rem_anchor_token(T_goto);
10570 rem_anchor_token(T_for);
10571 rem_anchor_token(T_float);
10572 rem_anchor_token(T_false);
10573 rem_anchor_token(T_extern);
10574 rem_anchor_token(T_enum);
10575 rem_anchor_token(T_dynamic_cast);
10576 rem_anchor_token(T_do);
10577 rem_anchor_token(T_double);
10578 rem_anchor_token(T_delete);
10579 rem_anchor_token(T_default);
10580 rem_anchor_token(T_continue);
10581 rem_anchor_token(T_const_cast);
10582 rem_anchor_token(T_const);
10583 rem_anchor_token(T_class);
10584 rem_anchor_token(T_char);
10585 rem_anchor_token(T_case);
10586 rem_anchor_token(T_break);
10587 rem_anchor_token(T_bool);
10588 rem_anchor_token(T_auto);
10589 rem_anchor_token(T_asm);
10590 rem_anchor_token(T___thread);
10591 rem_anchor_token(T___real__);
10592 rem_anchor_token(T___label__);
10593 rem_anchor_token(T___imag__);
10594 rem_anchor_token(T___func__);
10595 rem_anchor_token(T___extension__);
10596 rem_anchor_token(T___builtin_va_start);
10597 rem_anchor_token(T___attribute__);
10598 rem_anchor_token(T___alignof__);
10599 rem_anchor_token(T___PRETTY_FUNCTION__);
10600 rem_anchor_token(T___FUNCTION__);
10601 rem_anchor_token(T__Imaginary);
10602 rem_anchor_token(T__Complex);
10603 rem_anchor_token(T__Bool);
10604 rem_anchor_token(T_WIDE_STRING_LITERAL);
10605 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10606 rem_anchor_token(T_STRING_LITERAL);
10607 rem_anchor_token(T_PLUSPLUS);
10608 rem_anchor_token(T_MINUSMINUS);
10609 rem_anchor_token(T_INTEGER);
10610 rem_anchor_token(T_IDENTIFIER);
10611 rem_anchor_token(T_FLOATINGPOINT);
10612 rem_anchor_token(T_COLONCOLON);
10613 rem_anchor_token(T_CHARACTER_CONSTANT);
10614 rem_anchor_token('~');
10615 rem_anchor_token('{');
10616 rem_anchor_token('-');
10617 rem_anchor_token('+');
10618 rem_anchor_token('*');
10619 rem_anchor_token('(');
10620 rem_anchor_token('&');
10621 rem_anchor_token('!');
10622 rem_anchor_token('}');
10623 assert(current_scope == &statement->compound.scope);
10624 scope_pop(old_scope);
10625 environment_pop_to(top);
10632 * Check for unused global static functions and variables
10634 static void check_unused_globals(void)
10636 if (!warning.unused_function && !warning.unused_variable)
10639 for (const entity_t *entity = file_scope->entities; entity != NULL;
10640 entity = entity->base.next) {
10641 if (!is_declaration(entity))
10644 const declaration_t *declaration = &entity->declaration;
10645 if (declaration->used ||
10646 declaration->modifiers & DM_UNUSED ||
10647 declaration->modifiers & DM_USED ||
10648 declaration->storage_class != STORAGE_CLASS_STATIC)
10651 type_t *const type = declaration->type;
10653 if (entity->kind == ENTITY_FUNCTION) {
10654 /* inhibit warning for static inline functions */
10655 if (entity->function.is_inline)
10658 s = entity->function.statement != NULL ? "defined" : "declared";
10663 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10664 type, declaration->base.symbol, s);
10668 static void parse_global_asm(void)
10670 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10673 expect('(', end_error);
10675 statement->asms.asm_text = parse_string_literals();
10676 statement->base.next = unit->global_asm;
10677 unit->global_asm = statement;
10679 expect(')', end_error);
10680 expect(';', end_error);
10685 static void parse_linkage_specification(void)
10689 const char *linkage = parse_string_literals().begin;
10691 linkage_kind_t old_linkage = current_linkage;
10692 linkage_kind_t new_linkage;
10693 if (strcmp(linkage, "C") == 0) {
10694 new_linkage = LINKAGE_C;
10695 } else if (strcmp(linkage, "C++") == 0) {
10696 new_linkage = LINKAGE_CXX;
10698 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10699 new_linkage = LINKAGE_INVALID;
10701 current_linkage = new_linkage;
10703 if (next_if('{')) {
10705 expect('}', end_error);
10711 assert(current_linkage == new_linkage);
10712 current_linkage = old_linkage;
10715 static void parse_external(void)
10717 switch (token.type) {
10718 DECLARATION_START_NO_EXTERN
10720 case T___extension__:
10721 /* tokens below are for implicit int */
10722 case '&': /* & x; -> int& x; (and error later, because C++ has no
10724 case '*': /* * x; -> int* x; */
10725 case '(': /* (x); -> int (x); */
10726 parse_external_declaration();
10730 if (look_ahead(1)->type == T_STRING_LITERAL) {
10731 parse_linkage_specification();
10733 parse_external_declaration();
10738 parse_global_asm();
10742 parse_namespace_definition();
10746 if (!strict_mode) {
10748 warningf(HERE, "stray ';' outside of function");
10755 errorf(HERE, "stray %K outside of function", &token);
10756 if (token.type == '(' || token.type == '{' || token.type == '[')
10757 eat_until_matching_token(token.type);
10763 static void parse_externals(void)
10765 add_anchor_token('}');
10766 add_anchor_token(T_EOF);
10769 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10770 unsigned char token_anchor_copy[T_LAST_TOKEN];
10771 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10774 while (token.type != T_EOF && token.type != '}') {
10776 bool anchor_leak = false;
10777 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10778 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10780 /* the anchor set and its copy differs */
10781 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10782 anchor_leak = true;
10785 if (in_gcc_extension) {
10786 /* an gcc extension scope was not closed */
10787 errorf(HERE, "Leaked __extension__");
10788 anchor_leak = true;
10798 rem_anchor_token(T_EOF);
10799 rem_anchor_token('}');
10803 * Parse a translation unit.
10805 static void parse_translation_unit(void)
10807 add_anchor_token(T_EOF);
10812 if (token.type == T_EOF)
10815 errorf(HERE, "stray %K outside of function", &token);
10816 if (token.type == '(' || token.type == '{' || token.type == '[')
10817 eat_until_matching_token(token.type);
10825 * @return the translation unit or NULL if errors occurred.
10827 void start_parsing(void)
10829 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10830 label_stack = NEW_ARR_F(stack_entry_t, 0);
10831 diagnostic_count = 0;
10835 print_to_file(stderr);
10837 assert(unit == NULL);
10838 unit = allocate_ast_zero(sizeof(unit[0]));
10840 assert(file_scope == NULL);
10841 file_scope = &unit->scope;
10843 assert(current_scope == NULL);
10844 scope_push(&unit->scope);
10846 create_gnu_builtins();
10848 create_microsoft_intrinsics();
10851 translation_unit_t *finish_parsing(void)
10853 assert(current_scope == &unit->scope);
10856 assert(file_scope == &unit->scope);
10857 check_unused_globals();
10860 DEL_ARR_F(environment_stack);
10861 DEL_ARR_F(label_stack);
10863 translation_unit_t *result = unit;
10868 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10869 * are given length one. */
10870 static void complete_incomplete_arrays(void)
10872 size_t n = ARR_LEN(incomplete_arrays);
10873 for (size_t i = 0; i != n; ++i) {
10874 declaration_t *const decl = incomplete_arrays[i];
10875 type_t *const orig_type = decl->type;
10876 type_t *const type = skip_typeref(orig_type);
10878 if (!is_type_incomplete(type))
10881 if (warning.other) {
10882 warningf(&decl->base.source_position,
10883 "array '%#T' assumed to have one element",
10884 orig_type, decl->base.symbol);
10887 type_t *const new_type = duplicate_type(type);
10888 new_type->array.size_constant = true;
10889 new_type->array.has_implicit_size = true;
10890 new_type->array.size = 1;
10892 type_t *const result = identify_new_type(new_type);
10894 decl->type = result;
10898 void prepare_main_collect2(entity_t *entity)
10900 // create call to __main
10901 symbol_t *symbol = symbol_table_insert("__main");
10902 entity_t *subsubmain_ent
10903 = create_implicit_function(symbol, &builtin_source_position);
10905 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10906 type_t *ftype = subsubmain_ent->declaration.type;
10907 ref->base.source_position = builtin_source_position;
10908 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10909 ref->reference.entity = subsubmain_ent;
10911 expression_t *call = allocate_expression_zero(EXPR_CALL);
10912 call->base.source_position = builtin_source_position;
10913 call->base.type = type_void;
10914 call->call.function = ref;
10916 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10917 expr_statement->base.source_position = builtin_source_position;
10918 expr_statement->expression.expression = call;
10920 statement_t *statement = entity->function.statement;
10921 assert(statement->kind == STATEMENT_COMPOUND);
10922 compound_statement_t *compounds = &statement->compound;
10924 expr_statement->base.next = compounds->statements;
10925 compounds->statements = expr_statement;
10930 lookahead_bufpos = 0;
10931 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10934 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10935 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10936 parse_translation_unit();
10937 complete_incomplete_arrays();
10938 DEL_ARR_F(incomplete_arrays);
10939 incomplete_arrays = NULL;
10943 * Initialize the parser.
10945 void init_parser(void)
10947 sym_anonymous = symbol_table_insert("<anonymous>");
10949 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10951 init_expression_parsers();
10952 obstack_init(&temp_obst);
10954 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10955 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10959 * Terminate the parser.
10961 void exit_parser(void)
10963 obstack_free(&temp_obst, NULL);