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_sub_expression(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 end_error 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 entity_t *entity = symbol->entity;
706 for (; entity != NULL; entity = entity->base.symbol_next) {
707 if (entity->base.namespc == namespc)
714 /* §6.2.3:1 24) There is only one name space for tags even though three are
716 static entity_t *get_tag(symbol_t const *const symbol,
717 entity_kind_tag_t const kind)
719 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
720 if (entity != NULL && entity->kind != kind) {
722 "'%Y' defined as wrong kind of tag (previous definition %P)",
723 symbol, &entity->base.source_position);
730 * pushs an entity on the environment stack and links the corresponding symbol
733 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
735 symbol_t *symbol = entity->base.symbol;
736 entity_namespace_t namespc = entity->base.namespc;
737 assert(namespc != NAMESPACE_INVALID);
739 /* replace/add entity into entity list of the symbol */
742 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
747 /* replace an entry? */
748 if (iter->base.namespc == namespc) {
749 entity->base.symbol_next = iter->base.symbol_next;
755 /* remember old declaration */
757 entry.symbol = symbol;
758 entry.old_entity = iter;
759 entry.namespc = namespc;
760 ARR_APP1(stack_entry_t, *stack_ptr, entry);
764 * Push an entity on the environment stack.
766 static void environment_push(entity_t *entity)
768 assert(entity->base.source_position.input_name != NULL);
769 assert(entity->base.parent_scope != NULL);
770 stack_push(&environment_stack, entity);
774 * Push a declaration on the global label stack.
776 * @param declaration the declaration
778 static void label_push(entity_t *label)
780 /* we abuse the parameters scope as parent for the labels */
781 label->base.parent_scope = ¤t_function->parameters;
782 stack_push(&label_stack, label);
786 * pops symbols from the environment stack until @p new_top is the top element
788 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
790 stack_entry_t *stack = *stack_ptr;
791 size_t top = ARR_LEN(stack);
794 assert(new_top <= top);
798 for (i = top; i > new_top; --i) {
799 stack_entry_t *entry = &stack[i - 1];
801 entity_t *old_entity = entry->old_entity;
802 symbol_t *symbol = entry->symbol;
803 entity_namespace_t namespc = entry->namespc;
805 /* replace with old_entity/remove */
808 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
810 assert(iter != NULL);
811 /* replace an entry? */
812 if (iter->base.namespc == namespc)
816 /* restore definition from outer scopes (if there was one) */
817 if (old_entity != NULL) {
818 old_entity->base.symbol_next = iter->base.symbol_next;
819 *anchor = old_entity;
821 /* remove entry from list */
822 *anchor = iter->base.symbol_next;
826 ARR_SHRINKLEN(*stack_ptr, (int) new_top);
830 * Pop all entries from the environment stack until the new_top
833 * @param new_top the new stack top
835 static void environment_pop_to(size_t new_top)
837 stack_pop_to(&environment_stack, new_top);
841 * Pop all entries from the global label stack until the new_top
844 * @param new_top the new stack top
846 static void label_pop_to(size_t new_top)
848 stack_pop_to(&label_stack, new_top);
851 static int get_akind_rank(atomic_type_kind_t akind)
857 * Return the type rank for an atomic type.
859 static int get_rank(const type_t *type)
861 assert(!is_typeref(type));
862 if (type->kind == TYPE_ENUM)
863 return get_akind_rank(type->enumt.akind);
865 assert(type->kind == TYPE_ATOMIC);
866 return get_akind_rank(type->atomic.akind);
870 * §6.3.1.1:2 Do integer promotion for a given type.
872 * @param type the type to promote
873 * @return the promoted type
875 static type_t *promote_integer(type_t *type)
877 if (type->kind == TYPE_BITFIELD)
878 type = type->bitfield.base_type;
880 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
887 * Create a cast expression.
889 * @param expression the expression to cast
890 * @param dest_type the destination type
892 static expression_t *create_cast_expression(expression_t *expression,
895 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
897 cast->unary.value = expression;
898 cast->base.type = dest_type;
904 * Check if a given expression represents a null pointer constant.
906 * @param expression the expression to check
908 static bool is_null_pointer_constant(const expression_t *expression)
910 /* skip void* cast */
911 if (expression->kind == EXPR_UNARY_CAST ||
912 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
913 type_t *const type = skip_typeref(expression->base.type);
914 if (types_compatible(type, type_void_ptr))
915 expression = expression->unary.value;
918 type_t *const type = skip_typeref(expression->base.type);
920 is_type_integer(type) &&
921 is_constant_expression(expression) &&
922 !fold_constant_to_bool(expression);
926 * Create an implicit cast expression.
928 * @param expression the expression to cast
929 * @param dest_type the destination type
931 static expression_t *create_implicit_cast(expression_t *expression,
934 type_t *const source_type = expression->base.type;
936 if (source_type == dest_type)
939 return create_cast_expression(expression, dest_type);
942 typedef enum assign_error_t {
944 ASSIGN_ERROR_INCOMPATIBLE,
945 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
946 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
947 ASSIGN_WARNING_POINTER_FROM_INT,
948 ASSIGN_WARNING_INT_FROM_POINTER
951 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
952 const expression_t *const right,
954 const source_position_t *source_position)
956 type_t *const orig_type_right = right->base.type;
957 type_t *const type_left = skip_typeref(orig_type_left);
958 type_t *const type_right = skip_typeref(orig_type_right);
963 case ASSIGN_ERROR_INCOMPATIBLE:
964 errorf(source_position,
965 "destination type '%T' in %s is incompatible with type '%T'",
966 orig_type_left, context, orig_type_right);
969 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
971 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
972 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
974 /* the left type has all qualifiers from the right type */
975 unsigned missing_qualifiers
976 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
977 warningf(source_position,
978 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
979 orig_type_left, context, orig_type_right, missing_qualifiers);
984 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
986 warningf(source_position,
987 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
988 orig_type_left, context, right, orig_type_right);
992 case ASSIGN_WARNING_POINTER_FROM_INT:
994 warningf(source_position,
995 "%s makes pointer '%T' from integer '%T' without a cast",
996 context, orig_type_left, orig_type_right);
1000 case ASSIGN_WARNING_INT_FROM_POINTER:
1001 if (warning.other) {
1002 warningf(source_position,
1003 "%s makes integer '%T' from pointer '%T' without a cast",
1004 context, orig_type_left, orig_type_right);
1009 panic("invalid error value");
1013 /** Implements the rules from §6.5.16.1 */
1014 static assign_error_t semantic_assign(type_t *orig_type_left,
1015 const expression_t *const right)
1017 type_t *const orig_type_right = right->base.type;
1018 type_t *const type_left = skip_typeref(orig_type_left);
1019 type_t *const type_right = skip_typeref(orig_type_right);
1021 if (is_type_pointer(type_left)) {
1022 if (is_null_pointer_constant(right)) {
1023 return ASSIGN_SUCCESS;
1024 } else if (is_type_pointer(type_right)) {
1025 type_t *points_to_left
1026 = skip_typeref(type_left->pointer.points_to);
1027 type_t *points_to_right
1028 = skip_typeref(type_right->pointer.points_to);
1029 assign_error_t res = ASSIGN_SUCCESS;
1031 /* the left type has all qualifiers from the right type */
1032 unsigned missing_qualifiers
1033 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1034 if (missing_qualifiers != 0) {
1035 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1038 points_to_left = get_unqualified_type(points_to_left);
1039 points_to_right = get_unqualified_type(points_to_right);
1041 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1044 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1045 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1046 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1049 if (!types_compatible(points_to_left, points_to_right)) {
1050 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1054 } else if (is_type_integer(type_right)) {
1055 return ASSIGN_WARNING_POINTER_FROM_INT;
1057 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1058 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1059 && is_type_pointer(type_right))) {
1060 return ASSIGN_SUCCESS;
1061 } else if ((is_type_compound(type_left) && is_type_compound(type_right))
1062 || (is_type_builtin(type_left) && is_type_builtin(type_right))) {
1063 type_t *const unqual_type_left = get_unqualified_type(type_left);
1064 type_t *const unqual_type_right = get_unqualified_type(type_right);
1065 if (types_compatible(unqual_type_left, unqual_type_right)) {
1066 return ASSIGN_SUCCESS;
1068 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1069 return ASSIGN_WARNING_INT_FROM_POINTER;
1072 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1073 return ASSIGN_SUCCESS;
1075 return ASSIGN_ERROR_INCOMPATIBLE;
1078 static expression_t *parse_constant_expression(void)
1080 expression_t *result = parse_sub_expression(PREC_CONDITIONAL);
1082 if (!is_constant_expression(result)) {
1083 errorf(&result->base.source_position,
1084 "expression '%E' is not constant", result);
1090 static expression_t *parse_assignment_expression(void)
1092 return parse_sub_expression(PREC_ASSIGNMENT);
1095 static void warn_string_concat(const source_position_t *pos)
1097 if (warning.traditional) {
1098 warningf(pos, "traditional C rejects string constant concatenation");
1102 static string_t parse_string_literals(void)
1104 assert(token.type == T_STRING_LITERAL);
1105 string_t result = token.literal;
1109 while (token.type == T_STRING_LITERAL) {
1110 warn_string_concat(&token.source_position);
1111 result = concat_strings(&result, &token.literal);
1119 * compare two string, ignoring double underscores on the second.
1121 static int strcmp_underscore(const char *s1, const char *s2)
1123 if (s2[0] == '_' && s2[1] == '_') {
1124 size_t len2 = strlen(s2);
1125 size_t len1 = strlen(s1);
1126 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1127 return strncmp(s1, s2+2, len2-4);
1131 return strcmp(s1, s2);
1134 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1136 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1137 attribute->kind = kind;
1142 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1145 * __attribute__ ( ( attribute-list ) )
1149 * attribute_list , attrib
1154 * any-word ( identifier )
1155 * any-word ( identifier , nonempty-expr-list )
1156 * any-word ( expr-list )
1158 * where the "identifier" must not be declared as a type, and
1159 * "any-word" may be any identifier (including one declared as a
1160 * type), a reserved word storage class specifier, type specifier or
1161 * type qualifier. ??? This still leaves out most reserved keywords
1162 * (following the old parser), shouldn't we include them, and why not
1163 * allow identifiers declared as types to start the arguments?
1165 * Matze: this all looks confusing and little systematic, so we're even less
1166 * strict and parse any list of things which are identifiers or
1167 * (assignment-)expressions.
1169 static attribute_argument_t *parse_attribute_arguments(void)
1171 attribute_argument_t *first = NULL;
1172 attribute_argument_t **anchor = &first;
1173 if (token.type != ')') do {
1174 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1176 /* is it an identifier */
1177 if (token.type == T_IDENTIFIER
1178 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1179 symbol_t *symbol = token.symbol;
1180 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1181 argument->v.symbol = symbol;
1184 /* must be an expression */
1185 expression_t *expression = parse_assignment_expression();
1187 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1188 argument->v.expression = expression;
1191 /* append argument */
1193 anchor = &argument->next;
1194 } while (next_if(','));
1195 expect(')', end_error);
1204 static attribute_t *parse_attribute_asm(void)
1208 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1210 expect('(', end_error);
1211 attribute->a.arguments = parse_attribute_arguments();
1218 static symbol_t *get_symbol_from_token(void)
1220 switch(token.type) {
1222 return token.symbol;
1251 /* maybe we need more tokens ... add them on demand */
1252 return get_token_symbol(&token);
1258 static attribute_t *parse_attribute_gnu_single(void)
1260 /* parse "any-word" */
1261 symbol_t *symbol = get_symbol_from_token();
1262 if (symbol == NULL) {
1263 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1267 const char *name = symbol->string;
1270 attribute_kind_t kind;
1271 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1272 const char *attribute_name = get_attribute_name(kind);
1273 if (attribute_name != NULL
1274 && strcmp_underscore(attribute_name, name) == 0)
1278 if (kind >= ATTRIBUTE_GNU_LAST) {
1279 if (warning.attribute) {
1280 warningf(HERE, "unknown attribute '%s' ignored", name);
1282 /* TODO: we should still save the attribute in the list... */
1283 kind = ATTRIBUTE_UNKNOWN;
1286 attribute_t *attribute = allocate_attribute_zero(kind);
1288 /* parse arguments */
1290 attribute->a.arguments = parse_attribute_arguments();
1298 static attribute_t *parse_attribute_gnu(void)
1300 attribute_t *first = NULL;
1301 attribute_t **anchor = &first;
1303 eat(T___attribute__);
1304 expect('(', end_error);
1305 expect('(', end_error);
1307 if (token.type != ')') do {
1308 attribute_t *attribute = parse_attribute_gnu_single();
1309 if (attribute == NULL)
1312 *anchor = attribute;
1313 anchor = &attribute->next;
1314 } while (next_if(','));
1315 expect(')', end_error);
1316 expect(')', end_error);
1322 /** Parse attributes. */
1323 static attribute_t *parse_attributes(attribute_t *first)
1325 attribute_t **anchor = &first;
1327 while (*anchor != NULL)
1328 anchor = &(*anchor)->next;
1330 attribute_t *attribute;
1331 switch (token.type) {
1332 case T___attribute__:
1333 attribute = parse_attribute_gnu();
1337 attribute = parse_attribute_asm();
1342 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1347 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1350 case T__forceinline:
1352 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1357 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1362 /* TODO record modifier */
1364 warningf(HERE, "Ignoring declaration modifier %K", &token);
1365 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1372 *anchor = attribute;
1373 anchor = &attribute->next;
1377 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1379 static entity_t *determine_lhs_ent(expression_t *const expr,
1382 switch (expr->kind) {
1383 case EXPR_REFERENCE: {
1384 entity_t *const entity = expr->reference.entity;
1385 /* we should only find variables as lvalues... */
1386 if (entity->base.kind != ENTITY_VARIABLE
1387 && entity->base.kind != ENTITY_PARAMETER)
1393 case EXPR_ARRAY_ACCESS: {
1394 expression_t *const ref = expr->array_access.array_ref;
1395 entity_t * ent = NULL;
1396 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1397 ent = determine_lhs_ent(ref, lhs_ent);
1400 mark_vars_read(expr->select.compound, lhs_ent);
1402 mark_vars_read(expr->array_access.index, lhs_ent);
1407 if (is_type_compound(skip_typeref(expr->base.type))) {
1408 return determine_lhs_ent(expr->select.compound, lhs_ent);
1410 mark_vars_read(expr->select.compound, lhs_ent);
1415 case EXPR_UNARY_DEREFERENCE: {
1416 expression_t *const val = expr->unary.value;
1417 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1419 return determine_lhs_ent(val->unary.value, lhs_ent);
1421 mark_vars_read(val, NULL);
1427 mark_vars_read(expr, NULL);
1432 #define ENT_ANY ((entity_t*)-1)
1435 * Mark declarations, which are read. This is used to detect variables, which
1439 * x is not marked as "read", because it is only read to calculate its own new
1443 * x and y are not detected as "not read", because multiple variables are
1446 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1448 switch (expr->kind) {
1449 case EXPR_REFERENCE: {
1450 entity_t *const entity = expr->reference.entity;
1451 if (entity->kind != ENTITY_VARIABLE
1452 && entity->kind != ENTITY_PARAMETER)
1455 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1456 if (entity->kind == ENTITY_VARIABLE) {
1457 entity->variable.read = true;
1459 entity->parameter.read = true;
1466 // TODO respect pure/const
1467 mark_vars_read(expr->call.function, NULL);
1468 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1469 mark_vars_read(arg->expression, NULL);
1473 case EXPR_CONDITIONAL:
1474 // TODO lhs_decl should depend on whether true/false have an effect
1475 mark_vars_read(expr->conditional.condition, NULL);
1476 if (expr->conditional.true_expression != NULL)
1477 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1478 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1482 if (lhs_ent == ENT_ANY
1483 && !is_type_compound(skip_typeref(expr->base.type)))
1485 mark_vars_read(expr->select.compound, lhs_ent);
1488 case EXPR_ARRAY_ACCESS: {
1489 expression_t *const ref = expr->array_access.array_ref;
1490 mark_vars_read(ref, lhs_ent);
1491 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1492 mark_vars_read(expr->array_access.index, lhs_ent);
1497 mark_vars_read(expr->va_arge.ap, lhs_ent);
1501 mark_vars_read(expr->va_copye.src, lhs_ent);
1504 case EXPR_UNARY_CAST:
1505 /* Special case: Use void cast to mark a variable as "read" */
1506 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1511 case EXPR_UNARY_THROW:
1512 if (expr->unary.value == NULL)
1515 case EXPR_UNARY_DEREFERENCE:
1516 case EXPR_UNARY_DELETE:
1517 case EXPR_UNARY_DELETE_ARRAY:
1518 if (lhs_ent == ENT_ANY)
1522 case EXPR_UNARY_NEGATE:
1523 case EXPR_UNARY_PLUS:
1524 case EXPR_UNARY_BITWISE_NEGATE:
1525 case EXPR_UNARY_NOT:
1526 case EXPR_UNARY_TAKE_ADDRESS:
1527 case EXPR_UNARY_POSTFIX_INCREMENT:
1528 case EXPR_UNARY_POSTFIX_DECREMENT:
1529 case EXPR_UNARY_PREFIX_INCREMENT:
1530 case EXPR_UNARY_PREFIX_DECREMENT:
1531 case EXPR_UNARY_CAST_IMPLICIT:
1532 case EXPR_UNARY_ASSUME:
1534 mark_vars_read(expr->unary.value, lhs_ent);
1537 case EXPR_BINARY_ADD:
1538 case EXPR_BINARY_SUB:
1539 case EXPR_BINARY_MUL:
1540 case EXPR_BINARY_DIV:
1541 case EXPR_BINARY_MOD:
1542 case EXPR_BINARY_EQUAL:
1543 case EXPR_BINARY_NOTEQUAL:
1544 case EXPR_BINARY_LESS:
1545 case EXPR_BINARY_LESSEQUAL:
1546 case EXPR_BINARY_GREATER:
1547 case EXPR_BINARY_GREATEREQUAL:
1548 case EXPR_BINARY_BITWISE_AND:
1549 case EXPR_BINARY_BITWISE_OR:
1550 case EXPR_BINARY_BITWISE_XOR:
1551 case EXPR_BINARY_LOGICAL_AND:
1552 case EXPR_BINARY_LOGICAL_OR:
1553 case EXPR_BINARY_SHIFTLEFT:
1554 case EXPR_BINARY_SHIFTRIGHT:
1555 case EXPR_BINARY_COMMA:
1556 case EXPR_BINARY_ISGREATER:
1557 case EXPR_BINARY_ISGREATEREQUAL:
1558 case EXPR_BINARY_ISLESS:
1559 case EXPR_BINARY_ISLESSEQUAL:
1560 case EXPR_BINARY_ISLESSGREATER:
1561 case EXPR_BINARY_ISUNORDERED:
1562 mark_vars_read(expr->binary.left, lhs_ent);
1563 mark_vars_read(expr->binary.right, lhs_ent);
1566 case EXPR_BINARY_ASSIGN:
1567 case EXPR_BINARY_MUL_ASSIGN:
1568 case EXPR_BINARY_DIV_ASSIGN:
1569 case EXPR_BINARY_MOD_ASSIGN:
1570 case EXPR_BINARY_ADD_ASSIGN:
1571 case EXPR_BINARY_SUB_ASSIGN:
1572 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1573 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1574 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1575 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1576 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1577 if (lhs_ent == ENT_ANY)
1579 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1580 mark_vars_read(expr->binary.right, lhs_ent);
1585 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1591 case EXPR_STRING_LITERAL:
1592 case EXPR_WIDE_STRING_LITERAL:
1593 case EXPR_COMPOUND_LITERAL: // TODO init?
1595 case EXPR_CLASSIFY_TYPE:
1598 case EXPR_BUILTIN_CONSTANT_P:
1599 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1601 case EXPR_STATEMENT: // TODO
1602 case EXPR_LABEL_ADDRESS:
1603 case EXPR_REFERENCE_ENUM_VALUE:
1607 panic("unhandled expression");
1610 static designator_t *parse_designation(void)
1612 designator_t *result = NULL;
1613 designator_t **anchor = &result;
1616 designator_t *designator;
1617 switch (token.type) {
1619 designator = allocate_ast_zero(sizeof(designator[0]));
1620 designator->source_position = token.source_position;
1622 add_anchor_token(']');
1623 designator->array_index = parse_constant_expression();
1624 rem_anchor_token(']');
1625 expect(']', end_error);
1628 designator = allocate_ast_zero(sizeof(designator[0]));
1629 designator->source_position = token.source_position;
1631 if (token.type != T_IDENTIFIER) {
1632 parse_error_expected("while parsing designator",
1633 T_IDENTIFIER, NULL);
1636 designator->symbol = token.symbol;
1640 expect('=', end_error);
1644 assert(designator != NULL);
1645 *anchor = designator;
1646 anchor = &designator->next;
1652 static initializer_t *initializer_from_string(array_type_t *const type,
1653 const string_t *const string)
1655 /* TODO: check len vs. size of array type */
1658 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1659 initializer->string.string = *string;
1664 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1665 const string_t *const string)
1667 /* TODO: check len vs. size of array type */
1670 initializer_t *const initializer =
1671 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1672 initializer->wide_string.string = *string;
1678 * Build an initializer from a given expression.
1680 static initializer_t *initializer_from_expression(type_t *orig_type,
1681 expression_t *expression)
1683 /* TODO check that expression is a constant expression */
1685 /* §6.7.8.14/15 char array may be initialized by string literals */
1686 type_t *type = skip_typeref(orig_type);
1687 type_t *expr_type_orig = expression->base.type;
1688 type_t *expr_type = skip_typeref(expr_type_orig);
1690 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1691 array_type_t *const array_type = &type->array;
1692 type_t *const element_type = skip_typeref(array_type->element_type);
1694 if (element_type->kind == TYPE_ATOMIC) {
1695 atomic_type_kind_t akind = element_type->atomic.akind;
1696 switch (expression->kind) {
1697 case EXPR_STRING_LITERAL:
1698 if (akind == ATOMIC_TYPE_CHAR
1699 || akind == ATOMIC_TYPE_SCHAR
1700 || akind == ATOMIC_TYPE_UCHAR) {
1701 return initializer_from_string(array_type,
1702 &expression->string_literal.value);
1706 case EXPR_WIDE_STRING_LITERAL: {
1707 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1708 if (get_unqualified_type(element_type) == bare_wchar_type) {
1709 return initializer_from_wide_string(array_type,
1710 &expression->string_literal.value);
1721 assign_error_t error = semantic_assign(type, expression);
1722 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1724 report_assign_error(error, type, expression, "initializer",
1725 &expression->base.source_position);
1727 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1728 result->value.value = create_implicit_cast(expression, type);
1734 * Checks if a given expression can be used as an constant initializer.
1736 static bool is_initializer_constant(const expression_t *expression)
1738 return is_constant_expression(expression)
1739 || is_address_constant(expression);
1743 * Parses an scalar initializer.
1745 * §6.7.8.11; eat {} without warning
1747 static initializer_t *parse_scalar_initializer(type_t *type,
1748 bool must_be_constant)
1750 /* there might be extra {} hierarchies */
1754 warningf(HERE, "extra curly braces around scalar initializer");
1757 } while (next_if('{'));
1760 expression_t *expression = parse_assignment_expression();
1761 mark_vars_read(expression, NULL);
1762 if (must_be_constant && !is_initializer_constant(expression)) {
1763 errorf(&expression->base.source_position,
1764 "initialisation expression '%E' is not constant",
1768 initializer_t *initializer = initializer_from_expression(type, expression);
1770 if (initializer == NULL) {
1771 errorf(&expression->base.source_position,
1772 "expression '%E' (type '%T') doesn't match expected type '%T'",
1773 expression, expression->base.type, type);
1778 bool additional_warning_displayed = false;
1779 while (braces > 0) {
1781 if (token.type != '}') {
1782 if (!additional_warning_displayed && warning.other) {
1783 warningf(HERE, "additional elements in scalar initializer");
1784 additional_warning_displayed = true;
1795 * An entry in the type path.
1797 typedef struct type_path_entry_t type_path_entry_t;
1798 struct type_path_entry_t {
1799 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1801 size_t index; /**< For array types: the current index. */
1802 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1807 * A type path expression a position inside compound or array types.
1809 typedef struct type_path_t type_path_t;
1810 struct type_path_t {
1811 type_path_entry_t *path; /**< An flexible array containing the current path. */
1812 type_t *top_type; /**< type of the element the path points */
1813 size_t max_index; /**< largest index in outermost array */
1817 * Prints a type path for debugging.
1819 static __attribute__((unused)) void debug_print_type_path(
1820 const type_path_t *path)
1822 size_t len = ARR_LEN(path->path);
1824 for (size_t i = 0; i < len; ++i) {
1825 const type_path_entry_t *entry = & path->path[i];
1827 type_t *type = skip_typeref(entry->type);
1828 if (is_type_compound(type)) {
1829 /* in gcc mode structs can have no members */
1830 if (entry->v.compound_entry == NULL) {
1834 fprintf(stderr, ".%s",
1835 entry->v.compound_entry->base.symbol->string);
1836 } else if (is_type_array(type)) {
1837 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1839 fprintf(stderr, "-INVALID-");
1842 if (path->top_type != NULL) {
1843 fprintf(stderr, " (");
1844 print_type(path->top_type);
1845 fprintf(stderr, ")");
1850 * Return the top type path entry, ie. in a path
1851 * (type).a.b returns the b.
1853 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1855 size_t len = ARR_LEN(path->path);
1857 return &path->path[len-1];
1861 * Enlarge the type path by an (empty) element.
1863 static type_path_entry_t *append_to_type_path(type_path_t *path)
1865 size_t len = ARR_LEN(path->path);
1866 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1868 type_path_entry_t *result = & path->path[len];
1869 memset(result, 0, sizeof(result[0]));
1874 * Descending into a sub-type. Enter the scope of the current top_type.
1876 static void descend_into_subtype(type_path_t *path)
1878 type_t *orig_top_type = path->top_type;
1879 type_t *top_type = skip_typeref(orig_top_type);
1881 type_path_entry_t *top = append_to_type_path(path);
1882 top->type = top_type;
1884 if (is_type_compound(top_type)) {
1885 compound_t *compound = top_type->compound.compound;
1886 entity_t *entry = compound->members.entities;
1888 if (entry != NULL) {
1889 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1890 top->v.compound_entry = &entry->declaration;
1891 path->top_type = entry->declaration.type;
1893 path->top_type = NULL;
1895 } else if (is_type_array(top_type)) {
1897 path->top_type = top_type->array.element_type;
1899 assert(!is_type_valid(top_type));
1904 * Pop an entry from the given type path, ie. returning from
1905 * (type).a.b to (type).a
1907 static void ascend_from_subtype(type_path_t *path)
1909 type_path_entry_t *top = get_type_path_top(path);
1911 path->top_type = top->type;
1913 size_t len = ARR_LEN(path->path);
1914 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1918 * Pop entries from the given type path until the given
1919 * path level is reached.
1921 static void ascend_to(type_path_t *path, size_t top_path_level)
1923 size_t len = ARR_LEN(path->path);
1925 while (len > top_path_level) {
1926 ascend_from_subtype(path);
1927 len = ARR_LEN(path->path);
1931 static bool walk_designator(type_path_t *path, const designator_t *designator,
1932 bool used_in_offsetof)
1934 for (; designator != NULL; designator = designator->next) {
1935 type_path_entry_t *top = get_type_path_top(path);
1936 type_t *orig_type = top->type;
1938 type_t *type = skip_typeref(orig_type);
1940 if (designator->symbol != NULL) {
1941 symbol_t *symbol = designator->symbol;
1942 if (!is_type_compound(type)) {
1943 if (is_type_valid(type)) {
1944 errorf(&designator->source_position,
1945 "'.%Y' designator used for non-compound type '%T'",
1949 top->type = type_error_type;
1950 top->v.compound_entry = NULL;
1951 orig_type = type_error_type;
1953 compound_t *compound = type->compound.compound;
1954 entity_t *iter = compound->members.entities;
1955 for (; iter != NULL; iter = iter->base.next) {
1956 if (iter->base.symbol == symbol) {
1961 errorf(&designator->source_position,
1962 "'%T' has no member named '%Y'", orig_type, symbol);
1965 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1966 if (used_in_offsetof) {
1967 type_t *real_type = skip_typeref(iter->declaration.type);
1968 if (real_type->kind == TYPE_BITFIELD) {
1969 errorf(&designator->source_position,
1970 "offsetof designator '%Y' must not specify bitfield",
1976 top->type = orig_type;
1977 top->v.compound_entry = &iter->declaration;
1978 orig_type = iter->declaration.type;
1981 expression_t *array_index = designator->array_index;
1982 assert(designator->array_index != NULL);
1984 if (!is_type_array(type)) {
1985 if (is_type_valid(type)) {
1986 errorf(&designator->source_position,
1987 "[%E] designator used for non-array type '%T'",
1988 array_index, orig_type);
1993 long index = fold_constant_to_int(array_index);
1994 if (!used_in_offsetof) {
1996 errorf(&designator->source_position,
1997 "array index [%E] must be positive", array_index);
1998 } else if (type->array.size_constant) {
1999 long array_size = type->array.size;
2000 if (index >= array_size) {
2001 errorf(&designator->source_position,
2002 "designator [%E] (%d) exceeds array size %d",
2003 array_index, index, array_size);
2008 top->type = orig_type;
2009 top->v.index = (size_t) index;
2010 orig_type = type->array.element_type;
2012 path->top_type = orig_type;
2014 if (designator->next != NULL) {
2015 descend_into_subtype(path);
2024 static void advance_current_object(type_path_t *path, size_t top_path_level)
2026 type_path_entry_t *top = get_type_path_top(path);
2028 type_t *type = skip_typeref(top->type);
2029 if (is_type_union(type)) {
2030 /* in unions only the first element is initialized */
2031 top->v.compound_entry = NULL;
2032 } else if (is_type_struct(type)) {
2033 declaration_t *entry = top->v.compound_entry;
2035 entity_t *next_entity = entry->base.next;
2036 if (next_entity != NULL) {
2037 assert(is_declaration(next_entity));
2038 entry = &next_entity->declaration;
2043 top->v.compound_entry = entry;
2044 if (entry != NULL) {
2045 path->top_type = entry->type;
2048 } else if (is_type_array(type)) {
2049 assert(is_type_array(type));
2053 if (!type->array.size_constant || top->v.index < type->array.size) {
2057 assert(!is_type_valid(type));
2061 /* we're past the last member of the current sub-aggregate, try if we
2062 * can ascend in the type hierarchy and continue with another subobject */
2063 size_t len = ARR_LEN(path->path);
2065 if (len > top_path_level) {
2066 ascend_from_subtype(path);
2067 advance_current_object(path, top_path_level);
2069 path->top_type = NULL;
2074 * skip any {...} blocks until a closing bracket is reached.
2076 static void skip_initializers(void)
2080 while (token.type != '}') {
2081 if (token.type == T_EOF)
2083 if (token.type == '{') {
2091 static initializer_t *create_empty_initializer(void)
2093 static initializer_t empty_initializer
2094 = { .list = { { INITIALIZER_LIST }, 0 } };
2095 return &empty_initializer;
2099 * Parse a part of an initialiser for a struct or union,
2101 static initializer_t *parse_sub_initializer(type_path_t *path,
2102 type_t *outer_type, size_t top_path_level,
2103 parse_initializer_env_t *env)
2105 if (token.type == '}') {
2106 /* empty initializer */
2107 return create_empty_initializer();
2110 type_t *orig_type = path->top_type;
2111 type_t *type = NULL;
2113 if (orig_type == NULL) {
2114 /* We are initializing an empty compound. */
2116 type = skip_typeref(orig_type);
2119 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2122 designator_t *designator = NULL;
2123 if (token.type == '.' || token.type == '[') {
2124 designator = parse_designation();
2125 goto finish_designator;
2126 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2127 /* GNU-style designator ("identifier: value") */
2128 designator = allocate_ast_zero(sizeof(designator[0]));
2129 designator->source_position = token.source_position;
2130 designator->symbol = token.symbol;
2135 /* reset path to toplevel, evaluate designator from there */
2136 ascend_to(path, top_path_level);
2137 if (!walk_designator(path, designator, false)) {
2138 /* can't continue after designation error */
2142 initializer_t *designator_initializer
2143 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2144 designator_initializer->designator.designator = designator;
2145 ARR_APP1(initializer_t*, initializers, designator_initializer);
2147 orig_type = path->top_type;
2148 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2153 if (token.type == '{') {
2154 if (type != NULL && is_type_scalar(type)) {
2155 sub = parse_scalar_initializer(type, env->must_be_constant);
2159 if (env->entity != NULL) {
2161 "extra brace group at end of initializer for '%Y'",
2162 env->entity->base.symbol);
2164 errorf(HERE, "extra brace group at end of initializer");
2167 descend_into_subtype(path);
2169 add_anchor_token('}');
2170 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2172 rem_anchor_token('}');
2175 ascend_from_subtype(path);
2176 expect('}', end_error);
2178 expect('}', end_error);
2179 goto error_parse_next;
2183 /* must be an expression */
2184 expression_t *expression = parse_assignment_expression();
2185 mark_vars_read(expression, NULL);
2187 if (env->must_be_constant && !is_initializer_constant(expression)) {
2188 errorf(&expression->base.source_position,
2189 "Initialisation expression '%E' is not constant",
2194 /* we are already outside, ... */
2195 if (outer_type == NULL)
2196 goto error_parse_next;
2197 type_t *const outer_type_skip = skip_typeref(outer_type);
2198 if (is_type_compound(outer_type_skip) &&
2199 !outer_type_skip->compound.compound->complete) {
2200 goto error_parse_next;
2205 /* handle { "string" } special case */
2206 if ((expression->kind == EXPR_STRING_LITERAL
2207 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2208 && outer_type != NULL) {
2209 sub = initializer_from_expression(outer_type, expression);
2212 if (token.type != '}' && warning.other) {
2213 warningf(HERE, "excessive elements in initializer for type '%T'",
2216 /* TODO: eat , ... */
2221 /* descend into subtypes until expression matches type */
2223 orig_type = path->top_type;
2224 type = skip_typeref(orig_type);
2226 sub = initializer_from_expression(orig_type, expression);
2230 if (!is_type_valid(type)) {
2233 if (is_type_scalar(type)) {
2234 errorf(&expression->base.source_position,
2235 "expression '%E' doesn't match expected type '%T'",
2236 expression, orig_type);
2240 descend_into_subtype(path);
2244 /* update largest index of top array */
2245 const type_path_entry_t *first = &path->path[0];
2246 type_t *first_type = first->type;
2247 first_type = skip_typeref(first_type);
2248 if (is_type_array(first_type)) {
2249 size_t index = first->v.index;
2250 if (index > path->max_index)
2251 path->max_index = index;
2255 /* append to initializers list */
2256 ARR_APP1(initializer_t*, initializers, sub);
2259 if (warning.other) {
2260 if (env->entity != NULL) {
2261 warningf(HERE, "excess elements in initializer for '%Y'",
2262 env->entity->base.symbol);
2264 warningf(HERE, "excess elements in initializer");
2270 if (token.type == '}') {
2273 expect(',', end_error);
2274 if (token.type == '}') {
2279 /* advance to the next declaration if we are not at the end */
2280 advance_current_object(path, top_path_level);
2281 orig_type = path->top_type;
2282 if (orig_type != NULL)
2283 type = skip_typeref(orig_type);
2289 size_t len = ARR_LEN(initializers);
2290 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2291 initializer_t *result = allocate_ast_zero(size);
2292 result->kind = INITIALIZER_LIST;
2293 result->list.len = len;
2294 memcpy(&result->list.initializers, initializers,
2295 len * sizeof(initializers[0]));
2297 DEL_ARR_F(initializers);
2298 ascend_to(path, top_path_level+1);
2303 skip_initializers();
2304 DEL_ARR_F(initializers);
2305 ascend_to(path, top_path_level+1);
2309 static expression_t *make_size_literal(size_t value)
2311 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2312 literal->base.type = type_size_t;
2315 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2316 literal->literal.value = make_string(buf);
2322 * Parses an initializer. Parsers either a compound literal
2323 * (env->declaration == NULL) or an initializer of a declaration.
2325 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2327 type_t *type = skip_typeref(env->type);
2328 size_t max_index = 0;
2329 initializer_t *result;
2331 if (is_type_scalar(type)) {
2332 result = parse_scalar_initializer(type, env->must_be_constant);
2333 } else if (token.type == '{') {
2337 memset(&path, 0, sizeof(path));
2338 path.top_type = env->type;
2339 path.path = NEW_ARR_F(type_path_entry_t, 0);
2341 descend_into_subtype(&path);
2343 add_anchor_token('}');
2344 result = parse_sub_initializer(&path, env->type, 1, env);
2345 rem_anchor_token('}');
2347 max_index = path.max_index;
2348 DEL_ARR_F(path.path);
2350 expect('}', end_error);
2352 /* parse_scalar_initializer() also works in this case: we simply
2353 * have an expression without {} around it */
2354 result = parse_scalar_initializer(type, env->must_be_constant);
2357 /* §6.7.8:22 array initializers for arrays with unknown size determine
2358 * the array type size */
2359 if (is_type_array(type) && type->array.size_expression == NULL
2360 && result != NULL) {
2362 switch (result->kind) {
2363 case INITIALIZER_LIST:
2364 assert(max_index != 0xdeadbeaf);
2365 size = max_index + 1;
2368 case INITIALIZER_STRING:
2369 size = result->string.string.size;
2372 case INITIALIZER_WIDE_STRING:
2373 size = result->wide_string.string.size;
2376 case INITIALIZER_DESIGNATOR:
2377 case INITIALIZER_VALUE:
2378 /* can happen for parse errors */
2383 internal_errorf(HERE, "invalid initializer type");
2386 type_t *new_type = duplicate_type(type);
2388 new_type->array.size_expression = make_size_literal(size);
2389 new_type->array.size_constant = true;
2390 new_type->array.has_implicit_size = true;
2391 new_type->array.size = size;
2392 env->type = new_type;
2400 static void append_entity(scope_t *scope, entity_t *entity)
2402 if (scope->last_entity != NULL) {
2403 scope->last_entity->base.next = entity;
2405 scope->entities = entity;
2407 entity->base.parent_entity = current_entity;
2408 scope->last_entity = entity;
2412 static compound_t *parse_compound_type_specifier(bool is_struct)
2414 eat(is_struct ? T_struct : T_union);
2416 symbol_t *symbol = NULL;
2417 compound_t *compound = NULL;
2418 attribute_t *attributes = NULL;
2420 if (token.type == T___attribute__) {
2421 attributes = parse_attributes(NULL);
2424 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2425 if (token.type == T_IDENTIFIER) {
2426 /* the compound has a name, check if we have seen it already */
2427 symbol = token.symbol;
2430 entity_t *entity = get_tag(symbol, kind);
2431 if (entity != NULL) {
2432 compound = &entity->compound;
2433 if (compound->base.parent_scope != current_scope &&
2434 (token.type == '{' || token.type == ';')) {
2435 /* we're in an inner scope and have a definition. Shadow
2436 * existing definition in outer scope */
2438 } else if (compound->complete && token.type == '{') {
2439 assert(symbol != NULL);
2440 errorf(HERE, "multiple definitions of '%s %Y' (previous definition %P)",
2441 is_struct ? "struct" : "union", symbol,
2442 &compound->base.source_position);
2443 /* clear members in the hope to avoid further errors */
2444 compound->members.entities = NULL;
2447 } else if (token.type != '{') {
2449 parse_error_expected("while parsing struct type specifier",
2450 T_IDENTIFIER, '{', NULL);
2452 parse_error_expected("while parsing union type specifier",
2453 T_IDENTIFIER, '{', NULL);
2459 if (compound == NULL) {
2460 entity_t *entity = allocate_entity_zero(kind);
2461 compound = &entity->compound;
2463 compound->alignment = 1;
2464 compound->base.namespc = NAMESPACE_TAG;
2465 compound->base.source_position = token.source_position;
2466 compound->base.symbol = symbol;
2467 compound->base.parent_scope = current_scope;
2468 if (symbol != NULL) {
2469 environment_push(entity);
2471 append_entity(current_scope, entity);
2474 if (token.type == '{') {
2475 parse_compound_type_entries(compound);
2477 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2478 if (symbol == NULL) {
2479 assert(anonymous_entity == NULL);
2480 anonymous_entity = (entity_t*)compound;
2484 if (attributes != NULL) {
2485 handle_entity_attributes(attributes, (entity_t*) compound);
2491 static void parse_enum_entries(type_t *const enum_type)
2495 if (token.type == '}') {
2496 errorf(HERE, "empty enum not allowed");
2501 add_anchor_token('}');
2503 if (token.type != T_IDENTIFIER) {
2504 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2506 rem_anchor_token('}');
2510 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2511 entity->enum_value.enum_type = enum_type;
2512 entity->base.symbol = token.symbol;
2513 entity->base.source_position = token.source_position;
2517 expression_t *value = parse_constant_expression();
2519 value = create_implicit_cast(value, enum_type);
2520 entity->enum_value.value = value;
2525 record_entity(entity, false);
2526 } while (next_if(',') && token.type != '}');
2527 rem_anchor_token('}');
2529 expect('}', end_error);
2535 static type_t *parse_enum_specifier(void)
2541 switch (token.type) {
2543 symbol = token.symbol;
2546 entity = get_tag(symbol, ENTITY_ENUM);
2547 if (entity != NULL) {
2548 if (entity->base.parent_scope != current_scope &&
2549 (token.type == '{' || token.type == ';')) {
2550 /* we're in an inner scope and have a definition. Shadow
2551 * existing definition in outer scope */
2553 } else if (entity->enume.complete && token.type == '{') {
2554 errorf(HERE, "multiple definitions of 'enum %Y' (previous definition %P)",
2555 symbol, &entity->base.source_position);
2566 parse_error_expected("while parsing enum type specifier",
2567 T_IDENTIFIER, '{', NULL);
2571 if (entity == NULL) {
2572 entity = allocate_entity_zero(ENTITY_ENUM);
2573 entity->base.namespc = NAMESPACE_TAG;
2574 entity->base.source_position = token.source_position;
2575 entity->base.symbol = symbol;
2576 entity->base.parent_scope = current_scope;
2579 type_t *const type = allocate_type_zero(TYPE_ENUM);
2580 type->enumt.enume = &entity->enume;
2581 type->enumt.akind = ATOMIC_TYPE_INT;
2583 if (token.type == '{') {
2584 if (symbol != NULL) {
2585 environment_push(entity);
2587 append_entity(current_scope, entity);
2588 entity->enume.complete = true;
2590 parse_enum_entries(type);
2591 parse_attributes(NULL);
2593 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2594 if (symbol == NULL) {
2595 assert(anonymous_entity == NULL);
2596 anonymous_entity = entity;
2598 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2599 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2607 * if a symbol is a typedef to another type, return true
2609 static bool is_typedef_symbol(symbol_t *symbol)
2611 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2612 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2615 static type_t *parse_typeof(void)
2621 expect('(', end_error);
2622 add_anchor_token(')');
2624 expression_t *expression = NULL;
2626 bool old_type_prop = in_type_prop;
2627 bool old_gcc_extension = in_gcc_extension;
2628 in_type_prop = true;
2630 while (next_if(T___extension__)) {
2631 /* This can be a prefix to a typename or an expression. */
2632 in_gcc_extension = true;
2634 switch (token.type) {
2636 if (is_typedef_symbol(token.symbol)) {
2638 type = parse_typename();
2641 expression = parse_expression();
2642 type = revert_automatic_type_conversion(expression);
2646 in_type_prop = old_type_prop;
2647 in_gcc_extension = old_gcc_extension;
2649 rem_anchor_token(')');
2650 expect(')', end_error);
2652 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2653 typeof_type->typeoft.expression = expression;
2654 typeof_type->typeoft.typeof_type = type;
2661 typedef enum specifiers_t {
2662 SPECIFIER_SIGNED = 1 << 0,
2663 SPECIFIER_UNSIGNED = 1 << 1,
2664 SPECIFIER_LONG = 1 << 2,
2665 SPECIFIER_INT = 1 << 3,
2666 SPECIFIER_DOUBLE = 1 << 4,
2667 SPECIFIER_CHAR = 1 << 5,
2668 SPECIFIER_WCHAR_T = 1 << 6,
2669 SPECIFIER_SHORT = 1 << 7,
2670 SPECIFIER_LONG_LONG = 1 << 8,
2671 SPECIFIER_FLOAT = 1 << 9,
2672 SPECIFIER_BOOL = 1 << 10,
2673 SPECIFIER_VOID = 1 << 11,
2674 SPECIFIER_INT8 = 1 << 12,
2675 SPECIFIER_INT16 = 1 << 13,
2676 SPECIFIER_INT32 = 1 << 14,
2677 SPECIFIER_INT64 = 1 << 15,
2678 SPECIFIER_INT128 = 1 << 16,
2679 SPECIFIER_COMPLEX = 1 << 17,
2680 SPECIFIER_IMAGINARY = 1 << 18,
2683 static type_t *create_builtin_type(symbol_t *const symbol,
2684 type_t *const real_type)
2686 type_t *type = allocate_type_zero(TYPE_BUILTIN);
2687 type->builtin.symbol = symbol;
2688 type->builtin.real_type = real_type;
2689 return identify_new_type(type);
2692 static type_t *get_typedef_type(symbol_t *symbol)
2694 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2695 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2698 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2699 type->typedeft.typedefe = &entity->typedefe;
2704 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2706 expect('(', end_error);
2708 attribute_property_argument_t *property
2709 = allocate_ast_zero(sizeof(*property));
2712 if (token.type != T_IDENTIFIER) {
2713 parse_error_expected("while parsing property declspec",
2714 T_IDENTIFIER, NULL);
2719 symbol_t *symbol = token.symbol;
2721 if (strcmp(symbol->string, "put") == 0) {
2723 } else if (strcmp(symbol->string, "get") == 0) {
2726 errorf(HERE, "expected put or get in property declspec");
2729 expect('=', end_error);
2730 if (token.type != T_IDENTIFIER) {
2731 parse_error_expected("while parsing property declspec",
2732 T_IDENTIFIER, NULL);
2736 property->put_symbol = token.symbol;
2738 property->get_symbol = token.symbol;
2741 } while (next_if(','));
2743 attribute->a.property = property;
2745 expect(')', end_error);
2751 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2753 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2754 if (next_if(T_restrict)) {
2755 kind = ATTRIBUTE_MS_RESTRICT;
2756 } else if (token.type == T_IDENTIFIER) {
2757 const char *name = token.symbol->string;
2759 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2761 const char *attribute_name = get_attribute_name(k);
2762 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2768 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2769 warningf(HERE, "unknown __declspec '%s' ignored", name);
2772 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2776 attribute_t *attribute = allocate_attribute_zero(kind);
2778 if (kind == ATTRIBUTE_MS_PROPERTY) {
2779 return parse_attribute_ms_property(attribute);
2782 /* parse arguments */
2784 attribute->a.arguments = parse_attribute_arguments();
2789 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2793 expect('(', end_error);
2798 add_anchor_token(')');
2800 attribute_t **anchor = &first;
2802 while (*anchor != NULL)
2803 anchor = &(*anchor)->next;
2805 attribute_t *attribute
2806 = parse_microsoft_extended_decl_modifier_single();
2807 if (attribute == NULL)
2810 *anchor = attribute;
2811 anchor = &attribute->next;
2812 } while (next_if(','));
2814 rem_anchor_token(')');
2815 expect(')', end_error);
2819 rem_anchor_token(')');
2823 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2825 entity_t *entity = allocate_entity_zero(kind);
2826 entity->base.source_position = *HERE;
2827 entity->base.symbol = symbol;
2828 if (is_declaration(entity)) {
2829 entity->declaration.type = type_error_type;
2830 entity->declaration.implicit = true;
2831 } else if (kind == ENTITY_TYPEDEF) {
2832 entity->typedefe.type = type_error_type;
2833 entity->typedefe.builtin = true;
2835 if (kind != ENTITY_COMPOUND_MEMBER)
2836 record_entity(entity, false);
2840 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2842 type_t *type = NULL;
2843 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2844 unsigned type_specifiers = 0;
2845 bool newtype = false;
2846 bool saw_error = false;
2847 bool old_gcc_extension = in_gcc_extension;
2849 specifiers->source_position = token.source_position;
2852 specifiers->attributes = parse_attributes(specifiers->attributes);
2854 switch (token.type) {
2856 #define MATCH_STORAGE_CLASS(token, class) \
2858 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2859 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2861 specifiers->storage_class = class; \
2862 if (specifiers->thread_local) \
2863 goto check_thread_storage_class; \
2867 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2868 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2869 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2870 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2871 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2874 specifiers->attributes
2875 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2879 if (specifiers->thread_local) {
2880 errorf(HERE, "duplicate '__thread'");
2882 specifiers->thread_local = true;
2883 check_thread_storage_class:
2884 switch (specifiers->storage_class) {
2885 case STORAGE_CLASS_EXTERN:
2886 case STORAGE_CLASS_NONE:
2887 case STORAGE_CLASS_STATIC:
2891 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_stoarge_class;
2892 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_stoarge_class;
2893 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_stoarge_class;
2894 wrong_thread_stoarge_class:
2895 errorf(HERE, "'__thread' used with '%s'", wrong);
2902 /* type qualifiers */
2903 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2905 qualifiers |= qualifier; \
2909 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2910 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2911 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2912 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2913 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2914 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2915 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2916 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2918 case T___extension__:
2920 in_gcc_extension = true;
2923 /* type specifiers */
2924 #define MATCH_SPECIFIER(token, specifier, name) \
2926 if (type_specifiers & specifier) { \
2927 errorf(HERE, "multiple " name " type specifiers given"); \
2929 type_specifiers |= specifier; \
2934 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2935 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2936 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2937 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2938 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2939 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2940 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2941 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2942 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2943 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2944 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2945 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2946 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2947 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2948 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2949 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2950 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2951 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2955 specifiers->is_inline = true;
2959 case T__forceinline:
2961 specifiers->modifiers |= DM_FORCEINLINE;
2966 if (type_specifiers & SPECIFIER_LONG_LONG) {
2967 errorf(HERE, "multiple type specifiers given");
2968 } else if (type_specifiers & SPECIFIER_LONG) {
2969 type_specifiers |= SPECIFIER_LONG_LONG;
2971 type_specifiers |= SPECIFIER_LONG;
2976 #define CHECK_DOUBLE_TYPE() \
2977 if ( type != NULL) \
2978 errorf(HERE, "multiple data types in declaration specifiers");
2981 CHECK_DOUBLE_TYPE();
2982 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2984 type->compound.compound = parse_compound_type_specifier(true);
2987 CHECK_DOUBLE_TYPE();
2988 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2989 type->compound.compound = parse_compound_type_specifier(false);
2992 CHECK_DOUBLE_TYPE();
2993 type = parse_enum_specifier();
2996 CHECK_DOUBLE_TYPE();
2997 type = parse_typeof();
2999 case T___builtin_va_list:
3000 CHECK_DOUBLE_TYPE();
3001 type = duplicate_type(type_valist);
3005 case T_IDENTIFIER: {
3006 /* only parse identifier if we haven't found a type yet */
3007 if (type != NULL || type_specifiers != 0) {
3008 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3009 * declaration, so it doesn't generate errors about expecting '(' or
3011 switch (look_ahead(1)->type) {
3018 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3022 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3027 goto finish_specifiers;
3031 type_t *const typedef_type = get_typedef_type(token.symbol);
3032 if (typedef_type == NULL) {
3033 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3034 * declaration, so it doesn't generate 'implicit int' followed by more
3035 * errors later on. */
3036 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3042 errorf(HERE, "%K does not name a type", &token);
3045 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3047 type = allocate_type_zero(TYPE_TYPEDEF);
3048 type->typedeft.typedefe = &entity->typedefe;
3052 if (la1_type == '&' || la1_type == '*')
3053 goto finish_specifiers;
3058 goto finish_specifiers;
3063 type = typedef_type;
3067 /* function specifier */
3069 goto finish_specifiers;
3074 specifiers->attributes = parse_attributes(specifiers->attributes);
3076 in_gcc_extension = old_gcc_extension;
3078 if (type == NULL || (saw_error && type_specifiers != 0)) {
3079 atomic_type_kind_t atomic_type;
3081 /* match valid basic types */
3082 switch (type_specifiers) {
3083 case SPECIFIER_VOID:
3084 atomic_type = ATOMIC_TYPE_VOID;
3086 case SPECIFIER_WCHAR_T:
3087 atomic_type = ATOMIC_TYPE_WCHAR_T;
3089 case SPECIFIER_CHAR:
3090 atomic_type = ATOMIC_TYPE_CHAR;
3092 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3093 atomic_type = ATOMIC_TYPE_SCHAR;
3095 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3096 atomic_type = ATOMIC_TYPE_UCHAR;
3098 case SPECIFIER_SHORT:
3099 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3100 case SPECIFIER_SHORT | SPECIFIER_INT:
3101 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3102 atomic_type = ATOMIC_TYPE_SHORT;
3104 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3105 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3106 atomic_type = ATOMIC_TYPE_USHORT;
3109 case SPECIFIER_SIGNED:
3110 case SPECIFIER_SIGNED | SPECIFIER_INT:
3111 atomic_type = ATOMIC_TYPE_INT;
3113 case SPECIFIER_UNSIGNED:
3114 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3115 atomic_type = ATOMIC_TYPE_UINT;
3117 case SPECIFIER_LONG:
3118 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3119 case SPECIFIER_LONG | SPECIFIER_INT:
3120 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3121 atomic_type = ATOMIC_TYPE_LONG;
3123 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3124 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3125 atomic_type = ATOMIC_TYPE_ULONG;
3128 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3129 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3130 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3131 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3133 atomic_type = ATOMIC_TYPE_LONGLONG;
3134 goto warn_about_long_long;
3136 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3137 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3139 atomic_type = ATOMIC_TYPE_ULONGLONG;
3140 warn_about_long_long:
3141 if (warning.long_long) {
3142 warningf(&specifiers->source_position,
3143 "ISO C90 does not support 'long long'");
3147 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3148 atomic_type = unsigned_int8_type_kind;
3151 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3152 atomic_type = unsigned_int16_type_kind;
3155 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3156 atomic_type = unsigned_int32_type_kind;
3159 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3160 atomic_type = unsigned_int64_type_kind;
3163 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3164 atomic_type = unsigned_int128_type_kind;
3167 case SPECIFIER_INT8:
3168 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3169 atomic_type = int8_type_kind;
3172 case SPECIFIER_INT16:
3173 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3174 atomic_type = int16_type_kind;
3177 case SPECIFIER_INT32:
3178 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3179 atomic_type = int32_type_kind;
3182 case SPECIFIER_INT64:
3183 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3184 atomic_type = int64_type_kind;
3187 case SPECIFIER_INT128:
3188 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3189 atomic_type = int128_type_kind;
3192 case SPECIFIER_FLOAT:
3193 atomic_type = ATOMIC_TYPE_FLOAT;
3195 case SPECIFIER_DOUBLE:
3196 atomic_type = ATOMIC_TYPE_DOUBLE;
3198 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3199 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3201 case SPECIFIER_BOOL:
3202 atomic_type = ATOMIC_TYPE_BOOL;
3204 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3205 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3206 atomic_type = ATOMIC_TYPE_FLOAT;
3208 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3209 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3210 atomic_type = ATOMIC_TYPE_DOUBLE;
3212 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3213 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3214 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3217 /* invalid specifier combination, give an error message */
3218 if (type_specifiers == 0) {
3222 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3223 if (!(c_mode & _CXX) && !strict_mode) {
3224 if (warning.implicit_int) {
3225 warningf(HERE, "no type specifiers in declaration, using 'int'");
3227 atomic_type = ATOMIC_TYPE_INT;
3230 errorf(HERE, "no type specifiers given in declaration");
3232 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3233 (type_specifiers & SPECIFIER_UNSIGNED)) {
3234 errorf(HERE, "signed and unsigned specifiers given");
3235 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3236 errorf(HERE, "only integer types can be signed or unsigned");
3238 errorf(HERE, "multiple datatypes in declaration");
3243 if (type_specifiers & SPECIFIER_COMPLEX) {
3244 type = allocate_type_zero(TYPE_COMPLEX);
3245 type->complex.akind = atomic_type;
3246 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3247 type = allocate_type_zero(TYPE_IMAGINARY);
3248 type->imaginary.akind = atomic_type;
3250 type = allocate_type_zero(TYPE_ATOMIC);
3251 type->atomic.akind = atomic_type;
3254 } else if (type_specifiers != 0) {
3255 errorf(HERE, "multiple datatypes in declaration");
3258 /* FIXME: check type qualifiers here */
3259 type->base.qualifiers = qualifiers;
3262 type = identify_new_type(type);
3264 type = typehash_insert(type);
3267 if (specifiers->attributes != NULL)
3268 type = handle_type_attributes(specifiers->attributes, type);
3269 specifiers->type = type;
3273 specifiers->type = type_error_type;
3276 static type_qualifiers_t parse_type_qualifiers(void)
3278 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3281 switch (token.type) {
3282 /* type qualifiers */
3283 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3284 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3285 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3286 /* microsoft extended type modifiers */
3287 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3288 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3289 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3290 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3291 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3300 * Parses an K&R identifier list
3302 static void parse_identifier_list(scope_t *scope)
3305 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3306 entity->base.source_position = token.source_position;
3307 entity->base.namespc = NAMESPACE_NORMAL;
3308 entity->base.symbol = token.symbol;
3309 /* a K&R parameter has no type, yet */
3313 append_entity(scope, entity);
3314 } while (next_if(',') && token.type == T_IDENTIFIER);
3317 static entity_t *parse_parameter(void)
3319 declaration_specifiers_t specifiers;
3320 memset(&specifiers, 0, sizeof(specifiers));
3322 parse_declaration_specifiers(&specifiers);
3324 entity_t *entity = parse_declarator(&specifiers,
3325 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3326 anonymous_entity = NULL;
3330 static void semantic_parameter_incomplete(const entity_t *entity)
3332 assert(entity->kind == ENTITY_PARAMETER);
3334 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3335 * list in a function declarator that is part of a
3336 * definition of that function shall not have
3337 * incomplete type. */
3338 type_t *type = skip_typeref(entity->declaration.type);
3339 if (is_type_incomplete(type)) {
3340 errorf(&entity->base.source_position,
3341 "parameter '%#T' has incomplete type",
3342 entity->declaration.type, entity->base.symbol);
3346 static bool has_parameters(void)
3348 /* func(void) is not a parameter */
3349 if (token.type == T_IDENTIFIER) {
3350 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3353 if (entity->kind != ENTITY_TYPEDEF)
3355 if (skip_typeref(entity->typedefe.type) != type_void)
3357 } else if (token.type != T_void) {
3360 if (look_ahead(1)->type != ')')
3367 * Parses function type parameters (and optionally creates variable_t entities
3368 * for them in a scope)
3370 static void parse_parameters(function_type_t *type, scope_t *scope)
3373 add_anchor_token(')');
3374 int saved_comma_state = save_and_reset_anchor_state(',');
3376 if (token.type == T_IDENTIFIER &&
3377 !is_typedef_symbol(token.symbol)) {
3378 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3379 if (la1_type == ',' || la1_type == ')') {
3380 type->kr_style_parameters = true;
3381 parse_identifier_list(scope);
3382 goto parameters_finished;
3386 if (token.type == ')') {
3387 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3388 if (!(c_mode & _CXX))
3389 type->unspecified_parameters = true;
3390 goto parameters_finished;
3393 if (has_parameters()) {
3394 function_parameter_t **anchor = &type->parameters;
3396 switch (token.type) {
3399 type->variadic = true;
3400 goto parameters_finished;
3403 case T___extension__:
3406 entity_t *entity = parse_parameter();
3407 if (entity->kind == ENTITY_TYPEDEF) {
3408 errorf(&entity->base.source_position,
3409 "typedef not allowed as function parameter");
3412 assert(is_declaration(entity));
3414 semantic_parameter_incomplete(entity);
3416 function_parameter_t *const parameter =
3417 allocate_parameter(entity->declaration.type);
3419 if (scope != NULL) {
3420 append_entity(scope, entity);
3423 *anchor = parameter;
3424 anchor = ¶meter->next;
3429 goto parameters_finished;
3431 } while (next_if(','));
3435 parameters_finished:
3436 rem_anchor_token(')');
3437 expect(')', end_error);
3440 restore_anchor_state(',', saved_comma_state);
3443 typedef enum construct_type_kind_t {
3446 CONSTRUCT_REFERENCE,
3449 } construct_type_kind_t;
3451 typedef union construct_type_t construct_type_t;
3453 typedef struct construct_type_base_t {
3454 construct_type_kind_t kind;
3455 construct_type_t *next;
3456 } construct_type_base_t;
3458 typedef struct parsed_pointer_t {
3459 construct_type_base_t base;
3460 type_qualifiers_t type_qualifiers;
3461 variable_t *base_variable; /**< MS __based extension. */
3464 typedef struct parsed_reference_t {
3465 construct_type_base_t base;
3466 } parsed_reference_t;
3468 typedef struct construct_function_type_t {
3469 construct_type_base_t base;
3470 type_t *function_type;
3471 } construct_function_type_t;
3473 typedef struct parsed_array_t {
3474 construct_type_base_t base;
3475 type_qualifiers_t type_qualifiers;
3481 union construct_type_t {
3482 construct_type_kind_t kind;
3483 construct_type_base_t base;
3484 parsed_pointer_t pointer;
3485 parsed_reference_t reference;
3486 construct_function_type_t function;
3487 parsed_array_t array;
3490 static construct_type_t *parse_pointer_declarator(void)
3494 parsed_pointer_t *pointer = obstack_alloc(&temp_obst, sizeof(pointer[0]));
3495 memset(pointer, 0, sizeof(pointer[0]));
3496 pointer->base.kind = CONSTRUCT_POINTER;
3497 pointer->type_qualifiers = parse_type_qualifiers();
3498 //pointer->base_variable = base_variable;
3500 return (construct_type_t*) pointer;
3503 static construct_type_t *parse_reference_declarator(void)
3507 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->reference));
3508 parsed_reference_t *reference = &cons->reference;
3509 memset(reference, 0, sizeof(*reference));
3510 cons->kind = CONSTRUCT_REFERENCE;
3515 static construct_type_t *parse_array_declarator(void)
3518 add_anchor_token(']');
3520 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->array));
3521 parsed_array_t *array = &cons->array;
3522 memset(array, 0, sizeof(*array));
3523 cons->kind = CONSTRUCT_ARRAY;
3525 if (next_if(T_static))
3526 array->is_static = true;
3528 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3529 if (type_qualifiers != 0 && next_if(T_static))
3530 array->is_static = true;
3531 array->type_qualifiers = type_qualifiers;
3533 if (token.type == '*' && look_ahead(1)->type == ']') {
3534 array->is_variable = true;
3536 } else if (token.type != ']') {
3537 expression_t *const size = parse_assignment_expression();
3539 /* §6.7.5.2:1 Array size must have integer type */
3540 type_t *const orig_type = size->base.type;
3541 type_t *const type = skip_typeref(orig_type);
3542 if (!is_type_integer(type) && is_type_valid(type)) {
3543 errorf(&size->base.source_position,
3544 "array size '%E' must have integer type but has type '%T'",
3549 mark_vars_read(size, NULL);
3552 rem_anchor_token(']');
3553 expect(']', end_error);
3559 static construct_type_t *parse_function_declarator(scope_t *scope)
3561 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3562 function_type_t *ftype = &type->function;
3564 ftype->linkage = current_linkage;
3565 ftype->calling_convention = CC_DEFAULT;
3567 parse_parameters(ftype, scope);
3569 construct_type_t *cons = obstack_alloc(&temp_obst, sizeof(cons->function));
3570 construct_function_type_t *function = &cons->function;
3571 memset(function, 0, sizeof(*function));
3572 cons->kind = CONSTRUCT_FUNCTION;
3573 function->function_type = type;
3578 typedef struct parse_declarator_env_t {
3579 bool may_be_abstract : 1;
3580 bool must_be_abstract : 1;
3581 decl_modifiers_t modifiers;
3583 source_position_t source_position;
3585 attribute_t *attributes;
3586 } parse_declarator_env_t;
3588 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3590 /* construct a single linked list of construct_type_t's which describe
3591 * how to construct the final declarator type */
3592 construct_type_t *first = NULL;
3593 construct_type_t **anchor = &first;
3595 env->attributes = parse_attributes(env->attributes);
3598 construct_type_t *type;
3599 //variable_t *based = NULL; /* MS __based extension */
3600 switch (token.type) {
3602 if (!(c_mode & _CXX))
3603 errorf(HERE, "references are only available for C++");
3604 type = parse_reference_declarator();
3608 panic("based not supported anymore");
3613 type = parse_pointer_declarator();
3617 goto ptr_operator_end;
3621 anchor = &type->base.next;
3623 /* TODO: find out if this is correct */
3624 env->attributes = parse_attributes(env->attributes);
3628 construct_type_t *inner_types = NULL;
3630 switch (token.type) {
3632 if (env->must_be_abstract) {
3633 errorf(HERE, "no identifier expected in typename");
3635 env->symbol = token.symbol;
3636 env->source_position = token.source_position;
3641 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3642 * interpreted as ``function with no parameter specification'', rather
3643 * than redundant parentheses around the omitted identifier. */
3644 if (look_ahead(1)->type != ')') {
3646 add_anchor_token(')');
3647 inner_types = parse_inner_declarator(env);
3648 if (inner_types != NULL) {
3649 /* All later declarators only modify the return type */
3650 env->must_be_abstract = true;
3652 rem_anchor_token(')');
3653 expect(')', end_error);
3657 if (env->may_be_abstract)
3659 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3664 construct_type_t **const p = anchor;
3667 construct_type_t *type;
3668 switch (token.type) {
3670 scope_t *scope = NULL;
3671 if (!env->must_be_abstract) {
3672 scope = &env->parameters;
3675 type = parse_function_declarator(scope);
3679 type = parse_array_declarator();
3682 goto declarator_finished;
3685 /* insert in the middle of the list (at p) */
3686 type->base.next = *p;
3689 anchor = &type->base.next;
3692 declarator_finished:
3693 /* append inner_types at the end of the list, we don't to set anchor anymore
3694 * as it's not needed anymore */
3695 *anchor = inner_types;
3702 static type_t *construct_declarator_type(construct_type_t *construct_list,
3705 construct_type_t *iter = construct_list;
3706 for (; iter != NULL; iter = iter->base.next) {
3707 switch (iter->kind) {
3708 case CONSTRUCT_INVALID:
3710 case CONSTRUCT_FUNCTION: {
3711 construct_function_type_t *function = &iter->function;
3712 type_t *function_type = function->function_type;
3714 function_type->function.return_type = type;
3716 type_t *skipped_return_type = skip_typeref(type);
3718 if (is_type_function(skipped_return_type)) {
3719 errorf(HERE, "function returning function is not allowed");
3720 } else if (is_type_array(skipped_return_type)) {
3721 errorf(HERE, "function returning array is not allowed");
3723 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3725 "type qualifiers in return type of function type are meaningless");
3729 /* The function type was constructed earlier. Freeing it here will
3730 * destroy other types. */
3731 type = typehash_insert(function_type);
3735 case CONSTRUCT_POINTER: {
3736 if (is_type_reference(skip_typeref(type)))
3737 errorf(HERE, "cannot declare a pointer to reference");
3739 parsed_pointer_t *pointer = &iter->pointer;
3740 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3744 case CONSTRUCT_REFERENCE:
3745 if (is_type_reference(skip_typeref(type)))
3746 errorf(HERE, "cannot declare a reference to reference");
3748 type = make_reference_type(type);
3751 case CONSTRUCT_ARRAY: {
3752 if (is_type_reference(skip_typeref(type)))
3753 errorf(HERE, "cannot declare an array of references");
3755 parsed_array_t *array = &iter->array;
3756 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3758 expression_t *size_expression = array->size;
3759 if (size_expression != NULL) {
3761 = create_implicit_cast(size_expression, type_size_t);
3764 array_type->base.qualifiers = array->type_qualifiers;
3765 array_type->array.element_type = type;
3766 array_type->array.is_static = array->is_static;
3767 array_type->array.is_variable = array->is_variable;
3768 array_type->array.size_expression = size_expression;
3770 if (size_expression != NULL) {
3771 if (is_constant_expression(size_expression)) {
3773 = fold_constant_to_int(size_expression);
3774 array_type->array.size = size;
3775 array_type->array.size_constant = true;
3776 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3777 * have a value greater than zero. */
3779 if (size < 0 || !GNU_MODE) {
3780 errorf(&size_expression->base.source_position,
3781 "size of array must be greater than zero");
3782 } else if (warning.other) {
3783 warningf(&size_expression->base.source_position,
3784 "zero length arrays are a GCC extension");
3788 array_type->array.is_vla = true;
3792 type_t *skipped_type = skip_typeref(type);
3794 if (is_type_incomplete(skipped_type)) {
3795 errorf(HERE, "array of incomplete type '%T' is not allowed", type);
3796 } else if (is_type_function(skipped_type)) {
3797 errorf(HERE, "array of functions is not allowed");
3799 type = identify_new_type(array_type);
3803 internal_errorf(HERE, "invalid type construction found");
3809 static type_t *automatic_type_conversion(type_t *orig_type);
3811 static type_t *semantic_parameter(const source_position_t *pos,
3813 const declaration_specifiers_t *specifiers,
3816 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3817 * shall be adjusted to ``qualified pointer to type'',
3819 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3820 * type'' shall be adjusted to ``pointer to function
3821 * returning type'', as in 6.3.2.1. */
3822 type = automatic_type_conversion(type);
3824 if (specifiers->is_inline && is_type_valid(type)) {
3825 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3828 /* §6.9.1:6 The declarations in the declaration list shall contain
3829 * no storage-class specifier other than register and no
3830 * initializations. */
3831 if (specifiers->thread_local || (
3832 specifiers->storage_class != STORAGE_CLASS_NONE &&
3833 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3835 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3838 /* delay test for incomplete type, because we might have (void)
3839 * which is legal but incomplete... */
3844 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3845 declarator_flags_t flags)
3847 parse_declarator_env_t env;
3848 memset(&env, 0, sizeof(env));
3849 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3851 construct_type_t *construct_type = parse_inner_declarator(&env);
3853 construct_declarator_type(construct_type, specifiers->type);
3854 type_t *type = skip_typeref(orig_type);
3856 if (construct_type != NULL) {
3857 obstack_free(&temp_obst, construct_type);
3860 attribute_t *attributes = parse_attributes(env.attributes);
3861 /* append (shared) specifier attribute behind attributes of this
3863 attribute_t **anchor = &attributes;
3864 while (*anchor != NULL)
3865 anchor = &(*anchor)->next;
3866 *anchor = specifiers->attributes;
3869 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3870 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3871 entity->base.symbol = env.symbol;
3872 entity->base.source_position = env.source_position;
3873 entity->typedefe.type = orig_type;
3875 if (anonymous_entity != NULL) {
3876 if (is_type_compound(type)) {
3877 assert(anonymous_entity->compound.alias == NULL);
3878 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3879 anonymous_entity->kind == ENTITY_UNION);
3880 anonymous_entity->compound.alias = entity;
3881 anonymous_entity = NULL;
3882 } else if (is_type_enum(type)) {
3883 assert(anonymous_entity->enume.alias == NULL);
3884 assert(anonymous_entity->kind == ENTITY_ENUM);
3885 anonymous_entity->enume.alias = entity;
3886 anonymous_entity = NULL;
3890 /* create a declaration type entity */
3891 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3892 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3894 if (env.symbol != NULL) {
3895 if (specifiers->is_inline && is_type_valid(type)) {
3896 errorf(&env.source_position,
3897 "compound member '%Y' declared 'inline'", env.symbol);
3900 if (specifiers->thread_local ||
3901 specifiers->storage_class != STORAGE_CLASS_NONE) {
3902 errorf(&env.source_position,
3903 "compound member '%Y' must have no storage class",
3907 } else if (flags & DECL_IS_PARAMETER) {
3908 orig_type = semantic_parameter(&env.source_position, orig_type,
3909 specifiers, env.symbol);
3911 entity = allocate_entity_zero(ENTITY_PARAMETER);
3912 } else if (is_type_function(type)) {
3913 entity = allocate_entity_zero(ENTITY_FUNCTION);
3915 entity->function.is_inline = specifiers->is_inline;
3916 entity->function.parameters = env.parameters;
3918 if (env.symbol != NULL) {
3919 /* this needs fixes for C++ */
3920 bool in_function_scope = current_function != NULL;
3922 if (specifiers->thread_local || (
3923 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3924 specifiers->storage_class != STORAGE_CLASS_NONE &&
3925 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3927 errorf(&env.source_position,
3928 "invalid storage class for function '%Y'", env.symbol);
3932 entity = allocate_entity_zero(ENTITY_VARIABLE);
3934 entity->variable.thread_local = specifiers->thread_local;
3936 if (env.symbol != NULL) {
3937 if (specifiers->is_inline && is_type_valid(type)) {
3938 errorf(&env.source_position,
3939 "variable '%Y' declared 'inline'", env.symbol);
3942 bool invalid_storage_class = false;
3943 if (current_scope == file_scope) {
3944 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3945 specifiers->storage_class != STORAGE_CLASS_NONE &&
3946 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3947 invalid_storage_class = true;
3950 if (specifiers->thread_local &&
3951 specifiers->storage_class == STORAGE_CLASS_NONE) {
3952 invalid_storage_class = true;
3955 if (invalid_storage_class) {
3956 errorf(&env.source_position,
3957 "invalid storage class for variable '%Y'", env.symbol);
3962 if (env.symbol != NULL) {
3963 entity->base.symbol = env.symbol;
3964 entity->base.source_position = env.source_position;
3966 entity->base.source_position = specifiers->source_position;
3968 entity->base.namespc = NAMESPACE_NORMAL;
3969 entity->declaration.type = orig_type;
3970 entity->declaration.alignment = get_type_alignment(orig_type);
3971 entity->declaration.modifiers = env.modifiers;
3972 entity->declaration.attributes = attributes;
3974 storage_class_t storage_class = specifiers->storage_class;
3975 entity->declaration.declared_storage_class = storage_class;
3977 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3978 storage_class = STORAGE_CLASS_AUTO;
3979 entity->declaration.storage_class = storage_class;
3982 if (attributes != NULL) {
3983 handle_entity_attributes(attributes, entity);
3989 static type_t *parse_abstract_declarator(type_t *base_type)
3991 parse_declarator_env_t env;
3992 memset(&env, 0, sizeof(env));
3993 env.may_be_abstract = true;
3994 env.must_be_abstract = true;
3996 construct_type_t *construct_type = parse_inner_declarator(&env);
3998 type_t *result = construct_declarator_type(construct_type, base_type);
3999 if (construct_type != NULL) {
4000 obstack_free(&temp_obst, construct_type);
4002 result = handle_type_attributes(env.attributes, result);
4008 * Check if the declaration of main is suspicious. main should be a
4009 * function with external linkage, returning int, taking either zero
4010 * arguments, two, or three arguments of appropriate types, ie.
4012 * int main([ int argc, char **argv [, char **env ] ]).
4014 * @param decl the declaration to check
4015 * @param type the function type of the declaration
4017 static void check_main(const entity_t *entity)
4019 const source_position_t *pos = &entity->base.source_position;
4020 if (entity->kind != ENTITY_FUNCTION) {
4021 warningf(pos, "'main' is not a function");
4025 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4026 warningf(pos, "'main' is normally a non-static function");
4029 type_t *type = skip_typeref(entity->declaration.type);
4030 assert(is_type_function(type));
4032 function_type_t *func_type = &type->function;
4033 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4034 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4035 func_type->return_type);
4037 const function_parameter_t *parm = func_type->parameters;
4039 type_t *const first_type = parm->type;
4040 if (!types_compatible(skip_typeref(first_type), type_int)) {
4042 "first argument of 'main' should be 'int', but is '%T'",
4047 type_t *const second_type = parm->type;
4048 if (!types_compatible(skip_typeref(second_type), type_char_ptr_ptr)) {
4049 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'", second_type);
4053 type_t *const third_type = parm->type;
4054 if (!types_compatible(skip_typeref(third_type), type_char_ptr_ptr)) {
4055 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'", third_type);
4059 goto warn_arg_count;
4063 warningf(pos, "'main' takes only zero, two or three arguments");
4069 * Check if a symbol is the equal to "main".
4071 static bool is_sym_main(const symbol_t *const sym)
4073 return strcmp(sym->string, "main") == 0;
4076 static void error_redefined_as_different_kind(const source_position_t *pos,
4077 const entity_t *old, entity_kind_t new_kind)
4079 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4080 get_entity_kind_name(old->kind), old->base.symbol,
4081 get_entity_kind_name(new_kind), &old->base.source_position);
4084 static bool is_error_entity(entity_t *const ent)
4086 if (is_declaration(ent)) {
4087 return is_type_valid(skip_typeref(ent->declaration.type));
4088 } else if (ent->kind == ENTITY_TYPEDEF) {
4089 return is_type_valid(skip_typeref(ent->typedefe.type));
4094 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4096 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4097 if (attributes_equal(tattr, attr))
4104 * test wether new_list contains any attributes not included in old_list
4106 static bool has_new_attributes(const attribute_t *old_list,
4107 const attribute_t *new_list)
4109 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4110 if (!contains_attribute(old_list, attr))
4117 * Merge in attributes from an attribute list (probably from a previous
4118 * declaration with the same name). Warning: destroys the old structure
4119 * of the attribute list - don't reuse attributes after this call.
4121 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4124 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4126 if (contains_attribute(decl->attributes, attr))
4129 /* move attribute to new declarations attributes list */
4130 attr->next = decl->attributes;
4131 decl->attributes = attr;
4136 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4137 * for various problems that occur for multiple definitions
4139 entity_t *record_entity(entity_t *entity, const bool is_definition)
4141 const symbol_t *const symbol = entity->base.symbol;
4142 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4143 const source_position_t *pos = &entity->base.source_position;
4145 /* can happen in error cases */
4149 entity_t *const previous_entity = get_entity(symbol, namespc);
4150 /* pushing the same entity twice will break the stack structure */
4151 assert(previous_entity != entity);
4153 if (entity->kind == ENTITY_FUNCTION) {
4154 type_t *const orig_type = entity->declaration.type;
4155 type_t *const type = skip_typeref(orig_type);
4157 assert(is_type_function(type));
4158 if (type->function.unspecified_parameters &&
4159 warning.strict_prototypes &&
4160 previous_entity == NULL) {
4161 warningf(pos, "function declaration '%#T' is not a prototype",
4165 if (warning.main && current_scope == file_scope
4166 && is_sym_main(symbol)) {
4171 if (is_declaration(entity) &&
4172 warning.nested_externs &&
4173 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4174 current_scope != file_scope) {
4175 warningf(pos, "nested extern declaration of '%#T'",
4176 entity->declaration.type, symbol);
4179 if (previous_entity != NULL) {
4180 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4181 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4182 assert(previous_entity->kind == ENTITY_PARAMETER);
4184 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4185 entity->declaration.type, symbol,
4186 previous_entity->declaration.type, symbol,
4187 &previous_entity->base.source_position);
4191 if (previous_entity->base.parent_scope == current_scope) {
4192 if (previous_entity->kind != entity->kind) {
4193 if (!is_error_entity(previous_entity) && !is_error_entity(entity)) {
4194 error_redefined_as_different_kind(pos, previous_entity,
4199 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4200 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4201 symbol, &previous_entity->base.source_position);
4204 if (previous_entity->kind == ENTITY_TYPEDEF) {
4205 /* TODO: C++ allows this for exactly the same type */
4206 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4207 symbol, &previous_entity->base.source_position);
4211 /* at this point we should have only VARIABLES or FUNCTIONS */
4212 assert(is_declaration(previous_entity) && is_declaration(entity));
4214 declaration_t *const prev_decl = &previous_entity->declaration;
4215 declaration_t *const decl = &entity->declaration;
4217 /* can happen for K&R style declarations */
4218 if (prev_decl->type == NULL &&
4219 previous_entity->kind == ENTITY_PARAMETER &&
4220 entity->kind == ENTITY_PARAMETER) {
4221 prev_decl->type = decl->type;
4222 prev_decl->storage_class = decl->storage_class;
4223 prev_decl->declared_storage_class = decl->declared_storage_class;
4224 prev_decl->modifiers = decl->modifiers;
4225 return previous_entity;
4228 type_t *const orig_type = decl->type;
4229 assert(orig_type != NULL);
4230 type_t *const type = skip_typeref(orig_type);
4231 type_t *const prev_type = skip_typeref(prev_decl->type);
4233 if (!types_compatible(type, prev_type)) {
4235 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4236 orig_type, symbol, prev_decl->type, symbol,
4237 &previous_entity->base.source_position);
4239 unsigned old_storage_class = prev_decl->storage_class;
4241 if (warning.redundant_decls &&
4244 !(prev_decl->modifiers & DM_USED) &&
4245 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4246 warningf(&previous_entity->base.source_position,
4247 "unnecessary static forward declaration for '%#T'",
4248 prev_decl->type, symbol);
4251 storage_class_t new_storage_class = decl->storage_class;
4253 /* pretend no storage class means extern for function
4254 * declarations (except if the previous declaration is neither
4255 * none nor extern) */
4256 if (entity->kind == ENTITY_FUNCTION) {
4257 /* the previous declaration could have unspecified parameters or
4258 * be a typedef, so use the new type */
4259 if (prev_type->function.unspecified_parameters || is_definition)
4260 prev_decl->type = type;
4262 switch (old_storage_class) {
4263 case STORAGE_CLASS_NONE:
4264 old_storage_class = STORAGE_CLASS_EXTERN;
4267 case STORAGE_CLASS_EXTERN:
4268 if (is_definition) {
4269 if (warning.missing_prototypes &&
4270 prev_type->function.unspecified_parameters &&
4271 !is_sym_main(symbol)) {
4272 warningf(pos, "no previous prototype for '%#T'",
4275 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4276 new_storage_class = STORAGE_CLASS_EXTERN;
4283 } else if (is_type_incomplete(prev_type)) {
4284 prev_decl->type = type;
4287 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4288 new_storage_class == STORAGE_CLASS_EXTERN) {
4290 warn_redundant_declaration: ;
4292 = has_new_attributes(prev_decl->attributes,
4294 if (has_new_attrs) {
4295 merge_in_attributes(decl, prev_decl->attributes);
4296 } else if (!is_definition &&
4297 warning.redundant_decls &&
4298 is_type_valid(prev_type) &&
4299 strcmp(previous_entity->base.source_position.input_name,
4300 "<builtin>") != 0) {
4302 "redundant declaration for '%Y' (declared %P)",
4303 symbol, &previous_entity->base.source_position);
4305 } else if (current_function == NULL) {
4306 if (old_storage_class != STORAGE_CLASS_STATIC &&
4307 new_storage_class == STORAGE_CLASS_STATIC) {
4309 "static declaration of '%Y' follows non-static declaration (declared %P)",
4310 symbol, &previous_entity->base.source_position);
4311 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4312 prev_decl->storage_class = STORAGE_CLASS_NONE;
4313 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4315 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4317 goto error_redeclaration;
4318 goto warn_redundant_declaration;
4320 } else if (is_type_valid(prev_type)) {
4321 if (old_storage_class == new_storage_class) {
4322 error_redeclaration:
4323 errorf(pos, "redeclaration of '%Y' (declared %P)",
4324 symbol, &previous_entity->base.source_position);
4327 "redeclaration of '%Y' with different linkage (declared %P)",
4328 symbol, &previous_entity->base.source_position);
4333 prev_decl->modifiers |= decl->modifiers;
4334 if (entity->kind == ENTITY_FUNCTION) {
4335 previous_entity->function.is_inline |= entity->function.is_inline;
4337 return previous_entity;
4340 if (warning.shadow) {
4341 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4342 get_entity_kind_name(entity->kind), symbol,
4343 get_entity_kind_name(previous_entity->kind),
4344 &previous_entity->base.source_position);
4348 if (entity->kind == ENTITY_FUNCTION) {
4349 if (is_definition &&
4350 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4351 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4352 warningf(pos, "no previous prototype for '%#T'",
4353 entity->declaration.type, symbol);
4354 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4355 warningf(pos, "no previous declaration for '%#T'",
4356 entity->declaration.type, symbol);
4359 } else if (warning.missing_declarations &&
4360 entity->kind == ENTITY_VARIABLE &&
4361 current_scope == file_scope) {
4362 declaration_t *declaration = &entity->declaration;
4363 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4364 warningf(pos, "no previous declaration for '%#T'",
4365 declaration->type, symbol);
4370 assert(entity->base.parent_scope == NULL);
4371 assert(current_scope != NULL);
4373 entity->base.parent_scope = current_scope;
4374 entity->base.namespc = NAMESPACE_NORMAL;
4375 environment_push(entity);
4376 append_entity(current_scope, entity);
4381 static void parser_error_multiple_definition(entity_t *entity,
4382 const source_position_t *source_position)
4384 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4385 entity->base.symbol, &entity->base.source_position);
4388 static bool is_declaration_specifier(const token_t *token,
4389 bool only_specifiers_qualifiers)
4391 switch (token->type) {
4396 return is_typedef_symbol(token->symbol);
4398 case T___extension__:
4400 return !only_specifiers_qualifiers;
4407 static void parse_init_declarator_rest(entity_t *entity)
4409 assert(is_declaration(entity));
4410 declaration_t *const declaration = &entity->declaration;
4414 type_t *orig_type = declaration->type;
4415 type_t *type = skip_typeref(orig_type);
4417 if (entity->kind == ENTITY_VARIABLE
4418 && entity->variable.initializer != NULL) {
4419 parser_error_multiple_definition(entity, HERE);
4422 bool must_be_constant = false;
4423 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4424 entity->base.parent_scope == file_scope) {
4425 must_be_constant = true;
4428 if (is_type_function(type)) {
4429 errorf(&entity->base.source_position,
4430 "function '%#T' is initialized like a variable",
4431 orig_type, entity->base.symbol);
4432 orig_type = type_error_type;
4435 parse_initializer_env_t env;
4436 env.type = orig_type;
4437 env.must_be_constant = must_be_constant;
4438 env.entity = entity;
4439 current_init_decl = entity;
4441 initializer_t *initializer = parse_initializer(&env);
4442 current_init_decl = NULL;
4444 if (entity->kind == ENTITY_VARIABLE) {
4445 /* §6.7.5:22 array initializers for arrays with unknown size
4446 * determine the array type size */
4447 declaration->type = env.type;
4448 entity->variable.initializer = initializer;
4452 /* parse rest of a declaration without any declarator */
4453 static void parse_anonymous_declaration_rest(
4454 const declaration_specifiers_t *specifiers)
4457 anonymous_entity = NULL;
4459 if (warning.other) {
4460 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4461 specifiers->thread_local) {
4462 warningf(&specifiers->source_position,
4463 "useless storage class in empty declaration");
4466 type_t *type = specifiers->type;
4467 switch (type->kind) {
4468 case TYPE_COMPOUND_STRUCT:
4469 case TYPE_COMPOUND_UNION: {
4470 if (type->compound.compound->base.symbol == NULL) {
4471 warningf(&specifiers->source_position,
4472 "unnamed struct/union that defines no instances");
4481 warningf(&specifiers->source_position, "empty declaration");
4487 static void check_variable_type_complete(entity_t *ent)
4489 if (ent->kind != ENTITY_VARIABLE)
4492 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4493 * type for the object shall be complete [...] */
4494 declaration_t *decl = &ent->declaration;
4495 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4496 decl->storage_class == STORAGE_CLASS_STATIC)
4499 type_t *const orig_type = decl->type;
4500 type_t *const type = skip_typeref(orig_type);
4501 if (!is_type_incomplete(type))
4504 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4505 * are given length one. */
4506 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4507 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4511 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4512 orig_type, ent->base.symbol);
4516 static void parse_declaration_rest(entity_t *ndeclaration,
4517 const declaration_specifiers_t *specifiers,
4518 parsed_declaration_func finished_declaration,
4519 declarator_flags_t flags)
4521 add_anchor_token(';');
4522 add_anchor_token(',');
4524 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4526 if (token.type == '=') {
4527 parse_init_declarator_rest(entity);
4528 } else if (entity->kind == ENTITY_VARIABLE) {
4529 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4530 * [...] where the extern specifier is explicitly used. */
4531 declaration_t *decl = &entity->declaration;
4532 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4533 type_t *type = decl->type;
4534 if (is_type_reference(skip_typeref(type))) {
4535 errorf(&entity->base.source_position,
4536 "reference '%#T' must be initialized",
4537 type, entity->base.symbol);
4542 check_variable_type_complete(entity);
4547 add_anchor_token('=');
4548 ndeclaration = parse_declarator(specifiers, flags);
4549 rem_anchor_token('=');
4551 expect(';', end_error);
4554 anonymous_entity = NULL;
4555 rem_anchor_token(';');
4556 rem_anchor_token(',');
4559 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4561 symbol_t *symbol = entity->base.symbol;
4562 if (symbol == NULL) {
4563 errorf(HERE, "anonymous declaration not valid as function parameter");
4567 assert(entity->base.namespc == NAMESPACE_NORMAL);
4568 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4569 if (previous_entity == NULL
4570 || previous_entity->base.parent_scope != current_scope) {
4571 errorf(HERE, "expected declaration of a function parameter, found '%Y'",
4576 if (is_definition) {
4577 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4580 return record_entity(entity, false);
4583 static void parse_declaration(parsed_declaration_func finished_declaration,
4584 declarator_flags_t flags)
4586 declaration_specifiers_t specifiers;
4587 memset(&specifiers, 0, sizeof(specifiers));
4589 add_anchor_token(';');
4590 parse_declaration_specifiers(&specifiers);
4591 rem_anchor_token(';');
4593 if (token.type == ';') {
4594 parse_anonymous_declaration_rest(&specifiers);
4596 entity_t *entity = parse_declarator(&specifiers, flags);
4597 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4602 static type_t *get_default_promoted_type(type_t *orig_type)
4604 type_t *result = orig_type;
4606 type_t *type = skip_typeref(orig_type);
4607 if (is_type_integer(type)) {
4608 result = promote_integer(type);
4609 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4610 result = type_double;
4616 static void parse_kr_declaration_list(entity_t *entity)
4618 if (entity->kind != ENTITY_FUNCTION)
4621 type_t *type = skip_typeref(entity->declaration.type);
4622 assert(is_type_function(type));
4623 if (!type->function.kr_style_parameters)
4626 add_anchor_token('{');
4628 /* push function parameters */
4629 size_t const top = environment_top();
4630 scope_t *old_scope = scope_push(&entity->function.parameters);
4632 entity_t *parameter = entity->function.parameters.entities;
4633 for ( ; parameter != NULL; parameter = parameter->base.next) {
4634 assert(parameter->base.parent_scope == NULL);
4635 parameter->base.parent_scope = current_scope;
4636 environment_push(parameter);
4639 /* parse declaration list */
4641 switch (token.type) {
4643 case T___extension__:
4644 /* This covers symbols, which are no type, too, and results in
4645 * better error messages. The typical cases are misspelled type
4646 * names and missing includes. */
4648 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4656 /* pop function parameters */
4657 assert(current_scope == &entity->function.parameters);
4658 scope_pop(old_scope);
4659 environment_pop_to(top);
4661 /* update function type */
4662 type_t *new_type = duplicate_type(type);
4664 function_parameter_t *parameters = NULL;
4665 function_parameter_t **anchor = ¶meters;
4667 /* did we have an earlier prototype? */
4668 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4669 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4672 function_parameter_t *proto_parameter = NULL;
4673 if (proto_type != NULL) {
4674 type_t *proto_type_type = proto_type->declaration.type;
4675 proto_parameter = proto_type_type->function.parameters;
4676 /* If a K&R function definition has a variadic prototype earlier, then
4677 * make the function definition variadic, too. This should conform to
4678 * §6.7.5.3:15 and §6.9.1:8. */
4679 new_type->function.variadic = proto_type_type->function.variadic;
4681 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4683 new_type->function.unspecified_parameters = true;
4686 bool need_incompatible_warning = false;
4687 parameter = entity->function.parameters.entities;
4688 for (; parameter != NULL; parameter = parameter->base.next,
4690 proto_parameter == NULL ? NULL : proto_parameter->next) {
4691 if (parameter->kind != ENTITY_PARAMETER)
4694 type_t *parameter_type = parameter->declaration.type;
4695 if (parameter_type == NULL) {
4697 errorf(HERE, "no type specified for function parameter '%Y'",
4698 parameter->base.symbol);
4699 parameter_type = type_error_type;
4701 if (warning.implicit_int) {
4702 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4703 parameter->base.symbol);
4705 parameter_type = type_int;
4707 parameter->declaration.type = parameter_type;
4710 semantic_parameter_incomplete(parameter);
4712 /* we need the default promoted types for the function type */
4713 type_t *not_promoted = parameter_type;
4714 parameter_type = get_default_promoted_type(parameter_type);
4716 /* gcc special: if the type of the prototype matches the unpromoted
4717 * type don't promote */
4718 if (!strict_mode && proto_parameter != NULL) {
4719 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4720 type_t *promo_skip = skip_typeref(parameter_type);
4721 type_t *param_skip = skip_typeref(not_promoted);
4722 if (!types_compatible(proto_p_type, promo_skip)
4723 && types_compatible(proto_p_type, param_skip)) {
4725 need_incompatible_warning = true;
4726 parameter_type = not_promoted;
4729 function_parameter_t *const parameter
4730 = allocate_parameter(parameter_type);
4732 *anchor = parameter;
4733 anchor = ¶meter->next;
4736 new_type->function.parameters = parameters;
4737 new_type = identify_new_type(new_type);
4739 if (warning.other && need_incompatible_warning) {
4740 type_t *proto_type_type = proto_type->declaration.type;
4742 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4743 proto_type_type, proto_type->base.symbol,
4744 new_type, entity->base.symbol,
4745 &proto_type->base.source_position);
4748 entity->declaration.type = new_type;
4750 rem_anchor_token('{');
4753 static bool first_err = true;
4756 * When called with first_err set, prints the name of the current function,
4759 static void print_in_function(void)
4763 diagnosticf("%s: In function '%Y':\n",
4764 current_function->base.base.source_position.input_name,
4765 current_function->base.base.symbol);
4770 * Check if all labels are defined in the current function.
4771 * Check if all labels are used in the current function.
4773 static void check_labels(void)
4775 for (const goto_statement_t *goto_statement = goto_first;
4776 goto_statement != NULL;
4777 goto_statement = goto_statement->next) {
4778 /* skip computed gotos */
4779 if (goto_statement->expression != NULL)
4782 label_t *label = goto_statement->label;
4785 if (label->base.source_position.input_name == NULL) {
4786 print_in_function();
4787 errorf(&goto_statement->base.source_position,
4788 "label '%Y' used but not defined", label->base.symbol);
4792 if (warning.unused_label) {
4793 for (const label_statement_t *label_statement = label_first;
4794 label_statement != NULL;
4795 label_statement = label_statement->next) {
4796 label_t *label = label_statement->label;
4798 if (! label->used) {
4799 print_in_function();
4800 warningf(&label_statement->base.source_position,
4801 "label '%Y' defined but not used", label->base.symbol);
4807 static void warn_unused_entity(entity_t *entity, entity_t *last)
4809 entity_t const *const end = last != NULL ? last->base.next : NULL;
4810 for (; entity != end; entity = entity->base.next) {
4811 if (!is_declaration(entity))
4814 declaration_t *declaration = &entity->declaration;
4815 if (declaration->implicit)
4818 if (!declaration->used) {
4819 print_in_function();
4820 const char *what = get_entity_kind_name(entity->kind);
4821 warningf(&entity->base.source_position, "%s '%Y' is unused",
4822 what, entity->base.symbol);
4823 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4824 print_in_function();
4825 const char *what = get_entity_kind_name(entity->kind);
4826 warningf(&entity->base.source_position, "%s '%Y' is never read",
4827 what, entity->base.symbol);
4832 static void check_unused_variables(statement_t *const stmt, void *const env)
4836 switch (stmt->kind) {
4837 case STATEMENT_DECLARATION: {
4838 declaration_statement_t const *const decls = &stmt->declaration;
4839 warn_unused_entity(decls->declarations_begin,
4840 decls->declarations_end);
4845 warn_unused_entity(stmt->fors.scope.entities, NULL);
4854 * Check declarations of current_function for unused entities.
4856 static void check_declarations(void)
4858 if (warning.unused_parameter) {
4859 const scope_t *scope = ¤t_function->parameters;
4861 /* do not issue unused warnings for main */
4862 if (!is_sym_main(current_function->base.base.symbol)) {
4863 warn_unused_entity(scope->entities, NULL);
4866 if (warning.unused_variable) {
4867 walk_statements(current_function->statement, check_unused_variables,
4872 static int determine_truth(expression_t const* const cond)
4875 !is_constant_expression(cond) ? 0 :
4876 fold_constant_to_bool(cond) ? 1 :
4880 static void check_reachable(statement_t *);
4881 static bool reaches_end;
4883 static bool expression_returns(expression_t const *const expr)
4885 switch (expr->kind) {
4887 expression_t const *const func = expr->call.function;
4888 if (func->kind == EXPR_REFERENCE) {
4889 entity_t *entity = func->reference.entity;
4890 if (entity->kind == ENTITY_FUNCTION
4891 && entity->declaration.modifiers & DM_NORETURN)
4895 if (!expression_returns(func))
4898 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4899 if (!expression_returns(arg->expression))
4906 case EXPR_REFERENCE:
4907 case EXPR_REFERENCE_ENUM_VALUE:
4909 case EXPR_STRING_LITERAL:
4910 case EXPR_WIDE_STRING_LITERAL:
4911 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4912 case EXPR_LABEL_ADDRESS:
4913 case EXPR_CLASSIFY_TYPE:
4914 case EXPR_SIZEOF: // TODO handle obscure VLA case
4917 case EXPR_BUILTIN_CONSTANT_P:
4918 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4923 case EXPR_STATEMENT: {
4924 bool old_reaches_end = reaches_end;
4925 reaches_end = false;
4926 check_reachable(expr->statement.statement);
4927 bool returns = reaches_end;
4928 reaches_end = old_reaches_end;
4932 case EXPR_CONDITIONAL:
4933 // TODO handle constant expression
4935 if (!expression_returns(expr->conditional.condition))
4938 if (expr->conditional.true_expression != NULL
4939 && expression_returns(expr->conditional.true_expression))
4942 return expression_returns(expr->conditional.false_expression);
4945 return expression_returns(expr->select.compound);
4947 case EXPR_ARRAY_ACCESS:
4949 expression_returns(expr->array_access.array_ref) &&
4950 expression_returns(expr->array_access.index);
4953 return expression_returns(expr->va_starte.ap);
4956 return expression_returns(expr->va_arge.ap);
4959 return expression_returns(expr->va_copye.src);
4961 EXPR_UNARY_CASES_MANDATORY
4962 return expression_returns(expr->unary.value);
4964 case EXPR_UNARY_THROW:
4968 // TODO handle constant lhs of && and ||
4970 expression_returns(expr->binary.left) &&
4971 expression_returns(expr->binary.right);
4977 panic("unhandled expression");
4980 static bool initializer_returns(initializer_t const *const init)
4982 switch (init->kind) {
4983 case INITIALIZER_VALUE:
4984 return expression_returns(init->value.value);
4986 case INITIALIZER_LIST: {
4987 initializer_t * const* i = init->list.initializers;
4988 initializer_t * const* const end = i + init->list.len;
4989 bool returns = true;
4990 for (; i != end; ++i) {
4991 if (!initializer_returns(*i))
4997 case INITIALIZER_STRING:
4998 case INITIALIZER_WIDE_STRING:
4999 case INITIALIZER_DESIGNATOR: // designators have no payload
5002 panic("unhandled initializer");
5005 static bool noreturn_candidate;
5007 static void check_reachable(statement_t *const stmt)
5009 if (stmt->base.reachable)
5011 if (stmt->kind != STATEMENT_DO_WHILE)
5012 stmt->base.reachable = true;
5014 statement_t *last = stmt;
5016 switch (stmt->kind) {
5017 case STATEMENT_INVALID:
5018 case STATEMENT_EMPTY:
5020 next = stmt->base.next;
5023 case STATEMENT_DECLARATION: {
5024 declaration_statement_t const *const decl = &stmt->declaration;
5025 entity_t const * ent = decl->declarations_begin;
5026 entity_t const *const last = decl->declarations_end;
5028 for (;; ent = ent->base.next) {
5029 if (ent->kind == ENTITY_VARIABLE &&
5030 ent->variable.initializer != NULL &&
5031 !initializer_returns(ent->variable.initializer)) {
5038 next = stmt->base.next;
5042 case STATEMENT_COMPOUND:
5043 next = stmt->compound.statements;
5045 next = stmt->base.next;
5048 case STATEMENT_RETURN: {
5049 expression_t const *const val = stmt->returns.value;
5050 if (val == NULL || expression_returns(val))
5051 noreturn_candidate = false;
5055 case STATEMENT_IF: {
5056 if_statement_t const *const ifs = &stmt->ifs;
5057 expression_t const *const cond = ifs->condition;
5059 if (!expression_returns(cond))
5062 int const val = determine_truth(cond);
5065 check_reachable(ifs->true_statement);
5070 if (ifs->false_statement != NULL) {
5071 check_reachable(ifs->false_statement);
5075 next = stmt->base.next;
5079 case STATEMENT_SWITCH: {
5080 switch_statement_t const *const switchs = &stmt->switchs;
5081 expression_t const *const expr = switchs->expression;
5083 if (!expression_returns(expr))
5086 if (is_constant_expression(expr)) {
5087 long const val = fold_constant_to_int(expr);
5088 case_label_statement_t * defaults = NULL;
5089 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5090 if (i->expression == NULL) {
5095 if (i->first_case <= val && val <= i->last_case) {
5096 check_reachable((statement_t*)i);
5101 if (defaults != NULL) {
5102 check_reachable((statement_t*)defaults);
5106 bool has_default = false;
5107 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5108 if (i->expression == NULL)
5111 check_reachable((statement_t*)i);
5118 next = stmt->base.next;
5122 case STATEMENT_EXPRESSION: {
5123 /* Check for noreturn function call */
5124 expression_t const *const expr = stmt->expression.expression;
5125 if (!expression_returns(expr))
5128 next = stmt->base.next;
5132 case STATEMENT_CONTINUE:
5133 for (statement_t *parent = stmt;;) {
5134 parent = parent->base.parent;
5135 if (parent == NULL) /* continue not within loop */
5139 switch (parent->kind) {
5140 case STATEMENT_WHILE: goto continue_while;
5141 case STATEMENT_DO_WHILE: goto continue_do_while;
5142 case STATEMENT_FOR: goto continue_for;
5148 case STATEMENT_BREAK:
5149 for (statement_t *parent = stmt;;) {
5150 parent = parent->base.parent;
5151 if (parent == NULL) /* break not within loop/switch */
5154 switch (parent->kind) {
5155 case STATEMENT_SWITCH:
5156 case STATEMENT_WHILE:
5157 case STATEMENT_DO_WHILE:
5160 next = parent->base.next;
5161 goto found_break_parent;
5169 case STATEMENT_GOTO:
5170 if (stmt->gotos.expression) {
5171 if (!expression_returns(stmt->gotos.expression))
5174 statement_t *parent = stmt->base.parent;
5175 if (parent == NULL) /* top level goto */
5179 next = stmt->gotos.label->statement;
5180 if (next == NULL) /* missing label */
5185 case STATEMENT_LABEL:
5186 next = stmt->label.statement;
5189 case STATEMENT_CASE_LABEL:
5190 next = stmt->case_label.statement;
5193 case STATEMENT_WHILE: {
5194 while_statement_t const *const whiles = &stmt->whiles;
5195 expression_t const *const cond = whiles->condition;
5197 if (!expression_returns(cond))
5200 int const val = determine_truth(cond);
5203 check_reachable(whiles->body);
5208 next = stmt->base.next;
5212 case STATEMENT_DO_WHILE:
5213 next = stmt->do_while.body;
5216 case STATEMENT_FOR: {
5217 for_statement_t *const fors = &stmt->fors;
5219 if (fors->condition_reachable)
5221 fors->condition_reachable = true;
5223 expression_t const *const cond = fors->condition;
5228 } else if (expression_returns(cond)) {
5229 val = determine_truth(cond);
5235 check_reachable(fors->body);
5240 next = stmt->base.next;
5244 case STATEMENT_MS_TRY: {
5245 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5246 check_reachable(ms_try->try_statement);
5247 next = ms_try->final_statement;
5251 case STATEMENT_LEAVE: {
5252 statement_t *parent = stmt;
5254 parent = parent->base.parent;
5255 if (parent == NULL) /* __leave not within __try */
5258 if (parent->kind == STATEMENT_MS_TRY) {
5260 next = parent->ms_try.final_statement;
5268 panic("invalid statement kind");
5271 while (next == NULL) {
5272 next = last->base.parent;
5274 noreturn_candidate = false;
5276 type_t *const type = skip_typeref(current_function->base.type);
5277 assert(is_type_function(type));
5278 type_t *const ret = skip_typeref(type->function.return_type);
5279 if (warning.return_type &&
5280 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5281 is_type_valid(ret) &&
5282 !is_sym_main(current_function->base.base.symbol)) {
5283 warningf(&stmt->base.source_position,
5284 "control reaches end of non-void function");
5289 switch (next->kind) {
5290 case STATEMENT_INVALID:
5291 case STATEMENT_EMPTY:
5292 case STATEMENT_DECLARATION:
5293 case STATEMENT_EXPRESSION:
5295 case STATEMENT_RETURN:
5296 case STATEMENT_CONTINUE:
5297 case STATEMENT_BREAK:
5298 case STATEMENT_GOTO:
5299 case STATEMENT_LEAVE:
5300 panic("invalid control flow in function");
5302 case STATEMENT_COMPOUND:
5303 if (next->compound.stmt_expr) {
5309 case STATEMENT_SWITCH:
5310 case STATEMENT_LABEL:
5311 case STATEMENT_CASE_LABEL:
5313 next = next->base.next;
5316 case STATEMENT_WHILE: {
5318 if (next->base.reachable)
5320 next->base.reachable = true;
5322 while_statement_t const *const whiles = &next->whiles;
5323 expression_t const *const cond = whiles->condition;
5325 if (!expression_returns(cond))
5328 int const val = determine_truth(cond);
5331 check_reachable(whiles->body);
5337 next = next->base.next;
5341 case STATEMENT_DO_WHILE: {
5343 if (next->base.reachable)
5345 next->base.reachable = true;
5347 do_while_statement_t const *const dw = &next->do_while;
5348 expression_t const *const cond = dw->condition;
5350 if (!expression_returns(cond))
5353 int const val = determine_truth(cond);
5356 check_reachable(dw->body);
5362 next = next->base.next;
5366 case STATEMENT_FOR: {
5368 for_statement_t *const fors = &next->fors;
5370 fors->step_reachable = true;
5372 if (fors->condition_reachable)
5374 fors->condition_reachable = true;
5376 expression_t const *const cond = fors->condition;
5381 } else if (expression_returns(cond)) {
5382 val = determine_truth(cond);
5388 check_reachable(fors->body);
5394 next = next->base.next;
5398 case STATEMENT_MS_TRY:
5400 next = next->ms_try.final_statement;
5405 check_reachable(next);
5408 static void check_unreachable(statement_t* const stmt, void *const env)
5412 switch (stmt->kind) {
5413 case STATEMENT_DO_WHILE:
5414 if (!stmt->base.reachable) {
5415 expression_t const *const cond = stmt->do_while.condition;
5416 if (determine_truth(cond) >= 0) {
5417 warningf(&cond->base.source_position,
5418 "condition of do-while-loop is unreachable");
5423 case STATEMENT_FOR: {
5424 for_statement_t const* const fors = &stmt->fors;
5426 // if init and step are unreachable, cond is unreachable, too
5427 if (!stmt->base.reachable && !fors->step_reachable) {
5428 warningf(&stmt->base.source_position, "statement is unreachable");
5430 if (!stmt->base.reachable && fors->initialisation != NULL) {
5431 warningf(&fors->initialisation->base.source_position,
5432 "initialisation of for-statement is unreachable");
5435 if (!fors->condition_reachable && fors->condition != NULL) {
5436 warningf(&fors->condition->base.source_position,
5437 "condition of for-statement is unreachable");
5440 if (!fors->step_reachable && fors->step != NULL) {
5441 warningf(&fors->step->base.source_position,
5442 "step of for-statement is unreachable");
5448 case STATEMENT_COMPOUND:
5449 if (stmt->compound.statements != NULL)
5451 goto warn_unreachable;
5453 case STATEMENT_DECLARATION: {
5454 /* Only warn if there is at least one declarator with an initializer.
5455 * This typically occurs in switch statements. */
5456 declaration_statement_t const *const decl = &stmt->declaration;
5457 entity_t const * ent = decl->declarations_begin;
5458 entity_t const *const last = decl->declarations_end;
5460 for (;; ent = ent->base.next) {
5461 if (ent->kind == ENTITY_VARIABLE &&
5462 ent->variable.initializer != NULL) {
5463 goto warn_unreachable;
5473 if (!stmt->base.reachable)
5474 warningf(&stmt->base.source_position, "statement is unreachable");
5479 static void parse_external_declaration(void)
5481 /* function-definitions and declarations both start with declaration
5483 declaration_specifiers_t specifiers;
5484 memset(&specifiers, 0, sizeof(specifiers));
5486 add_anchor_token(';');
5487 parse_declaration_specifiers(&specifiers);
5488 rem_anchor_token(';');
5490 /* must be a declaration */
5491 if (token.type == ';') {
5492 parse_anonymous_declaration_rest(&specifiers);
5496 add_anchor_token(',');
5497 add_anchor_token('=');
5498 add_anchor_token(';');
5499 add_anchor_token('{');
5501 /* declarator is common to both function-definitions and declarations */
5502 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5504 rem_anchor_token('{');
5505 rem_anchor_token(';');
5506 rem_anchor_token('=');
5507 rem_anchor_token(',');
5509 /* must be a declaration */
5510 switch (token.type) {
5514 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5519 /* must be a function definition */
5520 parse_kr_declaration_list(ndeclaration);
5522 if (token.type != '{') {
5523 parse_error_expected("while parsing function definition", '{', NULL);
5524 eat_until_matching_token(';');
5528 assert(is_declaration(ndeclaration));
5529 type_t *const orig_type = ndeclaration->declaration.type;
5530 type_t * type = skip_typeref(orig_type);
5532 if (!is_type_function(type)) {
5533 if (is_type_valid(type)) {
5534 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5535 type, ndeclaration->base.symbol);
5539 } else if (is_typeref(orig_type)) {
5541 errorf(&ndeclaration->base.source_position,
5542 "type of function definition '%#T' is a typedef",
5543 orig_type, ndeclaration->base.symbol);
5546 if (warning.aggregate_return &&
5547 is_type_compound(skip_typeref(type->function.return_type))) {
5548 warningf(HERE, "function '%Y' returns an aggregate",
5549 ndeclaration->base.symbol);
5551 if (warning.traditional && !type->function.unspecified_parameters) {
5552 warningf(HERE, "traditional C rejects ISO C style function definition of function '%Y'",
5553 ndeclaration->base.symbol);
5555 if (warning.old_style_definition && type->function.unspecified_parameters) {
5556 warningf(HERE, "old-style function definition '%Y'",
5557 ndeclaration->base.symbol);
5560 /* §6.7.5.3:14 a function definition with () means no
5561 * parameters (and not unspecified parameters) */
5562 if (type->function.unspecified_parameters &&
5563 type->function.parameters == NULL) {
5564 type_t *copy = duplicate_type(type);
5565 copy->function.unspecified_parameters = false;
5566 type = identify_new_type(copy);
5568 ndeclaration->declaration.type = type;
5571 entity_t *const entity = record_entity(ndeclaration, true);
5572 assert(entity->kind == ENTITY_FUNCTION);
5573 assert(ndeclaration->kind == ENTITY_FUNCTION);
5575 function_t *function = &entity->function;
5576 if (ndeclaration != entity) {
5577 function->parameters = ndeclaration->function.parameters;
5579 assert(is_declaration(entity));
5580 type = skip_typeref(entity->declaration.type);
5582 /* push function parameters and switch scope */
5583 size_t const top = environment_top();
5584 scope_t *old_scope = scope_push(&function->parameters);
5586 entity_t *parameter = function->parameters.entities;
5587 for (; parameter != NULL; parameter = parameter->base.next) {
5588 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5589 parameter->base.parent_scope = current_scope;
5591 assert(parameter->base.parent_scope == NULL
5592 || parameter->base.parent_scope == current_scope);
5593 parameter->base.parent_scope = current_scope;
5594 if (parameter->base.symbol == NULL) {
5595 errorf(¶meter->base.source_position, "parameter name omitted");
5598 environment_push(parameter);
5601 if (function->statement != NULL) {
5602 parser_error_multiple_definition(entity, HERE);
5605 /* parse function body */
5606 int label_stack_top = label_top();
5607 function_t *old_current_function = current_function;
5608 entity_t *old_current_entity = current_entity;
5609 current_function = function;
5610 current_entity = (entity_t*) function;
5611 current_parent = NULL;
5614 goto_anchor = &goto_first;
5616 label_anchor = &label_first;
5618 statement_t *const body = parse_compound_statement(false);
5619 function->statement = body;
5622 check_declarations();
5623 if (warning.return_type ||
5624 warning.unreachable_code ||
5625 (warning.missing_noreturn
5626 && !(function->base.modifiers & DM_NORETURN))) {
5627 noreturn_candidate = true;
5628 check_reachable(body);
5629 if (warning.unreachable_code)
5630 walk_statements(body, check_unreachable, NULL);
5631 if (warning.missing_noreturn &&
5632 noreturn_candidate &&
5633 !(function->base.modifiers & DM_NORETURN)) {
5634 warningf(&body->base.source_position,
5635 "function '%#T' is candidate for attribute 'noreturn'",
5636 type, entity->base.symbol);
5640 assert(current_parent == NULL);
5641 assert(current_function == function);
5642 assert(current_entity == (entity_t*) function);
5643 current_entity = old_current_entity;
5644 current_function = old_current_function;
5645 label_pop_to(label_stack_top);
5648 assert(current_scope == &function->parameters);
5649 scope_pop(old_scope);
5650 environment_pop_to(top);
5653 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5654 source_position_t *source_position,
5655 const symbol_t *symbol)
5657 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5659 type->bitfield.base_type = base_type;
5660 type->bitfield.size_expression = size;
5663 type_t *skipped_type = skip_typeref(base_type);
5664 if (!is_type_integer(skipped_type)) {
5665 errorf(HERE, "bitfield base type '%T' is not an integer type",
5669 bit_size = get_type_size(base_type) * 8;
5672 if (is_constant_expression(size)) {
5673 long v = fold_constant_to_int(size);
5674 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5677 errorf(source_position, "negative width in bit-field '%Y'",
5679 } else if (v == 0 && symbol != NULL) {
5680 errorf(source_position, "zero width for bit-field '%Y'",
5682 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5683 errorf(source_position, "width of '%Y' exceeds its type",
5686 type->bitfield.bit_size = v;
5693 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5695 entity_t *iter = compound->members.entities;
5696 for (; iter != NULL; iter = iter->base.next) {
5697 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5700 if (iter->base.symbol == symbol) {
5702 } else if (iter->base.symbol == NULL) {
5703 /* search in anonymous structs and unions */
5704 type_t *type = skip_typeref(iter->declaration.type);
5705 if (is_type_compound(type)) {
5706 if (find_compound_entry(type->compound.compound, symbol)
5717 static void check_deprecated(const source_position_t *source_position,
5718 const entity_t *entity)
5720 if (!warning.deprecated_declarations)
5722 if (!is_declaration(entity))
5724 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5727 char const *const prefix = get_entity_kind_name(entity->kind);
5728 const char *deprecated_string
5729 = get_deprecated_string(entity->declaration.attributes);
5730 if (deprecated_string != NULL) {
5731 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5732 prefix, entity->base.symbol, &entity->base.source_position,
5735 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5736 entity->base.symbol, &entity->base.source_position);
5741 static expression_t *create_select(const source_position_t *pos,
5743 type_qualifiers_t qualifiers,
5746 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5748 check_deprecated(pos, entry);
5750 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5751 select->select.compound = addr;
5752 select->select.compound_entry = entry;
5754 type_t *entry_type = entry->declaration.type;
5755 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5757 /* we always do the auto-type conversions; the & and sizeof parser contains
5758 * code to revert this! */
5759 select->base.type = automatic_type_conversion(res_type);
5760 if (res_type->kind == TYPE_BITFIELD) {
5761 select->base.type = res_type->bitfield.base_type;
5768 * Find entry with symbol in compound. Search anonymous structs and unions and
5769 * creates implicit select expressions for them.
5770 * Returns the adress for the innermost compound.
5772 static expression_t *find_create_select(const source_position_t *pos,
5774 type_qualifiers_t qualifiers,
5775 compound_t *compound, symbol_t *symbol)
5777 entity_t *iter = compound->members.entities;
5778 for (; iter != NULL; iter = iter->base.next) {
5779 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5782 symbol_t *iter_symbol = iter->base.symbol;
5783 if (iter_symbol == NULL) {
5784 type_t *type = iter->declaration.type;
5785 if (type->kind != TYPE_COMPOUND_STRUCT
5786 && type->kind != TYPE_COMPOUND_UNION)
5789 compound_t *sub_compound = type->compound.compound;
5791 if (find_compound_entry(sub_compound, symbol) == NULL)
5794 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5795 sub_addr->base.source_position = *pos;
5796 sub_addr->select.implicit = true;
5797 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5801 if (iter_symbol == symbol) {
5802 return create_select(pos, addr, qualifiers, iter);
5809 static void parse_compound_declarators(compound_t *compound,
5810 const declaration_specifiers_t *specifiers)
5815 if (token.type == ':') {
5816 source_position_t source_position = *HERE;
5819 type_t *base_type = specifiers->type;
5820 expression_t *size = parse_constant_expression();
5822 type_t *type = make_bitfield_type(base_type, size,
5823 &source_position, NULL);
5825 attribute_t *attributes = parse_attributes(NULL);
5826 attribute_t **anchor = &attributes;
5827 while (*anchor != NULL)
5828 anchor = &(*anchor)->next;
5829 *anchor = specifiers->attributes;
5831 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5832 entity->base.namespc = NAMESPACE_NORMAL;
5833 entity->base.source_position = source_position;
5834 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5835 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5836 entity->declaration.type = type;
5837 entity->declaration.attributes = attributes;
5839 if (attributes != NULL) {
5840 handle_entity_attributes(attributes, entity);
5842 append_entity(&compound->members, entity);
5844 entity = parse_declarator(specifiers,
5845 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5846 if (entity->kind == ENTITY_TYPEDEF) {
5847 errorf(&entity->base.source_position,
5848 "typedef not allowed as compound member");
5850 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5852 /* make sure we don't define a symbol multiple times */
5853 symbol_t *symbol = entity->base.symbol;
5854 if (symbol != NULL) {
5855 entity_t *prev = find_compound_entry(compound, symbol);
5857 errorf(&entity->base.source_position,
5858 "multiple declarations of symbol '%Y' (declared %P)",
5859 symbol, &prev->base.source_position);
5863 if (token.type == ':') {
5864 source_position_t source_position = *HERE;
5866 expression_t *size = parse_constant_expression();
5868 type_t *type = entity->declaration.type;
5869 type_t *bitfield_type = make_bitfield_type(type, size,
5870 &source_position, entity->base.symbol);
5872 attribute_t *attributes = parse_attributes(NULL);
5873 entity->declaration.type = bitfield_type;
5874 handle_entity_attributes(attributes, entity);
5876 type_t *orig_type = entity->declaration.type;
5877 type_t *type = skip_typeref(orig_type);
5878 if (is_type_function(type)) {
5879 errorf(&entity->base.source_position,
5880 "compound member '%Y' must not have function type '%T'",
5881 entity->base.symbol, orig_type);
5882 } else if (is_type_incomplete(type)) {
5883 /* §6.7.2.1:16 flexible array member */
5884 if (!is_type_array(type) ||
5885 token.type != ';' ||
5886 look_ahead(1)->type != '}') {
5887 errorf(&entity->base.source_position,
5888 "compound member '%Y' has incomplete type '%T'",
5889 entity->base.symbol, orig_type);
5894 append_entity(&compound->members, entity);
5897 } while (next_if(','));
5898 expect(';', end_error);
5901 anonymous_entity = NULL;
5904 static void parse_compound_type_entries(compound_t *compound)
5907 add_anchor_token('}');
5909 while (token.type != '}') {
5910 if (token.type == T_EOF) {
5911 errorf(HERE, "EOF while parsing struct");
5914 declaration_specifiers_t specifiers;
5915 memset(&specifiers, 0, sizeof(specifiers));
5916 parse_declaration_specifiers(&specifiers);
5918 parse_compound_declarators(compound, &specifiers);
5920 rem_anchor_token('}');
5924 compound->complete = true;
5927 static type_t *parse_typename(void)
5929 declaration_specifiers_t specifiers;
5930 memset(&specifiers, 0, sizeof(specifiers));
5931 parse_declaration_specifiers(&specifiers);
5932 if (specifiers.storage_class != STORAGE_CLASS_NONE
5933 || specifiers.thread_local) {
5934 /* TODO: improve error message, user does probably not know what a
5935 * storage class is...
5937 errorf(HERE, "typename must not have a storage class");
5940 type_t *result = parse_abstract_declarator(specifiers.type);
5948 typedef expression_t* (*parse_expression_function)(void);
5949 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5951 typedef struct expression_parser_function_t expression_parser_function_t;
5952 struct expression_parser_function_t {
5953 parse_expression_function parser;
5954 precedence_t infix_precedence;
5955 parse_expression_infix_function infix_parser;
5958 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5961 * Prints an error message if an expression was expected but not read
5963 static expression_t *expected_expression_error(void)
5965 /* skip the error message if the error token was read */
5966 if (token.type != T_ERROR) {
5967 errorf(HERE, "expected expression, got token %K", &token);
5971 return create_invalid_expression();
5974 static type_t *get_string_type(void)
5976 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
5979 static type_t *get_wide_string_type(void)
5981 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5985 * Parse a string constant.
5987 static expression_t *parse_string_literal(void)
5989 source_position_t begin = token.source_position;
5990 string_t res = token.literal;
5991 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5994 while (token.type == T_STRING_LITERAL
5995 || token.type == T_WIDE_STRING_LITERAL) {
5996 warn_string_concat(&token.source_position);
5997 res = concat_strings(&res, &token.literal);
5999 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6002 expression_t *literal;
6004 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6005 literal->base.type = get_wide_string_type();
6007 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6008 literal->base.type = get_string_type();
6010 literal->base.source_position = begin;
6011 literal->literal.value = res;
6017 * Parse a boolean constant.
6019 static expression_t *parse_boolean_literal(bool value)
6021 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6022 literal->base.source_position = token.source_position;
6023 literal->base.type = type_bool;
6024 literal->literal.value.begin = value ? "true" : "false";
6025 literal->literal.value.size = value ? 4 : 5;
6031 static void warn_traditional_suffix(void)
6033 if (!warning.traditional)
6035 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6039 static void check_integer_suffix(void)
6041 symbol_t *suffix = token.symbol;
6045 bool not_traditional = false;
6046 const char *c = suffix->string;
6047 if (*c == 'l' || *c == 'L') {
6050 not_traditional = true;
6052 if (*c == 'u' || *c == 'U') {
6055 } else if (*c == 'u' || *c == 'U') {
6056 not_traditional = true;
6059 } else if (*c == 'u' || *c == 'U') {
6060 not_traditional = true;
6062 if (*c == 'l' || *c == 'L') {
6070 errorf(&token.source_position,
6071 "invalid suffix '%s' on integer constant", suffix->string);
6072 } else if (not_traditional) {
6073 warn_traditional_suffix();
6077 static type_t *check_floatingpoint_suffix(void)
6079 symbol_t *suffix = token.symbol;
6080 type_t *type = type_double;
6084 bool not_traditional = false;
6085 const char *c = suffix->string;
6086 if (*c == 'f' || *c == 'F') {
6089 } else if (*c == 'l' || *c == 'L') {
6091 type = type_long_double;
6094 errorf(&token.source_position,
6095 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6096 } else if (not_traditional) {
6097 warn_traditional_suffix();
6104 * Parse an integer constant.
6106 static expression_t *parse_number_literal(void)
6108 expression_kind_t kind;
6111 switch (token.type) {
6113 kind = EXPR_LITERAL_INTEGER;
6114 check_integer_suffix();
6117 case T_INTEGER_OCTAL:
6118 kind = EXPR_LITERAL_INTEGER_OCTAL;
6119 check_integer_suffix();
6122 case T_INTEGER_HEXADECIMAL:
6123 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6124 check_integer_suffix();
6127 case T_FLOATINGPOINT:
6128 kind = EXPR_LITERAL_FLOATINGPOINT;
6129 type = check_floatingpoint_suffix();
6131 case T_FLOATINGPOINT_HEXADECIMAL:
6132 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6133 type = check_floatingpoint_suffix();
6136 panic("unexpected token type in parse_number_literal");
6139 expression_t *literal = allocate_expression_zero(kind);
6140 literal->base.source_position = token.source_position;
6141 literal->base.type = type;
6142 literal->literal.value = token.literal;
6143 literal->literal.suffix = token.symbol;
6146 /* integer type depends on the size of the number and the size
6147 * representable by the types. The backend/codegeneration has to determine
6150 determine_literal_type(&literal->literal);
6155 * Parse a character constant.
6157 static expression_t *parse_character_constant(void)
6159 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6160 literal->base.source_position = token.source_position;
6161 literal->base.type = c_mode & _CXX ? type_char : type_int;
6162 literal->literal.value = token.literal;
6164 size_t len = literal->literal.value.size;
6166 if (!GNU_MODE && !(c_mode & _C99)) {
6167 errorf(HERE, "more than 1 character in character constant");
6168 } else if (warning.multichar) {
6169 literal->base.type = type_int;
6170 warningf(HERE, "multi-character character constant");
6179 * Parse a wide character constant.
6181 static expression_t *parse_wide_character_constant(void)
6183 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6184 literal->base.source_position = token.source_position;
6185 literal->base.type = type_int;
6186 literal->literal.value = token.literal;
6188 size_t len = wstrlen(&literal->literal.value);
6190 warningf(HERE, "multi-character character constant");
6197 static entity_t *create_implicit_function(symbol_t *symbol,
6198 const source_position_t *source_position)
6200 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6201 ntype->function.return_type = type_int;
6202 ntype->function.unspecified_parameters = true;
6203 ntype->function.linkage = LINKAGE_C;
6204 type_t *type = identify_new_type(ntype);
6206 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6207 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6208 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6209 entity->declaration.type = type;
6210 entity->declaration.implicit = true;
6211 entity->base.symbol = symbol;
6212 entity->base.source_position = *source_position;
6214 if (current_scope != NULL) {
6215 bool strict_prototypes_old = warning.strict_prototypes;
6216 warning.strict_prototypes = false;
6217 record_entity(entity, false);
6218 warning.strict_prototypes = strict_prototypes_old;
6225 * Performs automatic type cast as described in §6.3.2.1.
6227 * @param orig_type the original type
6229 static type_t *automatic_type_conversion(type_t *orig_type)
6231 type_t *type = skip_typeref(orig_type);
6232 if (is_type_array(type)) {
6233 array_type_t *array_type = &type->array;
6234 type_t *element_type = array_type->element_type;
6235 unsigned qualifiers = array_type->base.qualifiers;
6237 return make_pointer_type(element_type, qualifiers);
6240 if (is_type_function(type)) {
6241 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6248 * reverts the automatic casts of array to pointer types and function
6249 * to function-pointer types as defined §6.3.2.1
6251 type_t *revert_automatic_type_conversion(const expression_t *expression)
6253 switch (expression->kind) {
6254 case EXPR_REFERENCE: {
6255 entity_t *entity = expression->reference.entity;
6256 if (is_declaration(entity)) {
6257 return entity->declaration.type;
6258 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6259 return entity->enum_value.enum_type;
6261 panic("no declaration or enum in reference");
6266 entity_t *entity = expression->select.compound_entry;
6267 assert(is_declaration(entity));
6268 type_t *type = entity->declaration.type;
6269 return get_qualified_type(type,
6270 expression->base.type->base.qualifiers);
6273 case EXPR_UNARY_DEREFERENCE: {
6274 const expression_t *const value = expression->unary.value;
6275 type_t *const type = skip_typeref(value->base.type);
6276 if (!is_type_pointer(type))
6277 return type_error_type;
6278 return type->pointer.points_to;
6281 case EXPR_ARRAY_ACCESS: {
6282 const expression_t *array_ref = expression->array_access.array_ref;
6283 type_t *type_left = skip_typeref(array_ref->base.type);
6284 if (!is_type_pointer(type_left))
6285 return type_error_type;
6286 return type_left->pointer.points_to;
6289 case EXPR_STRING_LITERAL: {
6290 size_t size = expression->string_literal.value.size;
6291 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6294 case EXPR_WIDE_STRING_LITERAL: {
6295 size_t size = wstrlen(&expression->string_literal.value);
6296 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6299 case EXPR_COMPOUND_LITERAL:
6300 return expression->compound_literal.type;
6305 return expression->base.type;
6309 * Find an entity matching a symbol in a scope.
6310 * Uses current scope if scope is NULL
6312 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6313 namespace_tag_t namespc)
6315 if (scope == NULL) {
6316 return get_entity(symbol, namespc);
6319 /* we should optimize here, if scope grows above a certain size we should
6320 construct a hashmap here... */
6321 entity_t *entity = scope->entities;
6322 for ( ; entity != NULL; entity = entity->base.next) {
6323 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6330 static entity_t *parse_qualified_identifier(void)
6332 /* namespace containing the symbol */
6334 source_position_t pos;
6335 const scope_t *lookup_scope = NULL;
6337 if (next_if(T_COLONCOLON))
6338 lookup_scope = &unit->scope;
6342 if (token.type != T_IDENTIFIER) {
6343 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6344 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6346 symbol = token.symbol;
6351 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6353 if (!next_if(T_COLONCOLON))
6356 switch (entity->kind) {
6357 case ENTITY_NAMESPACE:
6358 lookup_scope = &entity->namespacee.members;
6363 lookup_scope = &entity->compound.members;
6366 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6367 symbol, get_entity_kind_name(entity->kind));
6372 if (entity == NULL) {
6373 if (!strict_mode && token.type == '(') {
6374 /* an implicitly declared function */
6375 if (warning.error_implicit_function_declaration) {
6376 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6377 } else if (warning.implicit_function_declaration) {
6378 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6381 entity = create_implicit_function(symbol, &pos);
6383 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6384 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6391 /* skip further qualifications */
6392 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6394 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6397 static expression_t *parse_reference(void)
6399 entity_t *entity = parse_qualified_identifier();
6402 if (is_declaration(entity)) {
6403 orig_type = entity->declaration.type;
6404 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6405 orig_type = entity->enum_value.enum_type;
6407 panic("expected declaration or enum value in reference");
6410 /* we always do the auto-type conversions; the & and sizeof parser contains
6411 * code to revert this! */
6412 type_t *type = automatic_type_conversion(orig_type);
6414 expression_kind_t kind = EXPR_REFERENCE;
6415 if (entity->kind == ENTITY_ENUM_VALUE)
6416 kind = EXPR_REFERENCE_ENUM_VALUE;
6418 expression_t *expression = allocate_expression_zero(kind);
6419 expression->reference.entity = entity;
6420 expression->base.type = type;
6422 /* this declaration is used */
6423 if (is_declaration(entity)) {
6424 entity->declaration.used = true;
6427 if (entity->base.parent_scope != file_scope
6428 && (current_function != NULL
6429 && entity->base.parent_scope->depth < current_function->parameters.depth)
6430 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6431 if (entity->kind == ENTITY_VARIABLE) {
6432 /* access of a variable from an outer function */
6433 entity->variable.address_taken = true;
6434 } else if (entity->kind == ENTITY_PARAMETER) {
6435 entity->parameter.address_taken = true;
6437 current_function->need_closure = true;
6440 check_deprecated(HERE, entity);
6442 if (warning.init_self && entity == current_init_decl && !in_type_prop
6443 && entity->kind == ENTITY_VARIABLE) {
6444 current_init_decl = NULL;
6445 warningf(HERE, "variable '%#T' is initialized by itself",
6446 entity->declaration.type, entity->base.symbol);
6452 static bool semantic_cast(expression_t *cast)
6454 expression_t *expression = cast->unary.value;
6455 type_t *orig_dest_type = cast->base.type;
6456 type_t *orig_type_right = expression->base.type;
6457 type_t const *dst_type = skip_typeref(orig_dest_type);
6458 type_t const *src_type = skip_typeref(orig_type_right);
6459 source_position_t const *pos = &cast->base.source_position;
6461 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6462 if (dst_type == type_void)
6465 /* only integer and pointer can be casted to pointer */
6466 if (is_type_pointer(dst_type) &&
6467 !is_type_pointer(src_type) &&
6468 !is_type_integer(src_type) &&
6469 is_type_valid(src_type)) {
6470 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6474 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6475 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6479 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6480 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6484 if (warning.cast_qual &&
6485 is_type_pointer(src_type) &&
6486 is_type_pointer(dst_type)) {
6487 type_t *src = skip_typeref(src_type->pointer.points_to);
6488 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6489 unsigned missing_qualifiers =
6490 src->base.qualifiers & ~dst->base.qualifiers;
6491 if (missing_qualifiers != 0) {
6493 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6494 missing_qualifiers, orig_type_right);
6500 static expression_t *parse_compound_literal(type_t *type)
6502 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6504 parse_initializer_env_t env;
6507 env.must_be_constant = false;
6508 initializer_t *initializer = parse_initializer(&env);
6511 expression->compound_literal.initializer = initializer;
6512 expression->compound_literal.type = type;
6513 expression->base.type = automatic_type_conversion(type);
6519 * Parse a cast expression.
6521 static expression_t *parse_cast(void)
6523 add_anchor_token(')');
6525 source_position_t source_position = token.source_position;
6527 type_t *type = parse_typename();
6529 rem_anchor_token(')');
6530 expect(')', end_error);
6532 if (token.type == '{') {
6533 return parse_compound_literal(type);
6536 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6537 cast->base.source_position = source_position;
6539 expression_t *value = parse_sub_expression(PREC_CAST);
6540 cast->base.type = type;
6541 cast->unary.value = value;
6543 if (! semantic_cast(cast)) {
6544 /* TODO: record the error in the AST. else it is impossible to detect it */
6549 return create_invalid_expression();
6553 * Parse a statement expression.
6555 static expression_t *parse_statement_expression(void)
6557 add_anchor_token(')');
6559 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6561 statement_t *statement = parse_compound_statement(true);
6562 statement->compound.stmt_expr = true;
6563 expression->statement.statement = statement;
6565 /* find last statement and use its type */
6566 type_t *type = type_void;
6567 const statement_t *stmt = statement->compound.statements;
6569 while (stmt->base.next != NULL)
6570 stmt = stmt->base.next;
6572 if (stmt->kind == STATEMENT_EXPRESSION) {
6573 type = stmt->expression.expression->base.type;
6575 } else if (warning.other) {
6576 warningf(&expression->base.source_position, "empty statement expression ({})");
6578 expression->base.type = type;
6580 rem_anchor_token(')');
6581 expect(')', end_error);
6588 * Parse a parenthesized expression.
6590 static expression_t *parse_parenthesized_expression(void)
6594 switch (token.type) {
6596 /* gcc extension: a statement expression */
6597 return parse_statement_expression();
6601 return parse_cast();
6603 if (is_typedef_symbol(token.symbol)) {
6604 return parse_cast();
6608 add_anchor_token(')');
6609 expression_t *result = parse_expression();
6610 result->base.parenthesized = true;
6611 rem_anchor_token(')');
6612 expect(')', end_error);
6618 static expression_t *parse_function_keyword(void)
6622 if (current_function == NULL) {
6623 errorf(HERE, "'__func__' used outside of a function");
6626 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6627 expression->base.type = type_char_ptr;
6628 expression->funcname.kind = FUNCNAME_FUNCTION;
6635 static expression_t *parse_pretty_function_keyword(void)
6637 if (current_function == NULL) {
6638 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6641 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6642 expression->base.type = type_char_ptr;
6643 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6645 eat(T___PRETTY_FUNCTION__);
6650 static expression_t *parse_funcsig_keyword(void)
6652 if (current_function == NULL) {
6653 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6656 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6657 expression->base.type = type_char_ptr;
6658 expression->funcname.kind = FUNCNAME_FUNCSIG;
6665 static expression_t *parse_funcdname_keyword(void)
6667 if (current_function == NULL) {
6668 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6671 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6672 expression->base.type = type_char_ptr;
6673 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6675 eat(T___FUNCDNAME__);
6680 static designator_t *parse_designator(void)
6682 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6683 result->source_position = *HERE;
6685 if (token.type != T_IDENTIFIER) {
6686 parse_error_expected("while parsing member designator",
6687 T_IDENTIFIER, NULL);
6690 result->symbol = token.symbol;
6693 designator_t *last_designator = result;
6696 if (token.type != T_IDENTIFIER) {
6697 parse_error_expected("while parsing member designator",
6698 T_IDENTIFIER, NULL);
6701 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6702 designator->source_position = *HERE;
6703 designator->symbol = token.symbol;
6706 last_designator->next = designator;
6707 last_designator = designator;
6711 add_anchor_token(']');
6712 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6713 designator->source_position = *HERE;
6714 designator->array_index = parse_expression();
6715 rem_anchor_token(']');
6716 expect(']', end_error);
6717 if (designator->array_index == NULL) {
6721 last_designator->next = designator;
6722 last_designator = designator;
6734 * Parse the __builtin_offsetof() expression.
6736 static expression_t *parse_offsetof(void)
6738 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6739 expression->base.type = type_size_t;
6741 eat(T___builtin_offsetof);
6743 expect('(', end_error);
6744 add_anchor_token(',');
6745 type_t *type = parse_typename();
6746 rem_anchor_token(',');
6747 expect(',', end_error);
6748 add_anchor_token(')');
6749 designator_t *designator = parse_designator();
6750 rem_anchor_token(')');
6751 expect(')', end_error);
6753 expression->offsetofe.type = type;
6754 expression->offsetofe.designator = designator;
6757 memset(&path, 0, sizeof(path));
6758 path.top_type = type;
6759 path.path = NEW_ARR_F(type_path_entry_t, 0);
6761 descend_into_subtype(&path);
6763 if (!walk_designator(&path, designator, true)) {
6764 return create_invalid_expression();
6767 DEL_ARR_F(path.path);
6771 return create_invalid_expression();
6775 * Parses a _builtin_va_start() expression.
6777 static expression_t *parse_va_start(void)
6779 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6781 eat(T___builtin_va_start);
6783 expect('(', end_error);
6784 add_anchor_token(',');
6785 expression->va_starte.ap = parse_assignment_expression();
6786 rem_anchor_token(',');
6787 expect(',', end_error);
6788 expression_t *const expr = parse_assignment_expression();
6789 if (expr->kind == EXPR_REFERENCE) {
6790 entity_t *const entity = expr->reference.entity;
6791 if (!current_function->base.type->function.variadic) {
6792 errorf(&expr->base.source_position,
6793 "'va_start' used in non-variadic function");
6794 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6795 entity->base.next != NULL ||
6796 entity->kind != ENTITY_PARAMETER) {
6797 errorf(&expr->base.source_position,
6798 "second argument of 'va_start' must be last parameter of the current function");
6800 expression->va_starte.parameter = &entity->variable;
6802 expect(')', end_error);
6805 expect(')', end_error);
6807 return create_invalid_expression();
6811 * Parses a __builtin_va_arg() expression.
6813 static expression_t *parse_va_arg(void)
6815 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6817 eat(T___builtin_va_arg);
6819 expect('(', end_error);
6821 ap.expression = parse_assignment_expression();
6822 expression->va_arge.ap = ap.expression;
6823 check_call_argument(type_valist, &ap, 1);
6825 expect(',', end_error);
6826 expression->base.type = parse_typename();
6827 expect(')', end_error);
6831 return create_invalid_expression();
6835 * Parses a __builtin_va_copy() expression.
6837 static expression_t *parse_va_copy(void)
6839 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6841 eat(T___builtin_va_copy);
6843 expect('(', end_error);
6844 expression_t *dst = parse_assignment_expression();
6845 assign_error_t error = semantic_assign(type_valist, dst);
6846 report_assign_error(error, type_valist, dst, "call argument 1",
6847 &dst->base.source_position);
6848 expression->va_copye.dst = dst;
6850 expect(',', end_error);
6852 call_argument_t src;
6853 src.expression = parse_assignment_expression();
6854 check_call_argument(type_valist, &src, 2);
6855 expression->va_copye.src = src.expression;
6856 expect(')', end_error);
6860 return create_invalid_expression();
6864 * Parses a __builtin_constant_p() expression.
6866 static expression_t *parse_builtin_constant(void)
6868 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6870 eat(T___builtin_constant_p);
6872 expect('(', end_error);
6873 add_anchor_token(')');
6874 expression->builtin_constant.value = parse_assignment_expression();
6875 rem_anchor_token(')');
6876 expect(')', end_error);
6877 expression->base.type = type_int;
6881 return create_invalid_expression();
6885 * Parses a __builtin_types_compatible_p() expression.
6887 static expression_t *parse_builtin_types_compatible(void)
6889 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6891 eat(T___builtin_types_compatible_p);
6893 expect('(', end_error);
6894 add_anchor_token(')');
6895 add_anchor_token(',');
6896 expression->builtin_types_compatible.left = parse_typename();
6897 rem_anchor_token(',');
6898 expect(',', end_error);
6899 expression->builtin_types_compatible.right = parse_typename();
6900 rem_anchor_token(')');
6901 expect(')', end_error);
6902 expression->base.type = type_int;
6906 return create_invalid_expression();
6910 * Parses a __builtin_is_*() compare expression.
6912 static expression_t *parse_compare_builtin(void)
6914 expression_t *expression;
6916 switch (token.type) {
6917 case T___builtin_isgreater:
6918 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6920 case T___builtin_isgreaterequal:
6921 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6923 case T___builtin_isless:
6924 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6926 case T___builtin_islessequal:
6927 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6929 case T___builtin_islessgreater:
6930 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6932 case T___builtin_isunordered:
6933 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6936 internal_errorf(HERE, "invalid compare builtin found");
6938 expression->base.source_position = *HERE;
6941 expect('(', end_error);
6942 expression->binary.left = parse_assignment_expression();
6943 expect(',', end_error);
6944 expression->binary.right = parse_assignment_expression();
6945 expect(')', end_error);
6947 type_t *const orig_type_left = expression->binary.left->base.type;
6948 type_t *const orig_type_right = expression->binary.right->base.type;
6950 type_t *const type_left = skip_typeref(orig_type_left);
6951 type_t *const type_right = skip_typeref(orig_type_right);
6952 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6953 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6954 type_error_incompatible("invalid operands in comparison",
6955 &expression->base.source_position, orig_type_left, orig_type_right);
6958 semantic_comparison(&expression->binary);
6963 return create_invalid_expression();
6967 * Parses a MS assume() expression.
6969 static expression_t *parse_assume(void)
6971 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6975 expect('(', end_error);
6976 add_anchor_token(')');
6977 expression->unary.value = parse_assignment_expression();
6978 rem_anchor_token(')');
6979 expect(')', end_error);
6981 expression->base.type = type_void;
6984 return create_invalid_expression();
6988 * Return the declaration for a given label symbol or create a new one.
6990 * @param symbol the symbol of the label
6992 static label_t *get_label(symbol_t *symbol)
6995 assert(current_function != NULL);
6997 label = get_entity(symbol, NAMESPACE_LABEL);
6998 /* if we found a local label, we already created the declaration */
6999 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7000 if (label->base.parent_scope != current_scope) {
7001 assert(label->base.parent_scope->depth < current_scope->depth);
7002 current_function->goto_to_outer = true;
7004 return &label->label;
7007 label = get_entity(symbol, NAMESPACE_LABEL);
7008 /* if we found a label in the same function, then we already created the
7011 && label->base.parent_scope == ¤t_function->parameters) {
7012 return &label->label;
7015 /* otherwise we need to create a new one */
7016 label = allocate_entity_zero(ENTITY_LABEL);
7017 label->base.namespc = NAMESPACE_LABEL;
7018 label->base.symbol = symbol;
7022 return &label->label;
7026 * Parses a GNU && label address expression.
7028 static expression_t *parse_label_address(void)
7030 source_position_t source_position = token.source_position;
7032 if (token.type != T_IDENTIFIER) {
7033 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7036 symbol_t *symbol = token.symbol;
7039 label_t *label = get_label(symbol);
7041 label->address_taken = true;
7043 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7044 expression->base.source_position = source_position;
7046 /* label address is threaten as a void pointer */
7047 expression->base.type = type_void_ptr;
7048 expression->label_address.label = label;
7051 return create_invalid_expression();
7055 * Parse a microsoft __noop expression.
7057 static expression_t *parse_noop_expression(void)
7059 /* the result is a (int)0 */
7060 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7061 literal->base.type = type_int;
7062 literal->base.source_position = token.source_position;
7063 literal->literal.value.begin = "__noop";
7064 literal->literal.value.size = 6;
7068 if (token.type == '(') {
7069 /* parse arguments */
7071 add_anchor_token(')');
7072 add_anchor_token(',');
7074 if (token.type != ')') do {
7075 (void)parse_assignment_expression();
7076 } while (next_if(','));
7078 rem_anchor_token(',');
7079 rem_anchor_token(')');
7080 expect(')', end_error);
7087 * Parses a primary expression.
7089 static expression_t *parse_primary_expression(void)
7091 switch (token.type) {
7092 case T_false: return parse_boolean_literal(false);
7093 case T_true: return parse_boolean_literal(true);
7095 case T_INTEGER_OCTAL:
7096 case T_INTEGER_HEXADECIMAL:
7097 case T_FLOATINGPOINT:
7098 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7099 case T_CHARACTER_CONSTANT: return parse_character_constant();
7100 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7101 case T_STRING_LITERAL:
7102 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7103 case T___FUNCTION__:
7104 case T___func__: return parse_function_keyword();
7105 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7106 case T___FUNCSIG__: return parse_funcsig_keyword();
7107 case T___FUNCDNAME__: return parse_funcdname_keyword();
7108 case T___builtin_offsetof: return parse_offsetof();
7109 case T___builtin_va_start: return parse_va_start();
7110 case T___builtin_va_arg: return parse_va_arg();
7111 case T___builtin_va_copy: return parse_va_copy();
7112 case T___builtin_isgreater:
7113 case T___builtin_isgreaterequal:
7114 case T___builtin_isless:
7115 case T___builtin_islessequal:
7116 case T___builtin_islessgreater:
7117 case T___builtin_isunordered: return parse_compare_builtin();
7118 case T___builtin_constant_p: return parse_builtin_constant();
7119 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7120 case T__assume: return parse_assume();
7123 return parse_label_address();
7126 case '(': return parse_parenthesized_expression();
7127 case T___noop: return parse_noop_expression();
7129 /* Gracefully handle type names while parsing expressions. */
7131 return parse_reference();
7133 if (!is_typedef_symbol(token.symbol)) {
7134 return parse_reference();
7138 source_position_t const pos = *HERE;
7139 type_t const *const type = parse_typename();
7140 errorf(&pos, "encountered type '%T' while parsing expression", type);
7141 return create_invalid_expression();
7145 errorf(HERE, "unexpected token %K, expected an expression", &token);
7146 return create_invalid_expression();
7150 * Check if the expression has the character type and issue a warning then.
7152 static void check_for_char_index_type(const expression_t *expression)
7154 type_t *const type = expression->base.type;
7155 const type_t *const base_type = skip_typeref(type);
7157 if (is_type_atomic(base_type, ATOMIC_TYPE_CHAR) &&
7158 warning.char_subscripts) {
7159 warningf(&expression->base.source_position,
7160 "array subscript has type '%T'", type);
7164 static expression_t *parse_array_expression(expression_t *left)
7166 expression_t *expression = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7169 add_anchor_token(']');
7171 expression_t *inside = parse_expression();
7173 type_t *const orig_type_left = left->base.type;
7174 type_t *const orig_type_inside = inside->base.type;
7176 type_t *const type_left = skip_typeref(orig_type_left);
7177 type_t *const type_inside = skip_typeref(orig_type_inside);
7179 type_t *return_type;
7180 array_access_expression_t *array_access = &expression->array_access;
7181 if (is_type_pointer(type_left)) {
7182 return_type = type_left->pointer.points_to;
7183 array_access->array_ref = left;
7184 array_access->index = inside;
7185 check_for_char_index_type(inside);
7186 } else if (is_type_pointer(type_inside)) {
7187 return_type = type_inside->pointer.points_to;
7188 array_access->array_ref = inside;
7189 array_access->index = left;
7190 array_access->flipped = true;
7191 check_for_char_index_type(left);
7193 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7195 "array access on object with non-pointer types '%T', '%T'",
7196 orig_type_left, orig_type_inside);
7198 return_type = type_error_type;
7199 array_access->array_ref = left;
7200 array_access->index = inside;
7203 expression->base.type = automatic_type_conversion(return_type);
7205 rem_anchor_token(']');
7206 expect(']', end_error);
7211 static expression_t *parse_typeprop(expression_kind_t const kind)
7213 expression_t *tp_expression = allocate_expression_zero(kind);
7214 tp_expression->base.type = type_size_t;
7216 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7218 /* we only refer to a type property, mark this case */
7219 bool old = in_type_prop;
7220 in_type_prop = true;
7223 expression_t *expression;
7224 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7226 add_anchor_token(')');
7227 orig_type = parse_typename();
7228 rem_anchor_token(')');
7229 expect(')', end_error);
7231 if (token.type == '{') {
7232 /* It was not sizeof(type) after all. It is sizeof of an expression
7233 * starting with a compound literal */
7234 expression = parse_compound_literal(orig_type);
7235 goto typeprop_expression;
7238 expression = parse_sub_expression(PREC_UNARY);
7240 typeprop_expression:
7241 tp_expression->typeprop.tp_expression = expression;
7243 orig_type = revert_automatic_type_conversion(expression);
7244 expression->base.type = orig_type;
7247 tp_expression->typeprop.type = orig_type;
7248 type_t const* const type = skip_typeref(orig_type);
7249 char const* const wrong_type =
7250 GNU_MODE && is_type_atomic(type, ATOMIC_TYPE_VOID) ? NULL :
7251 is_type_incomplete(type) ? "incomplete" :
7252 type->kind == TYPE_FUNCTION ? "function designator" :
7253 type->kind == TYPE_BITFIELD ? "bitfield" :
7255 if (wrong_type != NULL) {
7256 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7257 errorf(&tp_expression->base.source_position,
7258 "operand of %s expression must not be of %s type '%T'",
7259 what, wrong_type, orig_type);
7264 return tp_expression;
7267 static expression_t *parse_sizeof(void)
7269 return parse_typeprop(EXPR_SIZEOF);
7272 static expression_t *parse_alignof(void)
7274 return parse_typeprop(EXPR_ALIGNOF);
7277 static expression_t *parse_select_expression(expression_t *addr)
7279 assert(token.type == '.' || token.type == T_MINUSGREATER);
7280 bool select_left_arrow = (token.type == T_MINUSGREATER);
7283 if (token.type != T_IDENTIFIER) {
7284 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7285 return create_invalid_expression();
7287 symbol_t *symbol = token.symbol;
7290 type_t *const orig_type = addr->base.type;
7291 type_t *const type = skip_typeref(orig_type);
7294 bool saw_error = false;
7295 if (is_type_pointer(type)) {
7296 if (!select_left_arrow) {
7298 "request for member '%Y' in something not a struct or union, but '%T'",
7302 type_left = skip_typeref(type->pointer.points_to);
7304 if (select_left_arrow && is_type_valid(type)) {
7305 errorf(HERE, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7311 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7312 type_left->kind != TYPE_COMPOUND_UNION) {
7314 if (is_type_valid(type_left) && !saw_error) {
7316 "request for member '%Y' in something not a struct or union, but '%T'",
7319 return create_invalid_expression();
7322 compound_t *compound = type_left->compound.compound;
7323 if (!compound->complete) {
7324 errorf(HERE, "request for member '%Y' in incomplete type '%T'",
7326 return create_invalid_expression();
7329 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7330 expression_t *result
7331 = find_create_select(HERE, addr, qualifiers, compound, symbol);
7333 if (result == NULL) {
7334 errorf(HERE, "'%T' has no member named '%Y'", orig_type, symbol);
7335 return create_invalid_expression();
7341 static void check_call_argument(type_t *expected_type,
7342 call_argument_t *argument, unsigned pos)
7344 type_t *expected_type_skip = skip_typeref(expected_type);
7345 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7346 expression_t *arg_expr = argument->expression;
7347 type_t *arg_type = skip_typeref(arg_expr->base.type);
7349 /* handle transparent union gnu extension */
7350 if (is_type_union(expected_type_skip)
7351 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7352 compound_t *union_decl = expected_type_skip->compound.compound;
7353 type_t *best_type = NULL;
7354 entity_t *entry = union_decl->members.entities;
7355 for ( ; entry != NULL; entry = entry->base.next) {
7356 assert(is_declaration(entry));
7357 type_t *decl_type = entry->declaration.type;
7358 error = semantic_assign(decl_type, arg_expr);
7359 if (error == ASSIGN_ERROR_INCOMPATIBLE
7360 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7363 if (error == ASSIGN_SUCCESS) {
7364 best_type = decl_type;
7365 } else if (best_type == NULL) {
7366 best_type = decl_type;
7370 if (best_type != NULL) {
7371 expected_type = best_type;
7375 error = semantic_assign(expected_type, arg_expr);
7376 argument->expression = create_implicit_cast(arg_expr, expected_type);
7378 if (error != ASSIGN_SUCCESS) {
7379 /* report exact scope in error messages (like "in argument 3") */
7381 snprintf(buf, sizeof(buf), "call argument %u", pos);
7382 report_assign_error(error, expected_type, arg_expr, buf,
7383 &arg_expr->base.source_position);
7384 } else if (warning.traditional || warning.conversion) {
7385 type_t *const promoted_type = get_default_promoted_type(arg_type);
7386 if (!types_compatible(expected_type_skip, promoted_type) &&
7387 !types_compatible(expected_type_skip, type_void_ptr) &&
7388 !types_compatible(type_void_ptr, promoted_type)) {
7389 /* Deliberately show the skipped types in this warning */
7390 warningf(&arg_expr->base.source_position,
7391 "passing call argument %u as '%T' rather than '%T' due to prototype",
7392 pos, expected_type_skip, promoted_type);
7398 * Handle the semantic restrictions of builtin calls
7400 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7401 switch (call->function->reference.entity->function.btk) {
7402 case bk_gnu_builtin_return_address:
7403 case bk_gnu_builtin_frame_address: {
7404 /* argument must be constant */
7405 call_argument_t *argument = call->arguments;
7407 if (! is_constant_expression(argument->expression)) {
7408 errorf(&call->base.source_position,
7409 "argument of '%Y' must be a constant expression",
7410 call->function->reference.entity->base.symbol);
7414 case bk_gnu_builtin_prefetch: {
7415 /* second and third argument must be constant if existent */
7416 call_argument_t *rw = call->arguments->next;
7417 call_argument_t *locality = NULL;
7420 if (! is_constant_expression(rw->expression)) {
7421 errorf(&call->base.source_position,
7422 "second argument of '%Y' must be a constant expression",
7423 call->function->reference.entity->base.symbol);
7425 locality = rw->next;
7427 if (locality != NULL) {
7428 if (! is_constant_expression(locality->expression)) {
7429 errorf(&call->base.source_position,
7430 "third argument of '%Y' must be a constant expression",
7431 call->function->reference.entity->base.symbol);
7433 locality = rw->next;
7443 * Parse a call expression, ie. expression '( ... )'.
7445 * @param expression the function address
7447 static expression_t *parse_call_expression(expression_t *expression)
7449 expression_t *result = allocate_expression_zero(EXPR_CALL);
7450 call_expression_t *call = &result->call;
7451 call->function = expression;
7453 type_t *const orig_type = expression->base.type;
7454 type_t *const type = skip_typeref(orig_type);
7456 function_type_t *function_type = NULL;
7457 if (is_type_pointer(type)) {
7458 type_t *const to_type = skip_typeref(type->pointer.points_to);
7460 if (is_type_function(to_type)) {
7461 function_type = &to_type->function;
7462 call->base.type = function_type->return_type;
7466 if (function_type == NULL && is_type_valid(type)) {
7468 "called object '%E' (type '%T') is not a pointer to a function",
7469 expression, orig_type);
7472 /* parse arguments */
7474 add_anchor_token(')');
7475 add_anchor_token(',');
7477 if (token.type != ')') {
7478 call_argument_t **anchor = &call->arguments;
7480 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7481 argument->expression = parse_assignment_expression();
7484 anchor = &argument->next;
7485 } while (next_if(','));
7487 rem_anchor_token(',');
7488 rem_anchor_token(')');
7489 expect(')', end_error);
7491 if (function_type == NULL)
7494 /* check type and count of call arguments */
7495 function_parameter_t *parameter = function_type->parameters;
7496 call_argument_t *argument = call->arguments;
7497 if (!function_type->unspecified_parameters) {
7498 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7499 parameter = parameter->next, argument = argument->next) {
7500 check_call_argument(parameter->type, argument, ++pos);
7503 if (parameter != NULL) {
7504 errorf(HERE, "too few arguments to function '%E'", expression);
7505 } else if (argument != NULL && !function_type->variadic) {
7506 errorf(HERE, "too many arguments to function '%E'", expression);
7510 /* do default promotion for other arguments */
7511 for (; argument != NULL; argument = argument->next) {
7512 type_t *type = argument->expression->base.type;
7514 type = get_default_promoted_type(type);
7516 argument->expression
7517 = create_implicit_cast(argument->expression, type);
7520 check_format(&result->call);
7522 if (warning.aggregate_return &&
7523 is_type_compound(skip_typeref(function_type->return_type))) {
7524 warningf(&result->base.source_position,
7525 "function call has aggregate value");
7528 if (call->function->kind == EXPR_REFERENCE) {
7529 reference_expression_t *reference = &call->function->reference;
7530 if (reference->entity->kind == ENTITY_FUNCTION &&
7531 reference->entity->function.btk != bk_none)
7532 handle_builtin_argument_restrictions(call);
7539 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7541 static bool same_compound_type(const type_t *type1, const type_t *type2)
7544 is_type_compound(type1) &&
7545 type1->kind == type2->kind &&
7546 type1->compound.compound == type2->compound.compound;
7549 static expression_t const *get_reference_address(expression_t const *expr)
7551 bool regular_take_address = true;
7553 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7554 expr = expr->unary.value;
7556 regular_take_address = false;
7559 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7562 expr = expr->unary.value;
7565 if (expr->kind != EXPR_REFERENCE)
7568 /* special case for functions which are automatically converted to a
7569 * pointer to function without an extra TAKE_ADDRESS operation */
7570 if (!regular_take_address &&
7571 expr->reference.entity->kind != ENTITY_FUNCTION) {
7578 static void warn_reference_address_as_bool(expression_t const* expr)
7580 if (!warning.address)
7583 expr = get_reference_address(expr);
7585 warningf(&expr->base.source_position,
7586 "the address of '%Y' will always evaluate as 'true'",
7587 expr->reference.entity->base.symbol);
7591 static void warn_assignment_in_condition(const expression_t *const expr)
7593 if (!warning.parentheses)
7595 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7597 if (expr->base.parenthesized)
7599 warningf(&expr->base.source_position,
7600 "suggest parentheses around assignment used as truth value");
7603 static void semantic_condition(expression_t const *const expr,
7604 char const *const context)
7606 type_t *const type = skip_typeref(expr->base.type);
7607 if (is_type_scalar(type)) {
7608 warn_reference_address_as_bool(expr);
7609 warn_assignment_in_condition(expr);
7610 } else if (is_type_valid(type)) {
7611 errorf(&expr->base.source_position,
7612 "%s must have scalar type", context);
7617 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7619 * @param expression the conditional expression
7621 static expression_t *parse_conditional_expression(expression_t *expression)
7623 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7625 conditional_expression_t *conditional = &result->conditional;
7626 conditional->condition = expression;
7629 add_anchor_token(':');
7631 /* §6.5.15:2 The first operand shall have scalar type. */
7632 semantic_condition(expression, "condition of conditional operator");
7634 expression_t *true_expression = expression;
7635 bool gnu_cond = false;
7636 if (GNU_MODE && token.type == ':') {
7639 true_expression = parse_expression();
7641 rem_anchor_token(':');
7642 expect(':', end_error);
7644 expression_t *false_expression =
7645 parse_sub_expression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7647 type_t *const orig_true_type = true_expression->base.type;
7648 type_t *const orig_false_type = false_expression->base.type;
7649 type_t *const true_type = skip_typeref(orig_true_type);
7650 type_t *const false_type = skip_typeref(orig_false_type);
7653 type_t *result_type;
7654 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7655 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7656 /* ISO/IEC 14882:1998(E) §5.16:2 */
7657 if (true_expression->kind == EXPR_UNARY_THROW) {
7658 result_type = false_type;
7659 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7660 result_type = true_type;
7662 if (warning.other && (
7663 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7664 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7666 warningf(&conditional->base.source_position,
7667 "ISO C forbids conditional expression with only one void side");
7669 result_type = type_void;
7671 } else if (is_type_arithmetic(true_type)
7672 && is_type_arithmetic(false_type)) {
7673 result_type = semantic_arithmetic(true_type, false_type);
7675 true_expression = create_implicit_cast(true_expression, result_type);
7676 false_expression = create_implicit_cast(false_expression, result_type);
7678 conditional->true_expression = true_expression;
7679 conditional->false_expression = false_expression;
7680 conditional->base.type = result_type;
7681 } else if (same_compound_type(true_type, false_type)) {
7682 /* just take 1 of the 2 types */
7683 result_type = true_type;
7684 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7685 type_t *pointer_type;
7687 expression_t *other_expression;
7688 if (is_type_pointer(true_type) &&
7689 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7690 pointer_type = true_type;
7691 other_type = false_type;
7692 other_expression = false_expression;
7694 pointer_type = false_type;
7695 other_type = true_type;
7696 other_expression = true_expression;
7699 if (is_null_pointer_constant(other_expression)) {
7700 result_type = pointer_type;
7701 } else if (is_type_pointer(other_type)) {
7702 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7703 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7706 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7707 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7709 } else if (types_compatible(get_unqualified_type(to1),
7710 get_unqualified_type(to2))) {
7713 if (warning.other) {
7714 warningf(&conditional->base.source_position,
7715 "pointer types '%T' and '%T' in conditional expression are incompatible",
7716 true_type, false_type);
7721 type_t *const type =
7722 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7723 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7724 } else if (is_type_integer(other_type)) {
7725 if (warning.other) {
7726 warningf(&conditional->base.source_position,
7727 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7729 result_type = pointer_type;
7731 if (is_type_valid(other_type)) {
7732 type_error_incompatible("while parsing conditional",
7733 &expression->base.source_position, true_type, false_type);
7735 result_type = type_error_type;
7738 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7739 type_error_incompatible("while parsing conditional",
7740 &conditional->base.source_position, true_type,
7743 result_type = type_error_type;
7746 conditional->true_expression
7747 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7748 conditional->false_expression
7749 = create_implicit_cast(false_expression, result_type);
7750 conditional->base.type = result_type;
7755 * Parse an extension expression.
7757 static expression_t *parse_extension(void)
7759 eat(T___extension__);
7761 bool old_gcc_extension = in_gcc_extension;
7762 in_gcc_extension = true;
7763 expression_t *expression = parse_sub_expression(PREC_UNARY);
7764 in_gcc_extension = old_gcc_extension;
7769 * Parse a __builtin_classify_type() expression.
7771 static expression_t *parse_builtin_classify_type(void)
7773 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7774 result->base.type = type_int;
7776 eat(T___builtin_classify_type);
7778 expect('(', end_error);
7779 add_anchor_token(')');
7780 expression_t *expression = parse_expression();
7781 rem_anchor_token(')');
7782 expect(')', end_error);
7783 result->classify_type.type_expression = expression;
7787 return create_invalid_expression();
7791 * Parse a delete expression
7792 * ISO/IEC 14882:1998(E) §5.3.5
7794 static expression_t *parse_delete(void)
7796 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7797 result->base.type = type_void;
7802 result->kind = EXPR_UNARY_DELETE_ARRAY;
7803 expect(']', end_error);
7807 expression_t *const value = parse_sub_expression(PREC_CAST);
7808 result->unary.value = value;
7810 type_t *const type = skip_typeref(value->base.type);
7811 if (!is_type_pointer(type)) {
7812 if (is_type_valid(type)) {
7813 errorf(&value->base.source_position,
7814 "operand of delete must have pointer type");
7816 } else if (warning.other &&
7817 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7818 warningf(&value->base.source_position,
7819 "deleting 'void*' is undefined");
7826 * Parse a throw expression
7827 * ISO/IEC 14882:1998(E) §15:1
7829 static expression_t *parse_throw(void)
7831 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7832 result->base.type = type_void;
7836 expression_t *value = NULL;
7837 switch (token.type) {
7839 value = parse_assignment_expression();
7840 /* ISO/IEC 14882:1998(E) §15.1:3 */
7841 type_t *const orig_type = value->base.type;
7842 type_t *const type = skip_typeref(orig_type);
7843 if (is_type_incomplete(type)) {
7844 errorf(&value->base.source_position,
7845 "cannot throw object of incomplete type '%T'", orig_type);
7846 } else if (is_type_pointer(type)) {
7847 type_t *const points_to = skip_typeref(type->pointer.points_to);
7848 if (is_type_incomplete(points_to) &&
7849 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7850 errorf(&value->base.source_position,
7851 "cannot throw pointer to incomplete type '%T'", orig_type);
7859 result->unary.value = value;
7864 static bool check_pointer_arithmetic(const source_position_t *source_position,
7865 type_t *pointer_type,
7866 type_t *orig_pointer_type)
7868 type_t *points_to = pointer_type->pointer.points_to;
7869 points_to = skip_typeref(points_to);
7871 if (is_type_incomplete(points_to)) {
7872 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7873 errorf(source_position,
7874 "arithmetic with pointer to incomplete type '%T' not allowed",
7877 } else if (warning.pointer_arith) {
7878 warningf(source_position,
7879 "pointer of type '%T' used in arithmetic",
7882 } else if (is_type_function(points_to)) {
7884 errorf(source_position,
7885 "arithmetic with pointer to function type '%T' not allowed",
7888 } else if (warning.pointer_arith) {
7889 warningf(source_position,
7890 "pointer to a function '%T' used in arithmetic",
7897 static bool is_lvalue(const expression_t *expression)
7899 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7900 switch (expression->kind) {
7901 case EXPR_ARRAY_ACCESS:
7902 case EXPR_COMPOUND_LITERAL:
7903 case EXPR_REFERENCE:
7905 case EXPR_UNARY_DEREFERENCE:
7909 type_t *type = skip_typeref(expression->base.type);
7911 /* ISO/IEC 14882:1998(E) §3.10:3 */
7912 is_type_reference(type) ||
7913 /* Claim it is an lvalue, if the type is invalid. There was a parse
7914 * error before, which maybe prevented properly recognizing it as
7916 !is_type_valid(type);
7921 static void semantic_incdec(unary_expression_t *expression)
7923 type_t *const orig_type = expression->value->base.type;
7924 type_t *const type = skip_typeref(orig_type);
7925 if (is_type_pointer(type)) {
7926 if (!check_pointer_arithmetic(&expression->base.source_position,
7930 } else if (!is_type_real(type) && is_type_valid(type)) {
7931 /* TODO: improve error message */
7932 errorf(&expression->base.source_position,
7933 "operation needs an arithmetic or pointer type");
7936 if (!is_lvalue(expression->value)) {
7937 /* TODO: improve error message */
7938 errorf(&expression->base.source_position, "lvalue required as operand");
7940 expression->base.type = orig_type;
7943 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7945 type_t *const orig_type = expression->value->base.type;
7946 type_t *const type = skip_typeref(orig_type);
7947 if (!is_type_arithmetic(type)) {
7948 if (is_type_valid(type)) {
7949 /* TODO: improve error message */
7950 errorf(&expression->base.source_position,
7951 "operation needs an arithmetic type");
7956 expression->base.type = orig_type;
7959 static void semantic_unexpr_plus(unary_expression_t *expression)
7961 semantic_unexpr_arithmetic(expression);
7962 if (warning.traditional)
7963 warningf(&expression->base.source_position,
7964 "traditional C rejects the unary plus operator");
7967 static void semantic_not(unary_expression_t *expression)
7969 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7970 semantic_condition(expression->value, "operand of !");
7971 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7974 static void semantic_unexpr_integer(unary_expression_t *expression)
7976 type_t *const orig_type = expression->value->base.type;
7977 type_t *const type = skip_typeref(orig_type);
7978 if (!is_type_integer(type)) {
7979 if (is_type_valid(type)) {
7980 errorf(&expression->base.source_position,
7981 "operand of ~ must be of integer type");
7986 expression->base.type = orig_type;
7989 static void semantic_dereference(unary_expression_t *expression)
7991 type_t *const orig_type = expression->value->base.type;
7992 type_t *const type = skip_typeref(orig_type);
7993 if (!is_type_pointer(type)) {
7994 if (is_type_valid(type)) {
7995 errorf(&expression->base.source_position,
7996 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8001 type_t *result_type = type->pointer.points_to;
8002 result_type = automatic_type_conversion(result_type);
8003 expression->base.type = result_type;
8007 * Record that an address is taken (expression represents an lvalue).
8009 * @param expression the expression
8010 * @param may_be_register if true, the expression might be an register
8012 static void set_address_taken(expression_t *expression, bool may_be_register)
8014 if (expression->kind != EXPR_REFERENCE)
8017 entity_t *const entity = expression->reference.entity;
8019 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8022 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8023 && !may_be_register) {
8024 errorf(&expression->base.source_position,
8025 "address of register %s '%Y' requested",
8026 get_entity_kind_name(entity->kind), entity->base.symbol);
8029 if (entity->kind == ENTITY_VARIABLE) {
8030 entity->variable.address_taken = true;
8032 assert(entity->kind == ENTITY_PARAMETER);
8033 entity->parameter.address_taken = true;
8038 * Check the semantic of the address taken expression.
8040 static void semantic_take_addr(unary_expression_t *expression)
8042 expression_t *value = expression->value;
8043 value->base.type = revert_automatic_type_conversion(value);
8045 type_t *orig_type = value->base.type;
8046 type_t *type = skip_typeref(orig_type);
8047 if (!is_type_valid(type))
8051 if (!is_lvalue(value)) {
8052 errorf(&expression->base.source_position, "'&' requires an lvalue");
8054 if (type->kind == TYPE_BITFIELD) {
8055 errorf(&expression->base.source_position,
8056 "'&' not allowed on object with bitfield type '%T'",
8060 set_address_taken(value, false);
8062 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8065 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8066 static expression_t *parse_##unexpression_type(void) \
8068 expression_t *unary_expression \
8069 = allocate_expression_zero(unexpression_type); \
8071 unary_expression->unary.value = parse_sub_expression(PREC_UNARY); \
8073 sfunc(&unary_expression->unary); \
8075 return unary_expression; \
8078 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8079 semantic_unexpr_arithmetic)
8080 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8081 semantic_unexpr_plus)
8082 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8084 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8085 semantic_dereference)
8086 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8088 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8089 semantic_unexpr_integer)
8090 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8092 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8095 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8097 static expression_t *parse_##unexpression_type(expression_t *left) \
8099 expression_t *unary_expression \
8100 = allocate_expression_zero(unexpression_type); \
8102 unary_expression->unary.value = left; \
8104 sfunc(&unary_expression->unary); \
8106 return unary_expression; \
8109 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8110 EXPR_UNARY_POSTFIX_INCREMENT,
8112 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8113 EXPR_UNARY_POSTFIX_DECREMENT,
8116 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8118 /* TODO: handle complex + imaginary types */
8120 type_left = get_unqualified_type(type_left);
8121 type_right = get_unqualified_type(type_right);
8123 /* §6.3.1.8 Usual arithmetic conversions */
8124 if (type_left == type_long_double || type_right == type_long_double) {
8125 return type_long_double;
8126 } else if (type_left == type_double || type_right == type_double) {
8128 } else if (type_left == type_float || type_right == type_float) {
8132 type_left = promote_integer(type_left);
8133 type_right = promote_integer(type_right);
8135 if (type_left == type_right)
8138 bool const signed_left = is_type_signed(type_left);
8139 bool const signed_right = is_type_signed(type_right);
8140 int const rank_left = get_rank(type_left);
8141 int const rank_right = get_rank(type_right);
8143 if (signed_left == signed_right)
8144 return rank_left >= rank_right ? type_left : type_right;
8153 u_rank = rank_right;
8154 u_type = type_right;
8156 s_rank = rank_right;
8157 s_type = type_right;
8162 if (u_rank >= s_rank)
8165 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8167 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8168 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8172 case ATOMIC_TYPE_INT: return type_unsigned_int;
8173 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8174 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8176 default: panic("invalid atomic type");
8181 * Check the semantic restrictions for a binary expression.
8183 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8185 expression_t *const left = expression->left;
8186 expression_t *const right = expression->right;
8187 type_t *const orig_type_left = left->base.type;
8188 type_t *const orig_type_right = right->base.type;
8189 type_t *const type_left = skip_typeref(orig_type_left);
8190 type_t *const type_right = skip_typeref(orig_type_right);
8192 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8193 /* TODO: improve error message */
8194 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8195 errorf(&expression->base.source_position,
8196 "operation needs arithmetic types");
8201 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8202 expression->left = create_implicit_cast(left, arithmetic_type);
8203 expression->right = create_implicit_cast(right, arithmetic_type);
8204 expression->base.type = arithmetic_type;
8207 static void warn_div_by_zero(binary_expression_t const *const expression)
8209 if (!warning.div_by_zero ||
8210 !is_type_integer(expression->base.type))
8213 expression_t const *const right = expression->right;
8214 /* The type of the right operand can be different for /= */
8215 if (is_type_integer(right->base.type) &&
8216 is_constant_expression(right) &&
8217 !fold_constant_to_bool(right)) {
8218 warningf(&expression->base.source_position, "division by zero");
8223 * Check the semantic restrictions for a div/mod expression.
8225 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8227 semantic_binexpr_arithmetic(expression);
8228 warn_div_by_zero(expression);
8231 static void warn_addsub_in_shift(const expression_t *const expr)
8233 if (expr->base.parenthesized)
8237 switch (expr->kind) {
8238 case EXPR_BINARY_ADD: op = '+'; break;
8239 case EXPR_BINARY_SUB: op = '-'; break;
8243 warningf(&expr->base.source_position,
8244 "suggest parentheses around '%c' inside shift", op);
8247 static bool semantic_shift(binary_expression_t *expression)
8249 expression_t *const left = expression->left;
8250 expression_t *const right = expression->right;
8251 type_t *const orig_type_left = left->base.type;
8252 type_t *const orig_type_right = right->base.type;
8253 type_t * type_left = skip_typeref(orig_type_left);
8254 type_t * type_right = skip_typeref(orig_type_right);
8256 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8257 /* TODO: improve error message */
8258 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8259 errorf(&expression->base.source_position,
8260 "operands of shift operation must have integer types");
8265 type_left = promote_integer(type_left);
8267 if (is_constant_expression(right)) {
8268 long count = fold_constant_to_int(right);
8270 warningf(&right->base.source_position,
8271 "shift count must be non-negative");
8272 } else if ((unsigned long)count >=
8273 get_atomic_type_size(type_left->atomic.akind) * 8) {
8274 warningf(&right->base.source_position,
8275 "shift count must be less than type width");
8279 type_right = promote_integer(type_right);
8280 expression->right = create_implicit_cast(right, type_right);
8285 static void semantic_shift_op(binary_expression_t *expression)
8287 expression_t *const left = expression->left;
8288 expression_t *const right = expression->right;
8290 if (!semantic_shift(expression))
8293 if (warning.parentheses) {
8294 warn_addsub_in_shift(left);
8295 warn_addsub_in_shift(right);
8298 type_t *const orig_type_left = left->base.type;
8299 type_t * type_left = skip_typeref(orig_type_left);
8301 type_left = promote_integer(type_left);
8302 expression->left = create_implicit_cast(left, type_left);
8303 expression->base.type = type_left;
8306 static void semantic_add(binary_expression_t *expression)
8308 expression_t *const left = expression->left;
8309 expression_t *const right = expression->right;
8310 type_t *const orig_type_left = left->base.type;
8311 type_t *const orig_type_right = right->base.type;
8312 type_t *const type_left = skip_typeref(orig_type_left);
8313 type_t *const type_right = skip_typeref(orig_type_right);
8316 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8317 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8318 expression->left = create_implicit_cast(left, arithmetic_type);
8319 expression->right = create_implicit_cast(right, arithmetic_type);
8320 expression->base.type = arithmetic_type;
8321 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8322 check_pointer_arithmetic(&expression->base.source_position,
8323 type_left, orig_type_left);
8324 expression->base.type = type_left;
8325 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8326 check_pointer_arithmetic(&expression->base.source_position,
8327 type_right, orig_type_right);
8328 expression->base.type = type_right;
8329 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8330 errorf(&expression->base.source_position,
8331 "invalid operands to binary + ('%T', '%T')",
8332 orig_type_left, orig_type_right);
8336 static void semantic_sub(binary_expression_t *expression)
8338 expression_t *const left = expression->left;
8339 expression_t *const right = expression->right;
8340 type_t *const orig_type_left = left->base.type;
8341 type_t *const orig_type_right = right->base.type;
8342 type_t *const type_left = skip_typeref(orig_type_left);
8343 type_t *const type_right = skip_typeref(orig_type_right);
8344 source_position_t const *const pos = &expression->base.source_position;
8347 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8348 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8349 expression->left = create_implicit_cast(left, arithmetic_type);
8350 expression->right = create_implicit_cast(right, arithmetic_type);
8351 expression->base.type = arithmetic_type;
8352 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8353 check_pointer_arithmetic(&expression->base.source_position,
8354 type_left, orig_type_left);
8355 expression->base.type = type_left;
8356 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8357 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8358 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8359 if (!types_compatible(unqual_left, unqual_right)) {
8361 "subtracting pointers to incompatible types '%T' and '%T'",
8362 orig_type_left, orig_type_right);
8363 } else if (!is_type_object(unqual_left)) {
8364 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8365 errorf(pos, "subtracting pointers to non-object types '%T'",
8367 } else if (warning.other) {
8368 warningf(pos, "subtracting pointers to void");
8371 expression->base.type = type_ptrdiff_t;
8372 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8373 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8374 orig_type_left, orig_type_right);
8378 static void warn_string_literal_address(expression_t const* expr)
8380 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8381 expr = expr->unary.value;
8382 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8384 expr = expr->unary.value;
8387 if (expr->kind == EXPR_STRING_LITERAL
8388 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8389 warningf(&expr->base.source_position,
8390 "comparison with string literal results in unspecified behaviour");
8394 static void warn_comparison_in_comparison(const expression_t *const expr)
8396 if (expr->base.parenthesized)
8398 switch (expr->base.kind) {
8399 case EXPR_BINARY_LESS:
8400 case EXPR_BINARY_GREATER:
8401 case EXPR_BINARY_LESSEQUAL:
8402 case EXPR_BINARY_GREATEREQUAL:
8403 case EXPR_BINARY_NOTEQUAL:
8404 case EXPR_BINARY_EQUAL:
8405 warningf(&expr->base.source_position,
8406 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8413 static bool maybe_negative(expression_t const *const expr)
8416 !is_constant_expression(expr) ||
8417 fold_constant_to_int(expr) < 0;
8421 * Check the semantics of comparison expressions.
8423 * @param expression The expression to check.
8425 static void semantic_comparison(binary_expression_t *expression)
8427 expression_t *left = expression->left;
8428 expression_t *right = expression->right;
8430 if (warning.address) {
8431 warn_string_literal_address(left);
8432 warn_string_literal_address(right);
8434 expression_t const* const func_left = get_reference_address(left);
8435 if (func_left != NULL && is_null_pointer_constant(right)) {
8436 warningf(&expression->base.source_position,
8437 "the address of '%Y' will never be NULL",
8438 func_left->reference.entity->base.symbol);
8441 expression_t const* const func_right = get_reference_address(right);
8442 if (func_right != NULL && is_null_pointer_constant(right)) {
8443 warningf(&expression->base.source_position,
8444 "the address of '%Y' will never be NULL",
8445 func_right->reference.entity->base.symbol);
8449 if (warning.parentheses) {
8450 warn_comparison_in_comparison(left);
8451 warn_comparison_in_comparison(right);
8454 type_t *orig_type_left = left->base.type;
8455 type_t *orig_type_right = right->base.type;
8456 type_t *type_left = skip_typeref(orig_type_left);
8457 type_t *type_right = skip_typeref(orig_type_right);
8459 /* TODO non-arithmetic types */
8460 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8461 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8463 /* test for signed vs unsigned compares */
8464 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8465 bool const signed_left = is_type_signed(type_left);
8466 bool const signed_right = is_type_signed(type_right);
8467 if (signed_left != signed_right) {
8468 /* FIXME long long needs better const folding magic */
8469 /* TODO check whether constant value can be represented by other type */
8470 if ((signed_left && maybe_negative(left)) ||
8471 (signed_right && maybe_negative(right))) {
8472 warningf(&expression->base.source_position,
8473 "comparison between signed and unsigned");
8478 expression->left = create_implicit_cast(left, arithmetic_type);
8479 expression->right = create_implicit_cast(right, arithmetic_type);
8480 expression->base.type = arithmetic_type;
8481 if (warning.float_equal &&
8482 (expression->base.kind == EXPR_BINARY_EQUAL ||
8483 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8484 is_type_float(arithmetic_type)) {
8485 warningf(&expression->base.source_position,
8486 "comparing floating point with == or != is unsafe");
8488 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8489 /* TODO check compatibility */
8490 } else if (is_type_pointer(type_left)) {
8491 expression->right = create_implicit_cast(right, type_left);
8492 } else if (is_type_pointer(type_right)) {
8493 expression->left = create_implicit_cast(left, type_right);
8494 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8495 type_error_incompatible("invalid operands in comparison",
8496 &expression->base.source_position,
8497 type_left, type_right);
8499 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8503 * Checks if a compound type has constant fields.
8505 static bool has_const_fields(const compound_type_t *type)
8507 compound_t *compound = type->compound;
8508 entity_t *entry = compound->members.entities;
8510 for (; entry != NULL; entry = entry->base.next) {
8511 if (!is_declaration(entry))
8514 const type_t *decl_type = skip_typeref(entry->declaration.type);
8515 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8522 static bool is_valid_assignment_lhs(expression_t const* const left)
8524 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8525 type_t *const type_left = skip_typeref(orig_type_left);
8527 if (!is_lvalue(left)) {
8528 errorf(HERE, "left hand side '%E' of assignment is not an lvalue",
8533 if (left->kind == EXPR_REFERENCE
8534 && left->reference.entity->kind == ENTITY_FUNCTION) {
8535 errorf(HERE, "cannot assign to function '%E'", left);
8539 if (is_type_array(type_left)) {
8540 errorf(HERE, "cannot assign to array '%E'", left);
8543 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8544 errorf(HERE, "assignment to readonly location '%E' (type '%T')", left,
8548 if (is_type_incomplete(type_left)) {
8549 errorf(HERE, "left-hand side '%E' of assignment has incomplete type '%T'",
8550 left, orig_type_left);
8553 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8554 errorf(HERE, "cannot assign to '%E' because compound type '%T' has readonly fields",
8555 left, orig_type_left);
8562 static void semantic_arithmetic_assign(binary_expression_t *expression)
8564 expression_t *left = expression->left;
8565 expression_t *right = expression->right;
8566 type_t *orig_type_left = left->base.type;
8567 type_t *orig_type_right = right->base.type;
8569 if (!is_valid_assignment_lhs(left))
8572 type_t *type_left = skip_typeref(orig_type_left);
8573 type_t *type_right = skip_typeref(orig_type_right);
8575 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8576 /* TODO: improve error message */
8577 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8578 errorf(&expression->base.source_position,
8579 "operation needs arithmetic types");
8584 /* combined instructions are tricky. We can't create an implicit cast on
8585 * the left side, because we need the uncasted form for the store.
8586 * The ast2firm pass has to know that left_type must be right_type
8587 * for the arithmetic operation and create a cast by itself */
8588 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8589 expression->right = create_implicit_cast(right, arithmetic_type);
8590 expression->base.type = type_left;
8593 static void semantic_divmod_assign(binary_expression_t *expression)
8595 semantic_arithmetic_assign(expression);
8596 warn_div_by_zero(expression);
8599 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8601 expression_t *const left = expression->left;
8602 expression_t *const right = expression->right;
8603 type_t *const orig_type_left = left->base.type;
8604 type_t *const orig_type_right = right->base.type;
8605 type_t *const type_left = skip_typeref(orig_type_left);
8606 type_t *const type_right = skip_typeref(orig_type_right);
8608 if (!is_valid_assignment_lhs(left))
8611 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8612 /* combined instructions are tricky. We can't create an implicit cast on
8613 * the left side, because we need the uncasted form for the store.
8614 * The ast2firm pass has to know that left_type must be right_type
8615 * for the arithmetic operation and create a cast by itself */
8616 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8617 expression->right = create_implicit_cast(right, arithmetic_type);
8618 expression->base.type = type_left;
8619 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8620 check_pointer_arithmetic(&expression->base.source_position,
8621 type_left, orig_type_left);
8622 expression->base.type = type_left;
8623 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8624 errorf(&expression->base.source_position,
8625 "incompatible types '%T' and '%T' in assignment",
8626 orig_type_left, orig_type_right);
8630 static void semantic_integer_assign(binary_expression_t *expression)
8632 expression_t *left = expression->left;
8633 expression_t *right = expression->right;
8634 type_t *orig_type_left = left->base.type;
8635 type_t *orig_type_right = right->base.type;
8637 if (!is_valid_assignment_lhs(left))
8640 type_t *type_left = skip_typeref(orig_type_left);
8641 type_t *type_right = skip_typeref(orig_type_right);
8643 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8644 /* TODO: improve error message */
8645 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8646 errorf(&expression->base.source_position,
8647 "operation needs integer types");
8652 /* combined instructions are tricky. We can't create an implicit cast on
8653 * the left side, because we need the uncasted form for the store.
8654 * The ast2firm pass has to know that left_type must be right_type
8655 * for the arithmetic operation and create a cast by itself */
8656 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8657 expression->right = create_implicit_cast(right, arithmetic_type);
8658 expression->base.type = type_left;
8661 static void semantic_shift_assign(binary_expression_t *expression)
8663 expression_t *left = expression->left;
8665 if (!is_valid_assignment_lhs(left))
8668 if (!semantic_shift(expression))
8671 expression->base.type = skip_typeref(left->base.type);
8674 static void warn_logical_and_within_or(const expression_t *const expr)
8676 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8678 if (expr->base.parenthesized)
8680 warningf(&expr->base.source_position,
8681 "suggest parentheses around && within ||");
8685 * Check the semantic restrictions of a logical expression.
8687 static void semantic_logical_op(binary_expression_t *expression)
8689 /* §6.5.13:2 Each of the operands shall have scalar type.
8690 * §6.5.14:2 Each of the operands shall have scalar type. */
8691 semantic_condition(expression->left, "left operand of logical operator");
8692 semantic_condition(expression->right, "right operand of logical operator");
8693 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8694 warning.parentheses) {
8695 warn_logical_and_within_or(expression->left);
8696 warn_logical_and_within_or(expression->right);
8698 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8702 * Check the semantic restrictions of a binary assign expression.
8704 static void semantic_binexpr_assign(binary_expression_t *expression)
8706 expression_t *left = expression->left;
8707 type_t *orig_type_left = left->base.type;
8709 if (!is_valid_assignment_lhs(left))
8712 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8713 report_assign_error(error, orig_type_left, expression->right,
8714 "assignment", &left->base.source_position);
8715 expression->right = create_implicit_cast(expression->right, orig_type_left);
8716 expression->base.type = orig_type_left;
8720 * Determine if the outermost operation (or parts thereof) of the given
8721 * expression has no effect in order to generate a warning about this fact.
8722 * Therefore in some cases this only examines some of the operands of the
8723 * expression (see comments in the function and examples below).
8725 * f() + 23; // warning, because + has no effect
8726 * x || f(); // no warning, because x controls execution of f()
8727 * x ? y : f(); // warning, because y has no effect
8728 * (void)x; // no warning to be able to suppress the warning
8729 * This function can NOT be used for an "expression has definitely no effect"-
8731 static bool expression_has_effect(const expression_t *const expr)
8733 switch (expr->kind) {
8734 case EXPR_UNKNOWN: break;
8735 case EXPR_INVALID: return true; /* do NOT warn */
8736 case EXPR_REFERENCE: return false;
8737 case EXPR_REFERENCE_ENUM_VALUE: return false;
8738 case EXPR_LABEL_ADDRESS: return false;
8740 /* suppress the warning for microsoft __noop operations */
8741 case EXPR_LITERAL_MS_NOOP: return true;
8742 case EXPR_LITERAL_BOOLEAN:
8743 case EXPR_LITERAL_CHARACTER:
8744 case EXPR_LITERAL_WIDE_CHARACTER:
8745 case EXPR_LITERAL_INTEGER:
8746 case EXPR_LITERAL_INTEGER_OCTAL:
8747 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8748 case EXPR_LITERAL_FLOATINGPOINT:
8749 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8750 case EXPR_STRING_LITERAL: return false;
8751 case EXPR_WIDE_STRING_LITERAL: return false;
8754 const call_expression_t *const call = &expr->call;
8755 if (call->function->kind != EXPR_REFERENCE)
8758 switch (call->function->reference.entity->function.btk) {
8759 /* FIXME: which builtins have no effect? */
8760 default: return true;
8764 /* Generate the warning if either the left or right hand side of a
8765 * conditional expression has no effect */
8766 case EXPR_CONDITIONAL: {
8767 conditional_expression_t const *const cond = &expr->conditional;
8768 expression_t const *const t = cond->true_expression;
8770 (t == NULL || expression_has_effect(t)) &&
8771 expression_has_effect(cond->false_expression);
8774 case EXPR_SELECT: return false;
8775 case EXPR_ARRAY_ACCESS: return false;
8776 case EXPR_SIZEOF: return false;
8777 case EXPR_CLASSIFY_TYPE: return false;
8778 case EXPR_ALIGNOF: return false;
8780 case EXPR_FUNCNAME: return false;
8781 case EXPR_BUILTIN_CONSTANT_P: return false;
8782 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8783 case EXPR_OFFSETOF: return false;
8784 case EXPR_VA_START: return true;
8785 case EXPR_VA_ARG: return true;
8786 case EXPR_VA_COPY: return true;
8787 case EXPR_STATEMENT: return true; // TODO
8788 case EXPR_COMPOUND_LITERAL: return false;
8790 case EXPR_UNARY_NEGATE: return false;
8791 case EXPR_UNARY_PLUS: return false;
8792 case EXPR_UNARY_BITWISE_NEGATE: return false;
8793 case EXPR_UNARY_NOT: return false;
8794 case EXPR_UNARY_DEREFERENCE: return false;
8795 case EXPR_UNARY_TAKE_ADDRESS: return false;
8796 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8797 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8798 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8799 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8801 /* Treat void casts as if they have an effect in order to being able to
8802 * suppress the warning */
8803 case EXPR_UNARY_CAST: {
8804 type_t *const type = skip_typeref(expr->base.type);
8805 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8808 case EXPR_UNARY_CAST_IMPLICIT: return true;
8809 case EXPR_UNARY_ASSUME: return true;
8810 case EXPR_UNARY_DELETE: return true;
8811 case EXPR_UNARY_DELETE_ARRAY: return true;
8812 case EXPR_UNARY_THROW: return true;
8814 case EXPR_BINARY_ADD: return false;
8815 case EXPR_BINARY_SUB: return false;
8816 case EXPR_BINARY_MUL: return false;
8817 case EXPR_BINARY_DIV: return false;
8818 case EXPR_BINARY_MOD: return false;
8819 case EXPR_BINARY_EQUAL: return false;
8820 case EXPR_BINARY_NOTEQUAL: return false;
8821 case EXPR_BINARY_LESS: return false;
8822 case EXPR_BINARY_LESSEQUAL: return false;
8823 case EXPR_BINARY_GREATER: return false;
8824 case EXPR_BINARY_GREATEREQUAL: return false;
8825 case EXPR_BINARY_BITWISE_AND: return false;
8826 case EXPR_BINARY_BITWISE_OR: return false;
8827 case EXPR_BINARY_BITWISE_XOR: return false;
8828 case EXPR_BINARY_SHIFTLEFT: return false;
8829 case EXPR_BINARY_SHIFTRIGHT: return false;
8830 case EXPR_BINARY_ASSIGN: return true;
8831 case EXPR_BINARY_MUL_ASSIGN: return true;
8832 case EXPR_BINARY_DIV_ASSIGN: return true;
8833 case EXPR_BINARY_MOD_ASSIGN: return true;
8834 case EXPR_BINARY_ADD_ASSIGN: return true;
8835 case EXPR_BINARY_SUB_ASSIGN: return true;
8836 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8837 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8838 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8839 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8840 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8842 /* Only examine the right hand side of && and ||, because the left hand
8843 * side already has the effect of controlling the execution of the right
8845 case EXPR_BINARY_LOGICAL_AND:
8846 case EXPR_BINARY_LOGICAL_OR:
8847 /* Only examine the right hand side of a comma expression, because the left
8848 * hand side has a separate warning */
8849 case EXPR_BINARY_COMMA:
8850 return expression_has_effect(expr->binary.right);
8852 case EXPR_BINARY_ISGREATER: return false;
8853 case EXPR_BINARY_ISGREATEREQUAL: return false;
8854 case EXPR_BINARY_ISLESS: return false;
8855 case EXPR_BINARY_ISLESSEQUAL: return false;
8856 case EXPR_BINARY_ISLESSGREATER: return false;
8857 case EXPR_BINARY_ISUNORDERED: return false;
8860 internal_errorf(HERE, "unexpected expression");
8863 static void semantic_comma(binary_expression_t *expression)
8865 if (warning.unused_value) {
8866 const expression_t *const left = expression->left;
8867 if (!expression_has_effect(left)) {
8868 warningf(&left->base.source_position,
8869 "left-hand operand of comma expression has no effect");
8872 expression->base.type = expression->right->base.type;
8876 * @param prec_r precedence of the right operand
8878 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8879 static expression_t *parse_##binexpression_type(expression_t *left) \
8881 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8882 binexpr->binary.left = left; \
8885 expression_t *right = parse_sub_expression(prec_r); \
8887 binexpr->binary.right = right; \
8888 sfunc(&binexpr->binary); \
8893 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8894 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8895 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8896 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8897 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8898 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8899 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8900 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8901 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8902 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8903 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8904 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8905 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8906 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_arithmetic)
8907 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_arithmetic)
8908 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_arithmetic)
8909 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8910 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8911 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8912 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8913 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8914 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8915 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8916 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8917 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8918 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8919 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8920 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8921 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8922 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8925 static expression_t *parse_sub_expression(precedence_t precedence)
8927 if (token.type < 0) {
8928 return expected_expression_error();
8931 expression_parser_function_t *parser
8932 = &expression_parsers[token.type];
8933 source_position_t source_position = token.source_position;
8936 if (parser->parser != NULL) {
8937 left = parser->parser();
8939 left = parse_primary_expression();
8941 assert(left != NULL);
8942 left->base.source_position = source_position;
8945 if (token.type < 0) {
8946 return expected_expression_error();
8949 parser = &expression_parsers[token.type];
8950 if (parser->infix_parser == NULL)
8952 if (parser->infix_precedence < precedence)
8955 left = parser->infix_parser(left);
8957 assert(left != NULL);
8958 assert(left->kind != EXPR_UNKNOWN);
8959 left->base.source_position = source_position;
8966 * Parse an expression.
8968 static expression_t *parse_expression(void)
8970 return parse_sub_expression(PREC_EXPRESSION);
8974 * Register a parser for a prefix-like operator.
8976 * @param parser the parser function
8977 * @param token_type the token type of the prefix token
8979 static void register_expression_parser(parse_expression_function parser,
8982 expression_parser_function_t *entry = &expression_parsers[token_type];
8984 if (entry->parser != NULL) {
8985 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8986 panic("trying to register multiple expression parsers for a token");
8988 entry->parser = parser;
8992 * Register a parser for an infix operator with given precedence.
8994 * @param parser the parser function
8995 * @param token_type the token type of the infix operator
8996 * @param precedence the precedence of the operator
8998 static void register_infix_parser(parse_expression_infix_function parser,
8999 int token_type, precedence_t precedence)
9001 expression_parser_function_t *entry = &expression_parsers[token_type];
9003 if (entry->infix_parser != NULL) {
9004 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9005 panic("trying to register multiple infix expression parsers for a "
9008 entry->infix_parser = parser;
9009 entry->infix_precedence = precedence;
9013 * Initialize the expression parsers.
9015 static void init_expression_parsers(void)
9017 memset(&expression_parsers, 0, sizeof(expression_parsers));
9019 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9020 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9021 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9022 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9023 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9024 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9025 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9026 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9027 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9028 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9029 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9030 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9031 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9032 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9033 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9034 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9035 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9036 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9037 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9038 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9039 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9040 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9041 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9042 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9043 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9044 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9045 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9046 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9047 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9048 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9049 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9050 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9051 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9052 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9053 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9054 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9055 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9057 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9058 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9059 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9060 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9061 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9062 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9063 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9064 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9065 register_expression_parser(parse_sizeof, T_sizeof);
9066 register_expression_parser(parse_alignof, T___alignof__);
9067 register_expression_parser(parse_extension, T___extension__);
9068 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9069 register_expression_parser(parse_delete, T_delete);
9070 register_expression_parser(parse_throw, T_throw);
9074 * Parse a asm statement arguments specification.
9076 static asm_argument_t *parse_asm_arguments(bool is_out)
9078 asm_argument_t *result = NULL;
9079 asm_argument_t **anchor = &result;
9081 while (token.type == T_STRING_LITERAL || token.type == '[') {
9082 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9083 memset(argument, 0, sizeof(argument[0]));
9086 if (token.type != T_IDENTIFIER) {
9087 parse_error_expected("while parsing asm argument",
9088 T_IDENTIFIER, NULL);
9091 argument->symbol = token.symbol;
9093 expect(']', end_error);
9096 argument->constraints = parse_string_literals();
9097 expect('(', end_error);
9098 add_anchor_token(')');
9099 expression_t *expression = parse_expression();
9100 rem_anchor_token(')');
9102 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9103 * change size or type representation (e.g. int -> long is ok, but
9104 * int -> float is not) */
9105 if (expression->kind == EXPR_UNARY_CAST) {
9106 type_t *const type = expression->base.type;
9107 type_kind_t const kind = type->kind;
9108 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9111 if (kind == TYPE_ATOMIC) {
9112 atomic_type_kind_t const akind = type->atomic.akind;
9113 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9114 size = get_atomic_type_size(akind);
9116 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9117 size = get_atomic_type_size(get_intptr_kind());
9121 expression_t *const value = expression->unary.value;
9122 type_t *const value_type = value->base.type;
9123 type_kind_t const value_kind = value_type->kind;
9125 unsigned value_flags;
9126 unsigned value_size;
9127 if (value_kind == TYPE_ATOMIC) {
9128 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9129 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9130 value_size = get_atomic_type_size(value_akind);
9131 } else if (value_kind == TYPE_POINTER) {
9132 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9133 value_size = get_atomic_type_size(get_intptr_kind());
9138 if (value_flags != flags || value_size != size)
9142 } while (expression->kind == EXPR_UNARY_CAST);
9146 if (!is_lvalue(expression)) {
9147 errorf(&expression->base.source_position,
9148 "asm output argument is not an lvalue");
9151 if (argument->constraints.begin[0] == '=')
9152 determine_lhs_ent(expression, NULL);
9154 mark_vars_read(expression, NULL);
9156 mark_vars_read(expression, NULL);
9158 argument->expression = expression;
9159 expect(')', end_error);
9161 set_address_taken(expression, true);
9164 anchor = &argument->next;
9176 * Parse a asm statement clobber specification.
9178 static asm_clobber_t *parse_asm_clobbers(void)
9180 asm_clobber_t *result = NULL;
9181 asm_clobber_t **anchor = &result;
9183 while (token.type == T_STRING_LITERAL) {
9184 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9185 clobber->clobber = parse_string_literals();
9188 anchor = &clobber->next;
9198 * Parse an asm statement.
9200 static statement_t *parse_asm_statement(void)
9202 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9203 asm_statement_t *asm_statement = &statement->asms;
9207 if (next_if(T_volatile))
9208 asm_statement->is_volatile = true;
9210 expect('(', end_error);
9211 add_anchor_token(')');
9212 add_anchor_token(':');
9213 asm_statement->asm_text = parse_string_literals();
9215 if (!next_if(':')) {
9216 rem_anchor_token(':');
9220 asm_statement->outputs = parse_asm_arguments(true);
9221 if (!next_if(':')) {
9222 rem_anchor_token(':');
9226 asm_statement->inputs = parse_asm_arguments(false);
9227 if (!next_if(':')) {
9228 rem_anchor_token(':');
9231 rem_anchor_token(':');
9233 asm_statement->clobbers = parse_asm_clobbers();
9236 rem_anchor_token(')');
9237 expect(')', end_error);
9238 expect(';', end_error);
9240 if (asm_statement->outputs == NULL) {
9241 /* GCC: An 'asm' instruction without any output operands will be treated
9242 * identically to a volatile 'asm' instruction. */
9243 asm_statement->is_volatile = true;
9248 return create_invalid_statement();
9252 * Parse a case statement.
9254 static statement_t *parse_case_statement(void)
9256 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9257 source_position_t *const pos = &statement->base.source_position;
9261 expression_t *const expression = parse_expression();
9262 statement->case_label.expression = expression;
9263 if (!is_constant_expression(expression)) {
9264 /* This check does not prevent the error message in all cases of an
9265 * prior error while parsing the expression. At least it catches the
9266 * common case of a mistyped enum entry. */
9267 if (is_type_valid(skip_typeref(expression->base.type))) {
9268 errorf(pos, "case label does not reduce to an integer constant");
9270 statement->case_label.is_bad = true;
9272 long const val = fold_constant_to_int(expression);
9273 statement->case_label.first_case = val;
9274 statement->case_label.last_case = val;
9278 if (next_if(T_DOTDOTDOT)) {
9279 expression_t *const end_range = parse_expression();
9280 statement->case_label.end_range = end_range;
9281 if (!is_constant_expression(end_range)) {
9282 /* This check does not prevent the error message in all cases of an
9283 * prior error while parsing the expression. At least it catches the
9284 * common case of a mistyped enum entry. */
9285 if (is_type_valid(skip_typeref(end_range->base.type))) {
9286 errorf(pos, "case range does not reduce to an integer constant");
9288 statement->case_label.is_bad = true;
9290 long const val = fold_constant_to_int(end_range);
9291 statement->case_label.last_case = val;
9293 if (warning.other && val < statement->case_label.first_case) {
9294 statement->case_label.is_empty_range = true;
9295 warningf(pos, "empty range specified");
9301 PUSH_PARENT(statement);
9303 expect(':', end_error);
9306 if (current_switch != NULL) {
9307 if (! statement->case_label.is_bad) {
9308 /* Check for duplicate case values */
9309 case_label_statement_t *c = &statement->case_label;
9310 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9311 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9314 if (c->last_case < l->first_case || c->first_case > l->last_case)
9317 errorf(pos, "duplicate case value (previously used %P)",
9318 &l->base.source_position);
9322 /* link all cases into the switch statement */
9323 if (current_switch->last_case == NULL) {
9324 current_switch->first_case = &statement->case_label;
9326 current_switch->last_case->next = &statement->case_label;
9328 current_switch->last_case = &statement->case_label;
9330 errorf(pos, "case label not within a switch statement");
9333 statement_t *const inner_stmt = parse_statement();
9334 statement->case_label.statement = inner_stmt;
9335 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9336 errorf(&inner_stmt->base.source_position, "declaration after case label");
9344 * Parse a default statement.
9346 static statement_t *parse_default_statement(void)
9348 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9352 PUSH_PARENT(statement);
9354 expect(':', end_error);
9355 if (current_switch != NULL) {
9356 const case_label_statement_t *def_label = current_switch->default_label;
9357 if (def_label != NULL) {
9358 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9359 &def_label->base.source_position);
9361 current_switch->default_label = &statement->case_label;
9363 /* link all cases into the switch statement */
9364 if (current_switch->last_case == NULL) {
9365 current_switch->first_case = &statement->case_label;
9367 current_switch->last_case->next = &statement->case_label;
9369 current_switch->last_case = &statement->case_label;
9372 errorf(&statement->base.source_position,
9373 "'default' label not within a switch statement");
9376 statement_t *const inner_stmt = parse_statement();
9377 statement->case_label.statement = inner_stmt;
9378 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9379 errorf(&inner_stmt->base.source_position, "declaration after default label");
9386 return create_invalid_statement();
9390 * Parse a label statement.
9392 static statement_t *parse_label_statement(void)
9394 assert(token.type == T_IDENTIFIER);
9395 symbol_t *symbol = token.symbol;
9396 label_t *label = get_label(symbol);
9398 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9399 statement->label.label = label;
9403 PUSH_PARENT(statement);
9405 /* if statement is already set then the label is defined twice,
9406 * otherwise it was just mentioned in a goto/local label declaration so far
9408 if (label->statement != NULL) {
9409 errorf(HERE, "duplicate label '%Y' (declared %P)",
9410 symbol, &label->base.source_position);
9412 label->base.source_position = token.source_position;
9413 label->statement = statement;
9418 if (token.type == '}') {
9419 errorf(HERE, "label at end of compound statement");
9420 statement->label.statement = create_invalid_statement();
9421 } else if (token.type == ';') {
9422 /* Eat an empty statement here, to avoid the warning about an empty
9423 * statement after a label. label:; is commonly used to have a label
9424 * before a closing brace. */
9425 statement->label.statement = create_empty_statement();
9428 statement_t *const inner_stmt = parse_statement();
9429 statement->label.statement = inner_stmt;
9430 if (inner_stmt->kind == STATEMENT_DECLARATION) {
9431 errorf(&inner_stmt->base.source_position, "declaration after label");
9435 /* remember the labels in a list for later checking */
9436 *label_anchor = &statement->label;
9437 label_anchor = &statement->label.next;
9444 * Parse an if statement.
9446 static statement_t *parse_if(void)
9448 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9452 PUSH_PARENT(statement);
9454 add_anchor_token('{');
9456 expect('(', end_error);
9457 add_anchor_token(')');
9458 expression_t *const expr = parse_expression();
9459 statement->ifs.condition = expr;
9460 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9462 semantic_condition(expr, "condition of 'if'-statment");
9463 mark_vars_read(expr, NULL);
9464 rem_anchor_token(')');
9465 expect(')', end_error);
9468 rem_anchor_token('{');
9470 add_anchor_token(T_else);
9471 statement_t *const true_stmt = parse_statement();
9472 statement->ifs.true_statement = true_stmt;
9473 rem_anchor_token(T_else);
9475 if (next_if(T_else)) {
9476 statement->ifs.false_statement = parse_statement();
9477 } else if (warning.parentheses &&
9478 true_stmt->kind == STATEMENT_IF &&
9479 true_stmt->ifs.false_statement != NULL) {
9480 warningf(&true_stmt->base.source_position,
9481 "suggest explicit braces to avoid ambiguous 'else'");
9489 * Check that all enums are handled in a switch.
9491 * @param statement the switch statement to check
9493 static void check_enum_cases(const switch_statement_t *statement)
9495 const type_t *type = skip_typeref(statement->expression->base.type);
9496 if (! is_type_enum(type))
9498 const enum_type_t *enumt = &type->enumt;
9500 /* if we have a default, no warnings */
9501 if (statement->default_label != NULL)
9504 /* FIXME: calculation of value should be done while parsing */
9505 /* TODO: quadratic algorithm here. Change to an n log n one */
9506 long last_value = -1;
9507 const entity_t *entry = enumt->enume->base.next;
9508 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9509 entry = entry->base.next) {
9510 const expression_t *expression = entry->enum_value.value;
9511 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9513 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9514 if (l->expression == NULL)
9516 if (l->first_case <= value && value <= l->last_case) {
9522 warningf(&statement->base.source_position,
9523 "enumeration value '%Y' not handled in switch",
9524 entry->base.symbol);
9531 * Parse a switch statement.
9533 static statement_t *parse_switch(void)
9535 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9539 PUSH_PARENT(statement);
9541 expect('(', end_error);
9542 add_anchor_token(')');
9543 expression_t *const expr = parse_expression();
9544 mark_vars_read(expr, NULL);
9545 type_t * type = skip_typeref(expr->base.type);
9546 if (is_type_integer(type)) {
9547 type = promote_integer(type);
9548 if (warning.traditional) {
9549 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9550 warningf(&expr->base.source_position,
9551 "'%T' switch expression not converted to '%T' in ISO C",
9555 } else if (is_type_valid(type)) {
9556 errorf(&expr->base.source_position,
9557 "switch quantity is not an integer, but '%T'", type);
9558 type = type_error_type;
9560 statement->switchs.expression = create_implicit_cast(expr, type);
9561 expect(')', end_error);
9562 rem_anchor_token(')');
9564 switch_statement_t *rem = current_switch;
9565 current_switch = &statement->switchs;
9566 statement->switchs.body = parse_statement();
9567 current_switch = rem;
9569 if (warning.switch_default &&
9570 statement->switchs.default_label == NULL) {
9571 warningf(&statement->base.source_position, "switch has no default case");
9573 if (warning.switch_enum)
9574 check_enum_cases(&statement->switchs);
9580 return create_invalid_statement();
9583 static statement_t *parse_loop_body(statement_t *const loop)
9585 statement_t *const rem = current_loop;
9586 current_loop = loop;
9588 statement_t *const body = parse_statement();
9595 * Parse a while statement.
9597 static statement_t *parse_while(void)
9599 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9603 PUSH_PARENT(statement);
9605 expect('(', end_error);
9606 add_anchor_token(')');
9607 expression_t *const cond = parse_expression();
9608 statement->whiles.condition = cond;
9609 /* §6.8.5:2 The controlling expression of an iteration statement shall
9610 * have scalar type. */
9611 semantic_condition(cond, "condition of 'while'-statement");
9612 mark_vars_read(cond, NULL);
9613 rem_anchor_token(')');
9614 expect(')', end_error);
9616 statement->whiles.body = parse_loop_body(statement);
9622 return create_invalid_statement();
9626 * Parse a do statement.
9628 static statement_t *parse_do(void)
9630 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9634 PUSH_PARENT(statement);
9636 add_anchor_token(T_while);
9637 statement->do_while.body = parse_loop_body(statement);
9638 rem_anchor_token(T_while);
9640 expect(T_while, end_error);
9641 expect('(', end_error);
9642 add_anchor_token(')');
9643 expression_t *const cond = parse_expression();
9644 statement->do_while.condition = cond;
9645 /* §6.8.5:2 The controlling expression of an iteration statement shall
9646 * have scalar type. */
9647 semantic_condition(cond, "condition of 'do-while'-statement");
9648 mark_vars_read(cond, NULL);
9649 rem_anchor_token(')');
9650 expect(')', end_error);
9651 expect(';', end_error);
9657 return create_invalid_statement();
9661 * Parse a for statement.
9663 static statement_t *parse_for(void)
9665 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9669 expect('(', end_error1);
9670 add_anchor_token(')');
9672 PUSH_PARENT(statement);
9674 size_t const top = environment_top();
9675 scope_t *old_scope = scope_push(&statement->fors.scope);
9677 bool old_gcc_extension = in_gcc_extension;
9678 while (next_if(T___extension__)) {
9679 in_gcc_extension = true;
9683 } else if (is_declaration_specifier(&token, false)) {
9684 parse_declaration(record_entity, DECL_FLAGS_NONE);
9686 add_anchor_token(';');
9687 expression_t *const init = parse_expression();
9688 statement->fors.initialisation = init;
9689 mark_vars_read(init, ENT_ANY);
9690 if (warning.unused_value && !expression_has_effect(init)) {
9691 warningf(&init->base.source_position,
9692 "initialisation of 'for'-statement has no effect");
9694 rem_anchor_token(';');
9695 expect(';', end_error2);
9697 in_gcc_extension = old_gcc_extension;
9699 if (token.type != ';') {
9700 add_anchor_token(';');
9701 expression_t *const cond = parse_expression();
9702 statement->fors.condition = cond;
9703 /* §6.8.5:2 The controlling expression of an iteration statement
9704 * shall have scalar type. */
9705 semantic_condition(cond, "condition of 'for'-statement");
9706 mark_vars_read(cond, NULL);
9707 rem_anchor_token(';');
9709 expect(';', end_error2);
9710 if (token.type != ')') {
9711 expression_t *const step = parse_expression();
9712 statement->fors.step = step;
9713 mark_vars_read(step, ENT_ANY);
9714 if (warning.unused_value && !expression_has_effect(step)) {
9715 warningf(&step->base.source_position,
9716 "step of 'for'-statement has no effect");
9719 expect(')', end_error2);
9720 rem_anchor_token(')');
9721 statement->fors.body = parse_loop_body(statement);
9723 assert(current_scope == &statement->fors.scope);
9724 scope_pop(old_scope);
9725 environment_pop_to(top);
9732 rem_anchor_token(')');
9733 assert(current_scope == &statement->fors.scope);
9734 scope_pop(old_scope);
9735 environment_pop_to(top);
9739 return create_invalid_statement();
9743 * Parse a goto statement.
9745 static statement_t *parse_goto(void)
9747 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9750 if (GNU_MODE && next_if('*')) {
9751 expression_t *expression = parse_expression();
9752 mark_vars_read(expression, NULL);
9754 /* Argh: although documentation says the expression must be of type void*,
9755 * gcc accepts anything that can be casted into void* without error */
9756 type_t *type = expression->base.type;
9758 if (type != type_error_type) {
9759 if (!is_type_pointer(type) && !is_type_integer(type)) {
9760 errorf(&expression->base.source_position,
9761 "cannot convert to a pointer type");
9762 } else if (warning.other && type != type_void_ptr) {
9763 warningf(&expression->base.source_position,
9764 "type of computed goto expression should be 'void*' not '%T'", type);
9766 expression = create_implicit_cast(expression, type_void_ptr);
9769 statement->gotos.expression = expression;
9770 } else if (token.type == T_IDENTIFIER) {
9771 symbol_t *symbol = token.symbol;
9773 statement->gotos.label = get_label(symbol);
9776 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9778 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9783 /* remember the goto's in a list for later checking */
9784 *goto_anchor = &statement->gotos;
9785 goto_anchor = &statement->gotos.next;
9787 expect(';', end_error);
9791 return create_invalid_statement();
9795 * Parse a continue statement.
9797 static statement_t *parse_continue(void)
9799 if (current_loop == NULL) {
9800 errorf(HERE, "continue statement not within loop");
9803 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9806 expect(';', end_error);
9813 * Parse a break statement.
9815 static statement_t *parse_break(void)
9817 if (current_switch == NULL && current_loop == NULL) {
9818 errorf(HERE, "break statement not within loop or switch");
9821 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9824 expect(';', end_error);
9831 * Parse a __leave statement.
9833 static statement_t *parse_leave_statement(void)
9835 if (current_try == NULL) {
9836 errorf(HERE, "__leave statement not within __try");
9839 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9842 expect(';', end_error);
9849 * Check if a given entity represents a local variable.
9851 static bool is_local_variable(const entity_t *entity)
9853 if (entity->kind != ENTITY_VARIABLE)
9856 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9857 case STORAGE_CLASS_AUTO:
9858 case STORAGE_CLASS_REGISTER: {
9859 const type_t *type = skip_typeref(entity->declaration.type);
9860 if (is_type_function(type)) {
9872 * Check if a given expression represents a local variable.
9874 static bool expression_is_local_variable(const expression_t *expression)
9876 if (expression->base.kind != EXPR_REFERENCE) {
9879 const entity_t *entity = expression->reference.entity;
9880 return is_local_variable(entity);
9884 * Check if a given expression represents a local variable and
9885 * return its declaration then, else return NULL.
9887 entity_t *expression_is_variable(const expression_t *expression)
9889 if (expression->base.kind != EXPR_REFERENCE) {
9892 entity_t *entity = expression->reference.entity;
9893 if (entity->kind != ENTITY_VARIABLE)
9900 * Parse a return statement.
9902 static statement_t *parse_return(void)
9906 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9908 expression_t *return_value = NULL;
9909 if (token.type != ';') {
9910 return_value = parse_expression();
9911 mark_vars_read(return_value, NULL);
9914 const type_t *const func_type = skip_typeref(current_function->base.type);
9915 assert(is_type_function(func_type));
9916 type_t *const return_type = skip_typeref(func_type->function.return_type);
9918 source_position_t const *const pos = &statement->base.source_position;
9919 if (return_value != NULL) {
9920 type_t *return_value_type = skip_typeref(return_value->base.type);
9922 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9923 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9924 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9925 /* Only warn in C mode, because GCC does the same */
9926 if (c_mode & _CXX || strict_mode) {
9928 "'return' with a value, in function returning 'void'");
9929 } else if (warning.other) {
9931 "'return' with a value, in function returning 'void'");
9933 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9934 /* Only warn in C mode, because GCC does the same */
9937 "'return' with expression in function returning 'void'");
9938 } else if (warning.other) {
9940 "'return' with expression in function returning 'void'");
9944 assign_error_t error = semantic_assign(return_type, return_value);
9945 report_assign_error(error, return_type, return_value, "'return'",
9948 return_value = create_implicit_cast(return_value, return_type);
9949 /* check for returning address of a local var */
9950 if (warning.other && return_value != NULL
9951 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9952 const expression_t *expression = return_value->unary.value;
9953 if (expression_is_local_variable(expression)) {
9954 warningf(pos, "function returns address of local variable");
9957 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9958 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9959 if (c_mode & _CXX || strict_mode) {
9961 "'return' without value, in function returning non-void");
9964 "'return' without value, in function returning non-void");
9967 statement->returns.value = return_value;
9969 expect(';', end_error);
9976 * Parse a declaration statement.
9978 static statement_t *parse_declaration_statement(void)
9980 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9982 entity_t *before = current_scope->last_entity;
9984 parse_external_declaration();
9986 parse_declaration(record_entity, DECL_FLAGS_NONE);
9989 declaration_statement_t *const decl = &statement->declaration;
9990 entity_t *const begin =
9991 before != NULL ? before->base.next : current_scope->entities;
9992 decl->declarations_begin = begin;
9993 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9999 * Parse an expression statement, ie. expr ';'.
10001 static statement_t *parse_expression_statement(void)
10003 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10005 expression_t *const expr = parse_expression();
10006 statement->expression.expression = expr;
10007 mark_vars_read(expr, ENT_ANY);
10009 expect(';', end_error);
10016 * Parse a microsoft __try { } __finally { } or
10017 * __try{ } __except() { }
10019 static statement_t *parse_ms_try_statment(void)
10021 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10024 PUSH_PARENT(statement);
10026 ms_try_statement_t *rem = current_try;
10027 current_try = &statement->ms_try;
10028 statement->ms_try.try_statement = parse_compound_statement(false);
10033 if (next_if(T___except)) {
10034 expect('(', end_error);
10035 add_anchor_token(')');
10036 expression_t *const expr = parse_expression();
10037 mark_vars_read(expr, NULL);
10038 type_t * type = skip_typeref(expr->base.type);
10039 if (is_type_integer(type)) {
10040 type = promote_integer(type);
10041 } else if (is_type_valid(type)) {
10042 errorf(&expr->base.source_position,
10043 "__expect expression is not an integer, but '%T'", type);
10044 type = type_error_type;
10046 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10047 rem_anchor_token(')');
10048 expect(')', end_error);
10049 statement->ms_try.final_statement = parse_compound_statement(false);
10050 } else if (next_if(T__finally)) {
10051 statement->ms_try.final_statement = parse_compound_statement(false);
10053 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10054 return create_invalid_statement();
10058 return create_invalid_statement();
10061 static statement_t *parse_empty_statement(void)
10063 if (warning.empty_statement) {
10064 warningf(HERE, "statement is empty");
10066 statement_t *const statement = create_empty_statement();
10071 static statement_t *parse_local_label_declaration(void)
10073 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10077 entity_t *begin = NULL, *end = NULL;
10080 if (token.type != T_IDENTIFIER) {
10081 parse_error_expected("while parsing local label declaration",
10082 T_IDENTIFIER, NULL);
10085 symbol_t *symbol = token.symbol;
10086 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10087 if (entity != NULL && entity->base.parent_scope == current_scope) {
10088 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10089 symbol, &entity->base.source_position);
10091 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10093 entity->base.parent_scope = current_scope;
10094 entity->base.namespc = NAMESPACE_LABEL;
10095 entity->base.source_position = token.source_position;
10096 entity->base.symbol = symbol;
10099 end->base.next = entity;
10104 environment_push(entity);
10107 } while (next_if(','));
10110 statement->declaration.declarations_begin = begin;
10111 statement->declaration.declarations_end = end;
10115 static void parse_namespace_definition(void)
10119 entity_t *entity = NULL;
10120 symbol_t *symbol = NULL;
10122 if (token.type == T_IDENTIFIER) {
10123 symbol = token.symbol;
10126 entity = get_entity(symbol, NAMESPACE_NORMAL);
10128 && entity->kind != ENTITY_NAMESPACE
10129 && entity->base.parent_scope == current_scope) {
10130 if (!is_error_entity(entity)) {
10131 error_redefined_as_different_kind(&token.source_position,
10132 entity, ENTITY_NAMESPACE);
10138 if (entity == NULL) {
10139 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10140 entity->base.symbol = symbol;
10141 entity->base.source_position = token.source_position;
10142 entity->base.namespc = NAMESPACE_NORMAL;
10143 entity->base.parent_scope = current_scope;
10146 if (token.type == '=') {
10147 /* TODO: parse namespace alias */
10148 panic("namespace alias definition not supported yet");
10151 environment_push(entity);
10152 append_entity(current_scope, entity);
10154 size_t const top = environment_top();
10155 scope_t *old_scope = scope_push(&entity->namespacee.members);
10157 entity_t *old_current_entity = current_entity;
10158 current_entity = entity;
10160 expect('{', end_error);
10162 expect('}', end_error);
10165 assert(current_scope == &entity->namespacee.members);
10166 assert(current_entity == entity);
10167 current_entity = old_current_entity;
10168 scope_pop(old_scope);
10169 environment_pop_to(top);
10173 * Parse a statement.
10174 * There's also parse_statement() which additionally checks for
10175 * "statement has no effect" warnings
10177 static statement_t *intern_parse_statement(void)
10179 statement_t *statement = NULL;
10181 /* declaration or statement */
10182 add_anchor_token(';');
10183 switch (token.type) {
10184 case T_IDENTIFIER: {
10185 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10186 if (la1_type == ':') {
10187 statement = parse_label_statement();
10188 } else if (is_typedef_symbol(token.symbol)) {
10189 statement = parse_declaration_statement();
10191 /* it's an identifier, the grammar says this must be an
10192 * expression statement. However it is common that users mistype
10193 * declaration types, so we guess a bit here to improve robustness
10194 * for incorrect programs */
10195 switch (la1_type) {
10198 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL)
10199 goto expression_statment;
10204 statement = parse_declaration_statement();
10208 expression_statment:
10209 statement = parse_expression_statement();
10216 case T___extension__:
10217 /* This can be a prefix to a declaration or an expression statement.
10218 * We simply eat it now and parse the rest with tail recursion. */
10219 while (next_if(T___extension__)) {}
10220 bool old_gcc_extension = in_gcc_extension;
10221 in_gcc_extension = true;
10222 statement = intern_parse_statement();
10223 in_gcc_extension = old_gcc_extension;
10227 statement = parse_declaration_statement();
10231 statement = parse_local_label_declaration();
10234 case ';': statement = parse_empty_statement(); break;
10235 case '{': statement = parse_compound_statement(false); break;
10236 case T___leave: statement = parse_leave_statement(); break;
10237 case T___try: statement = parse_ms_try_statment(); break;
10238 case T_asm: statement = parse_asm_statement(); break;
10239 case T_break: statement = parse_break(); break;
10240 case T_case: statement = parse_case_statement(); break;
10241 case T_continue: statement = parse_continue(); break;
10242 case T_default: statement = parse_default_statement(); break;
10243 case T_do: statement = parse_do(); break;
10244 case T_for: statement = parse_for(); break;
10245 case T_goto: statement = parse_goto(); break;
10246 case T_if: statement = parse_if(); break;
10247 case T_return: statement = parse_return(); break;
10248 case T_switch: statement = parse_switch(); break;
10249 case T_while: statement = parse_while(); break;
10252 statement = parse_expression_statement();
10256 errorf(HERE, "unexpected token %K while parsing statement", &token);
10257 statement = create_invalid_statement();
10262 rem_anchor_token(';');
10264 assert(statement != NULL
10265 && statement->base.source_position.input_name != NULL);
10271 * parse a statement and emits "statement has no effect" warning if needed
10272 * (This is really a wrapper around intern_parse_statement with check for 1
10273 * single warning. It is needed, because for statement expressions we have
10274 * to avoid the warning on the last statement)
10276 static statement_t *parse_statement(void)
10278 statement_t *statement = intern_parse_statement();
10280 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10281 expression_t *expression = statement->expression.expression;
10282 if (!expression_has_effect(expression)) {
10283 warningf(&expression->base.source_position,
10284 "statement has no effect");
10292 * Parse a compound statement.
10294 static statement_t *parse_compound_statement(bool inside_expression_statement)
10296 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10298 PUSH_PARENT(statement);
10301 add_anchor_token('}');
10302 /* tokens, which can start a statement */
10303 /* TODO MS, __builtin_FOO */
10304 add_anchor_token('!');
10305 add_anchor_token('&');
10306 add_anchor_token('(');
10307 add_anchor_token('*');
10308 add_anchor_token('+');
10309 add_anchor_token('-');
10310 add_anchor_token('{');
10311 add_anchor_token('~');
10312 add_anchor_token(T_CHARACTER_CONSTANT);
10313 add_anchor_token(T_COLONCOLON);
10314 add_anchor_token(T_FLOATINGPOINT);
10315 add_anchor_token(T_IDENTIFIER);
10316 add_anchor_token(T_INTEGER);
10317 add_anchor_token(T_MINUSMINUS);
10318 add_anchor_token(T_PLUSPLUS);
10319 add_anchor_token(T_STRING_LITERAL);
10320 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10321 add_anchor_token(T_WIDE_STRING_LITERAL);
10322 add_anchor_token(T__Bool);
10323 add_anchor_token(T__Complex);
10324 add_anchor_token(T__Imaginary);
10325 add_anchor_token(T___FUNCTION__);
10326 add_anchor_token(T___PRETTY_FUNCTION__);
10327 add_anchor_token(T___alignof__);
10328 add_anchor_token(T___attribute__);
10329 add_anchor_token(T___builtin_va_start);
10330 add_anchor_token(T___extension__);
10331 add_anchor_token(T___func__);
10332 add_anchor_token(T___imag__);
10333 add_anchor_token(T___label__);
10334 add_anchor_token(T___real__);
10335 add_anchor_token(T___thread);
10336 add_anchor_token(T_asm);
10337 add_anchor_token(T_auto);
10338 add_anchor_token(T_bool);
10339 add_anchor_token(T_break);
10340 add_anchor_token(T_case);
10341 add_anchor_token(T_char);
10342 add_anchor_token(T_class);
10343 add_anchor_token(T_const);
10344 add_anchor_token(T_const_cast);
10345 add_anchor_token(T_continue);
10346 add_anchor_token(T_default);
10347 add_anchor_token(T_delete);
10348 add_anchor_token(T_double);
10349 add_anchor_token(T_do);
10350 add_anchor_token(T_dynamic_cast);
10351 add_anchor_token(T_enum);
10352 add_anchor_token(T_extern);
10353 add_anchor_token(T_false);
10354 add_anchor_token(T_float);
10355 add_anchor_token(T_for);
10356 add_anchor_token(T_goto);
10357 add_anchor_token(T_if);
10358 add_anchor_token(T_inline);
10359 add_anchor_token(T_int);
10360 add_anchor_token(T_long);
10361 add_anchor_token(T_new);
10362 add_anchor_token(T_operator);
10363 add_anchor_token(T_register);
10364 add_anchor_token(T_reinterpret_cast);
10365 add_anchor_token(T_restrict);
10366 add_anchor_token(T_return);
10367 add_anchor_token(T_short);
10368 add_anchor_token(T_signed);
10369 add_anchor_token(T_sizeof);
10370 add_anchor_token(T_static);
10371 add_anchor_token(T_static_cast);
10372 add_anchor_token(T_struct);
10373 add_anchor_token(T_switch);
10374 add_anchor_token(T_template);
10375 add_anchor_token(T_this);
10376 add_anchor_token(T_throw);
10377 add_anchor_token(T_true);
10378 add_anchor_token(T_try);
10379 add_anchor_token(T_typedef);
10380 add_anchor_token(T_typeid);
10381 add_anchor_token(T_typename);
10382 add_anchor_token(T_typeof);
10383 add_anchor_token(T_union);
10384 add_anchor_token(T_unsigned);
10385 add_anchor_token(T_using);
10386 add_anchor_token(T_void);
10387 add_anchor_token(T_volatile);
10388 add_anchor_token(T_wchar_t);
10389 add_anchor_token(T_while);
10391 size_t const top = environment_top();
10392 scope_t *old_scope = scope_push(&statement->compound.scope);
10394 statement_t **anchor = &statement->compound.statements;
10395 bool only_decls_so_far = true;
10396 while (token.type != '}') {
10397 if (token.type == T_EOF) {
10398 errorf(&statement->base.source_position,
10399 "EOF while parsing compound statement");
10402 statement_t *sub_statement = intern_parse_statement();
10403 if (is_invalid_statement(sub_statement)) {
10404 /* an error occurred. if we are at an anchor, return */
10410 if (warning.declaration_after_statement) {
10411 if (sub_statement->kind != STATEMENT_DECLARATION) {
10412 only_decls_so_far = false;
10413 } else if (!only_decls_so_far) {
10414 warningf(&sub_statement->base.source_position,
10415 "ISO C90 forbids mixed declarations and code");
10419 *anchor = sub_statement;
10421 while (sub_statement->base.next != NULL)
10422 sub_statement = sub_statement->base.next;
10424 anchor = &sub_statement->base.next;
10428 /* look over all statements again to produce no effect warnings */
10429 if (warning.unused_value) {
10430 statement_t *sub_statement = statement->compound.statements;
10431 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10432 if (sub_statement->kind != STATEMENT_EXPRESSION)
10434 /* don't emit a warning for the last expression in an expression
10435 * statement as it has always an effect */
10436 if (inside_expression_statement && sub_statement->base.next == NULL)
10439 expression_t *expression = sub_statement->expression.expression;
10440 if (!expression_has_effect(expression)) {
10441 warningf(&expression->base.source_position,
10442 "statement has no effect");
10448 rem_anchor_token(T_while);
10449 rem_anchor_token(T_wchar_t);
10450 rem_anchor_token(T_volatile);
10451 rem_anchor_token(T_void);
10452 rem_anchor_token(T_using);
10453 rem_anchor_token(T_unsigned);
10454 rem_anchor_token(T_union);
10455 rem_anchor_token(T_typeof);
10456 rem_anchor_token(T_typename);
10457 rem_anchor_token(T_typeid);
10458 rem_anchor_token(T_typedef);
10459 rem_anchor_token(T_try);
10460 rem_anchor_token(T_true);
10461 rem_anchor_token(T_throw);
10462 rem_anchor_token(T_this);
10463 rem_anchor_token(T_template);
10464 rem_anchor_token(T_switch);
10465 rem_anchor_token(T_struct);
10466 rem_anchor_token(T_static_cast);
10467 rem_anchor_token(T_static);
10468 rem_anchor_token(T_sizeof);
10469 rem_anchor_token(T_signed);
10470 rem_anchor_token(T_short);
10471 rem_anchor_token(T_return);
10472 rem_anchor_token(T_restrict);
10473 rem_anchor_token(T_reinterpret_cast);
10474 rem_anchor_token(T_register);
10475 rem_anchor_token(T_operator);
10476 rem_anchor_token(T_new);
10477 rem_anchor_token(T_long);
10478 rem_anchor_token(T_int);
10479 rem_anchor_token(T_inline);
10480 rem_anchor_token(T_if);
10481 rem_anchor_token(T_goto);
10482 rem_anchor_token(T_for);
10483 rem_anchor_token(T_float);
10484 rem_anchor_token(T_false);
10485 rem_anchor_token(T_extern);
10486 rem_anchor_token(T_enum);
10487 rem_anchor_token(T_dynamic_cast);
10488 rem_anchor_token(T_do);
10489 rem_anchor_token(T_double);
10490 rem_anchor_token(T_delete);
10491 rem_anchor_token(T_default);
10492 rem_anchor_token(T_continue);
10493 rem_anchor_token(T_const_cast);
10494 rem_anchor_token(T_const);
10495 rem_anchor_token(T_class);
10496 rem_anchor_token(T_char);
10497 rem_anchor_token(T_case);
10498 rem_anchor_token(T_break);
10499 rem_anchor_token(T_bool);
10500 rem_anchor_token(T_auto);
10501 rem_anchor_token(T_asm);
10502 rem_anchor_token(T___thread);
10503 rem_anchor_token(T___real__);
10504 rem_anchor_token(T___label__);
10505 rem_anchor_token(T___imag__);
10506 rem_anchor_token(T___func__);
10507 rem_anchor_token(T___extension__);
10508 rem_anchor_token(T___builtin_va_start);
10509 rem_anchor_token(T___attribute__);
10510 rem_anchor_token(T___alignof__);
10511 rem_anchor_token(T___PRETTY_FUNCTION__);
10512 rem_anchor_token(T___FUNCTION__);
10513 rem_anchor_token(T__Imaginary);
10514 rem_anchor_token(T__Complex);
10515 rem_anchor_token(T__Bool);
10516 rem_anchor_token(T_WIDE_STRING_LITERAL);
10517 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10518 rem_anchor_token(T_STRING_LITERAL);
10519 rem_anchor_token(T_PLUSPLUS);
10520 rem_anchor_token(T_MINUSMINUS);
10521 rem_anchor_token(T_INTEGER);
10522 rem_anchor_token(T_IDENTIFIER);
10523 rem_anchor_token(T_FLOATINGPOINT);
10524 rem_anchor_token(T_COLONCOLON);
10525 rem_anchor_token(T_CHARACTER_CONSTANT);
10526 rem_anchor_token('~');
10527 rem_anchor_token('{');
10528 rem_anchor_token('-');
10529 rem_anchor_token('+');
10530 rem_anchor_token('*');
10531 rem_anchor_token('(');
10532 rem_anchor_token('&');
10533 rem_anchor_token('!');
10534 rem_anchor_token('}');
10535 assert(current_scope == &statement->compound.scope);
10536 scope_pop(old_scope);
10537 environment_pop_to(top);
10544 * Check for unused global static functions and variables
10546 static void check_unused_globals(void)
10548 if (!warning.unused_function && !warning.unused_variable)
10551 for (const entity_t *entity = file_scope->entities; entity != NULL;
10552 entity = entity->base.next) {
10553 if (!is_declaration(entity))
10556 const declaration_t *declaration = &entity->declaration;
10557 if (declaration->used ||
10558 declaration->modifiers & DM_UNUSED ||
10559 declaration->modifiers & DM_USED ||
10560 declaration->storage_class != STORAGE_CLASS_STATIC)
10563 type_t *const type = declaration->type;
10565 if (entity->kind == ENTITY_FUNCTION) {
10566 /* inhibit warning for static inline functions */
10567 if (entity->function.is_inline)
10570 s = entity->function.statement != NULL ? "defined" : "declared";
10575 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10576 type, declaration->base.symbol, s);
10580 static void parse_global_asm(void)
10582 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10585 expect('(', end_error);
10587 statement->asms.asm_text = parse_string_literals();
10588 statement->base.next = unit->global_asm;
10589 unit->global_asm = statement;
10591 expect(')', end_error);
10592 expect(';', end_error);
10597 static void parse_linkage_specification(void)
10600 assert(token.type == T_STRING_LITERAL);
10602 const char *linkage = parse_string_literals().begin;
10604 linkage_kind_t old_linkage = current_linkage;
10605 linkage_kind_t new_linkage;
10606 if (strcmp(linkage, "C") == 0) {
10607 new_linkage = LINKAGE_C;
10608 } else if (strcmp(linkage, "C++") == 0) {
10609 new_linkage = LINKAGE_CXX;
10611 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10612 new_linkage = LINKAGE_INVALID;
10614 current_linkage = new_linkage;
10616 if (next_if('{')) {
10618 expect('}', end_error);
10624 assert(current_linkage == new_linkage);
10625 current_linkage = old_linkage;
10628 static void parse_external(void)
10630 switch (token.type) {
10631 DECLARATION_START_NO_EXTERN
10633 case T___extension__:
10634 /* tokens below are for implicit int */
10635 case '&': /* & x; -> int& x; (and error later, because C++ has no
10637 case '*': /* * x; -> int* x; */
10638 case '(': /* (x); -> int (x); */
10639 parse_external_declaration();
10643 if (look_ahead(1)->type == T_STRING_LITERAL) {
10644 parse_linkage_specification();
10646 parse_external_declaration();
10651 parse_global_asm();
10655 parse_namespace_definition();
10659 if (!strict_mode) {
10661 warningf(HERE, "stray ';' outside of function");
10668 errorf(HERE, "stray %K outside of function", &token);
10669 if (token.type == '(' || token.type == '{' || token.type == '[')
10670 eat_until_matching_token(token.type);
10676 static void parse_externals(void)
10678 add_anchor_token('}');
10679 add_anchor_token(T_EOF);
10682 unsigned char token_anchor_copy[T_LAST_TOKEN];
10683 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10686 while (token.type != T_EOF && token.type != '}') {
10688 bool anchor_leak = false;
10689 for (int i = 0; i != T_LAST_TOKEN; ++i) {
10690 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10692 errorf(HERE, "Leaked anchor token %k %d times", i, count);
10693 anchor_leak = true;
10696 if (in_gcc_extension) {
10697 errorf(HERE, "Leaked __extension__");
10698 anchor_leak = true;
10708 rem_anchor_token(T_EOF);
10709 rem_anchor_token('}');
10713 * Parse a translation unit.
10715 static void parse_translation_unit(void)
10717 add_anchor_token(T_EOF);
10722 if (token.type == T_EOF)
10725 errorf(HERE, "stray %K outside of function", &token);
10726 if (token.type == '(' || token.type == '{' || token.type == '[')
10727 eat_until_matching_token(token.type);
10735 * @return the translation unit or NULL if errors occurred.
10737 void start_parsing(void)
10739 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10740 label_stack = NEW_ARR_F(stack_entry_t, 0);
10741 diagnostic_count = 0;
10745 print_to_file(stderr);
10747 assert(unit == NULL);
10748 unit = allocate_ast_zero(sizeof(unit[0]));
10750 assert(file_scope == NULL);
10751 file_scope = &unit->scope;
10753 assert(current_scope == NULL);
10754 scope_push(&unit->scope);
10756 create_gnu_builtins();
10758 create_microsoft_intrinsics();
10761 translation_unit_t *finish_parsing(void)
10763 assert(current_scope == &unit->scope);
10766 assert(file_scope == &unit->scope);
10767 check_unused_globals();
10770 DEL_ARR_F(environment_stack);
10771 DEL_ARR_F(label_stack);
10773 translation_unit_t *result = unit;
10778 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10779 * are given length one. */
10780 static void complete_incomplete_arrays(void)
10782 size_t n = ARR_LEN(incomplete_arrays);
10783 for (size_t i = 0; i != n; ++i) {
10784 declaration_t *const decl = incomplete_arrays[i];
10785 type_t *const orig_type = decl->type;
10786 type_t *const type = skip_typeref(orig_type);
10788 if (!is_type_incomplete(type))
10791 if (warning.other) {
10792 warningf(&decl->base.source_position,
10793 "array '%#T' assumed to have one element",
10794 orig_type, decl->base.symbol);
10797 type_t *const new_type = duplicate_type(type);
10798 new_type->array.size_constant = true;
10799 new_type->array.has_implicit_size = true;
10800 new_type->array.size = 1;
10802 type_t *const result = identify_new_type(new_type);
10804 decl->type = result;
10808 void prepare_main_collect2(entity_t *entity)
10810 // create call to __main
10811 symbol_t *symbol = symbol_table_insert("__main");
10812 entity_t *subsubmain_ent
10813 = create_implicit_function(symbol, &builtin_source_position);
10815 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10816 type_t *ftype = subsubmain_ent->declaration.type;
10817 ref->base.source_position = builtin_source_position;
10818 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10819 ref->reference.entity = subsubmain_ent;
10821 expression_t *call = allocate_expression_zero(EXPR_CALL);
10822 call->base.source_position = builtin_source_position;
10823 call->base.type = type_void;
10824 call->call.function = ref;
10826 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10827 expr_statement->base.source_position = builtin_source_position;
10828 expr_statement->expression.expression = call;
10830 statement_t *statement = entity->function.statement;
10831 assert(statement->kind == STATEMENT_COMPOUND);
10832 compound_statement_t *compounds = &statement->compound;
10834 expr_statement->base.next = compounds->statements;
10835 compounds->statements = expr_statement;
10840 lookahead_bufpos = 0;
10841 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10844 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10845 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10846 parse_translation_unit();
10847 complete_incomplete_arrays();
10848 DEL_ARR_F(incomplete_arrays);
10849 incomplete_arrays = NULL;
10853 * Initialize the parser.
10855 void init_parser(void)
10857 sym_anonymous = symbol_table_insert("<anonymous>");
10859 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10861 init_expression_parsers();
10862 obstack_init(&temp_obst);
10864 symbol_t *const va_list_sym = symbol_table_insert("__builtin_va_list");
10865 type_valist = create_builtin_type(va_list_sym, type_void_ptr);
10869 * Terminate the parser.
10871 void exit_parser(void)
10873 obstack_free(&temp_obst, NULL);