2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const prev_parent = current_parent; \
116 ((void)(current_parent = (stmt)))
117 #define POP_PARENT ((void)(current_parent = prev_parent))
119 /** special symbol used for anonymous entities. */
120 static symbol_t *sym_anonymous = NULL;
122 /** The token anchor set */
123 static unsigned char token_anchor_set[T_LAST_TOKEN];
125 /** The current source position. */
126 #define HERE (&token.source_position)
128 /** true if we are in GCC mode. */
129 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
131 static statement_t *parse_compound_statement(bool inside_expression_statement);
132 static statement_t *parse_statement(void);
134 static expression_t *parse_subexpression(precedence_t);
135 static expression_t *parse_expression(void);
136 static type_t *parse_typename(void);
137 static void parse_externals(void);
138 static void parse_external(void);
140 static void parse_compound_type_entries(compound_t *compound_declaration);
142 static void check_call_argument(type_t *expected_type,
143 call_argument_t *argument, unsigned pos);
145 typedef enum declarator_flags_t {
147 DECL_MAY_BE_ABSTRACT = 1U << 0,
148 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
149 DECL_IS_PARAMETER = 1U << 2
150 } declarator_flags_t;
152 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
153 declarator_flags_t flags);
155 static void semantic_comparison(binary_expression_t *expression);
157 #define STORAGE_CLASSES \
158 STORAGE_CLASSES_NO_EXTERN \
161 #define STORAGE_CLASSES_NO_EXTERN \
168 #define TYPE_QUALIFIERS \
173 case T__forceinline: \
174 case T___attribute__:
176 #define COMPLEX_SPECIFIERS \
178 #define IMAGINARY_SPECIFIERS \
181 #define TYPE_SPECIFIERS \
183 case T___builtin_va_list: \
208 #define DECLARATION_START \
213 #define DECLARATION_START_NO_EXTERN \
214 STORAGE_CLASSES_NO_EXTERN \
218 #define TYPENAME_START \
222 #define EXPRESSION_START \
231 case T_CHARACTER_CONSTANT: \
232 case T_FLOATINGPOINT: \
233 case T_FLOATINGPOINT_HEXADECIMAL: \
235 case T_INTEGER_HEXADECIMAL: \
236 case T_INTEGER_OCTAL: \
239 case T_STRING_LITERAL: \
240 case T_WIDE_CHARACTER_CONSTANT: \
241 case T_WIDE_STRING_LITERAL: \
242 case T___FUNCDNAME__: \
243 case T___FUNCSIG__: \
244 case T___FUNCTION__: \
245 case T___PRETTY_FUNCTION__: \
246 case T___alignof__: \
247 case T___builtin_classify_type: \
248 case T___builtin_constant_p: \
249 case T___builtin_isgreater: \
250 case T___builtin_isgreaterequal: \
251 case T___builtin_isless: \
252 case T___builtin_islessequal: \
253 case T___builtin_islessgreater: \
254 case T___builtin_isunordered: \
255 case T___builtin_offsetof: \
256 case T___builtin_va_arg: \
257 case T___builtin_va_copy: \
258 case T___builtin_va_start: \
269 * Returns the size of a statement node.
271 * @param kind the statement kind
273 static size_t get_statement_struct_size(statement_kind_t kind)
275 static const size_t sizes[] = {
276 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
277 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
278 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
279 [STATEMENT_RETURN] = sizeof(return_statement_t),
280 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
281 [STATEMENT_IF] = sizeof(if_statement_t),
282 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
283 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
284 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
285 [STATEMENT_BREAK] = sizeof(statement_base_t),
286 [STATEMENT_GOTO] = sizeof(goto_statement_t),
287 [STATEMENT_LABEL] = sizeof(label_statement_t),
288 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
289 [STATEMENT_WHILE] = sizeof(while_statement_t),
290 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
291 [STATEMENT_FOR] = sizeof(for_statement_t),
292 [STATEMENT_ASM] = sizeof(asm_statement_t),
293 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
294 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
296 assert(kind < lengthof(sizes));
297 assert(sizes[kind] != 0);
302 * Returns the size of an expression node.
304 * @param kind the expression kind
306 static size_t get_expression_struct_size(expression_kind_t kind)
308 static const size_t sizes[] = {
309 [EXPR_INVALID] = sizeof(expression_base_t),
310 [EXPR_REFERENCE] = sizeof(reference_expression_t),
311 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
312 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
316 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
317 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
318 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
319 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
320 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
321 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
322 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
323 [EXPR_CALL] = sizeof(call_expression_t),
324 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
325 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
326 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
327 [EXPR_SELECT] = sizeof(select_expression_t),
328 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
329 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
330 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
331 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
332 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
333 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
334 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
335 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
336 [EXPR_VA_START] = sizeof(va_start_expression_t),
337 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
338 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
339 [EXPR_STATEMENT] = sizeof(statement_expression_t),
340 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
342 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
343 return sizes[EXPR_UNARY_FIRST];
345 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
346 return sizes[EXPR_BINARY_FIRST];
348 assert(kind < lengthof(sizes));
349 assert(sizes[kind] != 0);
354 * Allocate a statement node of given kind and initialize all
355 * fields with zero. Sets its source position to the position
356 * of the current token.
358 static statement_t *allocate_statement_zero(statement_kind_t kind)
360 size_t size = get_statement_struct_size(kind);
361 statement_t *res = allocate_ast_zero(size);
363 res->base.kind = kind;
364 res->base.parent = current_parent;
365 res->base.source_position = token.source_position;
370 * Allocate an expression node of given kind and initialize all
373 * @param kind the kind of the expression to allocate
375 static expression_t *allocate_expression_zero(expression_kind_t kind)
377 size_t size = get_expression_struct_size(kind);
378 expression_t *res = allocate_ast_zero(size);
380 res->base.kind = kind;
381 res->base.type = type_error_type;
382 res->base.source_position = token.source_position;
387 * Creates a new invalid expression at the source position
388 * of the current token.
390 static expression_t *create_invalid_expression(void)
392 return allocate_expression_zero(EXPR_INVALID);
396 * Creates a new invalid statement.
398 static statement_t *create_invalid_statement(void)
400 return allocate_statement_zero(STATEMENT_INVALID);
404 * Allocate a new empty statement.
406 static statement_t *create_empty_statement(void)
408 return allocate_statement_zero(STATEMENT_EMPTY);
411 static function_parameter_t *allocate_parameter(type_t *const type)
413 function_parameter_t *const param
414 = obstack_alloc(type_obst, sizeof(*param));
415 memset(param, 0, sizeof(*param));
421 * Returns the size of an initializer node.
423 * @param kind the initializer kind
425 static size_t get_initializer_size(initializer_kind_t kind)
427 static const size_t sizes[] = {
428 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
429 [INITIALIZER_STRING] = sizeof(initializer_string_t),
430 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
431 [INITIALIZER_LIST] = sizeof(initializer_list_t),
432 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
434 assert(kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate an initializer node of given kind and initialize all
443 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
445 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
452 * Returns the index of the top element of the environment stack.
454 static size_t environment_top(void)
456 return ARR_LEN(environment_stack);
460 * Returns the index of the top element of the global label stack.
462 static size_t label_top(void)
464 return ARR_LEN(label_stack);
468 * Return the next token.
470 static inline void next_token(void)
472 token = lookahead_buffer[lookahead_bufpos];
473 lookahead_buffer[lookahead_bufpos] = lexer_token;
476 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
479 print_token(stderr, &token);
480 fprintf(stderr, "\n");
484 static inline bool next_if(int const type)
486 if (token.type == type) {
495 * Return the next token with a given lookahead.
497 static inline const token_t *look_ahead(size_t num)
499 assert(0 < num && num <= MAX_LOOKAHEAD);
500 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
501 return &lookahead_buffer[pos];
505 * Adds a token type to the token type anchor set (a multi-set).
507 static void add_anchor_token(int token_type)
509 assert(0 <= token_type && token_type < T_LAST_TOKEN);
510 ++token_anchor_set[token_type];
514 * Set the number of tokens types of the given type
515 * to zero and return the old count.
517 static int save_and_reset_anchor_state(int token_type)
519 assert(0 <= token_type && token_type < T_LAST_TOKEN);
520 int count = token_anchor_set[token_type];
521 token_anchor_set[token_type] = 0;
526 * Restore the number of token types to the given count.
528 static void restore_anchor_state(int token_type, int count)
530 assert(0 <= token_type && token_type < T_LAST_TOKEN);
531 token_anchor_set[token_type] = count;
535 * Remove a token type from the token type anchor set (a multi-set).
537 static void rem_anchor_token(int token_type)
539 assert(0 <= token_type && token_type < T_LAST_TOKEN);
540 assert(token_anchor_set[token_type] != 0);
541 --token_anchor_set[token_type];
545 * Return true if the token type of the current token is
548 static bool at_anchor(void)
552 return token_anchor_set[token.type];
556 * Eat tokens until a matching token type is found.
558 static void eat_until_matching_token(int type)
562 case '(': end_token = ')'; break;
563 case '{': end_token = '}'; break;
564 case '[': end_token = ']'; break;
565 default: end_token = type; break;
568 unsigned parenthesis_count = 0;
569 unsigned brace_count = 0;
570 unsigned bracket_count = 0;
571 while (token.type != end_token ||
572 parenthesis_count != 0 ||
574 bracket_count != 0) {
575 switch (token.type) {
577 case '(': ++parenthesis_count; break;
578 case '{': ++brace_count; break;
579 case '[': ++bracket_count; break;
582 if (parenthesis_count > 0)
592 if (bracket_count > 0)
595 if (token.type == end_token &&
596 parenthesis_count == 0 &&
610 * Eat input tokens until an anchor is found.
612 static void eat_until_anchor(void)
614 while (token_anchor_set[token.type] == 0) {
615 if (token.type == '(' || token.type == '{' || token.type == '[')
616 eat_until_matching_token(token.type);
622 * Eat a whole block from input tokens.
624 static void eat_block(void)
626 eat_until_matching_token('{');
630 #define eat(token_type) (assert(token.type == (token_type)), next_token())
633 * Report a parse error because an expected token was not found.
636 #if defined __GNUC__ && __GNUC__ >= 4
637 __attribute__((sentinel))
639 void parse_error_expected(const char *message, ...)
641 if (message != NULL) {
642 errorf(HERE, "%s", message);
645 va_start(ap, message);
646 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
651 * Report an incompatible type.
653 static void type_error_incompatible(const char *msg,
654 const source_position_t *source_position, type_t *type1, type_t *type2)
656 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
661 * Expect the current token is the expected token.
662 * If not, generate an error, eat the current statement,
663 * and goto the error_label label.
665 #define expect(expected, error_label) \
667 if (UNLIKELY(token.type != (expected))) { \
668 parse_error_expected(NULL, (expected), NULL); \
669 add_anchor_token(expected); \
670 eat_until_anchor(); \
671 next_if((expected)); \
672 rem_anchor_token(expected); \
679 * Push a given scope on the scope stack and make it the
682 static scope_t *scope_push(scope_t *new_scope)
684 if (current_scope != NULL) {
685 new_scope->depth = current_scope->depth + 1;
688 scope_t *old_scope = current_scope;
689 current_scope = new_scope;
694 * Pop the current scope from the scope stack.
696 static void scope_pop(scope_t *old_scope)
698 current_scope = old_scope;
702 * Search an entity by its symbol in a given namespace.
704 static entity_t *get_entity(const symbol_t *const symbol,
705 namespace_tag_t namespc)
707 assert(namespc != NAMESPACE_INVALID);
708 entity_t *entity = symbol->entity;
709 for (; entity != NULL; entity = entity->base.symbol_next) {
710 if (entity->base.namespc == namespc)
717 /* §6.2.3:1 24) There is only one name space for tags even though three are
719 static entity_t *get_tag(symbol_t const *const symbol,
720 entity_kind_tag_t const kind)
722 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
723 if (entity != NULL && entity->kind != kind) {
725 "'%Y' defined as wrong kind of tag (previous definition %P)",
726 symbol, &entity->base.source_position);
733 * pushs an entity on the environment stack and links the corresponding symbol
736 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
738 symbol_t *symbol = entity->base.symbol;
739 entity_namespace_t namespc = entity->base.namespc;
740 assert(namespc != NAMESPACE_INVALID);
742 /* replace/add entity into entity list of the symbol */
745 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
750 /* replace an entry? */
751 if (iter->base.namespc == namespc) {
752 entity->base.symbol_next = iter->base.symbol_next;
758 /* remember old declaration */
760 entry.symbol = symbol;
761 entry.old_entity = iter;
762 entry.namespc = namespc;
763 ARR_APP1(stack_entry_t, *stack_ptr, entry);
767 * Push an entity on the environment stack.
769 static void environment_push(entity_t *entity)
771 assert(entity->base.source_position.input_name != NULL);
772 assert(entity->base.parent_scope != NULL);
773 stack_push(&environment_stack, entity);
777 * Push a declaration on the global label stack.
779 * @param declaration the declaration
781 static void label_push(entity_t *label)
783 /* we abuse the parameters scope as parent for the labels */
784 label->base.parent_scope = ¤t_function->parameters;
785 stack_push(&label_stack, label);
789 * pops symbols from the environment stack until @p new_top is the top element
791 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
793 stack_entry_t *stack = *stack_ptr;
794 size_t top = ARR_LEN(stack);
797 assert(new_top <= top);
801 for (i = top; i > new_top; --i) {
802 stack_entry_t *entry = &stack[i - 1];
804 entity_t *old_entity = entry->old_entity;
805 symbol_t *symbol = entry->symbol;
806 entity_namespace_t namespc = entry->namespc;
808 /* replace with old_entity/remove */
811 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
813 assert(iter != NULL);
814 /* replace an entry? */
815 if (iter->base.namespc == namespc)
819 /* restore definition from outer scopes (if there was one) */
820 if (old_entity != NULL) {
821 old_entity->base.symbol_next = iter->base.symbol_next;
822 *anchor = old_entity;
824 /* remove entry from list */
825 *anchor = iter->base.symbol_next;
829 ARR_SHRINKLEN(*stack_ptr, new_top);
833 * Pop all entries from the environment stack until the new_top
836 * @param new_top the new stack top
838 static void environment_pop_to(size_t new_top)
840 stack_pop_to(&environment_stack, new_top);
844 * Pop all entries from the global label stack until the new_top
847 * @param new_top the new stack top
849 static void label_pop_to(size_t new_top)
851 stack_pop_to(&label_stack, new_top);
854 static int get_akind_rank(atomic_type_kind_t akind)
860 * Return the type rank for an atomic type.
862 static int get_rank(const type_t *type)
864 assert(!is_typeref(type));
865 if (type->kind == TYPE_ENUM)
866 return get_akind_rank(type->enumt.akind);
868 assert(type->kind == TYPE_ATOMIC);
869 return get_akind_rank(type->atomic.akind);
873 * §6.3.1.1:2 Do integer promotion for a given type.
875 * @param type the type to promote
876 * @return the promoted type
878 static type_t *promote_integer(type_t *type)
880 if (type->kind == TYPE_BITFIELD)
881 type = type->bitfield.base_type;
883 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
890 * Create a cast expression.
892 * @param expression the expression to cast
893 * @param dest_type the destination type
895 static expression_t *create_cast_expression(expression_t *expression,
898 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
900 cast->unary.value = expression;
901 cast->base.type = dest_type;
907 * Check if a given expression represents a null pointer constant.
909 * @param expression the expression to check
911 static bool is_null_pointer_constant(const expression_t *expression)
913 /* skip void* cast */
914 if (expression->kind == EXPR_UNARY_CAST ||
915 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
916 type_t *const type = skip_typeref(expression->base.type);
917 if (types_compatible(type, type_void_ptr))
918 expression = expression->unary.value;
921 type_t *const type = skip_typeref(expression->base.type);
922 if (!is_type_integer(type))
924 switch (is_constant_expression(expression)) {
925 case EXPR_CLASS_ERROR: return true;
926 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
927 default: return false;
932 * Create an implicit cast expression.
934 * @param expression the expression to cast
935 * @param dest_type the destination type
937 static expression_t *create_implicit_cast(expression_t *expression,
940 type_t *const source_type = expression->base.type;
942 if (source_type == dest_type)
945 return create_cast_expression(expression, dest_type);
948 typedef enum assign_error_t {
950 ASSIGN_ERROR_INCOMPATIBLE,
951 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
952 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
953 ASSIGN_WARNING_POINTER_FROM_INT,
954 ASSIGN_WARNING_INT_FROM_POINTER
957 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
958 const expression_t *const right,
960 const source_position_t *source_position)
962 type_t *const orig_type_right = right->base.type;
963 type_t *const type_left = skip_typeref(orig_type_left);
964 type_t *const type_right = skip_typeref(orig_type_right);
969 case ASSIGN_ERROR_INCOMPATIBLE:
970 errorf(source_position,
971 "destination type '%T' in %s is incompatible with type '%T'",
972 orig_type_left, context, orig_type_right);
975 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
977 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
978 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
980 /* the left type has all qualifiers from the right type */
981 unsigned missing_qualifiers
982 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
983 warningf(source_position,
984 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
985 orig_type_left, context, orig_type_right, missing_qualifiers);
990 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
992 warningf(source_position,
993 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
994 orig_type_left, context, right, orig_type_right);
998 case ASSIGN_WARNING_POINTER_FROM_INT:
1000 warningf(source_position,
1001 "%s makes pointer '%T' from integer '%T' without a cast",
1002 context, orig_type_left, orig_type_right);
1006 case ASSIGN_WARNING_INT_FROM_POINTER:
1007 if (warning.other) {
1008 warningf(source_position,
1009 "%s makes integer '%T' from pointer '%T' without a cast",
1010 context, orig_type_left, orig_type_right);
1015 panic("invalid error value");
1019 /** Implements the rules from §6.5.16.1 */
1020 static assign_error_t semantic_assign(type_t *orig_type_left,
1021 const expression_t *const right)
1023 type_t *const orig_type_right = right->base.type;
1024 type_t *const type_left = skip_typeref(orig_type_left);
1025 type_t *const type_right = skip_typeref(orig_type_right);
1027 if (is_type_pointer(type_left)) {
1028 if (is_null_pointer_constant(right)) {
1029 return ASSIGN_SUCCESS;
1030 } else if (is_type_pointer(type_right)) {
1031 type_t *points_to_left
1032 = skip_typeref(type_left->pointer.points_to);
1033 type_t *points_to_right
1034 = skip_typeref(type_right->pointer.points_to);
1035 assign_error_t res = ASSIGN_SUCCESS;
1037 /* the left type has all qualifiers from the right type */
1038 unsigned missing_qualifiers
1039 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1040 if (missing_qualifiers != 0) {
1041 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1044 points_to_left = get_unqualified_type(points_to_left);
1045 points_to_right = get_unqualified_type(points_to_right);
1047 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1050 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1051 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1052 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1055 if (!types_compatible(points_to_left, points_to_right)) {
1056 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1060 } else if (is_type_integer(type_right)) {
1061 return ASSIGN_WARNING_POINTER_FROM_INT;
1063 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1064 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1065 && is_type_pointer(type_right))) {
1066 return ASSIGN_SUCCESS;
1067 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1068 type_t *const unqual_type_left = get_unqualified_type(type_left);
1069 type_t *const unqual_type_right = get_unqualified_type(type_right);
1070 if (types_compatible(unqual_type_left, unqual_type_right)) {
1071 return ASSIGN_SUCCESS;
1073 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1074 return ASSIGN_WARNING_INT_FROM_POINTER;
1077 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1078 return ASSIGN_SUCCESS;
1080 return ASSIGN_ERROR_INCOMPATIBLE;
1083 static expression_t *parse_constant_expression(void)
1085 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1087 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1088 errorf(&result->base.source_position,
1089 "expression '%E' is not constant", result);
1095 static expression_t *parse_assignment_expression(void)
1097 return parse_subexpression(PREC_ASSIGNMENT);
1100 static void warn_string_concat(const source_position_t *pos)
1102 if (warning.traditional) {
1103 warningf(pos, "traditional C rejects string constant concatenation");
1107 static string_t parse_string_literals(void)
1109 assert(token.type == T_STRING_LITERAL);
1110 string_t result = token.literal;
1114 while (token.type == T_STRING_LITERAL) {
1115 warn_string_concat(&token.source_position);
1116 result = concat_strings(&result, &token.literal);
1124 * compare two string, ignoring double underscores on the second.
1126 static int strcmp_underscore(const char *s1, const char *s2)
1128 if (s2[0] == '_' && s2[1] == '_') {
1129 size_t len2 = strlen(s2);
1130 size_t len1 = strlen(s1);
1131 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1132 return strncmp(s1, s2+2, len2-4);
1136 return strcmp(s1, s2);
1139 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1141 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1142 attribute->kind = kind;
1147 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1150 * __attribute__ ( ( attribute-list ) )
1154 * attribute_list , attrib
1159 * any-word ( identifier )
1160 * any-word ( identifier , nonempty-expr-list )
1161 * any-word ( expr-list )
1163 * where the "identifier" must not be declared as a type, and
1164 * "any-word" may be any identifier (including one declared as a
1165 * type), a reserved word storage class specifier, type specifier or
1166 * type qualifier. ??? This still leaves out most reserved keywords
1167 * (following the old parser), shouldn't we include them, and why not
1168 * allow identifiers declared as types to start the arguments?
1170 * Matze: this all looks confusing and little systematic, so we're even less
1171 * strict and parse any list of things which are identifiers or
1172 * (assignment-)expressions.
1174 static attribute_argument_t *parse_attribute_arguments(void)
1176 attribute_argument_t *first = NULL;
1177 attribute_argument_t **anchor = &first;
1178 if (token.type != ')') do {
1179 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1181 /* is it an identifier */
1182 if (token.type == T_IDENTIFIER
1183 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1184 symbol_t *symbol = token.symbol;
1185 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1186 argument->v.symbol = symbol;
1189 /* must be an expression */
1190 expression_t *expression = parse_assignment_expression();
1192 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1193 argument->v.expression = expression;
1196 /* append argument */
1198 anchor = &argument->next;
1199 } while (next_if(','));
1200 expect(')', end_error);
1209 static attribute_t *parse_attribute_asm(void)
1213 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1215 expect('(', end_error);
1216 attribute->a.arguments = parse_attribute_arguments();
1223 static symbol_t *get_symbol_from_token(void)
1225 switch(token.type) {
1227 return token.symbol;
1256 /* maybe we need more tokens ... add them on demand */
1257 return get_token_symbol(&token);
1263 static attribute_t *parse_attribute_gnu_single(void)
1265 /* parse "any-word" */
1266 symbol_t *symbol = get_symbol_from_token();
1267 if (symbol == NULL) {
1268 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1272 const char *name = symbol->string;
1275 attribute_kind_t kind;
1276 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1277 if (kind > ATTRIBUTE_GNU_LAST) {
1278 if (warning.attribute) {
1279 warningf(HERE, "unknown attribute '%s' ignored", name);
1281 /* TODO: we should still save the attribute in the list... */
1282 kind = ATTRIBUTE_UNKNOWN;
1286 const char *attribute_name = get_attribute_name(kind);
1287 if (attribute_name != NULL
1288 && strcmp_underscore(attribute_name, name) == 0)
1292 attribute_t *attribute = allocate_attribute_zero(kind);
1294 /* parse arguments */
1296 attribute->a.arguments = parse_attribute_arguments();
1301 static attribute_t *parse_attribute_gnu(void)
1303 attribute_t *first = NULL;
1304 attribute_t **anchor = &first;
1306 eat(T___attribute__);
1307 expect('(', end_error);
1308 expect('(', end_error);
1310 if (token.type != ')') do {
1311 attribute_t *attribute = parse_attribute_gnu_single();
1312 if (attribute == NULL)
1315 *anchor = attribute;
1316 anchor = &attribute->next;
1317 } while (next_if(','));
1318 expect(')', end_error);
1319 expect(')', end_error);
1325 /** Parse attributes. */
1326 static attribute_t *parse_attributes(attribute_t *first)
1328 attribute_t **anchor = &first;
1330 while (*anchor != NULL)
1331 anchor = &(*anchor)->next;
1333 attribute_t *attribute;
1334 switch (token.type) {
1335 case T___attribute__:
1336 attribute = parse_attribute_gnu();
1337 if (attribute == NULL)
1342 attribute = parse_attribute_asm();
1347 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1352 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1355 case T__forceinline:
1357 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1362 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1367 /* TODO record modifier */
1369 warningf(HERE, "Ignoring declaration modifier %K", &token);
1370 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1377 *anchor = attribute;
1378 anchor = &attribute->next;
1382 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1384 static entity_t *determine_lhs_ent(expression_t *const expr,
1387 switch (expr->kind) {
1388 case EXPR_REFERENCE: {
1389 entity_t *const entity = expr->reference.entity;
1390 /* we should only find variables as lvalues... */
1391 if (entity->base.kind != ENTITY_VARIABLE
1392 && entity->base.kind != ENTITY_PARAMETER)
1398 case EXPR_ARRAY_ACCESS: {
1399 expression_t *const ref = expr->array_access.array_ref;
1400 entity_t * ent = NULL;
1401 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1402 ent = determine_lhs_ent(ref, lhs_ent);
1405 mark_vars_read(expr->select.compound, lhs_ent);
1407 mark_vars_read(expr->array_access.index, lhs_ent);
1412 if (is_type_compound(skip_typeref(expr->base.type))) {
1413 return determine_lhs_ent(expr->select.compound, lhs_ent);
1415 mark_vars_read(expr->select.compound, lhs_ent);
1420 case EXPR_UNARY_DEREFERENCE: {
1421 expression_t *const val = expr->unary.value;
1422 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1424 return determine_lhs_ent(val->unary.value, lhs_ent);
1426 mark_vars_read(val, NULL);
1432 mark_vars_read(expr, NULL);
1437 #define ENT_ANY ((entity_t*)-1)
1440 * Mark declarations, which are read. This is used to detect variables, which
1444 * x is not marked as "read", because it is only read to calculate its own new
1448 * x and y are not detected as "not read", because multiple variables are
1451 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1453 switch (expr->kind) {
1454 case EXPR_REFERENCE: {
1455 entity_t *const entity = expr->reference.entity;
1456 if (entity->kind != ENTITY_VARIABLE
1457 && entity->kind != ENTITY_PARAMETER)
1460 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1461 if (entity->kind == ENTITY_VARIABLE) {
1462 entity->variable.read = true;
1464 entity->parameter.read = true;
1471 // TODO respect pure/const
1472 mark_vars_read(expr->call.function, NULL);
1473 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1474 mark_vars_read(arg->expression, NULL);
1478 case EXPR_CONDITIONAL:
1479 // TODO lhs_decl should depend on whether true/false have an effect
1480 mark_vars_read(expr->conditional.condition, NULL);
1481 if (expr->conditional.true_expression != NULL)
1482 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1483 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1487 if (lhs_ent == ENT_ANY
1488 && !is_type_compound(skip_typeref(expr->base.type)))
1490 mark_vars_read(expr->select.compound, lhs_ent);
1493 case EXPR_ARRAY_ACCESS: {
1494 expression_t *const ref = expr->array_access.array_ref;
1495 mark_vars_read(ref, lhs_ent);
1496 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1497 mark_vars_read(expr->array_access.index, lhs_ent);
1502 mark_vars_read(expr->va_arge.ap, lhs_ent);
1506 mark_vars_read(expr->va_copye.src, lhs_ent);
1509 case EXPR_UNARY_CAST:
1510 /* Special case: Use void cast to mark a variable as "read" */
1511 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1516 case EXPR_UNARY_THROW:
1517 if (expr->unary.value == NULL)
1520 case EXPR_UNARY_DEREFERENCE:
1521 case EXPR_UNARY_DELETE:
1522 case EXPR_UNARY_DELETE_ARRAY:
1523 if (lhs_ent == ENT_ANY)
1527 case EXPR_UNARY_NEGATE:
1528 case EXPR_UNARY_PLUS:
1529 case EXPR_UNARY_BITWISE_NEGATE:
1530 case EXPR_UNARY_NOT:
1531 case EXPR_UNARY_TAKE_ADDRESS:
1532 case EXPR_UNARY_POSTFIX_INCREMENT:
1533 case EXPR_UNARY_POSTFIX_DECREMENT:
1534 case EXPR_UNARY_PREFIX_INCREMENT:
1535 case EXPR_UNARY_PREFIX_DECREMENT:
1536 case EXPR_UNARY_CAST_IMPLICIT:
1537 case EXPR_UNARY_ASSUME:
1539 mark_vars_read(expr->unary.value, lhs_ent);
1542 case EXPR_BINARY_ADD:
1543 case EXPR_BINARY_SUB:
1544 case EXPR_BINARY_MUL:
1545 case EXPR_BINARY_DIV:
1546 case EXPR_BINARY_MOD:
1547 case EXPR_BINARY_EQUAL:
1548 case EXPR_BINARY_NOTEQUAL:
1549 case EXPR_BINARY_LESS:
1550 case EXPR_BINARY_LESSEQUAL:
1551 case EXPR_BINARY_GREATER:
1552 case EXPR_BINARY_GREATEREQUAL:
1553 case EXPR_BINARY_BITWISE_AND:
1554 case EXPR_BINARY_BITWISE_OR:
1555 case EXPR_BINARY_BITWISE_XOR:
1556 case EXPR_BINARY_LOGICAL_AND:
1557 case EXPR_BINARY_LOGICAL_OR:
1558 case EXPR_BINARY_SHIFTLEFT:
1559 case EXPR_BINARY_SHIFTRIGHT:
1560 case EXPR_BINARY_COMMA:
1561 case EXPR_BINARY_ISGREATER:
1562 case EXPR_BINARY_ISGREATEREQUAL:
1563 case EXPR_BINARY_ISLESS:
1564 case EXPR_BINARY_ISLESSEQUAL:
1565 case EXPR_BINARY_ISLESSGREATER:
1566 case EXPR_BINARY_ISUNORDERED:
1567 mark_vars_read(expr->binary.left, lhs_ent);
1568 mark_vars_read(expr->binary.right, lhs_ent);
1571 case EXPR_BINARY_ASSIGN:
1572 case EXPR_BINARY_MUL_ASSIGN:
1573 case EXPR_BINARY_DIV_ASSIGN:
1574 case EXPR_BINARY_MOD_ASSIGN:
1575 case EXPR_BINARY_ADD_ASSIGN:
1576 case EXPR_BINARY_SUB_ASSIGN:
1577 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1578 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1579 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1580 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1581 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1582 if (lhs_ent == ENT_ANY)
1584 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1585 mark_vars_read(expr->binary.right, lhs_ent);
1590 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1596 case EXPR_STRING_LITERAL:
1597 case EXPR_WIDE_STRING_LITERAL:
1598 case EXPR_COMPOUND_LITERAL: // TODO init?
1600 case EXPR_CLASSIFY_TYPE:
1603 case EXPR_BUILTIN_CONSTANT_P:
1604 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1606 case EXPR_STATEMENT: // TODO
1607 case EXPR_LABEL_ADDRESS:
1608 case EXPR_REFERENCE_ENUM_VALUE:
1612 panic("unhandled expression");
1615 static designator_t *parse_designation(void)
1617 designator_t *result = NULL;
1618 designator_t **anchor = &result;
1621 designator_t *designator;
1622 switch (token.type) {
1624 designator = allocate_ast_zero(sizeof(designator[0]));
1625 designator->source_position = token.source_position;
1627 add_anchor_token(']');
1628 designator->array_index = parse_constant_expression();
1629 rem_anchor_token(']');
1630 expect(']', end_error);
1633 designator = allocate_ast_zero(sizeof(designator[0]));
1634 designator->source_position = token.source_position;
1636 if (token.type != T_IDENTIFIER) {
1637 parse_error_expected("while parsing designator",
1638 T_IDENTIFIER, NULL);
1641 designator->symbol = token.symbol;
1645 expect('=', end_error);
1649 assert(designator != NULL);
1650 *anchor = designator;
1651 anchor = &designator->next;
1657 static initializer_t *initializer_from_string(array_type_t *const type,
1658 const string_t *const string)
1660 /* TODO: check len vs. size of array type */
1663 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1664 initializer->string.string = *string;
1669 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1670 const string_t *const string)
1672 /* TODO: check len vs. size of array type */
1675 initializer_t *const initializer =
1676 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1677 initializer->wide_string.string = *string;
1683 * Build an initializer from a given expression.
1685 static initializer_t *initializer_from_expression(type_t *orig_type,
1686 expression_t *expression)
1688 /* TODO check that expression is a constant expression */
1690 /* §6.7.8.14/15 char array may be initialized by string literals */
1691 type_t *type = skip_typeref(orig_type);
1692 type_t *expr_type_orig = expression->base.type;
1693 type_t *expr_type = skip_typeref(expr_type_orig);
1695 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1696 array_type_t *const array_type = &type->array;
1697 type_t *const element_type = skip_typeref(array_type->element_type);
1699 if (element_type->kind == TYPE_ATOMIC) {
1700 atomic_type_kind_t akind = element_type->atomic.akind;
1701 switch (expression->kind) {
1702 case EXPR_STRING_LITERAL:
1703 if (akind == ATOMIC_TYPE_CHAR
1704 || akind == ATOMIC_TYPE_SCHAR
1705 || akind == ATOMIC_TYPE_UCHAR) {
1706 return initializer_from_string(array_type,
1707 &expression->string_literal.value);
1711 case EXPR_WIDE_STRING_LITERAL: {
1712 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1713 if (get_unqualified_type(element_type) == bare_wchar_type) {
1714 return initializer_from_wide_string(array_type,
1715 &expression->string_literal.value);
1726 assign_error_t error = semantic_assign(type, expression);
1727 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1729 report_assign_error(error, type, expression, "initializer",
1730 &expression->base.source_position);
1732 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1733 result->value.value = create_implicit_cast(expression, type);
1739 * Checks if a given expression can be used as an constant initializer.
1741 static bool is_initializer_constant(const expression_t *expression)
1744 is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1745 is_address_constant(expression) != EXPR_CLASS_VARIABLE;
1749 * Parses an scalar initializer.
1751 * §6.7.8.11; eat {} without warning
1753 static initializer_t *parse_scalar_initializer(type_t *type,
1754 bool must_be_constant)
1756 /* there might be extra {} hierarchies */
1758 if (token.type == '{') {
1760 warningf(HERE, "extra curly braces around scalar initializer");
1764 } while (token.type == '{');
1767 expression_t *expression = parse_assignment_expression();
1768 mark_vars_read(expression, NULL);
1769 if (must_be_constant && !is_initializer_constant(expression)) {
1770 errorf(&expression->base.source_position,
1771 "initialisation expression '%E' is not constant",
1775 initializer_t *initializer = initializer_from_expression(type, expression);
1777 if (initializer == NULL) {
1778 errorf(&expression->base.source_position,
1779 "expression '%E' (type '%T') doesn't match expected type '%T'",
1780 expression, expression->base.type, type);
1785 bool additional_warning_displayed = false;
1786 while (braces > 0) {
1788 if (token.type != '}') {
1789 if (!additional_warning_displayed && warning.other) {
1790 warningf(HERE, "additional elements in scalar initializer");
1791 additional_warning_displayed = true;
1802 * An entry in the type path.
1804 typedef struct type_path_entry_t type_path_entry_t;
1805 struct type_path_entry_t {
1806 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1808 size_t index; /**< For array types: the current index. */
1809 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1814 * A type path expression a position inside compound or array types.
1816 typedef struct type_path_t type_path_t;
1817 struct type_path_t {
1818 type_path_entry_t *path; /**< An flexible array containing the current path. */
1819 type_t *top_type; /**< type of the element the path points */
1820 size_t max_index; /**< largest index in outermost array */
1824 * Prints a type path for debugging.
1826 static __attribute__((unused)) void debug_print_type_path(
1827 const type_path_t *path)
1829 size_t len = ARR_LEN(path->path);
1831 for (size_t i = 0; i < len; ++i) {
1832 const type_path_entry_t *entry = & path->path[i];
1834 type_t *type = skip_typeref(entry->type);
1835 if (is_type_compound(type)) {
1836 /* in gcc mode structs can have no members */
1837 if (entry->v.compound_entry == NULL) {
1841 fprintf(stderr, ".%s",
1842 entry->v.compound_entry->base.symbol->string);
1843 } else if (is_type_array(type)) {
1844 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1846 fprintf(stderr, "-INVALID-");
1849 if (path->top_type != NULL) {
1850 fprintf(stderr, " (");
1851 print_type(path->top_type);
1852 fprintf(stderr, ")");
1857 * Return the top type path entry, ie. in a path
1858 * (type).a.b returns the b.
1860 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1862 size_t len = ARR_LEN(path->path);
1864 return &path->path[len-1];
1868 * Enlarge the type path by an (empty) element.
1870 static type_path_entry_t *append_to_type_path(type_path_t *path)
1872 size_t len = ARR_LEN(path->path);
1873 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1875 type_path_entry_t *result = & path->path[len];
1876 memset(result, 0, sizeof(result[0]));
1881 * Descending into a sub-type. Enter the scope of the current top_type.
1883 static void descend_into_subtype(type_path_t *path)
1885 type_t *orig_top_type = path->top_type;
1886 type_t *top_type = skip_typeref(orig_top_type);
1888 type_path_entry_t *top = append_to_type_path(path);
1889 top->type = top_type;
1891 if (is_type_compound(top_type)) {
1892 compound_t *compound = top_type->compound.compound;
1893 entity_t *entry = compound->members.entities;
1895 if (entry != NULL) {
1896 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1897 top->v.compound_entry = &entry->declaration;
1898 path->top_type = entry->declaration.type;
1900 path->top_type = NULL;
1902 } else if (is_type_array(top_type)) {
1904 path->top_type = top_type->array.element_type;
1906 assert(!is_type_valid(top_type));
1911 * Pop an entry from the given type path, ie. returning from
1912 * (type).a.b to (type).a
1914 static void ascend_from_subtype(type_path_t *path)
1916 type_path_entry_t *top = get_type_path_top(path);
1918 path->top_type = top->type;
1920 size_t len = ARR_LEN(path->path);
1921 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1925 * Pop entries from the given type path until the given
1926 * path level is reached.
1928 static void ascend_to(type_path_t *path, size_t top_path_level)
1930 size_t len = ARR_LEN(path->path);
1932 while (len > top_path_level) {
1933 ascend_from_subtype(path);
1934 len = ARR_LEN(path->path);
1938 static bool walk_designator(type_path_t *path, const designator_t *designator,
1939 bool used_in_offsetof)
1941 for (; designator != NULL; designator = designator->next) {
1942 type_path_entry_t *top = get_type_path_top(path);
1943 type_t *orig_type = top->type;
1945 type_t *type = skip_typeref(orig_type);
1947 if (designator->symbol != NULL) {
1948 symbol_t *symbol = designator->symbol;
1949 if (!is_type_compound(type)) {
1950 if (is_type_valid(type)) {
1951 errorf(&designator->source_position,
1952 "'.%Y' designator used for non-compound type '%T'",
1956 top->type = type_error_type;
1957 top->v.compound_entry = NULL;
1958 orig_type = type_error_type;
1960 compound_t *compound = type->compound.compound;
1961 entity_t *iter = compound->members.entities;
1962 for (; iter != NULL; iter = iter->base.next) {
1963 if (iter->base.symbol == symbol) {
1968 errorf(&designator->source_position,
1969 "'%T' has no member named '%Y'", orig_type, symbol);
1972 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1973 if (used_in_offsetof) {
1974 type_t *real_type = skip_typeref(iter->declaration.type);
1975 if (real_type->kind == TYPE_BITFIELD) {
1976 errorf(&designator->source_position,
1977 "offsetof designator '%Y' must not specify bitfield",
1983 top->type = orig_type;
1984 top->v.compound_entry = &iter->declaration;
1985 orig_type = iter->declaration.type;
1988 expression_t *array_index = designator->array_index;
1989 assert(designator->array_index != NULL);
1991 if (!is_type_array(type)) {
1992 if (is_type_valid(type)) {
1993 errorf(&designator->source_position,
1994 "[%E] designator used for non-array type '%T'",
1995 array_index, orig_type);
2000 long index = fold_constant_to_int(array_index);
2001 if (!used_in_offsetof) {
2003 errorf(&designator->source_position,
2004 "array index [%E] must be positive", array_index);
2005 } else if (type->array.size_constant) {
2006 long array_size = type->array.size;
2007 if (index >= array_size) {
2008 errorf(&designator->source_position,
2009 "designator [%E] (%d) exceeds array size %d",
2010 array_index, index, array_size);
2015 top->type = orig_type;
2016 top->v.index = (size_t) index;
2017 orig_type = type->array.element_type;
2019 path->top_type = orig_type;
2021 if (designator->next != NULL) {
2022 descend_into_subtype(path);
2028 static void advance_current_object(type_path_t *path, size_t top_path_level)
2030 type_path_entry_t *top = get_type_path_top(path);
2032 type_t *type = skip_typeref(top->type);
2033 if (is_type_union(type)) {
2034 /* in unions only the first element is initialized */
2035 top->v.compound_entry = NULL;
2036 } else if (is_type_struct(type)) {
2037 declaration_t *entry = top->v.compound_entry;
2039 entity_t *next_entity = entry->base.next;
2040 if (next_entity != NULL) {
2041 assert(is_declaration(next_entity));
2042 entry = &next_entity->declaration;
2047 top->v.compound_entry = entry;
2048 if (entry != NULL) {
2049 path->top_type = entry->type;
2052 } else if (is_type_array(type)) {
2053 assert(is_type_array(type));
2057 if (!type->array.size_constant || top->v.index < type->array.size) {
2061 assert(!is_type_valid(type));
2065 /* we're past the last member of the current sub-aggregate, try if we
2066 * can ascend in the type hierarchy and continue with another subobject */
2067 size_t len = ARR_LEN(path->path);
2069 if (len > top_path_level) {
2070 ascend_from_subtype(path);
2071 advance_current_object(path, top_path_level);
2073 path->top_type = NULL;
2078 * skip any {...} blocks until a closing bracket is reached.
2080 static void skip_initializers(void)
2084 while (token.type != '}') {
2085 if (token.type == T_EOF)
2087 if (token.type == '{') {
2095 static initializer_t *create_empty_initializer(void)
2097 static initializer_t empty_initializer
2098 = { .list = { { INITIALIZER_LIST }, 0 } };
2099 return &empty_initializer;
2103 * Parse a part of an initialiser for a struct or union,
2105 static initializer_t *parse_sub_initializer(type_path_t *path,
2106 type_t *outer_type, size_t top_path_level,
2107 parse_initializer_env_t *env)
2109 if (token.type == '}') {
2110 /* empty initializer */
2111 return create_empty_initializer();
2114 type_t *orig_type = path->top_type;
2115 type_t *type = NULL;
2117 if (orig_type == NULL) {
2118 /* We are initializing an empty compound. */
2120 type = skip_typeref(orig_type);
2123 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2126 designator_t *designator = NULL;
2127 if (token.type == '.' || token.type == '[') {
2128 designator = parse_designation();
2129 goto finish_designator;
2130 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2131 /* GNU-style designator ("identifier: value") */
2132 designator = allocate_ast_zero(sizeof(designator[0]));
2133 designator->source_position = token.source_position;
2134 designator->symbol = token.symbol;
2139 /* reset path to toplevel, evaluate designator from there */
2140 ascend_to(path, top_path_level);
2141 if (!walk_designator(path, designator, false)) {
2142 /* can't continue after designation error */
2146 initializer_t *designator_initializer
2147 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2148 designator_initializer->designator.designator = designator;
2149 ARR_APP1(initializer_t*, initializers, designator_initializer);
2151 orig_type = path->top_type;
2152 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2157 if (token.type == '{') {
2158 if (type != NULL && is_type_scalar(type)) {
2159 sub = parse_scalar_initializer(type, env->must_be_constant);
2162 if (env->entity != NULL) {
2164 "extra brace group at end of initializer for '%Y'",
2165 env->entity->base.symbol);
2167 errorf(HERE, "extra brace group at end of initializer");
2172 descend_into_subtype(path);
2175 add_anchor_token('}');
2176 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2178 rem_anchor_token('}');
2181 ascend_from_subtype(path);
2182 expect('}', end_error);
2184 expect('}', end_error);
2185 goto error_parse_next;
2189 /* must be an expression */
2190 expression_t *expression = parse_assignment_expression();
2191 mark_vars_read(expression, NULL);
2193 if (env->must_be_constant && !is_initializer_constant(expression)) {
2194 errorf(&expression->base.source_position,
2195 "Initialisation expression '%E' is not constant",
2200 /* we are already outside, ... */
2201 if (outer_type == NULL)
2202 goto error_parse_next;
2203 type_t *const outer_type_skip = skip_typeref(outer_type);
2204 if (is_type_compound(outer_type_skip) &&
2205 !outer_type_skip->compound.compound->complete) {
2206 goto error_parse_next;
2211 /* handle { "string" } special case */
2212 if ((expression->kind == EXPR_STRING_LITERAL
2213 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2214 && outer_type != NULL) {
2215 sub = initializer_from_expression(outer_type, expression);
2218 if (token.type != '}' && warning.other) {
2219 warningf(HERE, "excessive elements in initializer for type '%T'",
2222 /* TODO: eat , ... */
2227 /* descend into subtypes until expression matches type */
2229 orig_type = path->top_type;
2230 type = skip_typeref(orig_type);
2232 sub = initializer_from_expression(orig_type, expression);
2236 if (!is_type_valid(type)) {
2239 if (is_type_scalar(type)) {
2240 errorf(&expression->base.source_position,
2241 "expression '%E' doesn't match expected type '%T'",
2242 expression, orig_type);
2246 descend_into_subtype(path);
2250 /* update largest index of top array */
2251 const type_path_entry_t *first = &path->path[0];
2252 type_t *first_type = first->type;
2253 first_type = skip_typeref(first_type);
2254 if (is_type_array(first_type)) {
2255 size_t index = first->v.index;
2256 if (index > path->max_index)
2257 path->max_index = index;
2261 /* append to initializers list */
2262 ARR_APP1(initializer_t*, initializers, sub);
2265 if (warning.other) {
2266 if (env->entity != NULL) {
2267 warningf(HERE, "excess elements in initializer for '%Y'",
2268 env->entity->base.symbol);
2270 warningf(HERE, "excess elements in initializer");
2276 if (token.type == '}') {
2279 expect(',', end_error);
2280 if (token.type == '}') {
2285 /* advance to the next declaration if we are not at the end */
2286 advance_current_object(path, top_path_level);
2287 orig_type = path->top_type;
2288 if (orig_type != NULL)
2289 type = skip_typeref(orig_type);
2295 size_t len = ARR_LEN(initializers);
2296 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2297 initializer_t *result = allocate_ast_zero(size);
2298 result->kind = INITIALIZER_LIST;
2299 result->list.len = len;
2300 memcpy(&result->list.initializers, initializers,
2301 len * sizeof(initializers[0]));
2303 DEL_ARR_F(initializers);
2304 ascend_to(path, top_path_level+1);
2309 skip_initializers();
2310 DEL_ARR_F(initializers);
2311 ascend_to(path, top_path_level+1);
2315 static expression_t *make_size_literal(size_t value)
2317 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2318 literal->base.type = type_size_t;
2321 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2322 literal->literal.value = make_string(buf);
2328 * Parses an initializer. Parsers either a compound literal
2329 * (env->declaration == NULL) or an initializer of a declaration.
2331 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2333 type_t *type = skip_typeref(env->type);
2334 size_t max_index = 0;
2335 initializer_t *result;
2337 if (is_type_scalar(type)) {
2338 result = parse_scalar_initializer(type, env->must_be_constant);
2339 } else if (token.type == '{') {
2343 memset(&path, 0, sizeof(path));
2344 path.top_type = env->type;
2345 path.path = NEW_ARR_F(type_path_entry_t, 0);
2347 descend_into_subtype(&path);
2349 add_anchor_token('}');
2350 result = parse_sub_initializer(&path, env->type, 1, env);
2351 rem_anchor_token('}');
2353 max_index = path.max_index;
2354 DEL_ARR_F(path.path);
2356 expect('}', end_error);
2359 /* parse_scalar_initializer() also works in this case: we simply
2360 * have an expression without {} around it */
2361 result = parse_scalar_initializer(type, env->must_be_constant);
2364 /* §6.7.8:22 array initializers for arrays with unknown size determine
2365 * the array type size */
2366 if (is_type_array(type) && type->array.size_expression == NULL
2367 && result != NULL) {
2369 switch (result->kind) {
2370 case INITIALIZER_LIST:
2371 assert(max_index != 0xdeadbeaf);
2372 size = max_index + 1;
2375 case INITIALIZER_STRING:
2376 size = result->string.string.size;
2379 case INITIALIZER_WIDE_STRING:
2380 size = result->wide_string.string.size;
2383 case INITIALIZER_DESIGNATOR:
2384 case INITIALIZER_VALUE:
2385 /* can happen for parse errors */
2390 internal_errorf(HERE, "invalid initializer type");
2393 type_t *new_type = duplicate_type(type);
2395 new_type->array.size_expression = make_size_literal(size);
2396 new_type->array.size_constant = true;
2397 new_type->array.has_implicit_size = true;
2398 new_type->array.size = size;
2399 env->type = new_type;
2405 static void append_entity(scope_t *scope, entity_t *entity)
2407 if (scope->last_entity != NULL) {
2408 scope->last_entity->base.next = entity;
2410 scope->entities = entity;
2412 entity->base.parent_entity = current_entity;
2413 scope->last_entity = entity;
2417 static compound_t *parse_compound_type_specifier(bool is_struct)
2419 source_position_t const pos = *HERE;
2420 eat(is_struct ? T_struct : T_union);
2422 symbol_t *symbol = NULL;
2423 entity_t *entity = NULL;
2424 attribute_t *attributes = NULL;
2426 if (token.type == T___attribute__) {
2427 attributes = parse_attributes(NULL);
2430 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2431 if (token.type == T_IDENTIFIER) {
2432 /* the compound has a name, check if we have seen it already */
2433 symbol = token.symbol;
2434 entity = get_tag(symbol, kind);
2437 if (entity != NULL) {
2438 if (entity->base.parent_scope != current_scope &&
2439 (token.type == '{' || token.type == ';')) {
2440 /* we're in an inner scope and have a definition. Shadow
2441 * existing definition in outer scope */
2443 } else if (entity->compound.complete && token.type == '{') {
2444 errorf(&pos, "multiple definitions of '%s %Y' (previous definition %P)",
2445 is_struct ? "struct" : "union", symbol,
2446 &entity->base.source_position);
2447 /* clear members in the hope to avoid further errors */
2448 entity->compound.members.entities = NULL;
2451 } else if (token.type != '{') {
2452 char const *const msg =
2453 is_struct ? "while parsing struct type specifier" :
2454 "while parsing union type specifier";
2455 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2460 if (entity == NULL) {
2461 entity = allocate_entity_zero(kind);
2463 entity->compound.alignment = 1;
2464 entity->base.namespc = NAMESPACE_TAG;
2465 entity->base.source_position = pos;
2466 entity->base.symbol = symbol;
2467 entity->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(&entity->compound);
2477 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2478 if (symbol == NULL) {
2479 assert(anonymous_entity == NULL);
2480 anonymous_entity = entity;
2484 if (attributes != NULL) {
2485 handle_entity_attributes(attributes, entity);
2488 return &entity->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.namespc = NAMESPACE_NORMAL;
2513 entity->base.symbol = token.symbol;
2514 entity->base.source_position = token.source_position;
2518 expression_t *value = parse_constant_expression();
2520 value = create_implicit_cast(value, enum_type);
2521 entity->enum_value.value = value;
2526 record_entity(entity, false);
2527 } while (next_if(',') && token.type != '}');
2528 rem_anchor_token('}');
2530 expect('}', end_error);
2536 static type_t *parse_enum_specifier(void)
2538 source_position_t const pos = *HERE;
2543 switch (token.type) {
2545 symbol = token.symbol;
2546 entity = get_tag(symbol, ENTITY_ENUM);
2549 if (entity != NULL) {
2550 if (entity->base.parent_scope != current_scope &&
2551 (token.type == '{' || token.type == ';')) {
2552 /* we're in an inner scope and have a definition. Shadow
2553 * existing definition in outer scope */
2555 } else if (entity->enume.complete && token.type == '{') {
2556 errorf(&pos, "multiple definitions of 'enum %Y' (previous definition %P)",
2557 symbol, &entity->base.source_position);
2568 parse_error_expected("while parsing enum type specifier",
2569 T_IDENTIFIER, '{', NULL);
2573 if (entity == NULL) {
2574 entity = allocate_entity_zero(ENTITY_ENUM);
2575 entity->base.namespc = NAMESPACE_TAG;
2576 entity->base.source_position = pos;
2577 entity->base.symbol = symbol;
2578 entity->base.parent_scope = current_scope;
2581 type_t *const type = allocate_type_zero(TYPE_ENUM);
2582 type->enumt.enume = &entity->enume;
2583 type->enumt.akind = ATOMIC_TYPE_INT;
2585 if (token.type == '{') {
2586 if (symbol != NULL) {
2587 environment_push(entity);
2589 append_entity(current_scope, entity);
2590 entity->enume.complete = true;
2592 parse_enum_entries(type);
2593 parse_attributes(NULL);
2595 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2596 if (symbol == NULL) {
2597 assert(anonymous_entity == NULL);
2598 anonymous_entity = entity;
2600 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2601 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2609 * if a symbol is a typedef to another type, return true
2611 static bool is_typedef_symbol(symbol_t *symbol)
2613 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2614 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2617 static type_t *parse_typeof(void)
2623 expect('(', end_error);
2624 add_anchor_token(')');
2626 expression_t *expression = NULL;
2628 bool old_type_prop = in_type_prop;
2629 bool old_gcc_extension = in_gcc_extension;
2630 in_type_prop = true;
2632 while (next_if(T___extension__)) {
2633 /* This can be a prefix to a typename or an expression. */
2634 in_gcc_extension = true;
2636 switch (token.type) {
2638 if (is_typedef_symbol(token.symbol)) {
2640 type = parse_typename();
2643 expression = parse_expression();
2644 type = revert_automatic_type_conversion(expression);
2648 in_type_prop = old_type_prop;
2649 in_gcc_extension = old_gcc_extension;
2651 rem_anchor_token(')');
2652 expect(')', end_error);
2654 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2655 typeof_type->typeoft.expression = expression;
2656 typeof_type->typeoft.typeof_type = type;
2663 typedef enum specifiers_t {
2664 SPECIFIER_SIGNED = 1 << 0,
2665 SPECIFIER_UNSIGNED = 1 << 1,
2666 SPECIFIER_LONG = 1 << 2,
2667 SPECIFIER_INT = 1 << 3,
2668 SPECIFIER_DOUBLE = 1 << 4,
2669 SPECIFIER_CHAR = 1 << 5,
2670 SPECIFIER_WCHAR_T = 1 << 6,
2671 SPECIFIER_SHORT = 1 << 7,
2672 SPECIFIER_LONG_LONG = 1 << 8,
2673 SPECIFIER_FLOAT = 1 << 9,
2674 SPECIFIER_BOOL = 1 << 10,
2675 SPECIFIER_VOID = 1 << 11,
2676 SPECIFIER_INT8 = 1 << 12,
2677 SPECIFIER_INT16 = 1 << 13,
2678 SPECIFIER_INT32 = 1 << 14,
2679 SPECIFIER_INT64 = 1 << 15,
2680 SPECIFIER_INT128 = 1 << 16,
2681 SPECIFIER_COMPLEX = 1 << 17,
2682 SPECIFIER_IMAGINARY = 1 << 18,
2685 static type_t *get_typedef_type(symbol_t *symbol)
2687 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2688 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2691 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2692 type->typedeft.typedefe = &entity->typedefe;
2697 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2699 expect('(', end_error);
2701 attribute_property_argument_t *property
2702 = allocate_ast_zero(sizeof(*property));
2705 if (token.type != T_IDENTIFIER) {
2706 parse_error_expected("while parsing property declspec",
2707 T_IDENTIFIER, NULL);
2712 symbol_t *symbol = token.symbol;
2714 if (strcmp(symbol->string, "put") == 0) {
2716 } else if (strcmp(symbol->string, "get") == 0) {
2719 errorf(HERE, "expected put or get in property declspec");
2722 expect('=', end_error);
2723 if (token.type != T_IDENTIFIER) {
2724 parse_error_expected("while parsing property declspec",
2725 T_IDENTIFIER, NULL);
2729 property->put_symbol = token.symbol;
2731 property->get_symbol = token.symbol;
2734 } while (next_if(','));
2736 attribute->a.property = property;
2738 expect(')', end_error);
2744 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2746 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2747 if (next_if(T_restrict)) {
2748 kind = ATTRIBUTE_MS_RESTRICT;
2749 } else if (token.type == T_IDENTIFIER) {
2750 const char *name = token.symbol->string;
2752 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2754 const char *attribute_name = get_attribute_name(k);
2755 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2761 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2762 warningf(HERE, "unknown __declspec '%s' ignored", name);
2765 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2769 attribute_t *attribute = allocate_attribute_zero(kind);
2771 if (kind == ATTRIBUTE_MS_PROPERTY) {
2772 return parse_attribute_ms_property(attribute);
2775 /* parse arguments */
2777 attribute->a.arguments = parse_attribute_arguments();
2782 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2786 expect('(', end_error);
2791 add_anchor_token(')');
2793 attribute_t **anchor = &first;
2795 while (*anchor != NULL)
2796 anchor = &(*anchor)->next;
2798 attribute_t *attribute
2799 = parse_microsoft_extended_decl_modifier_single();
2800 if (attribute == NULL)
2803 *anchor = attribute;
2804 anchor = &attribute->next;
2805 } while (next_if(','));
2807 rem_anchor_token(')');
2808 expect(')', end_error);
2812 rem_anchor_token(')');
2816 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2818 entity_t *entity = allocate_entity_zero(kind);
2819 entity->base.namespc = NAMESPACE_NORMAL;
2820 entity->base.source_position = *HERE;
2821 entity->base.symbol = symbol;
2822 if (is_declaration(entity)) {
2823 entity->declaration.type = type_error_type;
2824 entity->declaration.implicit = true;
2825 } else if (kind == ENTITY_TYPEDEF) {
2826 entity->typedefe.type = type_error_type;
2827 entity->typedefe.builtin = true;
2829 if (kind != ENTITY_COMPOUND_MEMBER)
2830 record_entity(entity, false);
2834 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2836 type_t *type = NULL;
2837 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2838 unsigned type_specifiers = 0;
2839 bool newtype = false;
2840 bool saw_error = false;
2841 bool old_gcc_extension = in_gcc_extension;
2843 memset(specifiers, 0, sizeof(*specifiers));
2844 specifiers->source_position = token.source_position;
2847 specifiers->attributes = parse_attributes(specifiers->attributes);
2849 switch (token.type) {
2851 #define MATCH_STORAGE_CLASS(token, class) \
2853 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2854 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2856 specifiers->storage_class = class; \
2857 if (specifiers->thread_local) \
2858 goto check_thread_storage_class; \
2862 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2863 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2864 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2865 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2866 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2869 specifiers->attributes
2870 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2874 if (specifiers->thread_local) {
2875 errorf(HERE, "duplicate '__thread'");
2877 specifiers->thread_local = true;
2878 check_thread_storage_class:
2879 switch (specifiers->storage_class) {
2880 case STORAGE_CLASS_EXTERN:
2881 case STORAGE_CLASS_NONE:
2882 case STORAGE_CLASS_STATIC:
2886 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2887 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2888 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2889 wrong_thread_storage_class:
2890 errorf(HERE, "'__thread' used with '%s'", wrong);
2897 /* type qualifiers */
2898 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2900 qualifiers |= qualifier; \
2904 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2905 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2906 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2907 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2908 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2909 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2910 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2911 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2913 case T___extension__:
2915 in_gcc_extension = true;
2918 /* type specifiers */
2919 #define MATCH_SPECIFIER(token, specifier, name) \
2921 if (type_specifiers & specifier) { \
2922 errorf(HERE, "multiple " name " type specifiers given"); \
2924 type_specifiers |= specifier; \
2929 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2930 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2931 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2932 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2933 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2934 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2935 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2936 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2937 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2938 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2939 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2940 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2941 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2942 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2943 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2944 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2945 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2946 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2950 specifiers->is_inline = true;
2954 case T__forceinline:
2956 specifiers->modifiers |= DM_FORCEINLINE;
2961 if (type_specifiers & SPECIFIER_LONG_LONG) {
2962 errorf(HERE, "too many long type specifiers given");
2963 } else if (type_specifiers & SPECIFIER_LONG) {
2964 type_specifiers |= SPECIFIER_LONG_LONG;
2966 type_specifiers |= SPECIFIER_LONG;
2971 #define CHECK_DOUBLE_TYPE() \
2972 if ( type != NULL) \
2973 errorf(HERE, "multiple data types in declaration specifiers");
2976 CHECK_DOUBLE_TYPE();
2977 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2979 type->compound.compound = parse_compound_type_specifier(true);
2982 CHECK_DOUBLE_TYPE();
2983 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2984 type->compound.compound = parse_compound_type_specifier(false);
2987 CHECK_DOUBLE_TYPE();
2988 type = parse_enum_specifier();
2991 CHECK_DOUBLE_TYPE();
2992 type = parse_typeof();
2994 case T___builtin_va_list:
2995 CHECK_DOUBLE_TYPE();
2996 type = duplicate_type(type_valist);
3000 case T_IDENTIFIER: {
3001 /* only parse identifier if we haven't found a type yet */
3002 if (type != NULL || type_specifiers != 0) {
3003 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3004 * declaration, so it doesn't generate errors about expecting '(' or
3006 switch (look_ahead(1)->type) {
3013 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3017 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3022 goto finish_specifiers;
3026 type_t *const typedef_type = get_typedef_type(token.symbol);
3027 if (typedef_type == NULL) {
3028 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3029 * declaration, so it doesn't generate 'implicit int' followed by more
3030 * errors later on. */
3031 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3037 errorf(HERE, "%K does not name a type", &token);
3040 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3042 type = allocate_type_zero(TYPE_TYPEDEF);
3043 type->typedeft.typedefe = &entity->typedefe;
3051 goto finish_specifiers;
3056 type = typedef_type;
3060 /* function specifier */
3062 goto finish_specifiers;
3067 specifiers->attributes = parse_attributes(specifiers->attributes);
3069 in_gcc_extension = old_gcc_extension;
3071 if (type == NULL || (saw_error && type_specifiers != 0)) {
3072 atomic_type_kind_t atomic_type;
3074 /* match valid basic types */
3075 switch (type_specifiers) {
3076 case SPECIFIER_VOID:
3077 atomic_type = ATOMIC_TYPE_VOID;
3079 case SPECIFIER_WCHAR_T:
3080 atomic_type = ATOMIC_TYPE_WCHAR_T;
3082 case SPECIFIER_CHAR:
3083 atomic_type = ATOMIC_TYPE_CHAR;
3085 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3086 atomic_type = ATOMIC_TYPE_SCHAR;
3088 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3089 atomic_type = ATOMIC_TYPE_UCHAR;
3091 case SPECIFIER_SHORT:
3092 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3093 case SPECIFIER_SHORT | SPECIFIER_INT:
3094 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3095 atomic_type = ATOMIC_TYPE_SHORT;
3097 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3098 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3099 atomic_type = ATOMIC_TYPE_USHORT;
3102 case SPECIFIER_SIGNED:
3103 case SPECIFIER_SIGNED | SPECIFIER_INT:
3104 atomic_type = ATOMIC_TYPE_INT;
3106 case SPECIFIER_UNSIGNED:
3107 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3108 atomic_type = ATOMIC_TYPE_UINT;
3110 case SPECIFIER_LONG:
3111 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3112 case SPECIFIER_LONG | SPECIFIER_INT:
3113 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3114 atomic_type = ATOMIC_TYPE_LONG;
3116 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3117 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3118 atomic_type = ATOMIC_TYPE_ULONG;
3121 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3122 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3123 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3124 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3126 atomic_type = ATOMIC_TYPE_LONGLONG;
3127 goto warn_about_long_long;
3129 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3130 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3132 atomic_type = ATOMIC_TYPE_ULONGLONG;
3133 warn_about_long_long:
3134 if (warning.long_long) {
3135 warningf(&specifiers->source_position,
3136 "ISO C90 does not support 'long long'");
3140 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3141 atomic_type = unsigned_int8_type_kind;
3144 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3145 atomic_type = unsigned_int16_type_kind;
3148 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3149 atomic_type = unsigned_int32_type_kind;
3152 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3153 atomic_type = unsigned_int64_type_kind;
3156 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3157 atomic_type = unsigned_int128_type_kind;
3160 case SPECIFIER_INT8:
3161 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3162 atomic_type = int8_type_kind;
3165 case SPECIFIER_INT16:
3166 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3167 atomic_type = int16_type_kind;
3170 case SPECIFIER_INT32:
3171 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3172 atomic_type = int32_type_kind;
3175 case SPECIFIER_INT64:
3176 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3177 atomic_type = int64_type_kind;
3180 case SPECIFIER_INT128:
3181 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3182 atomic_type = int128_type_kind;
3185 case SPECIFIER_FLOAT:
3186 atomic_type = ATOMIC_TYPE_FLOAT;
3188 case SPECIFIER_DOUBLE:
3189 atomic_type = ATOMIC_TYPE_DOUBLE;
3191 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3192 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3194 case SPECIFIER_BOOL:
3195 atomic_type = ATOMIC_TYPE_BOOL;
3197 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3198 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3199 atomic_type = ATOMIC_TYPE_FLOAT;
3201 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3202 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3203 atomic_type = ATOMIC_TYPE_DOUBLE;
3205 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3206 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3207 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3210 /* invalid specifier combination, give an error message */
3211 if (type_specifiers == 0) {
3213 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3214 if (!(c_mode & _CXX) && !strict_mode) {
3215 if (warning.implicit_int) {
3216 warningf(HERE, "no type specifiers in declaration, using 'int'");
3218 atomic_type = ATOMIC_TYPE_INT;
3221 errorf(HERE, "no type specifiers given in declaration");
3224 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3225 (type_specifiers & SPECIFIER_UNSIGNED)) {
3226 errorf(HERE, "signed and unsigned specifiers given");
3227 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3228 errorf(HERE, "only integer types can be signed or unsigned");
3230 errorf(HERE, "multiple datatypes in declaration");
3235 if (type_specifiers & SPECIFIER_COMPLEX) {
3236 type = allocate_type_zero(TYPE_COMPLEX);
3237 type->complex.akind = atomic_type;
3238 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3239 type = allocate_type_zero(TYPE_IMAGINARY);
3240 type->imaginary.akind = atomic_type;
3242 type = allocate_type_zero(TYPE_ATOMIC);
3243 type->atomic.akind = atomic_type;
3246 } else if (type_specifiers != 0) {
3247 errorf(HERE, "multiple datatypes in declaration");
3250 /* FIXME: check type qualifiers here */
3251 type->base.qualifiers = qualifiers;
3254 type = identify_new_type(type);
3256 type = typehash_insert(type);
3259 if (specifiers->attributes != NULL)
3260 type = handle_type_attributes(specifiers->attributes, type);
3261 specifiers->type = type;
3265 specifiers->type = type_error_type;
3268 static type_qualifiers_t parse_type_qualifiers(void)
3270 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3273 switch (token.type) {
3274 /* type qualifiers */
3275 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3276 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3277 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3278 /* microsoft extended type modifiers */
3279 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3280 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3281 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3282 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3283 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3292 * Parses an K&R identifier list
3294 static void parse_identifier_list(scope_t *scope)
3297 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3298 entity->base.source_position = token.source_position;
3299 entity->base.namespc = NAMESPACE_NORMAL;
3300 entity->base.symbol = token.symbol;
3301 /* a K&R parameter has no type, yet */
3305 append_entity(scope, entity);
3306 } while (next_if(',') && token.type == T_IDENTIFIER);
3309 static entity_t *parse_parameter(void)
3311 declaration_specifiers_t specifiers;
3312 parse_declaration_specifiers(&specifiers);
3314 entity_t *entity = parse_declarator(&specifiers,
3315 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3316 anonymous_entity = NULL;
3320 static void semantic_parameter_incomplete(const entity_t *entity)
3322 assert(entity->kind == ENTITY_PARAMETER);
3324 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3325 * list in a function declarator that is part of a
3326 * definition of that function shall not have
3327 * incomplete type. */
3328 type_t *type = skip_typeref(entity->declaration.type);
3329 if (is_type_incomplete(type)) {
3330 errorf(&entity->base.source_position,
3331 "parameter '%#T' has incomplete type",
3332 entity->declaration.type, entity->base.symbol);
3336 static bool has_parameters(void)
3338 /* func(void) is not a parameter */
3339 if (token.type == T_IDENTIFIER) {
3340 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3343 if (entity->kind != ENTITY_TYPEDEF)
3345 if (skip_typeref(entity->typedefe.type) != type_void)
3347 } else if (token.type != T_void) {
3350 if (look_ahead(1)->type != ')')
3357 * Parses function type parameters (and optionally creates variable_t entities
3358 * for them in a scope)
3360 static void parse_parameters(function_type_t *type, scope_t *scope)
3363 add_anchor_token(')');
3364 int saved_comma_state = save_and_reset_anchor_state(',');
3366 if (token.type == T_IDENTIFIER &&
3367 !is_typedef_symbol(token.symbol)) {
3368 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3369 if (la1_type == ',' || la1_type == ')') {
3370 type->kr_style_parameters = true;
3371 parse_identifier_list(scope);
3372 goto parameters_finished;
3376 if (token.type == ')') {
3377 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3378 if (!(c_mode & _CXX))
3379 type->unspecified_parameters = true;
3380 } else if (has_parameters()) {
3381 function_parameter_t **anchor = &type->parameters;
3383 switch (token.type) {
3386 type->variadic = true;
3387 goto parameters_finished;
3390 case T___extension__:
3393 entity_t *entity = parse_parameter();
3394 if (entity->kind == ENTITY_TYPEDEF) {
3395 errorf(&entity->base.source_position,
3396 "typedef not allowed as function parameter");
3399 assert(is_declaration(entity));
3401 semantic_parameter_incomplete(entity);
3403 function_parameter_t *const parameter =
3404 allocate_parameter(entity->declaration.type);
3406 if (scope != NULL) {
3407 append_entity(scope, entity);
3410 *anchor = parameter;
3411 anchor = ¶meter->next;
3416 goto parameters_finished;
3418 } while (next_if(','));
3421 parameters_finished:
3422 rem_anchor_token(')');
3423 expect(')', end_error);
3426 restore_anchor_state(',', saved_comma_state);
3429 typedef enum construct_type_kind_t {
3432 CONSTRUCT_REFERENCE,
3435 } construct_type_kind_t;
3437 typedef union construct_type_t construct_type_t;
3439 typedef struct construct_type_base_t {
3440 construct_type_kind_t kind;
3441 source_position_t pos;
3442 construct_type_t *next;
3443 } construct_type_base_t;
3445 typedef struct parsed_pointer_t {
3446 construct_type_base_t base;
3447 type_qualifiers_t type_qualifiers;
3448 variable_t *base_variable; /**< MS __based extension. */
3451 typedef struct parsed_reference_t {
3452 construct_type_base_t base;
3453 } parsed_reference_t;
3455 typedef struct construct_function_type_t {
3456 construct_type_base_t base;
3457 type_t *function_type;
3458 } construct_function_type_t;
3460 typedef struct parsed_array_t {
3461 construct_type_base_t base;
3462 type_qualifiers_t type_qualifiers;
3468 union construct_type_t {
3469 construct_type_kind_t kind;
3470 construct_type_base_t base;
3471 parsed_pointer_t pointer;
3472 parsed_reference_t reference;
3473 construct_function_type_t function;
3474 parsed_array_t array;
3477 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3479 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3480 memset(cons, 0, size);
3482 cons->base.pos = *HERE;
3487 static construct_type_t *parse_pointer_declarator(void)
3489 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3491 cons->pointer.type_qualifiers = parse_type_qualifiers();
3492 //cons->pointer.base_variable = base_variable;
3497 /* ISO/IEC 14882:1998(E) §8.3.2 */
3498 static construct_type_t *parse_reference_declarator(void)
3500 if (!(c_mode & _CXX))
3501 errorf(HERE, "references are only available for C++");
3503 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3510 static construct_type_t *parse_array_declarator(void)
3512 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3513 parsed_array_t *const array = &cons->array;
3516 add_anchor_token(']');
3518 bool is_static = next_if(T_static);
3520 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3523 is_static = next_if(T_static);
3525 array->type_qualifiers = type_qualifiers;
3526 array->is_static = is_static;
3528 expression_t *size = NULL;
3529 if (token.type == '*' && look_ahead(1)->type == ']') {
3530 array->is_variable = true;
3532 } else if (token.type != ']') {
3533 size = parse_assignment_expression();
3535 /* §6.7.5.2:1 Array size must have integer type */
3536 type_t *const orig_type = size->base.type;
3537 type_t *const type = skip_typeref(orig_type);
3538 if (!is_type_integer(type) && is_type_valid(type)) {
3539 errorf(&size->base.source_position,
3540 "array size '%E' must have integer type but has type '%T'",
3545 mark_vars_read(size, NULL);
3548 if (is_static && size == NULL)
3549 errorf(&array->base.pos, "static array parameters require a size");
3551 rem_anchor_token(']');
3552 expect(']', end_error);
3559 static construct_type_t *parse_function_declarator(scope_t *scope)
3561 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3563 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3564 function_type_t *ftype = &type->function;
3566 ftype->linkage = current_linkage;
3567 ftype->calling_convention = CC_DEFAULT;
3569 parse_parameters(ftype, scope);
3571 cons->function.function_type = type;
3576 typedef struct parse_declarator_env_t {
3577 bool may_be_abstract : 1;
3578 bool must_be_abstract : 1;
3579 decl_modifiers_t modifiers;
3581 source_position_t source_position;
3583 attribute_t *attributes;
3584 } parse_declarator_env_t;
3587 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3589 /* construct a single linked list of construct_type_t's which describe
3590 * how to construct the final declarator type */
3591 construct_type_t *first = NULL;
3592 construct_type_t **anchor = &first;
3594 env->attributes = parse_attributes(env->attributes);
3597 construct_type_t *type;
3598 //variable_t *based = NULL; /* MS __based extension */
3599 switch (token.type) {
3601 type = parse_reference_declarator();
3605 panic("based not supported anymore");
3610 type = parse_pointer_declarator();
3614 goto ptr_operator_end;
3618 anchor = &type->base.next;
3620 /* TODO: find out if this is correct */
3621 env->attributes = parse_attributes(env->attributes);
3625 construct_type_t *inner_types = NULL;
3627 switch (token.type) {
3629 if (env->must_be_abstract) {
3630 errorf(HERE, "no identifier expected in typename");
3632 env->symbol = token.symbol;
3633 env->source_position = token.source_position;
3639 /* Parenthesized declarator or function declarator? */
3640 token_t const *const la1 = look_ahead(1);
3641 switch (la1->type) {
3643 if (is_typedef_symbol(la1->symbol)) {
3645 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3646 * interpreted as ``function with no parameter specification'', rather
3647 * than redundant parentheses around the omitted identifier. */
3649 /* Function declarator. */
3650 if (!env->may_be_abstract) {
3651 errorf(HERE, "function declarator must have a name");
3658 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3659 /* Paranthesized declarator. */
3661 add_anchor_token(')');
3662 inner_types = parse_inner_declarator(env);
3663 if (inner_types != NULL) {
3664 /* All later declarators only modify the return type */
3665 env->must_be_abstract = true;
3667 rem_anchor_token(')');
3668 expect(')', end_error);
3676 if (env->may_be_abstract)
3678 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3683 construct_type_t **const p = anchor;
3686 construct_type_t *type;
3687 switch (token.type) {
3689 scope_t *scope = NULL;
3690 if (!env->must_be_abstract) {
3691 scope = &env->parameters;
3694 type = parse_function_declarator(scope);
3698 type = parse_array_declarator();
3701 goto declarator_finished;
3704 /* insert in the middle of the list (at p) */
3705 type->base.next = *p;
3708 anchor = &type->base.next;
3711 declarator_finished:
3712 /* append inner_types at the end of the list, we don't to set anchor anymore
3713 * as it's not needed anymore */
3714 *anchor = inner_types;
3721 static type_t *construct_declarator_type(construct_type_t *construct_list,
3724 construct_type_t *iter = construct_list;
3725 for (; iter != NULL; iter = iter->base.next) {
3726 source_position_t const* const pos = &iter->base.pos;
3727 switch (iter->kind) {
3728 case CONSTRUCT_INVALID:
3730 case CONSTRUCT_FUNCTION: {
3731 construct_function_type_t *function = &iter->function;
3732 type_t *function_type = function->function_type;
3734 function_type->function.return_type = type;
3736 type_t *skipped_return_type = skip_typeref(type);
3738 if (is_type_function(skipped_return_type)) {
3739 errorf(pos, "function returning function is not allowed");
3740 } else if (is_type_array(skipped_return_type)) {
3741 errorf(pos, "function returning array is not allowed");
3743 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3744 warningf(pos, "type qualifiers in return type of function type are meaningless");
3748 /* The function type was constructed earlier. Freeing it here will
3749 * destroy other types. */
3750 type = typehash_insert(function_type);
3754 case CONSTRUCT_POINTER: {
3755 if (is_type_reference(skip_typeref(type)))
3756 errorf(pos, "cannot declare a pointer to reference");
3758 parsed_pointer_t *pointer = &iter->pointer;
3759 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3763 case CONSTRUCT_REFERENCE:
3764 if (is_type_reference(skip_typeref(type)))
3765 errorf(pos, "cannot declare a reference to reference");
3767 type = make_reference_type(type);
3770 case CONSTRUCT_ARRAY: {
3771 if (is_type_reference(skip_typeref(type)))
3772 errorf(pos, "cannot declare an array of references");
3774 parsed_array_t *array = &iter->array;
3775 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3777 expression_t *size_expression = array->size;
3778 if (size_expression != NULL) {
3780 = create_implicit_cast(size_expression, type_size_t);
3783 array_type->base.qualifiers = array->type_qualifiers;
3784 array_type->array.element_type = type;
3785 array_type->array.is_static = array->is_static;
3786 array_type->array.is_variable = array->is_variable;
3787 array_type->array.size_expression = size_expression;
3789 if (size_expression != NULL) {
3790 switch (is_constant_expression(size_expression)) {
3791 case EXPR_CLASS_CONSTANT: {
3792 long const size = fold_constant_to_int(size_expression);
3793 array_type->array.size = size;
3794 array_type->array.size_constant = true;
3795 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3796 * have a value greater than zero. */
3798 if (size < 0 || !GNU_MODE) {
3799 errorf(&size_expression->base.source_position,
3800 "size of array must be greater than zero");
3801 } else if (warning.other) {
3802 warningf(&size_expression->base.source_position,
3803 "zero length arrays are a GCC extension");
3809 case EXPR_CLASS_VARIABLE:
3810 array_type->array.is_vla = true;
3813 case EXPR_CLASS_ERROR:
3818 type_t *skipped_type = skip_typeref(type);
3820 if (is_type_incomplete(skipped_type)) {
3821 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3822 } else if (is_type_function(skipped_type)) {
3823 errorf(pos, "array of functions is not allowed");
3825 type = identify_new_type(array_type);
3829 internal_errorf(pos, "invalid type construction found");
3835 static type_t *automatic_type_conversion(type_t *orig_type);
3837 static type_t *semantic_parameter(const source_position_t *pos,
3839 const declaration_specifiers_t *specifiers,
3842 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3843 * shall be adjusted to ``qualified pointer to type'',
3845 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3846 * type'' shall be adjusted to ``pointer to function
3847 * returning type'', as in 6.3.2.1. */
3848 type = automatic_type_conversion(type);
3850 if (specifiers->is_inline && is_type_valid(type)) {
3851 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3854 /* §6.9.1:6 The declarations in the declaration list shall contain
3855 * no storage-class specifier other than register and no
3856 * initializations. */
3857 if (specifiers->thread_local || (
3858 specifiers->storage_class != STORAGE_CLASS_NONE &&
3859 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3861 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3864 /* delay test for incomplete type, because we might have (void)
3865 * which is legal but incomplete... */
3870 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3871 declarator_flags_t flags)
3873 parse_declarator_env_t env;
3874 memset(&env, 0, sizeof(env));
3875 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3877 construct_type_t *construct_type = parse_inner_declarator(&env);
3879 construct_declarator_type(construct_type, specifiers->type);
3880 type_t *type = skip_typeref(orig_type);
3882 if (construct_type != NULL) {
3883 obstack_free(&temp_obst, construct_type);
3886 attribute_t *attributes = parse_attributes(env.attributes);
3887 /* append (shared) specifier attribute behind attributes of this
3889 attribute_t **anchor = &attributes;
3890 while (*anchor != NULL)
3891 anchor = &(*anchor)->next;
3892 *anchor = specifiers->attributes;
3895 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3896 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3897 entity->base.namespc = NAMESPACE_NORMAL;
3898 entity->base.symbol = env.symbol;
3899 entity->base.source_position = env.source_position;
3900 entity->typedefe.type = orig_type;
3902 if (anonymous_entity != NULL) {
3903 if (is_type_compound(type)) {
3904 assert(anonymous_entity->compound.alias == NULL);
3905 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3906 anonymous_entity->kind == ENTITY_UNION);
3907 anonymous_entity->compound.alias = entity;
3908 anonymous_entity = NULL;
3909 } else if (is_type_enum(type)) {
3910 assert(anonymous_entity->enume.alias == NULL);
3911 assert(anonymous_entity->kind == ENTITY_ENUM);
3912 anonymous_entity->enume.alias = entity;
3913 anonymous_entity = NULL;
3917 /* create a declaration type entity */
3918 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3919 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3921 if (env.symbol != NULL) {
3922 if (specifiers->is_inline && is_type_valid(type)) {
3923 errorf(&env.source_position,
3924 "compound member '%Y' declared 'inline'", env.symbol);
3927 if (specifiers->thread_local ||
3928 specifiers->storage_class != STORAGE_CLASS_NONE) {
3929 errorf(&env.source_position,
3930 "compound member '%Y' must have no storage class",
3934 } else if (flags & DECL_IS_PARAMETER) {
3935 orig_type = semantic_parameter(&env.source_position, orig_type,
3936 specifiers, env.symbol);
3938 entity = allocate_entity_zero(ENTITY_PARAMETER);
3939 } else if (is_type_function(type)) {
3940 entity = allocate_entity_zero(ENTITY_FUNCTION);
3942 entity->function.is_inline = specifiers->is_inline;
3943 entity->function.elf_visibility = default_visibility;
3944 entity->function.parameters = env.parameters;
3946 if (env.symbol != NULL) {
3947 /* this needs fixes for C++ */
3948 bool in_function_scope = current_function != NULL;
3950 if (specifiers->thread_local || (
3951 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3952 specifiers->storage_class != STORAGE_CLASS_NONE &&
3953 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3955 errorf(&env.source_position,
3956 "invalid storage class for function '%Y'", env.symbol);
3960 entity = allocate_entity_zero(ENTITY_VARIABLE);
3962 entity->variable.elf_visibility = default_visibility;
3963 entity->variable.thread_local = specifiers->thread_local;
3965 if (env.symbol != NULL) {
3966 if (specifiers->is_inline && is_type_valid(type)) {
3967 errorf(&env.source_position,
3968 "variable '%Y' declared 'inline'", env.symbol);
3971 bool invalid_storage_class = false;
3972 if (current_scope == file_scope) {
3973 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3974 specifiers->storage_class != STORAGE_CLASS_NONE &&
3975 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3976 invalid_storage_class = true;
3979 if (specifiers->thread_local &&
3980 specifiers->storage_class == STORAGE_CLASS_NONE) {
3981 invalid_storage_class = true;
3984 if (invalid_storage_class) {
3985 errorf(&env.source_position,
3986 "invalid storage class for variable '%Y'", env.symbol);
3991 if (env.symbol != NULL) {
3992 entity->base.symbol = env.symbol;
3993 entity->base.source_position = env.source_position;
3995 entity->base.source_position = specifiers->source_position;
3997 entity->base.namespc = NAMESPACE_NORMAL;
3998 entity->declaration.type = orig_type;
3999 entity->declaration.alignment = get_type_alignment(orig_type);
4000 entity->declaration.modifiers = env.modifiers;
4001 entity->declaration.attributes = attributes;
4003 storage_class_t storage_class = specifiers->storage_class;
4004 entity->declaration.declared_storage_class = storage_class;
4006 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4007 storage_class = STORAGE_CLASS_AUTO;
4008 entity->declaration.storage_class = storage_class;
4011 if (attributes != NULL) {
4012 handle_entity_attributes(attributes, entity);
4018 static type_t *parse_abstract_declarator(type_t *base_type)
4020 parse_declarator_env_t env;
4021 memset(&env, 0, sizeof(env));
4022 env.may_be_abstract = true;
4023 env.must_be_abstract = true;
4025 construct_type_t *construct_type = parse_inner_declarator(&env);
4027 type_t *result = construct_declarator_type(construct_type, base_type);
4028 if (construct_type != NULL) {
4029 obstack_free(&temp_obst, construct_type);
4031 result = handle_type_attributes(env.attributes, result);
4037 * Check if the declaration of main is suspicious. main should be a
4038 * function with external linkage, returning int, taking either zero
4039 * arguments, two, or three arguments of appropriate types, ie.
4041 * int main([ int argc, char **argv [, char **env ] ]).
4043 * @param decl the declaration to check
4044 * @param type the function type of the declaration
4046 static void check_main(const entity_t *entity)
4048 const source_position_t *pos = &entity->base.source_position;
4049 if (entity->kind != ENTITY_FUNCTION) {
4050 warningf(pos, "'main' is not a function");
4054 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4055 warningf(pos, "'main' is normally a non-static function");
4058 type_t *type = skip_typeref(entity->declaration.type);
4059 assert(is_type_function(type));
4061 function_type_t *func_type = &type->function;
4062 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4063 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4064 func_type->return_type);
4066 const function_parameter_t *parm = func_type->parameters;
4068 type_t *const first_type = skip_typeref(parm->type);
4069 type_t *const first_type_unqual = get_unqualified_type(first_type);
4070 if (!types_compatible(first_type_unqual, type_int)) {
4072 "first argument of 'main' should be 'int', but is '%T'",
4077 type_t *const second_type = skip_typeref(parm->type);
4078 type_t *const second_type_unqual
4079 = get_unqualified_type(second_type);
4080 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4081 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'",
4086 type_t *const third_type = skip_typeref(parm->type);
4087 type_t *const third_type_unqual
4088 = get_unqualified_type(third_type);
4089 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4090 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'",
4095 goto warn_arg_count;
4099 warningf(pos, "'main' takes only zero, two or three arguments");
4105 * Check if a symbol is the equal to "main".
4107 static bool is_sym_main(const symbol_t *const sym)
4109 return strcmp(sym->string, "main") == 0;
4112 static void error_redefined_as_different_kind(const source_position_t *pos,
4113 const entity_t *old, entity_kind_t new_kind)
4115 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4116 get_entity_kind_name(old->kind), old->base.symbol,
4117 get_entity_kind_name(new_kind), &old->base.source_position);
4120 static bool is_entity_valid(entity_t *const ent)
4122 if (is_declaration(ent)) {
4123 return is_type_valid(skip_typeref(ent->declaration.type));
4124 } else if (ent->kind == ENTITY_TYPEDEF) {
4125 return is_type_valid(skip_typeref(ent->typedefe.type));
4130 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4132 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4133 if (attributes_equal(tattr, attr))
4140 * test wether new_list contains any attributes not included in old_list
4142 static bool has_new_attributes(const attribute_t *old_list,
4143 const attribute_t *new_list)
4145 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4146 if (!contains_attribute(old_list, attr))
4153 * Merge in attributes from an attribute list (probably from a previous
4154 * declaration with the same name). Warning: destroys the old structure
4155 * of the attribute list - don't reuse attributes after this call.
4157 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4160 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4162 if (contains_attribute(decl->attributes, attr))
4165 /* move attribute to new declarations attributes list */
4166 attr->next = decl->attributes;
4167 decl->attributes = attr;
4172 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4173 * for various problems that occur for multiple definitions
4175 entity_t *record_entity(entity_t *entity, const bool is_definition)
4177 const symbol_t *const symbol = entity->base.symbol;
4178 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4179 const source_position_t *pos = &entity->base.source_position;
4181 /* can happen in error cases */
4185 entity_t *const previous_entity = get_entity(symbol, namespc);
4186 /* pushing the same entity twice will break the stack structure */
4187 assert(previous_entity != entity);
4189 if (entity->kind == ENTITY_FUNCTION) {
4190 type_t *const orig_type = entity->declaration.type;
4191 type_t *const type = skip_typeref(orig_type);
4193 assert(is_type_function(type));
4194 if (type->function.unspecified_parameters &&
4195 warning.strict_prototypes &&
4196 previous_entity == NULL) {
4197 warningf(pos, "function declaration '%#T' is not a prototype",
4201 if (warning.main && current_scope == file_scope
4202 && is_sym_main(symbol)) {
4207 if (is_declaration(entity) &&
4208 warning.nested_externs &&
4209 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4210 current_scope != file_scope) {
4211 warningf(pos, "nested extern declaration of '%#T'",
4212 entity->declaration.type, symbol);
4215 if (previous_entity != NULL) {
4216 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4217 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4218 assert(previous_entity->kind == ENTITY_PARAMETER);
4220 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4221 entity->declaration.type, symbol,
4222 previous_entity->declaration.type, symbol,
4223 &previous_entity->base.source_position);
4227 if (previous_entity->base.parent_scope == current_scope) {
4228 if (previous_entity->kind != entity->kind) {
4229 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4230 error_redefined_as_different_kind(pos, previous_entity,
4235 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4236 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4237 symbol, &previous_entity->base.source_position);
4240 if (previous_entity->kind == ENTITY_TYPEDEF) {
4241 /* TODO: C++ allows this for exactly the same type */
4242 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4243 symbol, &previous_entity->base.source_position);
4247 /* at this point we should have only VARIABLES or FUNCTIONS */
4248 assert(is_declaration(previous_entity) && is_declaration(entity));
4250 declaration_t *const prev_decl = &previous_entity->declaration;
4251 declaration_t *const decl = &entity->declaration;
4253 /* can happen for K&R style declarations */
4254 if (prev_decl->type == NULL &&
4255 previous_entity->kind == ENTITY_PARAMETER &&
4256 entity->kind == ENTITY_PARAMETER) {
4257 prev_decl->type = decl->type;
4258 prev_decl->storage_class = decl->storage_class;
4259 prev_decl->declared_storage_class = decl->declared_storage_class;
4260 prev_decl->modifiers = decl->modifiers;
4261 return previous_entity;
4264 type_t *const orig_type = decl->type;
4265 assert(orig_type != NULL);
4266 type_t *const type = skip_typeref(orig_type);
4267 type_t *const prev_type = skip_typeref(prev_decl->type);
4269 if (!types_compatible(type, prev_type)) {
4271 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4272 orig_type, symbol, prev_decl->type, symbol,
4273 &previous_entity->base.source_position);
4275 unsigned old_storage_class = prev_decl->storage_class;
4277 if (warning.redundant_decls &&
4280 !(prev_decl->modifiers & DM_USED) &&
4281 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4282 warningf(&previous_entity->base.source_position,
4283 "unnecessary static forward declaration for '%#T'",
4284 prev_decl->type, symbol);
4287 storage_class_t new_storage_class = decl->storage_class;
4289 /* pretend no storage class means extern for function
4290 * declarations (except if the previous declaration is neither
4291 * none nor extern) */
4292 if (entity->kind == ENTITY_FUNCTION) {
4293 /* the previous declaration could have unspecified parameters or
4294 * be a typedef, so use the new type */
4295 if (prev_type->function.unspecified_parameters || is_definition)
4296 prev_decl->type = type;
4298 switch (old_storage_class) {
4299 case STORAGE_CLASS_NONE:
4300 old_storage_class = STORAGE_CLASS_EXTERN;
4303 case STORAGE_CLASS_EXTERN:
4304 if (is_definition) {
4305 if (warning.missing_prototypes &&
4306 prev_type->function.unspecified_parameters &&
4307 !is_sym_main(symbol)) {
4308 warningf(pos, "no previous prototype for '%#T'",
4311 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4312 new_storage_class = STORAGE_CLASS_EXTERN;
4319 } else if (is_type_incomplete(prev_type)) {
4320 prev_decl->type = type;
4323 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4324 new_storage_class == STORAGE_CLASS_EXTERN) {
4326 warn_redundant_declaration: ;
4328 = has_new_attributes(prev_decl->attributes,
4330 if (has_new_attrs) {
4331 merge_in_attributes(decl, prev_decl->attributes);
4332 } else if (!is_definition &&
4333 warning.redundant_decls &&
4334 is_type_valid(prev_type) &&
4335 strcmp(previous_entity->base.source_position.input_name,
4336 "<builtin>") != 0) {
4338 "redundant declaration for '%Y' (declared %P)",
4339 symbol, &previous_entity->base.source_position);
4341 } else if (current_function == NULL) {
4342 if (old_storage_class != STORAGE_CLASS_STATIC &&
4343 new_storage_class == STORAGE_CLASS_STATIC) {
4345 "static declaration of '%Y' follows non-static declaration (declared %P)",
4346 symbol, &previous_entity->base.source_position);
4347 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4348 prev_decl->storage_class = STORAGE_CLASS_NONE;
4349 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4351 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4353 goto error_redeclaration;
4354 goto warn_redundant_declaration;
4356 } else if (is_type_valid(prev_type)) {
4357 if (old_storage_class == new_storage_class) {
4358 error_redeclaration:
4359 errorf(pos, "redeclaration of '%Y' (declared %P)",
4360 symbol, &previous_entity->base.source_position);
4363 "redeclaration of '%Y' with different linkage (declared %P)",
4364 symbol, &previous_entity->base.source_position);
4369 prev_decl->modifiers |= decl->modifiers;
4370 if (entity->kind == ENTITY_FUNCTION) {
4371 previous_entity->function.is_inline |= entity->function.is_inline;
4373 return previous_entity;
4376 if (warning.shadow ||
4377 (warning.shadow_local && previous_entity->base.parent_scope != file_scope)) {
4378 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4379 get_entity_kind_name(entity->kind), symbol,
4380 get_entity_kind_name(previous_entity->kind),
4381 &previous_entity->base.source_position);
4385 if (entity->kind == ENTITY_FUNCTION) {
4386 if (is_definition &&
4387 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4388 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4389 warningf(pos, "no previous prototype for '%#T'",
4390 entity->declaration.type, symbol);
4391 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4392 warningf(pos, "no previous declaration for '%#T'",
4393 entity->declaration.type, symbol);
4396 } else if (warning.missing_declarations &&
4397 entity->kind == ENTITY_VARIABLE &&
4398 current_scope == file_scope) {
4399 declaration_t *declaration = &entity->declaration;
4400 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4401 warningf(pos, "no previous declaration for '%#T'",
4402 declaration->type, symbol);
4407 assert(entity->base.parent_scope == NULL);
4408 assert(current_scope != NULL);
4410 entity->base.parent_scope = current_scope;
4411 entity->base.namespc = NAMESPACE_NORMAL;
4412 environment_push(entity);
4413 append_entity(current_scope, entity);
4418 static void parser_error_multiple_definition(entity_t *entity,
4419 const source_position_t *source_position)
4421 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4422 entity->base.symbol, &entity->base.source_position);
4425 static bool is_declaration_specifier(const token_t *token,
4426 bool only_specifiers_qualifiers)
4428 switch (token->type) {
4433 return is_typedef_symbol(token->symbol);
4435 case T___extension__:
4437 return !only_specifiers_qualifiers;
4444 static void parse_init_declarator_rest(entity_t *entity)
4446 type_t *orig_type = type_error_type;
4448 if (entity->base.kind == ENTITY_TYPEDEF) {
4449 errorf(&entity->base.source_position,
4450 "typedef '%Y' is initialized (use __typeof__ instead)",
4451 entity->base.symbol);
4453 assert(is_declaration(entity));
4454 orig_type = entity->declaration.type;
4458 type_t *type = skip_typeref(orig_type);
4460 if (entity->kind == ENTITY_VARIABLE
4461 && entity->variable.initializer != NULL) {
4462 parser_error_multiple_definition(entity, HERE);
4465 declaration_t *const declaration = &entity->declaration;
4466 bool must_be_constant = false;
4467 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4468 entity->base.parent_scope == file_scope) {
4469 must_be_constant = true;
4472 if (is_type_function(type)) {
4473 errorf(&entity->base.source_position,
4474 "function '%#T' is initialized like a variable",
4475 orig_type, entity->base.symbol);
4476 orig_type = type_error_type;
4479 parse_initializer_env_t env;
4480 env.type = orig_type;
4481 env.must_be_constant = must_be_constant;
4482 env.entity = entity;
4483 current_init_decl = entity;
4485 initializer_t *initializer = parse_initializer(&env);
4486 current_init_decl = NULL;
4488 if (entity->kind == ENTITY_VARIABLE) {
4489 /* §6.7.5:22 array initializers for arrays with unknown size
4490 * determine the array type size */
4491 declaration->type = env.type;
4492 entity->variable.initializer = initializer;
4496 /* parse rest of a declaration without any declarator */
4497 static void parse_anonymous_declaration_rest(
4498 const declaration_specifiers_t *specifiers)
4501 anonymous_entity = NULL;
4503 if (warning.other) {
4504 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4505 specifiers->thread_local) {
4506 warningf(&specifiers->source_position,
4507 "useless storage class in empty declaration");
4510 type_t *type = specifiers->type;
4511 switch (type->kind) {
4512 case TYPE_COMPOUND_STRUCT:
4513 case TYPE_COMPOUND_UNION: {
4514 if (type->compound.compound->base.symbol == NULL) {
4515 warningf(&specifiers->source_position,
4516 "unnamed struct/union that defines no instances");
4525 warningf(&specifiers->source_position, "empty declaration");
4531 static void check_variable_type_complete(entity_t *ent)
4533 if (ent->kind != ENTITY_VARIABLE)
4536 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4537 * type for the object shall be complete [...] */
4538 declaration_t *decl = &ent->declaration;
4539 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4540 decl->storage_class == STORAGE_CLASS_STATIC)
4543 type_t *const orig_type = decl->type;
4544 type_t *const type = skip_typeref(orig_type);
4545 if (!is_type_incomplete(type))
4548 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4549 * are given length one. */
4550 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4551 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4555 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4556 orig_type, ent->base.symbol);
4560 static void parse_declaration_rest(entity_t *ndeclaration,
4561 const declaration_specifiers_t *specifiers,
4562 parsed_declaration_func finished_declaration,
4563 declarator_flags_t flags)
4565 add_anchor_token(';');
4566 add_anchor_token(',');
4568 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4570 if (token.type == '=') {
4571 parse_init_declarator_rest(entity);
4572 } else if (entity->kind == ENTITY_VARIABLE) {
4573 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4574 * [...] where the extern specifier is explicitly used. */
4575 declaration_t *decl = &entity->declaration;
4576 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4577 type_t *type = decl->type;
4578 if (is_type_reference(skip_typeref(type))) {
4579 errorf(&entity->base.source_position,
4580 "reference '%#T' must be initialized",
4581 type, entity->base.symbol);
4586 check_variable_type_complete(entity);
4591 add_anchor_token('=');
4592 ndeclaration = parse_declarator(specifiers, flags);
4593 rem_anchor_token('=');
4595 expect(';', end_error);
4598 anonymous_entity = NULL;
4599 rem_anchor_token(';');
4600 rem_anchor_token(',');
4603 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4605 symbol_t *symbol = entity->base.symbol;
4606 if (symbol == NULL) {
4607 errorf(HERE, "anonymous declaration not valid as function parameter");
4611 assert(entity->base.namespc == NAMESPACE_NORMAL);
4612 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4613 if (previous_entity == NULL
4614 || previous_entity->base.parent_scope != current_scope) {
4615 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4620 if (is_definition) {
4621 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4624 return record_entity(entity, false);
4627 static void parse_declaration(parsed_declaration_func finished_declaration,
4628 declarator_flags_t flags)
4630 add_anchor_token(';');
4631 declaration_specifiers_t specifiers;
4632 parse_declaration_specifiers(&specifiers);
4633 rem_anchor_token(';');
4635 if (token.type == ';') {
4636 parse_anonymous_declaration_rest(&specifiers);
4638 entity_t *entity = parse_declarator(&specifiers, flags);
4639 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4644 static type_t *get_default_promoted_type(type_t *orig_type)
4646 type_t *result = orig_type;
4648 type_t *type = skip_typeref(orig_type);
4649 if (is_type_integer(type)) {
4650 result = promote_integer(type);
4651 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4652 result = type_double;
4658 static void parse_kr_declaration_list(entity_t *entity)
4660 if (entity->kind != ENTITY_FUNCTION)
4663 type_t *type = skip_typeref(entity->declaration.type);
4664 assert(is_type_function(type));
4665 if (!type->function.kr_style_parameters)
4668 add_anchor_token('{');
4670 /* push function parameters */
4671 size_t const top = environment_top();
4672 scope_t *old_scope = scope_push(&entity->function.parameters);
4674 entity_t *parameter = entity->function.parameters.entities;
4675 for ( ; parameter != NULL; parameter = parameter->base.next) {
4676 assert(parameter->base.parent_scope == NULL);
4677 parameter->base.parent_scope = current_scope;
4678 environment_push(parameter);
4681 /* parse declaration list */
4683 switch (token.type) {
4685 case T___extension__:
4686 /* This covers symbols, which are no type, too, and results in
4687 * better error messages. The typical cases are misspelled type
4688 * names and missing includes. */
4690 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4698 /* pop function parameters */
4699 assert(current_scope == &entity->function.parameters);
4700 scope_pop(old_scope);
4701 environment_pop_to(top);
4703 /* update function type */
4704 type_t *new_type = duplicate_type(type);
4706 function_parameter_t *parameters = NULL;
4707 function_parameter_t **anchor = ¶meters;
4709 /* did we have an earlier prototype? */
4710 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4711 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4714 function_parameter_t *proto_parameter = NULL;
4715 if (proto_type != NULL) {
4716 type_t *proto_type_type = proto_type->declaration.type;
4717 proto_parameter = proto_type_type->function.parameters;
4718 /* If a K&R function definition has a variadic prototype earlier, then
4719 * make the function definition variadic, too. This should conform to
4720 * §6.7.5.3:15 and §6.9.1:8. */
4721 new_type->function.variadic = proto_type_type->function.variadic;
4723 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4725 new_type->function.unspecified_parameters = true;
4728 bool need_incompatible_warning = false;
4729 parameter = entity->function.parameters.entities;
4730 for (; parameter != NULL; parameter = parameter->base.next,
4732 proto_parameter == NULL ? NULL : proto_parameter->next) {
4733 if (parameter->kind != ENTITY_PARAMETER)
4736 type_t *parameter_type = parameter->declaration.type;
4737 if (parameter_type == NULL) {
4739 errorf(HERE, "no type specified for function parameter '%Y'",
4740 parameter->base.symbol);
4741 parameter_type = type_error_type;
4743 if (warning.implicit_int) {
4744 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4745 parameter->base.symbol);
4747 parameter_type = type_int;
4749 parameter->declaration.type = parameter_type;
4752 semantic_parameter_incomplete(parameter);
4754 /* we need the default promoted types for the function type */
4755 type_t *not_promoted = parameter_type;
4756 parameter_type = get_default_promoted_type(parameter_type);
4758 /* gcc special: if the type of the prototype matches the unpromoted
4759 * type don't promote */
4760 if (!strict_mode && proto_parameter != NULL) {
4761 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4762 type_t *promo_skip = skip_typeref(parameter_type);
4763 type_t *param_skip = skip_typeref(not_promoted);
4764 if (!types_compatible(proto_p_type, promo_skip)
4765 && types_compatible(proto_p_type, param_skip)) {
4767 need_incompatible_warning = true;
4768 parameter_type = not_promoted;
4771 function_parameter_t *const parameter
4772 = allocate_parameter(parameter_type);
4774 *anchor = parameter;
4775 anchor = ¶meter->next;
4778 new_type->function.parameters = parameters;
4779 new_type = identify_new_type(new_type);
4781 if (warning.other && need_incompatible_warning) {
4782 type_t *proto_type_type = proto_type->declaration.type;
4784 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4785 proto_type_type, proto_type->base.symbol,
4786 new_type, entity->base.symbol,
4787 &proto_type->base.source_position);
4790 entity->declaration.type = new_type;
4792 rem_anchor_token('{');
4795 static bool first_err = true;
4798 * When called with first_err set, prints the name of the current function,
4801 static void print_in_function(void)
4805 diagnosticf("%s: In function '%Y':\n",
4806 current_function->base.base.source_position.input_name,
4807 current_function->base.base.symbol);
4812 * Check if all labels are defined in the current function.
4813 * Check if all labels are used in the current function.
4815 static void check_labels(void)
4817 for (const goto_statement_t *goto_statement = goto_first;
4818 goto_statement != NULL;
4819 goto_statement = goto_statement->next) {
4820 /* skip computed gotos */
4821 if (goto_statement->expression != NULL)
4824 label_t *label = goto_statement->label;
4827 if (label->base.source_position.input_name == NULL) {
4828 print_in_function();
4829 errorf(&goto_statement->base.source_position,
4830 "label '%Y' used but not defined", label->base.symbol);
4834 if (warning.unused_label) {
4835 for (const label_statement_t *label_statement = label_first;
4836 label_statement != NULL;
4837 label_statement = label_statement->next) {
4838 label_t *label = label_statement->label;
4840 if (! label->used) {
4841 print_in_function();
4842 warningf(&label_statement->base.source_position,
4843 "label '%Y' defined but not used", label->base.symbol);
4849 static void warn_unused_entity(entity_t *entity, entity_t *last)
4851 entity_t const *const end = last != NULL ? last->base.next : NULL;
4852 for (; entity != end; entity = entity->base.next) {
4853 if (!is_declaration(entity))
4856 declaration_t *declaration = &entity->declaration;
4857 if (declaration->implicit)
4860 if (!declaration->used) {
4861 print_in_function();
4862 const char *what = get_entity_kind_name(entity->kind);
4863 warningf(&entity->base.source_position, "%s '%Y' is unused",
4864 what, entity->base.symbol);
4865 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4866 print_in_function();
4867 const char *what = get_entity_kind_name(entity->kind);
4868 warningf(&entity->base.source_position, "%s '%Y' is never read",
4869 what, entity->base.symbol);
4874 static void check_unused_variables(statement_t *const stmt, void *const env)
4878 switch (stmt->kind) {
4879 case STATEMENT_DECLARATION: {
4880 declaration_statement_t const *const decls = &stmt->declaration;
4881 warn_unused_entity(decls->declarations_begin,
4882 decls->declarations_end);
4887 warn_unused_entity(stmt->fors.scope.entities, NULL);
4896 * Check declarations of current_function for unused entities.
4898 static void check_declarations(void)
4900 if (warning.unused_parameter) {
4901 const scope_t *scope = ¤t_function->parameters;
4903 /* do not issue unused warnings for main */
4904 if (!is_sym_main(current_function->base.base.symbol)) {
4905 warn_unused_entity(scope->entities, NULL);
4908 if (warning.unused_variable) {
4909 walk_statements(current_function->statement, check_unused_variables,
4914 static int determine_truth(expression_t const* const cond)
4917 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4918 fold_constant_to_bool(cond) ? 1 :
4922 static void check_reachable(statement_t *);
4923 static bool reaches_end;
4925 static bool expression_returns(expression_t const *const expr)
4927 switch (expr->kind) {
4929 expression_t const *const func = expr->call.function;
4930 if (func->kind == EXPR_REFERENCE) {
4931 entity_t *entity = func->reference.entity;
4932 if (entity->kind == ENTITY_FUNCTION
4933 && entity->declaration.modifiers & DM_NORETURN)
4937 if (!expression_returns(func))
4940 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4941 if (!expression_returns(arg->expression))
4948 case EXPR_REFERENCE:
4949 case EXPR_REFERENCE_ENUM_VALUE:
4951 case EXPR_STRING_LITERAL:
4952 case EXPR_WIDE_STRING_LITERAL:
4953 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4954 case EXPR_LABEL_ADDRESS:
4955 case EXPR_CLASSIFY_TYPE:
4956 case EXPR_SIZEOF: // TODO handle obscure VLA case
4959 case EXPR_BUILTIN_CONSTANT_P:
4960 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4965 case EXPR_STATEMENT: {
4966 bool old_reaches_end = reaches_end;
4967 reaches_end = false;
4968 check_reachable(expr->statement.statement);
4969 bool returns = reaches_end;
4970 reaches_end = old_reaches_end;
4974 case EXPR_CONDITIONAL:
4975 // TODO handle constant expression
4977 if (!expression_returns(expr->conditional.condition))
4980 if (expr->conditional.true_expression != NULL
4981 && expression_returns(expr->conditional.true_expression))
4984 return expression_returns(expr->conditional.false_expression);
4987 return expression_returns(expr->select.compound);
4989 case EXPR_ARRAY_ACCESS:
4991 expression_returns(expr->array_access.array_ref) &&
4992 expression_returns(expr->array_access.index);
4995 return expression_returns(expr->va_starte.ap);
4998 return expression_returns(expr->va_arge.ap);
5001 return expression_returns(expr->va_copye.src);
5003 EXPR_UNARY_CASES_MANDATORY
5004 return expression_returns(expr->unary.value);
5006 case EXPR_UNARY_THROW:
5010 // TODO handle constant lhs of && and ||
5012 expression_returns(expr->binary.left) &&
5013 expression_returns(expr->binary.right);
5019 panic("unhandled expression");
5022 static bool initializer_returns(initializer_t const *const init)
5024 switch (init->kind) {
5025 case INITIALIZER_VALUE:
5026 return expression_returns(init->value.value);
5028 case INITIALIZER_LIST: {
5029 initializer_t * const* i = init->list.initializers;
5030 initializer_t * const* const end = i + init->list.len;
5031 bool returns = true;
5032 for (; i != end; ++i) {
5033 if (!initializer_returns(*i))
5039 case INITIALIZER_STRING:
5040 case INITIALIZER_WIDE_STRING:
5041 case INITIALIZER_DESIGNATOR: // designators have no payload
5044 panic("unhandled initializer");
5047 static bool noreturn_candidate;
5049 static void check_reachable(statement_t *const stmt)
5051 if (stmt->base.reachable)
5053 if (stmt->kind != STATEMENT_DO_WHILE)
5054 stmt->base.reachable = true;
5056 statement_t *last = stmt;
5058 switch (stmt->kind) {
5059 case STATEMENT_INVALID:
5060 case STATEMENT_EMPTY:
5062 next = stmt->base.next;
5065 case STATEMENT_DECLARATION: {
5066 declaration_statement_t const *const decl = &stmt->declaration;
5067 entity_t const * ent = decl->declarations_begin;
5068 entity_t const *const last = decl->declarations_end;
5070 for (;; ent = ent->base.next) {
5071 if (ent->kind == ENTITY_VARIABLE &&
5072 ent->variable.initializer != NULL &&
5073 !initializer_returns(ent->variable.initializer)) {
5080 next = stmt->base.next;
5084 case STATEMENT_COMPOUND:
5085 next = stmt->compound.statements;
5087 next = stmt->base.next;
5090 case STATEMENT_RETURN: {
5091 expression_t const *const val = stmt->returns.value;
5092 if (val == NULL || expression_returns(val))
5093 noreturn_candidate = false;
5097 case STATEMENT_IF: {
5098 if_statement_t const *const ifs = &stmt->ifs;
5099 expression_t const *const cond = ifs->condition;
5101 if (!expression_returns(cond))
5104 int const val = determine_truth(cond);
5107 check_reachable(ifs->true_statement);
5112 if (ifs->false_statement != NULL) {
5113 check_reachable(ifs->false_statement);
5117 next = stmt->base.next;
5121 case STATEMENT_SWITCH: {
5122 switch_statement_t const *const switchs = &stmt->switchs;
5123 expression_t const *const expr = switchs->expression;
5125 if (!expression_returns(expr))
5128 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5129 long const val = fold_constant_to_int(expr);
5130 case_label_statement_t * defaults = NULL;
5131 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5132 if (i->expression == NULL) {
5137 if (i->first_case <= val && val <= i->last_case) {
5138 check_reachable((statement_t*)i);
5143 if (defaults != NULL) {
5144 check_reachable((statement_t*)defaults);
5148 bool has_default = false;
5149 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5150 if (i->expression == NULL)
5153 check_reachable((statement_t*)i);
5160 next = stmt->base.next;
5164 case STATEMENT_EXPRESSION: {
5165 /* Check for noreturn function call */
5166 expression_t const *const expr = stmt->expression.expression;
5167 if (!expression_returns(expr))
5170 next = stmt->base.next;
5174 case STATEMENT_CONTINUE:
5175 for (statement_t *parent = stmt;;) {
5176 parent = parent->base.parent;
5177 if (parent == NULL) /* continue not within loop */
5181 switch (parent->kind) {
5182 case STATEMENT_WHILE: goto continue_while;
5183 case STATEMENT_DO_WHILE: goto continue_do_while;
5184 case STATEMENT_FOR: goto continue_for;
5190 case STATEMENT_BREAK:
5191 for (statement_t *parent = stmt;;) {
5192 parent = parent->base.parent;
5193 if (parent == NULL) /* break not within loop/switch */
5196 switch (parent->kind) {
5197 case STATEMENT_SWITCH:
5198 case STATEMENT_WHILE:
5199 case STATEMENT_DO_WHILE:
5202 next = parent->base.next;
5203 goto found_break_parent;
5211 case STATEMENT_GOTO:
5212 if (stmt->gotos.expression) {
5213 if (!expression_returns(stmt->gotos.expression))
5216 statement_t *parent = stmt->base.parent;
5217 if (parent == NULL) /* top level goto */
5221 next = stmt->gotos.label->statement;
5222 if (next == NULL) /* missing label */
5227 case STATEMENT_LABEL:
5228 next = stmt->label.statement;
5231 case STATEMENT_CASE_LABEL:
5232 next = stmt->case_label.statement;
5235 case STATEMENT_WHILE: {
5236 while_statement_t const *const whiles = &stmt->whiles;
5237 expression_t const *const cond = whiles->condition;
5239 if (!expression_returns(cond))
5242 int const val = determine_truth(cond);
5245 check_reachable(whiles->body);
5250 next = stmt->base.next;
5254 case STATEMENT_DO_WHILE:
5255 next = stmt->do_while.body;
5258 case STATEMENT_FOR: {
5259 for_statement_t *const fors = &stmt->fors;
5261 if (fors->condition_reachable)
5263 fors->condition_reachable = true;
5265 expression_t const *const cond = fors->condition;
5270 } else if (expression_returns(cond)) {
5271 val = determine_truth(cond);
5277 check_reachable(fors->body);
5282 next = stmt->base.next;
5286 case STATEMENT_MS_TRY: {
5287 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5288 check_reachable(ms_try->try_statement);
5289 next = ms_try->final_statement;
5293 case STATEMENT_LEAVE: {
5294 statement_t *parent = stmt;
5296 parent = parent->base.parent;
5297 if (parent == NULL) /* __leave not within __try */
5300 if (parent->kind == STATEMENT_MS_TRY) {
5302 next = parent->ms_try.final_statement;
5310 panic("invalid statement kind");
5313 while (next == NULL) {
5314 next = last->base.parent;
5316 noreturn_candidate = false;
5318 type_t *const type = skip_typeref(current_function->base.type);
5319 assert(is_type_function(type));
5320 type_t *const ret = skip_typeref(type->function.return_type);
5321 if (warning.return_type &&
5322 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5323 is_type_valid(ret) &&
5324 !is_sym_main(current_function->base.base.symbol)) {
5325 warningf(&stmt->base.source_position,
5326 "control reaches end of non-void function");
5331 switch (next->kind) {
5332 case STATEMENT_INVALID:
5333 case STATEMENT_EMPTY:
5334 case STATEMENT_DECLARATION:
5335 case STATEMENT_EXPRESSION:
5337 case STATEMENT_RETURN:
5338 case STATEMENT_CONTINUE:
5339 case STATEMENT_BREAK:
5340 case STATEMENT_GOTO:
5341 case STATEMENT_LEAVE:
5342 panic("invalid control flow in function");
5344 case STATEMENT_COMPOUND:
5345 if (next->compound.stmt_expr) {
5351 case STATEMENT_SWITCH:
5352 case STATEMENT_LABEL:
5353 case STATEMENT_CASE_LABEL:
5355 next = next->base.next;
5358 case STATEMENT_WHILE: {
5360 if (next->base.reachable)
5362 next->base.reachable = true;
5364 while_statement_t const *const whiles = &next->whiles;
5365 expression_t const *const cond = whiles->condition;
5367 if (!expression_returns(cond))
5370 int const val = determine_truth(cond);
5373 check_reachable(whiles->body);
5379 next = next->base.next;
5383 case STATEMENT_DO_WHILE: {
5385 if (next->base.reachable)
5387 next->base.reachable = true;
5389 do_while_statement_t const *const dw = &next->do_while;
5390 expression_t const *const cond = dw->condition;
5392 if (!expression_returns(cond))
5395 int const val = determine_truth(cond);
5398 check_reachable(dw->body);
5404 next = next->base.next;
5408 case STATEMENT_FOR: {
5410 for_statement_t *const fors = &next->fors;
5412 fors->step_reachable = true;
5414 if (fors->condition_reachable)
5416 fors->condition_reachable = true;
5418 expression_t const *const cond = fors->condition;
5423 } else if (expression_returns(cond)) {
5424 val = determine_truth(cond);
5430 check_reachable(fors->body);
5436 next = next->base.next;
5440 case STATEMENT_MS_TRY:
5442 next = next->ms_try.final_statement;
5447 check_reachable(next);
5450 static void check_unreachable(statement_t* const stmt, void *const env)
5454 switch (stmt->kind) {
5455 case STATEMENT_DO_WHILE:
5456 if (!stmt->base.reachable) {
5457 expression_t const *const cond = stmt->do_while.condition;
5458 if (determine_truth(cond) >= 0) {
5459 warningf(&cond->base.source_position,
5460 "condition of do-while-loop is unreachable");
5465 case STATEMENT_FOR: {
5466 for_statement_t const* const fors = &stmt->fors;
5468 // if init and step are unreachable, cond is unreachable, too
5469 if (!stmt->base.reachable && !fors->step_reachable) {
5470 warningf(&stmt->base.source_position, "statement is unreachable");
5472 if (!stmt->base.reachable && fors->initialisation != NULL) {
5473 warningf(&fors->initialisation->base.source_position,
5474 "initialisation of for-statement is unreachable");
5477 if (!fors->condition_reachable && fors->condition != NULL) {
5478 warningf(&fors->condition->base.source_position,
5479 "condition of for-statement is unreachable");
5482 if (!fors->step_reachable && fors->step != NULL) {
5483 warningf(&fors->step->base.source_position,
5484 "step of for-statement is unreachable");
5490 case STATEMENT_COMPOUND:
5491 if (stmt->compound.statements != NULL)
5493 goto warn_unreachable;
5495 case STATEMENT_DECLARATION: {
5496 /* Only warn if there is at least one declarator with an initializer.
5497 * This typically occurs in switch statements. */
5498 declaration_statement_t const *const decl = &stmt->declaration;
5499 entity_t const * ent = decl->declarations_begin;
5500 entity_t const *const last = decl->declarations_end;
5502 for (;; ent = ent->base.next) {
5503 if (ent->kind == ENTITY_VARIABLE &&
5504 ent->variable.initializer != NULL) {
5505 goto warn_unreachable;
5515 if (!stmt->base.reachable)
5516 warningf(&stmt->base.source_position, "statement is unreachable");
5521 static void parse_external_declaration(void)
5523 /* function-definitions and declarations both start with declaration
5525 add_anchor_token(';');
5526 declaration_specifiers_t specifiers;
5527 parse_declaration_specifiers(&specifiers);
5528 rem_anchor_token(';');
5530 /* must be a declaration */
5531 if (token.type == ';') {
5532 parse_anonymous_declaration_rest(&specifiers);
5536 add_anchor_token(',');
5537 add_anchor_token('=');
5538 add_anchor_token(';');
5539 add_anchor_token('{');
5541 /* declarator is common to both function-definitions and declarations */
5542 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5544 rem_anchor_token('{');
5545 rem_anchor_token(';');
5546 rem_anchor_token('=');
5547 rem_anchor_token(',');
5549 /* must be a declaration */
5550 switch (token.type) {
5554 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5559 /* must be a function definition */
5560 parse_kr_declaration_list(ndeclaration);
5562 if (token.type != '{') {
5563 parse_error_expected("while parsing function definition", '{', NULL);
5564 eat_until_matching_token(';');
5568 assert(is_declaration(ndeclaration));
5569 type_t *const orig_type = ndeclaration->declaration.type;
5570 type_t * type = skip_typeref(orig_type);
5572 if (!is_type_function(type)) {
5573 if (is_type_valid(type)) {
5574 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5575 type, ndeclaration->base.symbol);
5579 } else if (is_typeref(orig_type)) {
5581 errorf(&ndeclaration->base.source_position,
5582 "type of function definition '%#T' is a typedef",
5583 orig_type, ndeclaration->base.symbol);
5586 if (warning.aggregate_return &&
5587 is_type_compound(skip_typeref(type->function.return_type))) {
5588 warningf(&ndeclaration->base.source_position, "function '%Y' returns an aggregate",
5589 ndeclaration->base.symbol);
5591 if (warning.traditional && !type->function.unspecified_parameters) {
5592 warningf(&ndeclaration->base.source_position, "traditional C rejects ISO C style function definition of function '%Y'",
5593 ndeclaration->base.symbol);
5595 if (warning.old_style_definition && type->function.unspecified_parameters) {
5596 warningf(&ndeclaration->base.source_position, "old-style function definition '%Y'",
5597 ndeclaration->base.symbol);
5600 /* §6.7.5.3:14 a function definition with () means no
5601 * parameters (and not unspecified parameters) */
5602 if (type->function.unspecified_parameters &&
5603 type->function.parameters == NULL) {
5604 type_t *copy = duplicate_type(type);
5605 copy->function.unspecified_parameters = false;
5606 type = identify_new_type(copy);
5608 ndeclaration->declaration.type = type;
5611 entity_t *const entity = record_entity(ndeclaration, true);
5612 assert(entity->kind == ENTITY_FUNCTION);
5613 assert(ndeclaration->kind == ENTITY_FUNCTION);
5615 function_t *const function = &entity->function;
5616 if (ndeclaration != entity) {
5617 function->parameters = ndeclaration->function.parameters;
5619 assert(is_declaration(entity));
5620 type = skip_typeref(entity->declaration.type);
5622 /* push function parameters and switch scope */
5623 size_t const top = environment_top();
5624 scope_t *old_scope = scope_push(&function->parameters);
5626 entity_t *parameter = function->parameters.entities;
5627 for (; parameter != NULL; parameter = parameter->base.next) {
5628 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5629 parameter->base.parent_scope = current_scope;
5631 assert(parameter->base.parent_scope == NULL
5632 || parameter->base.parent_scope == current_scope);
5633 parameter->base.parent_scope = current_scope;
5634 if (parameter->base.symbol == NULL) {
5635 errorf(¶meter->base.source_position, "parameter name omitted");
5638 environment_push(parameter);
5641 if (function->statement != NULL) {
5642 parser_error_multiple_definition(entity, HERE);
5645 /* parse function body */
5646 int label_stack_top = label_top();
5647 function_t *old_current_function = current_function;
5648 entity_t *old_current_entity = current_entity;
5649 current_function = function;
5650 current_entity = entity;
5651 current_parent = NULL;
5654 goto_anchor = &goto_first;
5656 label_anchor = &label_first;
5658 statement_t *const body = parse_compound_statement(false);
5659 function->statement = body;
5662 check_declarations();
5663 if (warning.return_type ||
5664 warning.unreachable_code ||
5665 (warning.missing_noreturn
5666 && !(function->base.modifiers & DM_NORETURN))) {
5667 noreturn_candidate = true;
5668 check_reachable(body);
5669 if (warning.unreachable_code)
5670 walk_statements(body, check_unreachable, NULL);
5671 if (warning.missing_noreturn &&
5672 noreturn_candidate &&
5673 !(function->base.modifiers & DM_NORETURN)) {
5674 warningf(&body->base.source_position,
5675 "function '%#T' is candidate for attribute 'noreturn'",
5676 type, entity->base.symbol);
5680 assert(current_parent == NULL);
5681 assert(current_function == function);
5682 assert(current_entity == entity);
5683 current_entity = old_current_entity;
5684 current_function = old_current_function;
5685 label_pop_to(label_stack_top);
5688 assert(current_scope == &function->parameters);
5689 scope_pop(old_scope);
5690 environment_pop_to(top);
5693 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5694 source_position_t *source_position,
5695 const symbol_t *symbol)
5697 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5699 type->bitfield.base_type = base_type;
5700 type->bitfield.size_expression = size;
5703 type_t *skipped_type = skip_typeref(base_type);
5704 if (!is_type_integer(skipped_type)) {
5705 errorf(HERE, "bitfield base type '%T' is not an integer type",
5709 bit_size = get_type_size(base_type) * 8;
5712 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5713 long v = fold_constant_to_int(size);
5714 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5717 errorf(source_position, "negative width in bit-field '%Y'",
5719 } else if (v == 0 && symbol != NULL) {
5720 errorf(source_position, "zero width for bit-field '%Y'",
5722 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5723 errorf(source_position, "width of '%Y' exceeds its type",
5726 type->bitfield.bit_size = v;
5733 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5735 entity_t *iter = compound->members.entities;
5736 for (; iter != NULL; iter = iter->base.next) {
5737 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5740 if (iter->base.symbol == symbol) {
5742 } else if (iter->base.symbol == NULL) {
5743 /* search in anonymous structs and unions */
5744 type_t *type = skip_typeref(iter->declaration.type);
5745 if (is_type_compound(type)) {
5746 if (find_compound_entry(type->compound.compound, symbol)
5757 static void check_deprecated(const source_position_t *source_position,
5758 const entity_t *entity)
5760 if (!warning.deprecated_declarations)
5762 if (!is_declaration(entity))
5764 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5767 char const *const prefix = get_entity_kind_name(entity->kind);
5768 const char *deprecated_string
5769 = get_deprecated_string(entity->declaration.attributes);
5770 if (deprecated_string != NULL) {
5771 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5772 prefix, entity->base.symbol, &entity->base.source_position,
5775 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5776 entity->base.symbol, &entity->base.source_position);
5781 static expression_t *create_select(const source_position_t *pos,
5783 type_qualifiers_t qualifiers,
5786 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5788 check_deprecated(pos, entry);
5790 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5791 select->select.compound = addr;
5792 select->select.compound_entry = entry;
5794 type_t *entry_type = entry->declaration.type;
5795 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5797 /* we always do the auto-type conversions; the & and sizeof parser contains
5798 * code to revert this! */
5799 select->base.type = automatic_type_conversion(res_type);
5800 if (res_type->kind == TYPE_BITFIELD) {
5801 select->base.type = res_type->bitfield.base_type;
5808 * Find entry with symbol in compound. Search anonymous structs and unions and
5809 * creates implicit select expressions for them.
5810 * Returns the adress for the innermost compound.
5812 static expression_t *find_create_select(const source_position_t *pos,
5814 type_qualifiers_t qualifiers,
5815 compound_t *compound, symbol_t *symbol)
5817 entity_t *iter = compound->members.entities;
5818 for (; iter != NULL; iter = iter->base.next) {
5819 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5822 symbol_t *iter_symbol = iter->base.symbol;
5823 if (iter_symbol == NULL) {
5824 type_t *type = iter->declaration.type;
5825 if (type->kind != TYPE_COMPOUND_STRUCT
5826 && type->kind != TYPE_COMPOUND_UNION)
5829 compound_t *sub_compound = type->compound.compound;
5831 if (find_compound_entry(sub_compound, symbol) == NULL)
5834 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5835 sub_addr->base.source_position = *pos;
5836 sub_addr->select.implicit = true;
5837 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5841 if (iter_symbol == symbol) {
5842 return create_select(pos, addr, qualifiers, iter);
5849 static void parse_compound_declarators(compound_t *compound,
5850 const declaration_specifiers_t *specifiers)
5855 if (token.type == ':') {
5856 source_position_t source_position = *HERE;
5859 type_t *base_type = specifiers->type;
5860 expression_t *size = parse_constant_expression();
5862 type_t *type = make_bitfield_type(base_type, size,
5863 &source_position, NULL);
5865 attribute_t *attributes = parse_attributes(NULL);
5866 attribute_t **anchor = &attributes;
5867 while (*anchor != NULL)
5868 anchor = &(*anchor)->next;
5869 *anchor = specifiers->attributes;
5871 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5872 entity->base.namespc = NAMESPACE_NORMAL;
5873 entity->base.source_position = source_position;
5874 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5875 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5876 entity->declaration.type = type;
5877 entity->declaration.attributes = attributes;
5879 if (attributes != NULL) {
5880 handle_entity_attributes(attributes, entity);
5882 append_entity(&compound->members, entity);
5884 entity = parse_declarator(specifiers,
5885 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5886 if (entity->kind == ENTITY_TYPEDEF) {
5887 errorf(&entity->base.source_position,
5888 "typedef not allowed as compound member");
5890 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5892 /* make sure we don't define a symbol multiple times */
5893 symbol_t *symbol = entity->base.symbol;
5894 if (symbol != NULL) {
5895 entity_t *prev = find_compound_entry(compound, symbol);
5897 errorf(&entity->base.source_position,
5898 "multiple declarations of symbol '%Y' (declared %P)",
5899 symbol, &prev->base.source_position);
5903 if (token.type == ':') {
5904 source_position_t source_position = *HERE;
5906 expression_t *size = parse_constant_expression();
5908 type_t *type = entity->declaration.type;
5909 type_t *bitfield_type = make_bitfield_type(type, size,
5910 &source_position, entity->base.symbol);
5912 attribute_t *attributes = parse_attributes(NULL);
5913 entity->declaration.type = bitfield_type;
5914 handle_entity_attributes(attributes, entity);
5916 type_t *orig_type = entity->declaration.type;
5917 type_t *type = skip_typeref(orig_type);
5918 if (is_type_function(type)) {
5919 errorf(&entity->base.source_position,
5920 "compound member '%Y' must not have function type '%T'",
5921 entity->base.symbol, orig_type);
5922 } else if (is_type_incomplete(type)) {
5923 /* §6.7.2.1:16 flexible array member */
5924 if (!is_type_array(type) ||
5925 token.type != ';' ||
5926 look_ahead(1)->type != '}') {
5927 errorf(&entity->base.source_position,
5928 "compound member '%Y' has incomplete type '%T'",
5929 entity->base.symbol, orig_type);
5934 append_entity(&compound->members, entity);
5937 } while (next_if(','));
5938 expect(';', end_error);
5941 anonymous_entity = NULL;
5944 static void parse_compound_type_entries(compound_t *compound)
5947 add_anchor_token('}');
5949 while (token.type != '}') {
5950 if (token.type == T_EOF) {
5951 errorf(HERE, "EOF while parsing struct");
5954 declaration_specifiers_t specifiers;
5955 parse_declaration_specifiers(&specifiers);
5956 parse_compound_declarators(compound, &specifiers);
5958 rem_anchor_token('}');
5962 compound->complete = true;
5965 static type_t *parse_typename(void)
5967 declaration_specifiers_t specifiers;
5968 parse_declaration_specifiers(&specifiers);
5969 if (specifiers.storage_class != STORAGE_CLASS_NONE
5970 || specifiers.thread_local) {
5971 /* TODO: improve error message, user does probably not know what a
5972 * storage class is...
5974 errorf(HERE, "typename must not have a storage class");
5977 type_t *result = parse_abstract_declarator(specifiers.type);
5985 typedef expression_t* (*parse_expression_function)(void);
5986 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5988 typedef struct expression_parser_function_t expression_parser_function_t;
5989 struct expression_parser_function_t {
5990 parse_expression_function parser;
5991 precedence_t infix_precedence;
5992 parse_expression_infix_function infix_parser;
5995 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5998 * Prints an error message if an expression was expected but not read
6000 static expression_t *expected_expression_error(void)
6002 /* skip the error message if the error token was read */
6003 if (token.type != T_ERROR) {
6004 errorf(HERE, "expected expression, got token %K", &token);
6008 return create_invalid_expression();
6011 static type_t *get_string_type(void)
6013 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6016 static type_t *get_wide_string_type(void)
6018 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6022 * Parse a string constant.
6024 static expression_t *parse_string_literal(void)
6026 source_position_t begin = token.source_position;
6027 string_t res = token.literal;
6028 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6031 while (token.type == T_STRING_LITERAL
6032 || token.type == T_WIDE_STRING_LITERAL) {
6033 warn_string_concat(&token.source_position);
6034 res = concat_strings(&res, &token.literal);
6036 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6039 expression_t *literal;
6041 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6042 literal->base.type = get_wide_string_type();
6044 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6045 literal->base.type = get_string_type();
6047 literal->base.source_position = begin;
6048 literal->literal.value = res;
6054 * Parse a boolean constant.
6056 static expression_t *parse_boolean_literal(bool value)
6058 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6059 literal->base.source_position = token.source_position;
6060 literal->base.type = type_bool;
6061 literal->literal.value.begin = value ? "true" : "false";
6062 literal->literal.value.size = value ? 4 : 5;
6068 static void warn_traditional_suffix(void)
6070 if (!warning.traditional)
6072 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6076 static void check_integer_suffix(void)
6078 symbol_t *suffix = token.symbol;
6082 bool not_traditional = false;
6083 const char *c = suffix->string;
6084 if (*c == 'l' || *c == 'L') {
6087 not_traditional = true;
6089 if (*c == 'u' || *c == 'U') {
6092 } else if (*c == 'u' || *c == 'U') {
6093 not_traditional = true;
6096 } else if (*c == 'u' || *c == 'U') {
6097 not_traditional = true;
6099 if (*c == 'l' || *c == 'L') {
6107 errorf(&token.source_position,
6108 "invalid suffix '%s' on integer constant", suffix->string);
6109 } else if (not_traditional) {
6110 warn_traditional_suffix();
6114 static type_t *check_floatingpoint_suffix(void)
6116 symbol_t *suffix = token.symbol;
6117 type_t *type = type_double;
6121 bool not_traditional = false;
6122 const char *c = suffix->string;
6123 if (*c == 'f' || *c == 'F') {
6126 } else if (*c == 'l' || *c == 'L') {
6128 type = type_long_double;
6131 errorf(&token.source_position,
6132 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6133 } else if (not_traditional) {
6134 warn_traditional_suffix();
6141 * Parse an integer constant.
6143 static expression_t *parse_number_literal(void)
6145 expression_kind_t kind;
6148 switch (token.type) {
6150 kind = EXPR_LITERAL_INTEGER;
6151 check_integer_suffix();
6154 case T_INTEGER_OCTAL:
6155 kind = EXPR_LITERAL_INTEGER_OCTAL;
6156 check_integer_suffix();
6159 case T_INTEGER_HEXADECIMAL:
6160 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6161 check_integer_suffix();
6164 case T_FLOATINGPOINT:
6165 kind = EXPR_LITERAL_FLOATINGPOINT;
6166 type = check_floatingpoint_suffix();
6168 case T_FLOATINGPOINT_HEXADECIMAL:
6169 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6170 type = check_floatingpoint_suffix();
6173 panic("unexpected token type in parse_number_literal");
6176 expression_t *literal = allocate_expression_zero(kind);
6177 literal->base.source_position = token.source_position;
6178 literal->base.type = type;
6179 literal->literal.value = token.literal;
6180 literal->literal.suffix = token.symbol;
6183 /* integer type depends on the size of the number and the size
6184 * representable by the types. The backend/codegeneration has to determine
6187 determine_literal_type(&literal->literal);
6192 * Parse a character constant.
6194 static expression_t *parse_character_constant(void)
6196 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6197 literal->base.source_position = token.source_position;
6198 literal->base.type = c_mode & _CXX ? type_char : type_int;
6199 literal->literal.value = token.literal;
6201 size_t len = literal->literal.value.size;
6203 if (!GNU_MODE && !(c_mode & _C99)) {
6204 errorf(HERE, "more than 1 character in character constant");
6205 } else if (warning.multichar) {
6206 literal->base.type = type_int;
6207 warningf(HERE, "multi-character character constant");
6216 * Parse a wide character constant.
6218 static expression_t *parse_wide_character_constant(void)
6220 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6221 literal->base.source_position = token.source_position;
6222 literal->base.type = type_int;
6223 literal->literal.value = token.literal;
6225 size_t len = wstrlen(&literal->literal.value);
6227 warningf(HERE, "multi-character character constant");
6234 static entity_t *create_implicit_function(symbol_t *symbol,
6235 const source_position_t *source_position)
6237 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6238 ntype->function.return_type = type_int;
6239 ntype->function.unspecified_parameters = true;
6240 ntype->function.linkage = LINKAGE_C;
6241 type_t *type = identify_new_type(ntype);
6243 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6244 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6245 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6246 entity->declaration.type = type;
6247 entity->declaration.implicit = true;
6248 entity->base.namespc = NAMESPACE_NORMAL;
6249 entity->base.symbol = symbol;
6250 entity->base.source_position = *source_position;
6252 if (current_scope != NULL) {
6253 bool strict_prototypes_old = warning.strict_prototypes;
6254 warning.strict_prototypes = false;
6255 record_entity(entity, false);
6256 warning.strict_prototypes = strict_prototypes_old;
6263 * Performs automatic type cast as described in §6.3.2.1.
6265 * @param orig_type the original type
6267 static type_t *automatic_type_conversion(type_t *orig_type)
6269 type_t *type = skip_typeref(orig_type);
6270 if (is_type_array(type)) {
6271 array_type_t *array_type = &type->array;
6272 type_t *element_type = array_type->element_type;
6273 unsigned qualifiers = array_type->base.qualifiers;
6275 return make_pointer_type(element_type, qualifiers);
6278 if (is_type_function(type)) {
6279 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6286 * reverts the automatic casts of array to pointer types and function
6287 * to function-pointer types as defined §6.3.2.1
6289 type_t *revert_automatic_type_conversion(const expression_t *expression)
6291 switch (expression->kind) {
6292 case EXPR_REFERENCE: {
6293 entity_t *entity = expression->reference.entity;
6294 if (is_declaration(entity)) {
6295 return entity->declaration.type;
6296 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6297 return entity->enum_value.enum_type;
6299 panic("no declaration or enum in reference");
6304 entity_t *entity = expression->select.compound_entry;
6305 assert(is_declaration(entity));
6306 type_t *type = entity->declaration.type;
6307 return get_qualified_type(type,
6308 expression->base.type->base.qualifiers);
6311 case EXPR_UNARY_DEREFERENCE: {
6312 const expression_t *const value = expression->unary.value;
6313 type_t *const type = skip_typeref(value->base.type);
6314 if (!is_type_pointer(type))
6315 return type_error_type;
6316 return type->pointer.points_to;
6319 case EXPR_ARRAY_ACCESS: {
6320 const expression_t *array_ref = expression->array_access.array_ref;
6321 type_t *type_left = skip_typeref(array_ref->base.type);
6322 if (!is_type_pointer(type_left))
6323 return type_error_type;
6324 return type_left->pointer.points_to;
6327 case EXPR_STRING_LITERAL: {
6328 size_t size = expression->string_literal.value.size;
6329 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6332 case EXPR_WIDE_STRING_LITERAL: {
6333 size_t size = wstrlen(&expression->string_literal.value);
6334 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6337 case EXPR_COMPOUND_LITERAL:
6338 return expression->compound_literal.type;
6343 return expression->base.type;
6347 * Find an entity matching a symbol in a scope.
6348 * Uses current scope if scope is NULL
6350 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6351 namespace_tag_t namespc)
6353 if (scope == NULL) {
6354 return get_entity(symbol, namespc);
6357 /* we should optimize here, if scope grows above a certain size we should
6358 construct a hashmap here... */
6359 entity_t *entity = scope->entities;
6360 for ( ; entity != NULL; entity = entity->base.next) {
6361 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6368 static entity_t *parse_qualified_identifier(void)
6370 /* namespace containing the symbol */
6372 source_position_t pos;
6373 const scope_t *lookup_scope = NULL;
6375 if (next_if(T_COLONCOLON))
6376 lookup_scope = &unit->scope;
6380 if (token.type != T_IDENTIFIER) {
6381 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6382 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6384 symbol = token.symbol;
6389 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6391 if (!next_if(T_COLONCOLON))
6394 switch (entity->kind) {
6395 case ENTITY_NAMESPACE:
6396 lookup_scope = &entity->namespacee.members;
6401 lookup_scope = &entity->compound.members;
6404 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6405 symbol, get_entity_kind_name(entity->kind));
6410 if (entity == NULL) {
6411 if (!strict_mode && token.type == '(') {
6412 /* an implicitly declared function */
6413 if (warning.error_implicit_function_declaration) {
6414 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6415 } else if (warning.implicit_function_declaration) {
6416 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6419 entity = create_implicit_function(symbol, &pos);
6421 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6422 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6429 /* skip further qualifications */
6430 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6432 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6435 static expression_t *parse_reference(void)
6437 source_position_t const pos = token.source_position;
6438 entity_t *const entity = parse_qualified_identifier();
6441 if (is_declaration(entity)) {
6442 orig_type = entity->declaration.type;
6443 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6444 orig_type = entity->enum_value.enum_type;
6446 panic("expected declaration or enum value in reference");
6449 /* we always do the auto-type conversions; the & and sizeof parser contains
6450 * code to revert this! */
6451 type_t *type = automatic_type_conversion(orig_type);
6453 expression_kind_t kind = EXPR_REFERENCE;
6454 if (entity->kind == ENTITY_ENUM_VALUE)
6455 kind = EXPR_REFERENCE_ENUM_VALUE;
6457 expression_t *expression = allocate_expression_zero(kind);
6458 expression->base.source_position = pos;
6459 expression->base.type = type;
6460 expression->reference.entity = entity;
6462 /* this declaration is used */
6463 if (is_declaration(entity)) {
6464 entity->declaration.used = true;
6467 if (entity->base.parent_scope != file_scope
6468 && (current_function != NULL
6469 && entity->base.parent_scope->depth < current_function->parameters.depth)
6470 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6471 if (entity->kind == ENTITY_VARIABLE) {
6472 /* access of a variable from an outer function */
6473 entity->variable.address_taken = true;
6474 } else if (entity->kind == ENTITY_PARAMETER) {
6475 entity->parameter.address_taken = true;
6477 current_function->need_closure = true;
6480 check_deprecated(HERE, entity);
6482 if (warning.init_self && entity == current_init_decl && !in_type_prop
6483 && entity->kind == ENTITY_VARIABLE) {
6484 current_init_decl = NULL;
6485 warningf(&pos, "variable '%#T' is initialized by itself",
6486 entity->declaration.type, entity->base.symbol);
6492 static bool semantic_cast(expression_t *cast)
6494 expression_t *expression = cast->unary.value;
6495 type_t *orig_dest_type = cast->base.type;
6496 type_t *orig_type_right = expression->base.type;
6497 type_t const *dst_type = skip_typeref(orig_dest_type);
6498 type_t const *src_type = skip_typeref(orig_type_right);
6499 source_position_t const *pos = &cast->base.source_position;
6501 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6502 if (dst_type == type_void)
6505 /* only integer and pointer can be casted to pointer */
6506 if (is_type_pointer(dst_type) &&
6507 !is_type_pointer(src_type) &&
6508 !is_type_integer(src_type) &&
6509 is_type_valid(src_type)) {
6510 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6514 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6515 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6519 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6520 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6524 if (warning.cast_qual &&
6525 is_type_pointer(src_type) &&
6526 is_type_pointer(dst_type)) {
6527 type_t *src = skip_typeref(src_type->pointer.points_to);
6528 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6529 unsigned missing_qualifiers =
6530 src->base.qualifiers & ~dst->base.qualifiers;
6531 if (missing_qualifiers != 0) {
6533 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6534 missing_qualifiers, orig_type_right);
6540 static expression_t *parse_compound_literal(type_t *type)
6542 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6544 parse_initializer_env_t env;
6547 env.must_be_constant = false;
6548 initializer_t *initializer = parse_initializer(&env);
6551 expression->compound_literal.initializer = initializer;
6552 expression->compound_literal.type = type;
6553 expression->base.type = automatic_type_conversion(type);
6559 * Parse a cast expression.
6561 static expression_t *parse_cast(void)
6563 source_position_t source_position = token.source_position;
6566 add_anchor_token(')');
6568 type_t *type = parse_typename();
6570 rem_anchor_token(')');
6571 expect(')', end_error);
6573 if (token.type == '{') {
6574 return parse_compound_literal(type);
6577 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6578 cast->base.source_position = source_position;
6580 expression_t *value = parse_subexpression(PREC_CAST);
6581 cast->base.type = type;
6582 cast->unary.value = value;
6584 if (! semantic_cast(cast)) {
6585 /* TODO: record the error in the AST. else it is impossible to detect it */
6590 return create_invalid_expression();
6594 * Parse a statement expression.
6596 static expression_t *parse_statement_expression(void)
6598 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6601 add_anchor_token(')');
6603 statement_t *statement = parse_compound_statement(true);
6604 statement->compound.stmt_expr = true;
6605 expression->statement.statement = statement;
6607 /* find last statement and use its type */
6608 type_t *type = type_void;
6609 const statement_t *stmt = statement->compound.statements;
6611 while (stmt->base.next != NULL)
6612 stmt = stmt->base.next;
6614 if (stmt->kind == STATEMENT_EXPRESSION) {
6615 type = stmt->expression.expression->base.type;
6617 } else if (warning.other) {
6618 warningf(&expression->base.source_position, "empty statement expression ({})");
6620 expression->base.type = type;
6622 rem_anchor_token(')');
6623 expect(')', end_error);
6630 * Parse a parenthesized expression.
6632 static expression_t *parse_parenthesized_expression(void)
6634 token_t const* const la1 = look_ahead(1);
6635 switch (la1->type) {
6637 /* gcc extension: a statement expression */
6638 return parse_statement_expression();
6641 if (is_typedef_symbol(la1->symbol)) {
6644 return parse_cast();
6649 add_anchor_token(')');
6650 expression_t *result = parse_expression();
6651 result->base.parenthesized = true;
6652 rem_anchor_token(')');
6653 expect(')', end_error);
6659 static expression_t *parse_function_keyword(void)
6663 if (current_function == NULL) {
6664 errorf(HERE, "'__func__' used outside of a function");
6667 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6668 expression->base.type = type_char_ptr;
6669 expression->funcname.kind = FUNCNAME_FUNCTION;
6676 static expression_t *parse_pretty_function_keyword(void)
6678 if (current_function == NULL) {
6679 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6682 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6683 expression->base.type = type_char_ptr;
6684 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6686 eat(T___PRETTY_FUNCTION__);
6691 static expression_t *parse_funcsig_keyword(void)
6693 if (current_function == NULL) {
6694 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6697 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6698 expression->base.type = type_char_ptr;
6699 expression->funcname.kind = FUNCNAME_FUNCSIG;
6706 static expression_t *parse_funcdname_keyword(void)
6708 if (current_function == NULL) {
6709 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6712 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6713 expression->base.type = type_char_ptr;
6714 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6716 eat(T___FUNCDNAME__);
6721 static designator_t *parse_designator(void)
6723 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6724 result->source_position = *HERE;
6726 if (token.type != T_IDENTIFIER) {
6727 parse_error_expected("while parsing member designator",
6728 T_IDENTIFIER, NULL);
6731 result->symbol = token.symbol;
6734 designator_t *last_designator = result;
6737 if (token.type != T_IDENTIFIER) {
6738 parse_error_expected("while parsing member designator",
6739 T_IDENTIFIER, NULL);
6742 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6743 designator->source_position = *HERE;
6744 designator->symbol = token.symbol;
6747 last_designator->next = designator;
6748 last_designator = designator;
6752 add_anchor_token(']');
6753 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6754 designator->source_position = *HERE;
6755 designator->array_index = parse_expression();
6756 rem_anchor_token(']');
6757 expect(']', end_error);
6758 if (designator->array_index == NULL) {
6762 last_designator->next = designator;
6763 last_designator = designator;
6775 * Parse the __builtin_offsetof() expression.
6777 static expression_t *parse_offsetof(void)
6779 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6780 expression->base.type = type_size_t;
6782 eat(T___builtin_offsetof);
6784 expect('(', end_error);
6785 add_anchor_token(',');
6786 type_t *type = parse_typename();
6787 rem_anchor_token(',');
6788 expect(',', end_error);
6789 add_anchor_token(')');
6790 designator_t *designator = parse_designator();
6791 rem_anchor_token(')');
6792 expect(')', end_error);
6794 expression->offsetofe.type = type;
6795 expression->offsetofe.designator = designator;
6798 memset(&path, 0, sizeof(path));
6799 path.top_type = type;
6800 path.path = NEW_ARR_F(type_path_entry_t, 0);
6802 descend_into_subtype(&path);
6804 if (!walk_designator(&path, designator, true)) {
6805 return create_invalid_expression();
6808 DEL_ARR_F(path.path);
6812 return create_invalid_expression();
6816 * Parses a _builtin_va_start() expression.
6818 static expression_t *parse_va_start(void)
6820 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6822 eat(T___builtin_va_start);
6824 expect('(', end_error);
6825 add_anchor_token(',');
6826 expression->va_starte.ap = parse_assignment_expression();
6827 rem_anchor_token(',');
6828 expect(',', end_error);
6829 expression_t *const expr = parse_assignment_expression();
6830 if (expr->kind == EXPR_REFERENCE) {
6831 entity_t *const entity = expr->reference.entity;
6832 if (!current_function->base.type->function.variadic) {
6833 errorf(&expr->base.source_position,
6834 "'va_start' used in non-variadic function");
6835 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6836 entity->base.next != NULL ||
6837 entity->kind != ENTITY_PARAMETER) {
6838 errorf(&expr->base.source_position,
6839 "second argument of 'va_start' must be last parameter of the current function");
6841 expression->va_starte.parameter = &entity->variable;
6843 expect(')', end_error);
6846 expect(')', end_error);
6848 return create_invalid_expression();
6852 * Parses a __builtin_va_arg() expression.
6854 static expression_t *parse_va_arg(void)
6856 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6858 eat(T___builtin_va_arg);
6860 expect('(', end_error);
6862 ap.expression = parse_assignment_expression();
6863 expression->va_arge.ap = ap.expression;
6864 check_call_argument(type_valist, &ap, 1);
6866 expect(',', end_error);
6867 expression->base.type = parse_typename();
6868 expect(')', end_error);
6872 return create_invalid_expression();
6876 * Parses a __builtin_va_copy() expression.
6878 static expression_t *parse_va_copy(void)
6880 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6882 eat(T___builtin_va_copy);
6884 expect('(', end_error);
6885 expression_t *dst = parse_assignment_expression();
6886 assign_error_t error = semantic_assign(type_valist, dst);
6887 report_assign_error(error, type_valist, dst, "call argument 1",
6888 &dst->base.source_position);
6889 expression->va_copye.dst = dst;
6891 expect(',', end_error);
6893 call_argument_t src;
6894 src.expression = parse_assignment_expression();
6895 check_call_argument(type_valist, &src, 2);
6896 expression->va_copye.src = src.expression;
6897 expect(')', end_error);
6901 return create_invalid_expression();
6905 * Parses a __builtin_constant_p() expression.
6907 static expression_t *parse_builtin_constant(void)
6909 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6911 eat(T___builtin_constant_p);
6913 expect('(', end_error);
6914 add_anchor_token(')');
6915 expression->builtin_constant.value = parse_assignment_expression();
6916 rem_anchor_token(')');
6917 expect(')', end_error);
6918 expression->base.type = type_int;
6922 return create_invalid_expression();
6926 * Parses a __builtin_types_compatible_p() expression.
6928 static expression_t *parse_builtin_types_compatible(void)
6930 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6932 eat(T___builtin_types_compatible_p);
6934 expect('(', end_error);
6935 add_anchor_token(')');
6936 add_anchor_token(',');
6937 expression->builtin_types_compatible.left = parse_typename();
6938 rem_anchor_token(',');
6939 expect(',', end_error);
6940 expression->builtin_types_compatible.right = parse_typename();
6941 rem_anchor_token(')');
6942 expect(')', end_error);
6943 expression->base.type = type_int;
6947 return create_invalid_expression();
6951 * Parses a __builtin_is_*() compare expression.
6953 static expression_t *parse_compare_builtin(void)
6955 expression_t *expression;
6957 switch (token.type) {
6958 case T___builtin_isgreater:
6959 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6961 case T___builtin_isgreaterequal:
6962 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6964 case T___builtin_isless:
6965 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6967 case T___builtin_islessequal:
6968 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6970 case T___builtin_islessgreater:
6971 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6973 case T___builtin_isunordered:
6974 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6977 internal_errorf(HERE, "invalid compare builtin found");
6979 expression->base.source_position = *HERE;
6982 expect('(', end_error);
6983 expression->binary.left = parse_assignment_expression();
6984 expect(',', end_error);
6985 expression->binary.right = parse_assignment_expression();
6986 expect(')', end_error);
6988 type_t *const orig_type_left = expression->binary.left->base.type;
6989 type_t *const orig_type_right = expression->binary.right->base.type;
6991 type_t *const type_left = skip_typeref(orig_type_left);
6992 type_t *const type_right = skip_typeref(orig_type_right);
6993 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6994 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6995 type_error_incompatible("invalid operands in comparison",
6996 &expression->base.source_position, orig_type_left, orig_type_right);
6999 semantic_comparison(&expression->binary);
7004 return create_invalid_expression();
7008 * Parses a MS assume() expression.
7010 static expression_t *parse_assume(void)
7012 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7016 expect('(', end_error);
7017 add_anchor_token(')');
7018 expression->unary.value = parse_assignment_expression();
7019 rem_anchor_token(')');
7020 expect(')', end_error);
7022 expression->base.type = type_void;
7025 return create_invalid_expression();
7029 * Return the declaration for a given label symbol or create a new one.
7031 * @param symbol the symbol of the label
7033 static label_t *get_label(symbol_t *symbol)
7036 assert(current_function != NULL);
7038 label = get_entity(symbol, NAMESPACE_LABEL);
7039 /* if we found a local label, we already created the declaration */
7040 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7041 if (label->base.parent_scope != current_scope) {
7042 assert(label->base.parent_scope->depth < current_scope->depth);
7043 current_function->goto_to_outer = true;
7045 return &label->label;
7048 label = get_entity(symbol, NAMESPACE_LABEL);
7049 /* if we found a label in the same function, then we already created the
7052 && label->base.parent_scope == ¤t_function->parameters) {
7053 return &label->label;
7056 /* otherwise we need to create a new one */
7057 label = allocate_entity_zero(ENTITY_LABEL);
7058 label->base.namespc = NAMESPACE_LABEL;
7059 label->base.symbol = symbol;
7063 return &label->label;
7067 * Parses a GNU && label address expression.
7069 static expression_t *parse_label_address(void)
7071 source_position_t source_position = token.source_position;
7073 if (token.type != T_IDENTIFIER) {
7074 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7077 symbol_t *symbol = token.symbol;
7080 label_t *label = get_label(symbol);
7082 label->address_taken = true;
7084 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7085 expression->base.source_position = source_position;
7087 /* label address is threaten as a void pointer */
7088 expression->base.type = type_void_ptr;
7089 expression->label_address.label = label;
7092 return create_invalid_expression();
7096 * Parse a microsoft __noop expression.
7098 static expression_t *parse_noop_expression(void)
7100 /* the result is a (int)0 */
7101 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7102 literal->base.type = type_int;
7103 literal->base.source_position = token.source_position;
7104 literal->literal.value.begin = "__noop";
7105 literal->literal.value.size = 6;
7109 if (token.type == '(') {
7110 /* parse arguments */
7112 add_anchor_token(')');
7113 add_anchor_token(',');
7115 if (token.type != ')') do {
7116 (void)parse_assignment_expression();
7117 } while (next_if(','));
7119 rem_anchor_token(',');
7120 rem_anchor_token(')');
7121 expect(')', end_error);
7128 * Parses a primary expression.
7130 static expression_t *parse_primary_expression(void)
7132 switch (token.type) {
7133 case T_false: return parse_boolean_literal(false);
7134 case T_true: return parse_boolean_literal(true);
7136 case T_INTEGER_OCTAL:
7137 case T_INTEGER_HEXADECIMAL:
7138 case T_FLOATINGPOINT:
7139 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7140 case T_CHARACTER_CONSTANT: return parse_character_constant();
7141 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7142 case T_STRING_LITERAL:
7143 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7144 case T___FUNCTION__:
7145 case T___func__: return parse_function_keyword();
7146 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7147 case T___FUNCSIG__: return parse_funcsig_keyword();
7148 case T___FUNCDNAME__: return parse_funcdname_keyword();
7149 case T___builtin_offsetof: return parse_offsetof();
7150 case T___builtin_va_start: return parse_va_start();
7151 case T___builtin_va_arg: return parse_va_arg();
7152 case T___builtin_va_copy: return parse_va_copy();
7153 case T___builtin_isgreater:
7154 case T___builtin_isgreaterequal:
7155 case T___builtin_isless:
7156 case T___builtin_islessequal:
7157 case T___builtin_islessgreater:
7158 case T___builtin_isunordered: return parse_compare_builtin();
7159 case T___builtin_constant_p: return parse_builtin_constant();
7160 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7161 case T__assume: return parse_assume();
7164 return parse_label_address();
7167 case '(': return parse_parenthesized_expression();
7168 case T___noop: return parse_noop_expression();
7170 /* Gracefully handle type names while parsing expressions. */
7172 return parse_reference();
7174 if (!is_typedef_symbol(token.symbol)) {
7175 return parse_reference();
7179 source_position_t const pos = *HERE;
7180 type_t const *const type = parse_typename();
7181 errorf(&pos, "encountered type '%T' while parsing expression", type);
7182 return create_invalid_expression();
7186 errorf(HERE, "unexpected token %K, expected an expression", &token);
7188 return create_invalid_expression();
7191 static expression_t *parse_array_expression(expression_t *left)
7193 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7194 array_access_expression_t *const arr = &expr->array_access;
7197 add_anchor_token(']');
7199 expression_t *const inside = parse_expression();
7201 type_t *const orig_type_left = left->base.type;
7202 type_t *const orig_type_inside = inside->base.type;
7204 type_t *const type_left = skip_typeref(orig_type_left);
7205 type_t *const type_inside = skip_typeref(orig_type_inside);
7211 if (is_type_pointer(type_left)) {
7214 idx_type = type_inside;
7215 res_type = type_left->pointer.points_to;
7217 } else if (is_type_pointer(type_inside)) {
7218 arr->flipped = true;
7221 idx_type = type_left;
7222 res_type = type_inside->pointer.points_to;
7224 res_type = automatic_type_conversion(res_type);
7225 if (!is_type_integer(idx_type)) {
7226 errorf(&idx->base.source_position, "array subscript must have integer type");
7227 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR) && warning.char_subscripts) {
7228 warningf(&idx->base.source_position, "array subscript has char type");
7231 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7233 "array access on object with non-pointer types '%T', '%T'",
7234 orig_type_left, orig_type_inside);
7236 res_type = type_error_type;
7241 arr->array_ref = ref;
7243 arr->base.type = res_type;
7245 rem_anchor_token(']');
7246 expect(']', end_error);
7251 static expression_t *parse_typeprop(expression_kind_t const kind)
7253 expression_t *tp_expression = allocate_expression_zero(kind);
7254 tp_expression->base.type = type_size_t;
7256 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7258 /* we only refer to a type property, mark this case */
7259 bool old = in_type_prop;
7260 in_type_prop = true;
7263 expression_t *expression;
7264 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7266 add_anchor_token(')');
7267 orig_type = parse_typename();
7268 rem_anchor_token(')');
7269 expect(')', end_error);
7271 if (token.type == '{') {
7272 /* It was not sizeof(type) after all. It is sizeof of an expression
7273 * starting with a compound literal */
7274 expression = parse_compound_literal(orig_type);
7275 goto typeprop_expression;
7278 expression = parse_subexpression(PREC_UNARY);
7280 typeprop_expression:
7281 tp_expression->typeprop.tp_expression = expression;
7283 orig_type = revert_automatic_type_conversion(expression);
7284 expression->base.type = orig_type;
7287 tp_expression->typeprop.type = orig_type;
7288 type_t const* const type = skip_typeref(orig_type);
7289 char const* wrong_type = NULL;
7290 if (is_type_incomplete(type)) {
7291 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7292 wrong_type = "incomplete";
7293 } else if (type->kind == TYPE_FUNCTION) {
7295 /* function types are allowed (and return 1) */
7296 if (warning.other) {
7297 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7298 warningf(&tp_expression->base.source_position,
7299 "%s expression with function argument returns invalid result", what);
7302 wrong_type = "function";
7305 if (is_type_incomplete(type))
7306 wrong_type = "incomplete";
7308 if (type->kind == TYPE_BITFIELD)
7309 wrong_type = "bitfield";
7311 if (wrong_type != NULL) {
7312 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7313 errorf(&tp_expression->base.source_position,
7314 "operand of %s expression must not be of %s type '%T'",
7315 what, wrong_type, orig_type);
7320 return tp_expression;
7323 static expression_t *parse_sizeof(void)
7325 return parse_typeprop(EXPR_SIZEOF);
7328 static expression_t *parse_alignof(void)
7330 return parse_typeprop(EXPR_ALIGNOF);
7333 static expression_t *parse_select_expression(expression_t *addr)
7335 assert(token.type == '.' || token.type == T_MINUSGREATER);
7336 bool select_left_arrow = (token.type == T_MINUSGREATER);
7337 source_position_t const pos = *HERE;
7340 if (token.type != T_IDENTIFIER) {
7341 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7342 return create_invalid_expression();
7344 symbol_t *symbol = token.symbol;
7347 type_t *const orig_type = addr->base.type;
7348 type_t *const type = skip_typeref(orig_type);
7351 bool saw_error = false;
7352 if (is_type_pointer(type)) {
7353 if (!select_left_arrow) {
7355 "request for member '%Y' in something not a struct or union, but '%T'",
7359 type_left = skip_typeref(type->pointer.points_to);
7361 if (select_left_arrow && is_type_valid(type)) {
7362 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7368 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7369 type_left->kind != TYPE_COMPOUND_UNION) {
7371 if (is_type_valid(type_left) && !saw_error) {
7373 "request for member '%Y' in something not a struct or union, but '%T'",
7376 return create_invalid_expression();
7379 compound_t *compound = type_left->compound.compound;
7380 if (!compound->complete) {
7381 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7383 return create_invalid_expression();
7386 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7387 expression_t *result =
7388 find_create_select(&pos, addr, qualifiers, compound, symbol);
7390 if (result == NULL) {
7391 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7392 return create_invalid_expression();
7398 static void check_call_argument(type_t *expected_type,
7399 call_argument_t *argument, unsigned pos)
7401 type_t *expected_type_skip = skip_typeref(expected_type);
7402 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7403 expression_t *arg_expr = argument->expression;
7404 type_t *arg_type = skip_typeref(arg_expr->base.type);
7406 /* handle transparent union gnu extension */
7407 if (is_type_union(expected_type_skip)
7408 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7409 compound_t *union_decl = expected_type_skip->compound.compound;
7410 type_t *best_type = NULL;
7411 entity_t *entry = union_decl->members.entities;
7412 for ( ; entry != NULL; entry = entry->base.next) {
7413 assert(is_declaration(entry));
7414 type_t *decl_type = entry->declaration.type;
7415 error = semantic_assign(decl_type, arg_expr);
7416 if (error == ASSIGN_ERROR_INCOMPATIBLE
7417 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7420 if (error == ASSIGN_SUCCESS) {
7421 best_type = decl_type;
7422 } else if (best_type == NULL) {
7423 best_type = decl_type;
7427 if (best_type != NULL) {
7428 expected_type = best_type;
7432 error = semantic_assign(expected_type, arg_expr);
7433 argument->expression = create_implicit_cast(arg_expr, expected_type);
7435 if (error != ASSIGN_SUCCESS) {
7436 /* report exact scope in error messages (like "in argument 3") */
7438 snprintf(buf, sizeof(buf), "call argument %u", pos);
7439 report_assign_error(error, expected_type, arg_expr, buf,
7440 &arg_expr->base.source_position);
7441 } else if (warning.traditional || warning.conversion) {
7442 type_t *const promoted_type = get_default_promoted_type(arg_type);
7443 if (!types_compatible(expected_type_skip, promoted_type) &&
7444 !types_compatible(expected_type_skip, type_void_ptr) &&
7445 !types_compatible(type_void_ptr, promoted_type)) {
7446 /* Deliberately show the skipped types in this warning */
7447 warningf(&arg_expr->base.source_position,
7448 "passing call argument %u as '%T' rather than '%T' due to prototype",
7449 pos, expected_type_skip, promoted_type);
7455 * Handle the semantic restrictions of builtin calls
7457 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7458 switch (call->function->reference.entity->function.btk) {
7459 case bk_gnu_builtin_return_address:
7460 case bk_gnu_builtin_frame_address: {
7461 /* argument must be constant */
7462 call_argument_t *argument = call->arguments;
7464 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7465 errorf(&call->base.source_position,
7466 "argument of '%Y' must be a constant expression",
7467 call->function->reference.entity->base.symbol);
7471 case bk_gnu_builtin_object_size:
7472 if (call->arguments == NULL)
7475 call_argument_t *arg = call->arguments->next;
7476 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7477 errorf(&call->base.source_position,
7478 "second argument of '%Y' must be a constant expression",
7479 call->function->reference.entity->base.symbol);
7482 case bk_gnu_builtin_prefetch:
7483 /* second and third argument must be constant if existent */
7484 if (call->arguments == NULL)
7486 call_argument_t *rw = call->arguments->next;
7487 call_argument_t *locality = NULL;
7490 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7491 errorf(&call->base.source_position,
7492 "second argument of '%Y' must be a constant expression",
7493 call->function->reference.entity->base.symbol);
7495 locality = rw->next;
7497 if (locality != NULL) {
7498 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7499 errorf(&call->base.source_position,
7500 "third argument of '%Y' must be a constant expression",
7501 call->function->reference.entity->base.symbol);
7503 locality = rw->next;
7512 * Parse a call expression, ie. expression '( ... )'.
7514 * @param expression the function address
7516 static expression_t *parse_call_expression(expression_t *expression)
7518 expression_t *result = allocate_expression_zero(EXPR_CALL);
7519 call_expression_t *call = &result->call;
7520 call->function = expression;
7522 type_t *const orig_type = expression->base.type;
7523 type_t *const type = skip_typeref(orig_type);
7525 function_type_t *function_type = NULL;
7526 if (is_type_pointer(type)) {
7527 type_t *const to_type = skip_typeref(type->pointer.points_to);
7529 if (is_type_function(to_type)) {
7530 function_type = &to_type->function;
7531 call->base.type = function_type->return_type;
7535 if (function_type == NULL && is_type_valid(type)) {
7537 "called object '%E' (type '%T') is not a pointer to a function",
7538 expression, orig_type);
7541 /* parse arguments */
7543 add_anchor_token(')');
7544 add_anchor_token(',');
7546 if (token.type != ')') {
7547 call_argument_t **anchor = &call->arguments;
7549 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7550 argument->expression = parse_assignment_expression();
7553 anchor = &argument->next;
7554 } while (next_if(','));
7556 rem_anchor_token(',');
7557 rem_anchor_token(')');
7558 expect(')', end_error);
7560 if (function_type == NULL)
7563 /* check type and count of call arguments */
7564 function_parameter_t *parameter = function_type->parameters;
7565 call_argument_t *argument = call->arguments;
7566 if (!function_type->unspecified_parameters) {
7567 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7568 parameter = parameter->next, argument = argument->next) {
7569 check_call_argument(parameter->type, argument, ++pos);
7572 if (parameter != NULL) {
7573 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7574 } else if (argument != NULL && !function_type->variadic) {
7575 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7579 /* do default promotion for other arguments */
7580 for (; argument != NULL; argument = argument->next) {
7581 type_t *type = argument->expression->base.type;
7582 if (!is_type_object(skip_typeref(type))) {
7583 errorf(&argument->expression->base.source_position,
7584 "call argument '%E' must not be void", argument->expression);
7587 type = get_default_promoted_type(type);
7589 argument->expression
7590 = create_implicit_cast(argument->expression, type);
7595 if (warning.aggregate_return &&
7596 is_type_compound(skip_typeref(function_type->return_type))) {
7597 warningf(&expression->base.source_position,
7598 "function call has aggregate value");
7601 if (expression->kind == EXPR_REFERENCE) {
7602 reference_expression_t *reference = &expression->reference;
7603 if (reference->entity->kind == ENTITY_FUNCTION &&
7604 reference->entity->function.btk != bk_none)
7605 handle_builtin_argument_restrictions(call);
7612 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7614 static bool same_compound_type(const type_t *type1, const type_t *type2)
7617 is_type_compound(type1) &&
7618 type1->kind == type2->kind &&
7619 type1->compound.compound == type2->compound.compound;
7622 static expression_t const *get_reference_address(expression_t const *expr)
7624 bool regular_take_address = true;
7626 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7627 expr = expr->unary.value;
7629 regular_take_address = false;
7632 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7635 expr = expr->unary.value;
7638 if (expr->kind != EXPR_REFERENCE)
7641 /* special case for functions which are automatically converted to a
7642 * pointer to function without an extra TAKE_ADDRESS operation */
7643 if (!regular_take_address &&
7644 expr->reference.entity->kind != ENTITY_FUNCTION) {
7651 static void warn_reference_address_as_bool(expression_t const* expr)
7653 if (!warning.address)
7656 expr = get_reference_address(expr);
7658 warningf(&expr->base.source_position,
7659 "the address of '%Y' will always evaluate as 'true'",
7660 expr->reference.entity->base.symbol);
7664 static void warn_assignment_in_condition(const expression_t *const expr)
7666 if (!warning.parentheses)
7668 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7670 if (expr->base.parenthesized)
7672 warningf(&expr->base.source_position,
7673 "suggest parentheses around assignment used as truth value");
7676 static void semantic_condition(expression_t const *const expr,
7677 char const *const context)
7679 type_t *const type = skip_typeref(expr->base.type);
7680 if (is_type_scalar(type)) {
7681 warn_reference_address_as_bool(expr);
7682 warn_assignment_in_condition(expr);
7683 } else if (is_type_valid(type)) {
7684 errorf(&expr->base.source_position,
7685 "%s must have scalar type", context);
7690 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7692 * @param expression the conditional expression
7694 static expression_t *parse_conditional_expression(expression_t *expression)
7696 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7698 conditional_expression_t *conditional = &result->conditional;
7699 conditional->condition = expression;
7702 add_anchor_token(':');
7704 /* §6.5.15:2 The first operand shall have scalar type. */
7705 semantic_condition(expression, "condition of conditional operator");
7707 expression_t *true_expression = expression;
7708 bool gnu_cond = false;
7709 if (GNU_MODE && token.type == ':') {
7712 true_expression = parse_expression();
7714 rem_anchor_token(':');
7715 expect(':', end_error);
7717 expression_t *false_expression =
7718 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7720 type_t *const orig_true_type = true_expression->base.type;
7721 type_t *const orig_false_type = false_expression->base.type;
7722 type_t *const true_type = skip_typeref(orig_true_type);
7723 type_t *const false_type = skip_typeref(orig_false_type);
7726 type_t *result_type;
7727 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7728 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7729 /* ISO/IEC 14882:1998(E) §5.16:2 */
7730 if (true_expression->kind == EXPR_UNARY_THROW) {
7731 result_type = false_type;
7732 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7733 result_type = true_type;
7735 if (warning.other && (
7736 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7737 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7739 warningf(&conditional->base.source_position,
7740 "ISO C forbids conditional expression with only one void side");
7742 result_type = type_void;
7744 } else if (is_type_arithmetic(true_type)
7745 && is_type_arithmetic(false_type)) {
7746 result_type = semantic_arithmetic(true_type, false_type);
7747 } else if (same_compound_type(true_type, false_type)) {
7748 /* just take 1 of the 2 types */
7749 result_type = true_type;
7750 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7751 type_t *pointer_type;
7753 expression_t *other_expression;
7754 if (is_type_pointer(true_type) &&
7755 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7756 pointer_type = true_type;
7757 other_type = false_type;
7758 other_expression = false_expression;
7760 pointer_type = false_type;
7761 other_type = true_type;
7762 other_expression = true_expression;
7765 if (is_null_pointer_constant(other_expression)) {
7766 result_type = pointer_type;
7767 } else if (is_type_pointer(other_type)) {
7768 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7769 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7772 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7773 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7775 } else if (types_compatible(get_unqualified_type(to1),
7776 get_unqualified_type(to2))) {
7779 if (warning.other) {
7780 warningf(&conditional->base.source_position,
7781 "pointer types '%T' and '%T' in conditional expression are incompatible",
7782 true_type, false_type);
7787 type_t *const type =
7788 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7789 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7790 } else if (is_type_integer(other_type)) {
7791 if (warning.other) {
7792 warningf(&conditional->base.source_position,
7793 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7795 result_type = pointer_type;
7797 if (is_type_valid(other_type)) {
7798 type_error_incompatible("while parsing conditional",
7799 &expression->base.source_position, true_type, false_type);
7801 result_type = type_error_type;
7804 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7805 type_error_incompatible("while parsing conditional",
7806 &conditional->base.source_position, true_type,
7809 result_type = type_error_type;
7812 conditional->true_expression
7813 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7814 conditional->false_expression
7815 = create_implicit_cast(false_expression, result_type);
7816 conditional->base.type = result_type;
7821 * Parse an extension expression.
7823 static expression_t *parse_extension(void)
7825 eat(T___extension__);
7827 bool old_gcc_extension = in_gcc_extension;
7828 in_gcc_extension = true;
7829 expression_t *expression = parse_subexpression(PREC_UNARY);
7830 in_gcc_extension = old_gcc_extension;
7835 * Parse a __builtin_classify_type() expression.
7837 static expression_t *parse_builtin_classify_type(void)
7839 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7840 result->base.type = type_int;
7842 eat(T___builtin_classify_type);
7844 expect('(', end_error);
7845 add_anchor_token(')');
7846 expression_t *expression = parse_expression();
7847 rem_anchor_token(')');
7848 expect(')', end_error);
7849 result->classify_type.type_expression = expression;
7853 return create_invalid_expression();
7857 * Parse a delete expression
7858 * ISO/IEC 14882:1998(E) §5.3.5
7860 static expression_t *parse_delete(void)
7862 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7863 result->base.type = type_void;
7868 result->kind = EXPR_UNARY_DELETE_ARRAY;
7869 expect(']', end_error);
7873 expression_t *const value = parse_subexpression(PREC_CAST);
7874 result->unary.value = value;
7876 type_t *const type = skip_typeref(value->base.type);
7877 if (!is_type_pointer(type)) {
7878 if (is_type_valid(type)) {
7879 errorf(&value->base.source_position,
7880 "operand of delete must have pointer type");
7882 } else if (warning.other &&
7883 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7884 warningf(&value->base.source_position,
7885 "deleting 'void*' is undefined");
7892 * Parse a throw expression
7893 * ISO/IEC 14882:1998(E) §15:1
7895 static expression_t *parse_throw(void)
7897 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7898 result->base.type = type_void;
7902 expression_t *value = NULL;
7903 switch (token.type) {
7905 value = parse_assignment_expression();
7906 /* ISO/IEC 14882:1998(E) §15.1:3 */
7907 type_t *const orig_type = value->base.type;
7908 type_t *const type = skip_typeref(orig_type);
7909 if (is_type_incomplete(type)) {
7910 errorf(&value->base.source_position,
7911 "cannot throw object of incomplete type '%T'", orig_type);
7912 } else if (is_type_pointer(type)) {
7913 type_t *const points_to = skip_typeref(type->pointer.points_to);
7914 if (is_type_incomplete(points_to) &&
7915 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7916 errorf(&value->base.source_position,
7917 "cannot throw pointer to incomplete type '%T'", orig_type);
7925 result->unary.value = value;
7930 static bool check_pointer_arithmetic(const source_position_t *source_position,
7931 type_t *pointer_type,
7932 type_t *orig_pointer_type)
7934 type_t *points_to = pointer_type->pointer.points_to;
7935 points_to = skip_typeref(points_to);
7937 if (is_type_incomplete(points_to)) {
7938 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7939 errorf(source_position,
7940 "arithmetic with pointer to incomplete type '%T' not allowed",
7943 } else if (warning.pointer_arith) {
7944 warningf(source_position,
7945 "pointer of type '%T' used in arithmetic",
7948 } else if (is_type_function(points_to)) {
7950 errorf(source_position,
7951 "arithmetic with pointer to function type '%T' not allowed",
7954 } else if (warning.pointer_arith) {
7955 warningf(source_position,
7956 "pointer to a function '%T' used in arithmetic",
7963 static bool is_lvalue(const expression_t *expression)
7965 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7966 switch (expression->kind) {
7967 case EXPR_ARRAY_ACCESS:
7968 case EXPR_COMPOUND_LITERAL:
7969 case EXPR_REFERENCE:
7971 case EXPR_UNARY_DEREFERENCE:
7975 type_t *type = skip_typeref(expression->base.type);
7977 /* ISO/IEC 14882:1998(E) §3.10:3 */
7978 is_type_reference(type) ||
7979 /* Claim it is an lvalue, if the type is invalid. There was a parse
7980 * error before, which maybe prevented properly recognizing it as
7982 !is_type_valid(type);
7987 static void semantic_incdec(unary_expression_t *expression)
7989 type_t *const orig_type = expression->value->base.type;
7990 type_t *const type = skip_typeref(orig_type);
7991 if (is_type_pointer(type)) {
7992 if (!check_pointer_arithmetic(&expression->base.source_position,
7996 } else if (!is_type_real(type) && is_type_valid(type)) {
7997 /* TODO: improve error message */
7998 errorf(&expression->base.source_position,
7999 "operation needs an arithmetic or pointer type");
8002 if (!is_lvalue(expression->value)) {
8003 /* TODO: improve error message */
8004 errorf(&expression->base.source_position, "lvalue required as operand");
8006 expression->base.type = orig_type;
8009 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8011 type_t *const orig_type = expression->value->base.type;
8012 type_t *const type = skip_typeref(orig_type);
8013 if (!is_type_arithmetic(type)) {
8014 if (is_type_valid(type)) {
8015 /* TODO: improve error message */
8016 errorf(&expression->base.source_position,
8017 "operation needs an arithmetic type");
8022 expression->base.type = orig_type;
8025 static void semantic_unexpr_plus(unary_expression_t *expression)
8027 semantic_unexpr_arithmetic(expression);
8028 if (warning.traditional)
8029 warningf(&expression->base.source_position,
8030 "traditional C rejects the unary plus operator");
8033 static void semantic_not(unary_expression_t *expression)
8035 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8036 semantic_condition(expression->value, "operand of !");
8037 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8040 static void semantic_unexpr_integer(unary_expression_t *expression)
8042 type_t *const orig_type = expression->value->base.type;
8043 type_t *const type = skip_typeref(orig_type);
8044 if (!is_type_integer(type)) {
8045 if (is_type_valid(type)) {
8046 errorf(&expression->base.source_position,
8047 "operand of ~ must be of integer type");
8052 expression->base.type = orig_type;
8055 static void semantic_dereference(unary_expression_t *expression)
8057 type_t *const orig_type = expression->value->base.type;
8058 type_t *const type = skip_typeref(orig_type);
8059 if (!is_type_pointer(type)) {
8060 if (is_type_valid(type)) {
8061 errorf(&expression->base.source_position,
8062 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8067 type_t *result_type = type->pointer.points_to;
8068 result_type = automatic_type_conversion(result_type);
8069 expression->base.type = result_type;
8073 * Record that an address is taken (expression represents an lvalue).
8075 * @param expression the expression
8076 * @param may_be_register if true, the expression might be an register
8078 static void set_address_taken(expression_t *expression, bool may_be_register)
8080 if (expression->kind != EXPR_REFERENCE)
8083 entity_t *const entity = expression->reference.entity;
8085 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8088 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8089 && !may_be_register) {
8090 errorf(&expression->base.source_position,
8091 "address of register %s '%Y' requested",
8092 get_entity_kind_name(entity->kind), entity->base.symbol);
8095 if (entity->kind == ENTITY_VARIABLE) {
8096 entity->variable.address_taken = true;
8098 assert(entity->kind == ENTITY_PARAMETER);
8099 entity->parameter.address_taken = true;
8104 * Check the semantic of the address taken expression.
8106 static void semantic_take_addr(unary_expression_t *expression)
8108 expression_t *value = expression->value;
8109 value->base.type = revert_automatic_type_conversion(value);
8111 type_t *orig_type = value->base.type;
8112 type_t *type = skip_typeref(orig_type);
8113 if (!is_type_valid(type))
8117 if (!is_lvalue(value)) {
8118 errorf(&expression->base.source_position, "'&' requires an lvalue");
8120 if (type->kind == TYPE_BITFIELD) {
8121 errorf(&expression->base.source_position,
8122 "'&' not allowed on object with bitfield type '%T'",
8126 set_address_taken(value, false);
8128 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8131 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8132 static expression_t *parse_##unexpression_type(void) \
8134 expression_t *unary_expression \
8135 = allocate_expression_zero(unexpression_type); \
8137 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8139 sfunc(&unary_expression->unary); \
8141 return unary_expression; \
8144 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8145 semantic_unexpr_arithmetic)
8146 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8147 semantic_unexpr_plus)
8148 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8150 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8151 semantic_dereference)
8152 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8154 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8155 semantic_unexpr_integer)
8156 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8158 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8161 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8163 static expression_t *parse_##unexpression_type(expression_t *left) \
8165 expression_t *unary_expression \
8166 = allocate_expression_zero(unexpression_type); \
8168 unary_expression->unary.value = left; \
8170 sfunc(&unary_expression->unary); \
8172 return unary_expression; \
8175 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8176 EXPR_UNARY_POSTFIX_INCREMENT,
8178 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8179 EXPR_UNARY_POSTFIX_DECREMENT,
8182 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8184 /* TODO: handle complex + imaginary types */
8186 type_left = get_unqualified_type(type_left);
8187 type_right = get_unqualified_type(type_right);
8189 /* §6.3.1.8 Usual arithmetic conversions */
8190 if (type_left == type_long_double || type_right == type_long_double) {
8191 return type_long_double;
8192 } else if (type_left == type_double || type_right == type_double) {
8194 } else if (type_left == type_float || type_right == type_float) {
8198 type_left = promote_integer(type_left);
8199 type_right = promote_integer(type_right);
8201 if (type_left == type_right)
8204 bool const signed_left = is_type_signed(type_left);
8205 bool const signed_right = is_type_signed(type_right);
8206 int const rank_left = get_rank(type_left);
8207 int const rank_right = get_rank(type_right);
8209 if (signed_left == signed_right)
8210 return rank_left >= rank_right ? type_left : type_right;
8219 u_rank = rank_right;
8220 u_type = type_right;
8222 s_rank = rank_right;
8223 s_type = type_right;
8228 if (u_rank >= s_rank)
8231 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8233 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8234 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8238 case ATOMIC_TYPE_INT: return type_unsigned_int;
8239 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8240 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8242 default: panic("invalid atomic type");
8247 * Check the semantic restrictions for a binary expression.
8249 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8251 expression_t *const left = expression->left;
8252 expression_t *const right = expression->right;
8253 type_t *const orig_type_left = left->base.type;
8254 type_t *const orig_type_right = right->base.type;
8255 type_t *const type_left = skip_typeref(orig_type_left);
8256 type_t *const type_right = skip_typeref(orig_type_right);
8258 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8259 /* TODO: improve error message */
8260 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8261 errorf(&expression->base.source_position,
8262 "operation needs arithmetic types");
8267 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8268 expression->left = create_implicit_cast(left, arithmetic_type);
8269 expression->right = create_implicit_cast(right, arithmetic_type);
8270 expression->base.type = arithmetic_type;
8273 static void semantic_binexpr_integer(binary_expression_t *const expression)
8275 expression_t *const left = expression->left;
8276 expression_t *const right = expression->right;
8277 type_t *const orig_type_left = left->base.type;
8278 type_t *const orig_type_right = right->base.type;
8279 type_t *const type_left = skip_typeref(orig_type_left);
8280 type_t *const type_right = skip_typeref(orig_type_right);
8282 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8283 /* TODO: improve error message */
8284 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8285 errorf(&expression->base.source_position,
8286 "operation needs integer types");
8291 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8292 expression->left = create_implicit_cast(left, result_type);
8293 expression->right = create_implicit_cast(right, result_type);
8294 expression->base.type = result_type;
8297 static void warn_div_by_zero(binary_expression_t const *const expression)
8299 if (!warning.div_by_zero ||
8300 !is_type_integer(expression->base.type))
8303 expression_t const *const right = expression->right;
8304 /* The type of the right operand can be different for /= */
8305 if (is_type_integer(right->base.type) &&
8306 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8307 !fold_constant_to_bool(right)) {
8308 warningf(&expression->base.source_position, "division by zero");
8313 * Check the semantic restrictions for a div/mod expression.
8315 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8317 semantic_binexpr_arithmetic(expression);
8318 warn_div_by_zero(expression);
8321 static void warn_addsub_in_shift(const expression_t *const expr)
8323 if (expr->base.parenthesized)
8327 switch (expr->kind) {
8328 case EXPR_BINARY_ADD: op = '+'; break;
8329 case EXPR_BINARY_SUB: op = '-'; break;
8333 warningf(&expr->base.source_position,
8334 "suggest parentheses around '%c' inside shift", op);
8337 static bool semantic_shift(binary_expression_t *expression)
8339 expression_t *const left = expression->left;
8340 expression_t *const right = expression->right;
8341 type_t *const orig_type_left = left->base.type;
8342 type_t *const orig_type_right = right->base.type;
8343 type_t * type_left = skip_typeref(orig_type_left);
8344 type_t * type_right = skip_typeref(orig_type_right);
8346 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8347 /* TODO: improve error message */
8348 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8349 errorf(&expression->base.source_position,
8350 "operands of shift operation must have integer types");
8355 type_left = promote_integer(type_left);
8357 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8358 long count = fold_constant_to_int(right);
8360 warningf(&right->base.source_position,
8361 "shift count must be non-negative");
8362 } else if ((unsigned long)count >=
8363 get_atomic_type_size(type_left->atomic.akind) * 8) {
8364 warningf(&right->base.source_position,
8365 "shift count must be less than type width");
8369 type_right = promote_integer(type_right);
8370 expression->right = create_implicit_cast(right, type_right);
8375 static void semantic_shift_op(binary_expression_t *expression)
8377 expression_t *const left = expression->left;
8378 expression_t *const right = expression->right;
8380 if (!semantic_shift(expression))
8383 if (warning.parentheses) {
8384 warn_addsub_in_shift(left);
8385 warn_addsub_in_shift(right);
8388 type_t *const orig_type_left = left->base.type;
8389 type_t * type_left = skip_typeref(orig_type_left);
8391 type_left = promote_integer(type_left);
8392 expression->left = create_implicit_cast(left, type_left);
8393 expression->base.type = type_left;
8396 static void semantic_add(binary_expression_t *expression)
8398 expression_t *const left = expression->left;
8399 expression_t *const right = expression->right;
8400 type_t *const orig_type_left = left->base.type;
8401 type_t *const orig_type_right = right->base.type;
8402 type_t *const type_left = skip_typeref(orig_type_left);
8403 type_t *const type_right = skip_typeref(orig_type_right);
8406 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8407 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8408 expression->left = create_implicit_cast(left, arithmetic_type);
8409 expression->right = create_implicit_cast(right, arithmetic_type);
8410 expression->base.type = arithmetic_type;
8411 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8412 check_pointer_arithmetic(&expression->base.source_position,
8413 type_left, orig_type_left);
8414 expression->base.type = type_left;
8415 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8416 check_pointer_arithmetic(&expression->base.source_position,
8417 type_right, orig_type_right);
8418 expression->base.type = type_right;
8419 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8420 errorf(&expression->base.source_position,
8421 "invalid operands to binary + ('%T', '%T')",
8422 orig_type_left, orig_type_right);
8426 static void semantic_sub(binary_expression_t *expression)
8428 expression_t *const left = expression->left;
8429 expression_t *const right = expression->right;
8430 type_t *const orig_type_left = left->base.type;
8431 type_t *const orig_type_right = right->base.type;
8432 type_t *const type_left = skip_typeref(orig_type_left);
8433 type_t *const type_right = skip_typeref(orig_type_right);
8434 source_position_t const *const pos = &expression->base.source_position;
8437 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8438 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8439 expression->left = create_implicit_cast(left, arithmetic_type);
8440 expression->right = create_implicit_cast(right, arithmetic_type);
8441 expression->base.type = arithmetic_type;
8442 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8443 check_pointer_arithmetic(&expression->base.source_position,
8444 type_left, orig_type_left);
8445 expression->base.type = type_left;
8446 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8447 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8448 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8449 if (!types_compatible(unqual_left, unqual_right)) {
8451 "subtracting pointers to incompatible types '%T' and '%T'",
8452 orig_type_left, orig_type_right);
8453 } else if (!is_type_object(unqual_left)) {
8454 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8455 errorf(pos, "subtracting pointers to non-object types '%T'",
8457 } else if (warning.other) {
8458 warningf(pos, "subtracting pointers to void");
8461 expression->base.type = type_ptrdiff_t;
8462 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8463 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8464 orig_type_left, orig_type_right);
8468 static void warn_string_literal_address(expression_t const* expr)
8470 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8471 expr = expr->unary.value;
8472 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8474 expr = expr->unary.value;
8477 if (expr->kind == EXPR_STRING_LITERAL
8478 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8479 warningf(&expr->base.source_position,
8480 "comparison with string literal results in unspecified behaviour");
8484 static void warn_comparison_in_comparison(const expression_t *const expr)
8486 if (expr->base.parenthesized)
8488 switch (expr->base.kind) {
8489 case EXPR_BINARY_LESS:
8490 case EXPR_BINARY_GREATER:
8491 case EXPR_BINARY_LESSEQUAL:
8492 case EXPR_BINARY_GREATEREQUAL:
8493 case EXPR_BINARY_NOTEQUAL:
8494 case EXPR_BINARY_EQUAL:
8495 warningf(&expr->base.source_position,
8496 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8503 static bool maybe_negative(expression_t const *const expr)
8505 switch (is_constant_expression(expr)) {
8506 case EXPR_CLASS_ERROR: return false;
8507 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8508 default: return true;
8513 * Check the semantics of comparison expressions.
8515 * @param expression The expression to check.
8517 static void semantic_comparison(binary_expression_t *expression)
8519 expression_t *left = expression->left;
8520 expression_t *right = expression->right;
8522 if (warning.address) {
8523 warn_string_literal_address(left);
8524 warn_string_literal_address(right);
8526 expression_t const* const func_left = get_reference_address(left);
8527 if (func_left != NULL && is_null_pointer_constant(right)) {
8528 warningf(&expression->base.source_position,
8529 "the address of '%Y' will never be NULL",
8530 func_left->reference.entity->base.symbol);
8533 expression_t const* const func_right = get_reference_address(right);
8534 if (func_right != NULL && is_null_pointer_constant(right)) {
8535 warningf(&expression->base.source_position,
8536 "the address of '%Y' will never be NULL",
8537 func_right->reference.entity->base.symbol);
8541 if (warning.parentheses) {
8542 warn_comparison_in_comparison(left);
8543 warn_comparison_in_comparison(right);
8546 type_t *orig_type_left = left->base.type;
8547 type_t *orig_type_right = right->base.type;
8548 type_t *type_left = skip_typeref(orig_type_left);
8549 type_t *type_right = skip_typeref(orig_type_right);
8551 /* TODO non-arithmetic types */
8552 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8553 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8555 /* test for signed vs unsigned compares */
8556 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8557 bool const signed_left = is_type_signed(type_left);
8558 bool const signed_right = is_type_signed(type_right);
8559 if (signed_left != signed_right) {
8560 /* FIXME long long needs better const folding magic */
8561 /* TODO check whether constant value can be represented by other type */
8562 if ((signed_left && maybe_negative(left)) ||
8563 (signed_right && maybe_negative(right))) {
8564 warningf(&expression->base.source_position,
8565 "comparison between signed and unsigned");
8570 expression->left = create_implicit_cast(left, arithmetic_type);
8571 expression->right = create_implicit_cast(right, arithmetic_type);
8572 expression->base.type = arithmetic_type;
8573 if (warning.float_equal &&
8574 (expression->base.kind == EXPR_BINARY_EQUAL ||
8575 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8576 is_type_float(arithmetic_type)) {
8577 warningf(&expression->base.source_position,
8578 "comparing floating point with == or != is unsafe");
8580 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8581 /* TODO check compatibility */
8582 } else if (is_type_pointer(type_left)) {
8583 expression->right = create_implicit_cast(right, type_left);
8584 } else if (is_type_pointer(type_right)) {
8585 expression->left = create_implicit_cast(left, type_right);
8586 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8587 type_error_incompatible("invalid operands in comparison",
8588 &expression->base.source_position,
8589 type_left, type_right);
8591 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8595 * Checks if a compound type has constant fields.
8597 static bool has_const_fields(const compound_type_t *type)
8599 compound_t *compound = type->compound;
8600 entity_t *entry = compound->members.entities;
8602 for (; entry != NULL; entry = entry->base.next) {
8603 if (!is_declaration(entry))
8606 const type_t *decl_type = skip_typeref(entry->declaration.type);
8607 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8614 static bool is_valid_assignment_lhs(expression_t const* const left)
8616 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8617 type_t *const type_left = skip_typeref(orig_type_left);
8619 if (!is_lvalue(left)) {
8620 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8625 if (left->kind == EXPR_REFERENCE
8626 && left->reference.entity->kind == ENTITY_FUNCTION) {
8627 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8631 if (is_type_array(type_left)) {
8632 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8635 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8636 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8640 if (is_type_incomplete(type_left)) {
8641 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8642 left, orig_type_left);
8645 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8646 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8647 left, orig_type_left);
8654 static void semantic_arithmetic_assign(binary_expression_t *expression)
8656 expression_t *left = expression->left;
8657 expression_t *right = expression->right;
8658 type_t *orig_type_left = left->base.type;
8659 type_t *orig_type_right = right->base.type;
8661 if (!is_valid_assignment_lhs(left))
8664 type_t *type_left = skip_typeref(orig_type_left);
8665 type_t *type_right = skip_typeref(orig_type_right);
8667 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8668 /* TODO: improve error message */
8669 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8670 errorf(&expression->base.source_position,
8671 "operation needs arithmetic types");
8676 /* combined instructions are tricky. We can't create an implicit cast on
8677 * the left side, because we need the uncasted form for the store.
8678 * The ast2firm pass has to know that left_type must be right_type
8679 * for the arithmetic operation and create a cast by itself */
8680 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8681 expression->right = create_implicit_cast(right, arithmetic_type);
8682 expression->base.type = type_left;
8685 static void semantic_divmod_assign(binary_expression_t *expression)
8687 semantic_arithmetic_assign(expression);
8688 warn_div_by_zero(expression);
8691 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8693 expression_t *const left = expression->left;
8694 expression_t *const right = expression->right;
8695 type_t *const orig_type_left = left->base.type;
8696 type_t *const orig_type_right = right->base.type;
8697 type_t *const type_left = skip_typeref(orig_type_left);
8698 type_t *const type_right = skip_typeref(orig_type_right);
8700 if (!is_valid_assignment_lhs(left))
8703 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8704 /* combined instructions are tricky. We can't create an implicit cast on
8705 * the left side, because we need the uncasted form for the store.
8706 * The ast2firm pass has to know that left_type must be right_type
8707 * for the arithmetic operation and create a cast by itself */
8708 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8709 expression->right = create_implicit_cast(right, arithmetic_type);
8710 expression->base.type = type_left;
8711 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8712 check_pointer_arithmetic(&expression->base.source_position,
8713 type_left, orig_type_left);
8714 expression->base.type = type_left;
8715 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8716 errorf(&expression->base.source_position,
8717 "incompatible types '%T' and '%T' in assignment",
8718 orig_type_left, orig_type_right);
8722 static void semantic_integer_assign(binary_expression_t *expression)
8724 expression_t *left = expression->left;
8725 expression_t *right = expression->right;
8726 type_t *orig_type_left = left->base.type;
8727 type_t *orig_type_right = right->base.type;
8729 if (!is_valid_assignment_lhs(left))
8732 type_t *type_left = skip_typeref(orig_type_left);
8733 type_t *type_right = skip_typeref(orig_type_right);
8735 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8736 /* TODO: improve error message */
8737 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8738 errorf(&expression->base.source_position,
8739 "operation needs integer types");
8744 /* combined instructions are tricky. We can't create an implicit cast on
8745 * the left side, because we need the uncasted form for the store.
8746 * The ast2firm pass has to know that left_type must be right_type
8747 * for the arithmetic operation and create a cast by itself */
8748 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8749 expression->right = create_implicit_cast(right, arithmetic_type);
8750 expression->base.type = type_left;
8753 static void semantic_shift_assign(binary_expression_t *expression)
8755 expression_t *left = expression->left;
8757 if (!is_valid_assignment_lhs(left))
8760 if (!semantic_shift(expression))
8763 expression->base.type = skip_typeref(left->base.type);
8766 static void warn_logical_and_within_or(const expression_t *const expr)
8768 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8770 if (expr->base.parenthesized)
8772 warningf(&expr->base.source_position,
8773 "suggest parentheses around && within ||");
8777 * Check the semantic restrictions of a logical expression.
8779 static void semantic_logical_op(binary_expression_t *expression)
8781 /* §6.5.13:2 Each of the operands shall have scalar type.
8782 * §6.5.14:2 Each of the operands shall have scalar type. */
8783 semantic_condition(expression->left, "left operand of logical operator");
8784 semantic_condition(expression->right, "right operand of logical operator");
8785 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8786 warning.parentheses) {
8787 warn_logical_and_within_or(expression->left);
8788 warn_logical_and_within_or(expression->right);
8790 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8794 * Check the semantic restrictions of a binary assign expression.
8796 static void semantic_binexpr_assign(binary_expression_t *expression)
8798 expression_t *left = expression->left;
8799 type_t *orig_type_left = left->base.type;
8801 if (!is_valid_assignment_lhs(left))
8804 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8805 report_assign_error(error, orig_type_left, expression->right,
8806 "assignment", &left->base.source_position);
8807 expression->right = create_implicit_cast(expression->right, orig_type_left);
8808 expression->base.type = orig_type_left;
8812 * Determine if the outermost operation (or parts thereof) of the given
8813 * expression has no effect in order to generate a warning about this fact.
8814 * Therefore in some cases this only examines some of the operands of the
8815 * expression (see comments in the function and examples below).
8817 * f() + 23; // warning, because + has no effect
8818 * x || f(); // no warning, because x controls execution of f()
8819 * x ? y : f(); // warning, because y has no effect
8820 * (void)x; // no warning to be able to suppress the warning
8821 * This function can NOT be used for an "expression has definitely no effect"-
8823 static bool expression_has_effect(const expression_t *const expr)
8825 switch (expr->kind) {
8826 case EXPR_UNKNOWN: break;
8827 case EXPR_INVALID: return true; /* do NOT warn */
8828 case EXPR_REFERENCE: return false;
8829 case EXPR_REFERENCE_ENUM_VALUE: return false;
8830 case EXPR_LABEL_ADDRESS: return false;
8832 /* suppress the warning for microsoft __noop operations */
8833 case EXPR_LITERAL_MS_NOOP: return true;
8834 case EXPR_LITERAL_BOOLEAN:
8835 case EXPR_LITERAL_CHARACTER:
8836 case EXPR_LITERAL_WIDE_CHARACTER:
8837 case EXPR_LITERAL_INTEGER:
8838 case EXPR_LITERAL_INTEGER_OCTAL:
8839 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8840 case EXPR_LITERAL_FLOATINGPOINT:
8841 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8842 case EXPR_STRING_LITERAL: return false;
8843 case EXPR_WIDE_STRING_LITERAL: return false;
8846 const call_expression_t *const call = &expr->call;
8847 if (call->function->kind != EXPR_REFERENCE)
8850 switch (call->function->reference.entity->function.btk) {
8851 /* FIXME: which builtins have no effect? */
8852 default: return true;
8856 /* Generate the warning if either the left or right hand side of a
8857 * conditional expression has no effect */
8858 case EXPR_CONDITIONAL: {
8859 conditional_expression_t const *const cond = &expr->conditional;
8860 expression_t const *const t = cond->true_expression;
8862 (t == NULL || expression_has_effect(t)) &&
8863 expression_has_effect(cond->false_expression);
8866 case EXPR_SELECT: return false;
8867 case EXPR_ARRAY_ACCESS: return false;
8868 case EXPR_SIZEOF: return false;
8869 case EXPR_CLASSIFY_TYPE: return false;
8870 case EXPR_ALIGNOF: return false;
8872 case EXPR_FUNCNAME: return false;
8873 case EXPR_BUILTIN_CONSTANT_P: return false;
8874 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8875 case EXPR_OFFSETOF: return false;
8876 case EXPR_VA_START: return true;
8877 case EXPR_VA_ARG: return true;
8878 case EXPR_VA_COPY: return true;
8879 case EXPR_STATEMENT: return true; // TODO
8880 case EXPR_COMPOUND_LITERAL: return false;
8882 case EXPR_UNARY_NEGATE: return false;
8883 case EXPR_UNARY_PLUS: return false;
8884 case EXPR_UNARY_BITWISE_NEGATE: return false;
8885 case EXPR_UNARY_NOT: return false;
8886 case EXPR_UNARY_DEREFERENCE: return false;
8887 case EXPR_UNARY_TAKE_ADDRESS: return false;
8888 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8889 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8890 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8891 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8893 /* Treat void casts as if they have an effect in order to being able to
8894 * suppress the warning */
8895 case EXPR_UNARY_CAST: {
8896 type_t *const type = skip_typeref(expr->base.type);
8897 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8900 case EXPR_UNARY_CAST_IMPLICIT: return true;
8901 case EXPR_UNARY_ASSUME: return true;
8902 case EXPR_UNARY_DELETE: return true;
8903 case EXPR_UNARY_DELETE_ARRAY: return true;
8904 case EXPR_UNARY_THROW: return true;
8906 case EXPR_BINARY_ADD: return false;
8907 case EXPR_BINARY_SUB: return false;
8908 case EXPR_BINARY_MUL: return false;
8909 case EXPR_BINARY_DIV: return false;
8910 case EXPR_BINARY_MOD: return false;
8911 case EXPR_BINARY_EQUAL: return false;
8912 case EXPR_BINARY_NOTEQUAL: return false;
8913 case EXPR_BINARY_LESS: return false;
8914 case EXPR_BINARY_LESSEQUAL: return false;
8915 case EXPR_BINARY_GREATER: return false;
8916 case EXPR_BINARY_GREATEREQUAL: return false;
8917 case EXPR_BINARY_BITWISE_AND: return false;
8918 case EXPR_BINARY_BITWISE_OR: return false;
8919 case EXPR_BINARY_BITWISE_XOR: return false;
8920 case EXPR_BINARY_SHIFTLEFT: return false;
8921 case EXPR_BINARY_SHIFTRIGHT: return false;
8922 case EXPR_BINARY_ASSIGN: return true;
8923 case EXPR_BINARY_MUL_ASSIGN: return true;
8924 case EXPR_BINARY_DIV_ASSIGN: return true;
8925 case EXPR_BINARY_MOD_ASSIGN: return true;
8926 case EXPR_BINARY_ADD_ASSIGN: return true;
8927 case EXPR_BINARY_SUB_ASSIGN: return true;
8928 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8929 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8930 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8931 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8932 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8934 /* Only examine the right hand side of && and ||, because the left hand
8935 * side already has the effect of controlling the execution of the right
8937 case EXPR_BINARY_LOGICAL_AND:
8938 case EXPR_BINARY_LOGICAL_OR:
8939 /* Only examine the right hand side of a comma expression, because the left
8940 * hand side has a separate warning */
8941 case EXPR_BINARY_COMMA:
8942 return expression_has_effect(expr->binary.right);
8944 case EXPR_BINARY_ISGREATER: return false;
8945 case EXPR_BINARY_ISGREATEREQUAL: return false;
8946 case EXPR_BINARY_ISLESS: return false;
8947 case EXPR_BINARY_ISLESSEQUAL: return false;
8948 case EXPR_BINARY_ISLESSGREATER: return false;
8949 case EXPR_BINARY_ISUNORDERED: return false;
8952 internal_errorf(HERE, "unexpected expression");
8955 static void semantic_comma(binary_expression_t *expression)
8957 if (warning.unused_value) {
8958 const expression_t *const left = expression->left;
8959 if (!expression_has_effect(left)) {
8960 warningf(&left->base.source_position,
8961 "left-hand operand of comma expression has no effect");
8964 expression->base.type = expression->right->base.type;
8968 * @param prec_r precedence of the right operand
8970 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8971 static expression_t *parse_##binexpression_type(expression_t *left) \
8973 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8974 binexpr->binary.left = left; \
8977 expression_t *right = parse_subexpression(prec_r); \
8979 binexpr->binary.right = right; \
8980 sfunc(&binexpr->binary); \
8985 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8986 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8987 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8988 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8989 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8990 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8991 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8992 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8993 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8994 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8995 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8996 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8997 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8998 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8999 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
9000 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
9001 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9002 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9003 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9004 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9005 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9006 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9007 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9008 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9009 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9010 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9011 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9012 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9013 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9014 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9017 static expression_t *parse_subexpression(precedence_t precedence)
9019 if (token.type < 0) {
9020 return expected_expression_error();
9023 expression_parser_function_t *parser
9024 = &expression_parsers[token.type];
9025 source_position_t source_position = token.source_position;
9028 if (parser->parser != NULL) {
9029 left = parser->parser();
9031 left = parse_primary_expression();
9033 assert(left != NULL);
9034 left->base.source_position = source_position;
9037 if (token.type < 0) {
9038 return expected_expression_error();
9041 parser = &expression_parsers[token.type];
9042 if (parser->infix_parser == NULL)
9044 if (parser->infix_precedence < precedence)
9047 left = parser->infix_parser(left);
9049 assert(left != NULL);
9050 assert(left->kind != EXPR_UNKNOWN);
9051 left->base.source_position = source_position;
9058 * Parse an expression.
9060 static expression_t *parse_expression(void)
9062 return parse_subexpression(PREC_EXPRESSION);
9066 * Register a parser for a prefix-like operator.
9068 * @param parser the parser function
9069 * @param token_type the token type of the prefix token
9071 static void register_expression_parser(parse_expression_function parser,
9074 expression_parser_function_t *entry = &expression_parsers[token_type];
9076 if (entry->parser != NULL) {
9077 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9078 panic("trying to register multiple expression parsers for a token");
9080 entry->parser = parser;
9084 * Register a parser for an infix operator with given precedence.
9086 * @param parser the parser function
9087 * @param token_type the token type of the infix operator
9088 * @param precedence the precedence of the operator
9090 static void register_infix_parser(parse_expression_infix_function parser,
9091 int token_type, precedence_t precedence)
9093 expression_parser_function_t *entry = &expression_parsers[token_type];
9095 if (entry->infix_parser != NULL) {
9096 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9097 panic("trying to register multiple infix expression parsers for a "
9100 entry->infix_parser = parser;
9101 entry->infix_precedence = precedence;
9105 * Initialize the expression parsers.
9107 static void init_expression_parsers(void)
9109 memset(&expression_parsers, 0, sizeof(expression_parsers));
9111 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9112 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9113 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9114 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9115 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9116 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9117 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9118 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9119 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9120 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9121 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9122 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9123 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9124 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9125 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9126 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9127 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9128 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9129 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9130 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9131 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9132 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9133 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9134 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9135 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9136 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9137 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9138 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9139 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9140 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9141 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9142 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9143 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9144 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9145 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9146 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9147 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9149 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9150 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9151 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9152 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9153 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9154 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9155 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9156 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9157 register_expression_parser(parse_sizeof, T_sizeof);
9158 register_expression_parser(parse_alignof, T___alignof__);
9159 register_expression_parser(parse_extension, T___extension__);
9160 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9161 register_expression_parser(parse_delete, T_delete);
9162 register_expression_parser(parse_throw, T_throw);
9166 * Parse a asm statement arguments specification.
9168 static asm_argument_t *parse_asm_arguments(bool is_out)
9170 asm_argument_t *result = NULL;
9171 asm_argument_t **anchor = &result;
9173 while (token.type == T_STRING_LITERAL || token.type == '[') {
9174 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9175 memset(argument, 0, sizeof(argument[0]));
9178 if (token.type != T_IDENTIFIER) {
9179 parse_error_expected("while parsing asm argument",
9180 T_IDENTIFIER, NULL);
9183 argument->symbol = token.symbol;
9185 expect(']', end_error);
9188 argument->constraints = parse_string_literals();
9189 expect('(', end_error);
9190 add_anchor_token(')');
9191 expression_t *expression = parse_expression();
9192 rem_anchor_token(')');
9194 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9195 * change size or type representation (e.g. int -> long is ok, but
9196 * int -> float is not) */
9197 if (expression->kind == EXPR_UNARY_CAST) {
9198 type_t *const type = expression->base.type;
9199 type_kind_t const kind = type->kind;
9200 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9203 if (kind == TYPE_ATOMIC) {
9204 atomic_type_kind_t const akind = type->atomic.akind;
9205 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9206 size = get_atomic_type_size(akind);
9208 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9209 size = get_atomic_type_size(get_intptr_kind());
9213 expression_t *const value = expression->unary.value;
9214 type_t *const value_type = value->base.type;
9215 type_kind_t const value_kind = value_type->kind;
9217 unsigned value_flags;
9218 unsigned value_size;
9219 if (value_kind == TYPE_ATOMIC) {
9220 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9221 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9222 value_size = get_atomic_type_size(value_akind);
9223 } else if (value_kind == TYPE_POINTER) {
9224 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9225 value_size = get_atomic_type_size(get_intptr_kind());
9230 if (value_flags != flags || value_size != size)
9234 } while (expression->kind == EXPR_UNARY_CAST);
9238 if (!is_lvalue(expression)) {
9239 errorf(&expression->base.source_position,
9240 "asm output argument is not an lvalue");
9243 if (argument->constraints.begin[0] == '=')
9244 determine_lhs_ent(expression, NULL);
9246 mark_vars_read(expression, NULL);
9248 mark_vars_read(expression, NULL);
9250 argument->expression = expression;
9251 expect(')', end_error);
9253 set_address_taken(expression, true);
9256 anchor = &argument->next;
9268 * Parse a asm statement clobber specification.
9270 static asm_clobber_t *parse_asm_clobbers(void)
9272 asm_clobber_t *result = NULL;
9273 asm_clobber_t **anchor = &result;
9275 while (token.type == T_STRING_LITERAL) {
9276 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9277 clobber->clobber = parse_string_literals();
9280 anchor = &clobber->next;
9290 * Parse an asm statement.
9292 static statement_t *parse_asm_statement(void)
9294 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9295 asm_statement_t *asm_statement = &statement->asms;
9299 if (next_if(T_volatile))
9300 asm_statement->is_volatile = true;
9302 expect('(', end_error);
9303 add_anchor_token(')');
9304 if (token.type != T_STRING_LITERAL) {
9305 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9308 asm_statement->asm_text = parse_string_literals();
9310 add_anchor_token(':');
9311 if (!next_if(':')) {
9312 rem_anchor_token(':');
9316 asm_statement->outputs = parse_asm_arguments(true);
9317 if (!next_if(':')) {
9318 rem_anchor_token(':');
9322 asm_statement->inputs = parse_asm_arguments(false);
9323 if (!next_if(':')) {
9324 rem_anchor_token(':');
9327 rem_anchor_token(':');
9329 asm_statement->clobbers = parse_asm_clobbers();
9332 rem_anchor_token(')');
9333 expect(')', end_error);
9334 expect(';', end_error);
9336 if (asm_statement->outputs == NULL) {
9337 /* GCC: An 'asm' instruction without any output operands will be treated
9338 * identically to a volatile 'asm' instruction. */
9339 asm_statement->is_volatile = true;
9344 return create_invalid_statement();
9347 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9349 statement_t *inner_stmt;
9350 switch (token.type) {
9352 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9353 inner_stmt = create_invalid_statement();
9357 if (label->kind == STATEMENT_LABEL) {
9358 /* Eat an empty statement here, to avoid the warning about an empty
9359 * statement after a label. label:; is commonly used to have a label
9360 * before a closing brace. */
9361 inner_stmt = create_empty_statement();
9368 inner_stmt = parse_statement();
9369 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9370 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9371 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9379 * Parse a case statement.
9381 static statement_t *parse_case_statement(void)
9383 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9384 source_position_t *const pos = &statement->base.source_position;
9388 expression_t *const expression = parse_expression();
9389 statement->case_label.expression = expression;
9390 expression_classification_t const expr_class = is_constant_expression(expression);
9391 if (expr_class != EXPR_CLASS_CONSTANT) {
9392 if (expr_class != EXPR_CLASS_ERROR) {
9393 errorf(pos, "case label does not reduce to an integer constant");
9395 statement->case_label.is_bad = true;
9397 long const val = fold_constant_to_int(expression);
9398 statement->case_label.first_case = val;
9399 statement->case_label.last_case = val;
9403 if (next_if(T_DOTDOTDOT)) {
9404 expression_t *const end_range = parse_expression();
9405 statement->case_label.end_range = end_range;
9406 expression_classification_t const end_class = is_constant_expression(end_range);
9407 if (end_class != EXPR_CLASS_CONSTANT) {
9408 if (end_class != EXPR_CLASS_ERROR) {
9409 errorf(pos, "case range does not reduce to an integer constant");
9411 statement->case_label.is_bad = true;
9413 long const val = fold_constant_to_int(end_range);
9414 statement->case_label.last_case = val;
9416 if (warning.other && val < statement->case_label.first_case) {
9417 statement->case_label.is_empty_range = true;
9418 warningf(pos, "empty range specified");
9424 PUSH_PARENT(statement);
9426 expect(':', end_error);
9429 if (current_switch != NULL) {
9430 if (! statement->case_label.is_bad) {
9431 /* Check for duplicate case values */
9432 case_label_statement_t *c = &statement->case_label;
9433 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9434 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9437 if (c->last_case < l->first_case || c->first_case > l->last_case)
9440 errorf(pos, "duplicate case value (previously used %P)",
9441 &l->base.source_position);
9445 /* link all cases into the switch statement */
9446 if (current_switch->last_case == NULL) {
9447 current_switch->first_case = &statement->case_label;
9449 current_switch->last_case->next = &statement->case_label;
9451 current_switch->last_case = &statement->case_label;
9453 errorf(pos, "case label not within a switch statement");
9456 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9463 * Parse a default statement.
9465 static statement_t *parse_default_statement(void)
9467 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9471 PUSH_PARENT(statement);
9473 expect(':', end_error);
9476 if (current_switch != NULL) {
9477 const case_label_statement_t *def_label = current_switch->default_label;
9478 if (def_label != NULL) {
9479 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9480 &def_label->base.source_position);
9482 current_switch->default_label = &statement->case_label;
9484 /* link all cases into the switch statement */
9485 if (current_switch->last_case == NULL) {
9486 current_switch->first_case = &statement->case_label;
9488 current_switch->last_case->next = &statement->case_label;
9490 current_switch->last_case = &statement->case_label;
9493 errorf(&statement->base.source_position,
9494 "'default' label not within a switch statement");
9497 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9504 * Parse a label statement.
9506 static statement_t *parse_label_statement(void)
9508 assert(token.type == T_IDENTIFIER);
9509 symbol_t *symbol = token.symbol;
9510 label_t *label = get_label(symbol);
9512 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9513 statement->label.label = label;
9517 PUSH_PARENT(statement);
9519 /* if statement is already set then the label is defined twice,
9520 * otherwise it was just mentioned in a goto/local label declaration so far
9522 if (label->statement != NULL) {
9523 errorf(HERE, "duplicate label '%Y' (declared %P)",
9524 symbol, &label->base.source_position);
9526 label->base.source_position = token.source_position;
9527 label->statement = statement;
9532 statement->label.statement = parse_label_inner_statement(statement, "label");
9534 /* remember the labels in a list for later checking */
9535 *label_anchor = &statement->label;
9536 label_anchor = &statement->label.next;
9543 * Parse an if statement.
9545 static statement_t *parse_if(void)
9547 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9551 PUSH_PARENT(statement);
9553 add_anchor_token('{');
9555 expect('(', end_error);
9556 add_anchor_token(')');
9557 expression_t *const expr = parse_expression();
9558 statement->ifs.condition = expr;
9559 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9561 semantic_condition(expr, "condition of 'if'-statment");
9562 mark_vars_read(expr, NULL);
9563 rem_anchor_token(')');
9564 expect(')', end_error);
9567 rem_anchor_token('{');
9569 add_anchor_token(T_else);
9570 statement_t *const true_stmt = parse_statement();
9571 statement->ifs.true_statement = true_stmt;
9572 rem_anchor_token(T_else);
9574 if (next_if(T_else)) {
9575 statement->ifs.false_statement = parse_statement();
9576 } else if (warning.parentheses &&
9577 true_stmt->kind == STATEMENT_IF &&
9578 true_stmt->ifs.false_statement != NULL) {
9579 warningf(&true_stmt->base.source_position,
9580 "suggest explicit braces to avoid ambiguous 'else'");
9588 * Check that all enums are handled in a switch.
9590 * @param statement the switch statement to check
9592 static void check_enum_cases(const switch_statement_t *statement)
9594 const type_t *type = skip_typeref(statement->expression->base.type);
9595 if (! is_type_enum(type))
9597 const enum_type_t *enumt = &type->enumt;
9599 /* if we have a default, no warnings */
9600 if (statement->default_label != NULL)
9603 /* FIXME: calculation of value should be done while parsing */
9604 /* TODO: quadratic algorithm here. Change to an n log n one */
9605 long last_value = -1;
9606 const entity_t *entry = enumt->enume->base.next;
9607 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9608 entry = entry->base.next) {
9609 const expression_t *expression = entry->enum_value.value;
9610 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9612 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9613 if (l->expression == NULL)
9615 if (l->first_case <= value && value <= l->last_case) {
9621 warningf(&statement->base.source_position,
9622 "enumeration value '%Y' not handled in switch",
9623 entry->base.symbol);
9630 * Parse a switch statement.
9632 static statement_t *parse_switch(void)
9634 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9638 PUSH_PARENT(statement);
9640 expect('(', end_error);
9641 add_anchor_token(')');
9642 expression_t *const expr = parse_expression();
9643 mark_vars_read(expr, NULL);
9644 type_t * type = skip_typeref(expr->base.type);
9645 if (is_type_integer(type)) {
9646 type = promote_integer(type);
9647 if (warning.traditional) {
9648 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9649 warningf(&expr->base.source_position,
9650 "'%T' switch expression not converted to '%T' in ISO C",
9654 } else if (is_type_valid(type)) {
9655 errorf(&expr->base.source_position,
9656 "switch quantity is not an integer, but '%T'", type);
9657 type = type_error_type;
9659 statement->switchs.expression = create_implicit_cast(expr, type);
9660 expect(')', end_error);
9661 rem_anchor_token(')');
9663 switch_statement_t *rem = current_switch;
9664 current_switch = &statement->switchs;
9665 statement->switchs.body = parse_statement();
9666 current_switch = rem;
9668 if (warning.switch_default &&
9669 statement->switchs.default_label == NULL) {
9670 warningf(&statement->base.source_position, "switch has no default case");
9672 if (warning.switch_enum)
9673 check_enum_cases(&statement->switchs);
9679 return create_invalid_statement();
9682 static statement_t *parse_loop_body(statement_t *const loop)
9684 statement_t *const rem = current_loop;
9685 current_loop = loop;
9687 statement_t *const body = parse_statement();
9694 * Parse a while statement.
9696 static statement_t *parse_while(void)
9698 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9702 PUSH_PARENT(statement);
9704 expect('(', end_error);
9705 add_anchor_token(')');
9706 expression_t *const cond = parse_expression();
9707 statement->whiles.condition = cond;
9708 /* §6.8.5:2 The controlling expression of an iteration statement shall
9709 * have scalar type. */
9710 semantic_condition(cond, "condition of 'while'-statement");
9711 mark_vars_read(cond, NULL);
9712 rem_anchor_token(')');
9713 expect(')', end_error);
9715 statement->whiles.body = parse_loop_body(statement);
9721 return create_invalid_statement();
9725 * Parse a do statement.
9727 static statement_t *parse_do(void)
9729 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9733 PUSH_PARENT(statement);
9735 add_anchor_token(T_while);
9736 statement->do_while.body = parse_loop_body(statement);
9737 rem_anchor_token(T_while);
9739 expect(T_while, end_error);
9740 expect('(', end_error);
9741 add_anchor_token(')');
9742 expression_t *const cond = parse_expression();
9743 statement->do_while.condition = cond;
9744 /* §6.8.5:2 The controlling expression of an iteration statement shall
9745 * have scalar type. */
9746 semantic_condition(cond, "condition of 'do-while'-statement");
9747 mark_vars_read(cond, NULL);
9748 rem_anchor_token(')');
9749 expect(')', end_error);
9750 expect(';', end_error);
9756 return create_invalid_statement();
9760 * Parse a for statement.
9762 static statement_t *parse_for(void)
9764 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9768 expect('(', end_error1);
9769 add_anchor_token(')');
9771 PUSH_PARENT(statement);
9773 size_t const top = environment_top();
9774 scope_t *old_scope = scope_push(&statement->fors.scope);
9776 bool old_gcc_extension = in_gcc_extension;
9777 while (next_if(T___extension__)) {
9778 in_gcc_extension = true;
9782 } else if (is_declaration_specifier(&token, false)) {
9783 parse_declaration(record_entity, DECL_FLAGS_NONE);
9785 add_anchor_token(';');
9786 expression_t *const init = parse_expression();
9787 statement->fors.initialisation = init;
9788 mark_vars_read(init, ENT_ANY);
9789 if (warning.unused_value && !expression_has_effect(init)) {
9790 warningf(&init->base.source_position,
9791 "initialisation of 'for'-statement has no effect");
9793 rem_anchor_token(';');
9794 expect(';', end_error2);
9796 in_gcc_extension = old_gcc_extension;
9798 if (token.type != ';') {
9799 add_anchor_token(';');
9800 expression_t *const cond = parse_expression();
9801 statement->fors.condition = cond;
9802 /* §6.8.5:2 The controlling expression of an iteration statement
9803 * shall have scalar type. */
9804 semantic_condition(cond, "condition of 'for'-statement");
9805 mark_vars_read(cond, NULL);
9806 rem_anchor_token(';');
9808 expect(';', end_error2);
9809 if (token.type != ')') {
9810 expression_t *const step = parse_expression();
9811 statement->fors.step = step;
9812 mark_vars_read(step, ENT_ANY);
9813 if (warning.unused_value && !expression_has_effect(step)) {
9814 warningf(&step->base.source_position,
9815 "step of 'for'-statement has no effect");
9818 expect(')', end_error2);
9819 rem_anchor_token(')');
9820 statement->fors.body = parse_loop_body(statement);
9822 assert(current_scope == &statement->fors.scope);
9823 scope_pop(old_scope);
9824 environment_pop_to(top);
9831 rem_anchor_token(')');
9832 assert(current_scope == &statement->fors.scope);
9833 scope_pop(old_scope);
9834 environment_pop_to(top);
9838 return create_invalid_statement();
9842 * Parse a goto statement.
9844 static statement_t *parse_goto(void)
9846 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9849 if (GNU_MODE && next_if('*')) {
9850 expression_t *expression = parse_expression();
9851 mark_vars_read(expression, NULL);
9853 /* Argh: although documentation says the expression must be of type void*,
9854 * gcc accepts anything that can be casted into void* without error */
9855 type_t *type = expression->base.type;
9857 if (type != type_error_type) {
9858 if (!is_type_pointer(type) && !is_type_integer(type)) {
9859 errorf(&expression->base.source_position,
9860 "cannot convert to a pointer type");
9861 } else if (warning.other && type != type_void_ptr) {
9862 warningf(&expression->base.source_position,
9863 "type of computed goto expression should be 'void*' not '%T'", type);
9865 expression = create_implicit_cast(expression, type_void_ptr);
9868 statement->gotos.expression = expression;
9869 } else if (token.type == T_IDENTIFIER) {
9870 symbol_t *symbol = token.symbol;
9872 statement->gotos.label = get_label(symbol);
9875 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9877 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9879 return create_invalid_statement();
9882 /* remember the goto's in a list for later checking */
9883 *goto_anchor = &statement->gotos;
9884 goto_anchor = &statement->gotos.next;
9886 expect(';', end_error);
9893 * Parse a continue statement.
9895 static statement_t *parse_continue(void)
9897 if (current_loop == NULL) {
9898 errorf(HERE, "continue statement not within loop");
9901 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9904 expect(';', end_error);
9911 * Parse a break statement.
9913 static statement_t *parse_break(void)
9915 if (current_switch == NULL && current_loop == NULL) {
9916 errorf(HERE, "break statement not within loop or switch");
9919 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9922 expect(';', end_error);
9929 * Parse a __leave statement.
9931 static statement_t *parse_leave_statement(void)
9933 if (current_try == NULL) {
9934 errorf(HERE, "__leave statement not within __try");
9937 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9940 expect(';', end_error);
9947 * Check if a given entity represents a local variable.
9949 static bool is_local_variable(const entity_t *entity)
9951 if (entity->kind != ENTITY_VARIABLE)
9954 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9955 case STORAGE_CLASS_AUTO:
9956 case STORAGE_CLASS_REGISTER: {
9957 const type_t *type = skip_typeref(entity->declaration.type);
9958 if (is_type_function(type)) {
9970 * Check if a given expression represents a local variable.
9972 static bool expression_is_local_variable(const expression_t *expression)
9974 if (expression->base.kind != EXPR_REFERENCE) {
9977 const entity_t *entity = expression->reference.entity;
9978 return is_local_variable(entity);
9982 * Check if a given expression represents a local variable and
9983 * return its declaration then, else return NULL.
9985 entity_t *expression_is_variable(const expression_t *expression)
9987 if (expression->base.kind != EXPR_REFERENCE) {
9990 entity_t *entity = expression->reference.entity;
9991 if (entity->kind != ENTITY_VARIABLE)
9998 * Parse a return statement.
10000 static statement_t *parse_return(void)
10004 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10006 expression_t *return_value = NULL;
10007 if (token.type != ';') {
10008 return_value = parse_expression();
10009 mark_vars_read(return_value, NULL);
10012 const type_t *const func_type = skip_typeref(current_function->base.type);
10013 assert(is_type_function(func_type));
10014 type_t *const return_type = skip_typeref(func_type->function.return_type);
10016 source_position_t const *const pos = &statement->base.source_position;
10017 if (return_value != NULL) {
10018 type_t *return_value_type = skip_typeref(return_value->base.type);
10020 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10021 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10022 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10023 /* Only warn in C mode, because GCC does the same */
10024 if (c_mode & _CXX || strict_mode) {
10026 "'return' with a value, in function returning 'void'");
10027 } else if (warning.other) {
10029 "'return' with a value, in function returning 'void'");
10031 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10032 /* Only warn in C mode, because GCC does the same */
10035 "'return' with expression in function returning 'void'");
10036 } else if (warning.other) {
10038 "'return' with expression in function returning 'void'");
10042 assign_error_t error = semantic_assign(return_type, return_value);
10043 report_assign_error(error, return_type, return_value, "'return'",
10046 return_value = create_implicit_cast(return_value, return_type);
10047 /* check for returning address of a local var */
10048 if (warning.other && return_value != NULL
10049 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10050 const expression_t *expression = return_value->unary.value;
10051 if (expression_is_local_variable(expression)) {
10052 warningf(pos, "function returns address of local variable");
10055 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10056 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10057 if (c_mode & _CXX || strict_mode) {
10059 "'return' without value, in function returning non-void");
10062 "'return' without value, in function returning non-void");
10065 statement->returns.value = return_value;
10067 expect(';', end_error);
10074 * Parse a declaration statement.
10076 static statement_t *parse_declaration_statement(void)
10078 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10080 entity_t *before = current_scope->last_entity;
10082 parse_external_declaration();
10084 parse_declaration(record_entity, DECL_FLAGS_NONE);
10087 declaration_statement_t *const decl = &statement->declaration;
10088 entity_t *const begin =
10089 before != NULL ? before->base.next : current_scope->entities;
10090 decl->declarations_begin = begin;
10091 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10097 * Parse an expression statement, ie. expr ';'.
10099 static statement_t *parse_expression_statement(void)
10101 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10103 expression_t *const expr = parse_expression();
10104 statement->expression.expression = expr;
10105 mark_vars_read(expr, ENT_ANY);
10107 expect(';', end_error);
10114 * Parse a microsoft __try { } __finally { } or
10115 * __try{ } __except() { }
10117 static statement_t *parse_ms_try_statment(void)
10119 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10122 PUSH_PARENT(statement);
10124 ms_try_statement_t *rem = current_try;
10125 current_try = &statement->ms_try;
10126 statement->ms_try.try_statement = parse_compound_statement(false);
10131 if (next_if(T___except)) {
10132 expect('(', end_error);
10133 add_anchor_token(')');
10134 expression_t *const expr = parse_expression();
10135 mark_vars_read(expr, NULL);
10136 type_t * type = skip_typeref(expr->base.type);
10137 if (is_type_integer(type)) {
10138 type = promote_integer(type);
10139 } else if (is_type_valid(type)) {
10140 errorf(&expr->base.source_position,
10141 "__expect expression is not an integer, but '%T'", type);
10142 type = type_error_type;
10144 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10145 rem_anchor_token(')');
10146 expect(')', end_error);
10147 statement->ms_try.final_statement = parse_compound_statement(false);
10148 } else if (next_if(T__finally)) {
10149 statement->ms_try.final_statement = parse_compound_statement(false);
10151 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10152 return create_invalid_statement();
10156 return create_invalid_statement();
10159 static statement_t *parse_empty_statement(void)
10161 if (warning.empty_statement) {
10162 warningf(HERE, "statement is empty");
10164 statement_t *const statement = create_empty_statement();
10169 static statement_t *parse_local_label_declaration(void)
10171 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10175 entity_t *begin = NULL;
10176 entity_t *end = NULL;
10177 entity_t **anchor = &begin;
10179 if (token.type != T_IDENTIFIER) {
10180 parse_error_expected("while parsing local label declaration",
10181 T_IDENTIFIER, NULL);
10184 symbol_t *symbol = token.symbol;
10185 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10186 if (entity != NULL && entity->base.parent_scope == current_scope) {
10187 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10188 symbol, &entity->base.source_position);
10190 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10192 entity->base.parent_scope = current_scope;
10193 entity->base.namespc = NAMESPACE_LABEL;
10194 entity->base.source_position = token.source_position;
10195 entity->base.symbol = symbol;
10198 anchor = &entity->base.next;
10201 environment_push(entity);
10204 } while (next_if(','));
10205 expect(';', end_error);
10207 statement->declaration.declarations_begin = begin;
10208 statement->declaration.declarations_end = end;
10212 static void parse_namespace_definition(void)
10216 entity_t *entity = NULL;
10217 symbol_t *symbol = NULL;
10219 if (token.type == T_IDENTIFIER) {
10220 symbol = token.symbol;
10223 entity = get_entity(symbol, NAMESPACE_NORMAL);
10225 && entity->kind != ENTITY_NAMESPACE
10226 && entity->base.parent_scope == current_scope) {
10227 if (is_entity_valid(entity)) {
10228 error_redefined_as_different_kind(&token.source_position,
10229 entity, ENTITY_NAMESPACE);
10235 if (entity == NULL) {
10236 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10237 entity->base.symbol = symbol;
10238 entity->base.source_position = token.source_position;
10239 entity->base.namespc = NAMESPACE_NORMAL;
10240 entity->base.parent_scope = current_scope;
10243 if (token.type == '=') {
10244 /* TODO: parse namespace alias */
10245 panic("namespace alias definition not supported yet");
10248 environment_push(entity);
10249 append_entity(current_scope, entity);
10251 size_t const top = environment_top();
10252 scope_t *old_scope = scope_push(&entity->namespacee.members);
10254 entity_t *old_current_entity = current_entity;
10255 current_entity = entity;
10257 expect('{', end_error);
10259 expect('}', end_error);
10262 assert(current_scope == &entity->namespacee.members);
10263 assert(current_entity == entity);
10264 current_entity = old_current_entity;
10265 scope_pop(old_scope);
10266 environment_pop_to(top);
10270 * Parse a statement.
10271 * There's also parse_statement() which additionally checks for
10272 * "statement has no effect" warnings
10274 static statement_t *intern_parse_statement(void)
10276 statement_t *statement = NULL;
10278 /* declaration or statement */
10279 add_anchor_token(';');
10280 switch (token.type) {
10281 case T_IDENTIFIER: {
10282 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10283 if (la1_type == ':') {
10284 statement = parse_label_statement();
10285 } else if (is_typedef_symbol(token.symbol)) {
10286 statement = parse_declaration_statement();
10288 /* it's an identifier, the grammar says this must be an
10289 * expression statement. However it is common that users mistype
10290 * declaration types, so we guess a bit here to improve robustness
10291 * for incorrect programs */
10292 switch (la1_type) {
10295 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10297 statement = parse_expression_statement();
10301 statement = parse_declaration_statement();
10309 case T___extension__:
10310 /* This can be a prefix to a declaration or an expression statement.
10311 * We simply eat it now and parse the rest with tail recursion. */
10312 while (next_if(T___extension__)) {}
10313 bool old_gcc_extension = in_gcc_extension;
10314 in_gcc_extension = true;
10315 statement = intern_parse_statement();
10316 in_gcc_extension = old_gcc_extension;
10320 statement = parse_declaration_statement();
10324 statement = parse_local_label_declaration();
10327 case ';': statement = parse_empty_statement(); break;
10328 case '{': statement = parse_compound_statement(false); break;
10329 case T___leave: statement = parse_leave_statement(); break;
10330 case T___try: statement = parse_ms_try_statment(); break;
10331 case T_asm: statement = parse_asm_statement(); break;
10332 case T_break: statement = parse_break(); break;
10333 case T_case: statement = parse_case_statement(); break;
10334 case T_continue: statement = parse_continue(); break;
10335 case T_default: statement = parse_default_statement(); break;
10336 case T_do: statement = parse_do(); break;
10337 case T_for: statement = parse_for(); break;
10338 case T_goto: statement = parse_goto(); break;
10339 case T_if: statement = parse_if(); break;
10340 case T_return: statement = parse_return(); break;
10341 case T_switch: statement = parse_switch(); break;
10342 case T_while: statement = parse_while(); break;
10345 statement = parse_expression_statement();
10349 errorf(HERE, "unexpected token %K while parsing statement", &token);
10350 statement = create_invalid_statement();
10355 rem_anchor_token(';');
10357 assert(statement != NULL
10358 && statement->base.source_position.input_name != NULL);
10364 * parse a statement and emits "statement has no effect" warning if needed
10365 * (This is really a wrapper around intern_parse_statement with check for 1
10366 * single warning. It is needed, because for statement expressions we have
10367 * to avoid the warning on the last statement)
10369 static statement_t *parse_statement(void)
10371 statement_t *statement = intern_parse_statement();
10373 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10374 expression_t *expression = statement->expression.expression;
10375 if (!expression_has_effect(expression)) {
10376 warningf(&expression->base.source_position,
10377 "statement has no effect");
10385 * Parse a compound statement.
10387 static statement_t *parse_compound_statement(bool inside_expression_statement)
10389 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10391 PUSH_PARENT(statement);
10394 add_anchor_token('}');
10395 /* tokens, which can start a statement */
10396 /* TODO MS, __builtin_FOO */
10397 add_anchor_token('!');
10398 add_anchor_token('&');
10399 add_anchor_token('(');
10400 add_anchor_token('*');
10401 add_anchor_token('+');
10402 add_anchor_token('-');
10403 add_anchor_token('{');
10404 add_anchor_token('~');
10405 add_anchor_token(T_CHARACTER_CONSTANT);
10406 add_anchor_token(T_COLONCOLON);
10407 add_anchor_token(T_FLOATINGPOINT);
10408 add_anchor_token(T_IDENTIFIER);
10409 add_anchor_token(T_INTEGER);
10410 add_anchor_token(T_MINUSMINUS);
10411 add_anchor_token(T_PLUSPLUS);
10412 add_anchor_token(T_STRING_LITERAL);
10413 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10414 add_anchor_token(T_WIDE_STRING_LITERAL);
10415 add_anchor_token(T__Bool);
10416 add_anchor_token(T__Complex);
10417 add_anchor_token(T__Imaginary);
10418 add_anchor_token(T___FUNCTION__);
10419 add_anchor_token(T___PRETTY_FUNCTION__);
10420 add_anchor_token(T___alignof__);
10421 add_anchor_token(T___attribute__);
10422 add_anchor_token(T___builtin_va_start);
10423 add_anchor_token(T___extension__);
10424 add_anchor_token(T___func__);
10425 add_anchor_token(T___imag__);
10426 add_anchor_token(T___label__);
10427 add_anchor_token(T___real__);
10428 add_anchor_token(T___thread);
10429 add_anchor_token(T_asm);
10430 add_anchor_token(T_auto);
10431 add_anchor_token(T_bool);
10432 add_anchor_token(T_break);
10433 add_anchor_token(T_case);
10434 add_anchor_token(T_char);
10435 add_anchor_token(T_class);
10436 add_anchor_token(T_const);
10437 add_anchor_token(T_const_cast);
10438 add_anchor_token(T_continue);
10439 add_anchor_token(T_default);
10440 add_anchor_token(T_delete);
10441 add_anchor_token(T_double);
10442 add_anchor_token(T_do);
10443 add_anchor_token(T_dynamic_cast);
10444 add_anchor_token(T_enum);
10445 add_anchor_token(T_extern);
10446 add_anchor_token(T_false);
10447 add_anchor_token(T_float);
10448 add_anchor_token(T_for);
10449 add_anchor_token(T_goto);
10450 add_anchor_token(T_if);
10451 add_anchor_token(T_inline);
10452 add_anchor_token(T_int);
10453 add_anchor_token(T_long);
10454 add_anchor_token(T_new);
10455 add_anchor_token(T_operator);
10456 add_anchor_token(T_register);
10457 add_anchor_token(T_reinterpret_cast);
10458 add_anchor_token(T_restrict);
10459 add_anchor_token(T_return);
10460 add_anchor_token(T_short);
10461 add_anchor_token(T_signed);
10462 add_anchor_token(T_sizeof);
10463 add_anchor_token(T_static);
10464 add_anchor_token(T_static_cast);
10465 add_anchor_token(T_struct);
10466 add_anchor_token(T_switch);
10467 add_anchor_token(T_template);
10468 add_anchor_token(T_this);
10469 add_anchor_token(T_throw);
10470 add_anchor_token(T_true);
10471 add_anchor_token(T_try);
10472 add_anchor_token(T_typedef);
10473 add_anchor_token(T_typeid);
10474 add_anchor_token(T_typename);
10475 add_anchor_token(T_typeof);
10476 add_anchor_token(T_union);
10477 add_anchor_token(T_unsigned);
10478 add_anchor_token(T_using);
10479 add_anchor_token(T_void);
10480 add_anchor_token(T_volatile);
10481 add_anchor_token(T_wchar_t);
10482 add_anchor_token(T_while);
10484 size_t const top = environment_top();
10485 scope_t *old_scope = scope_push(&statement->compound.scope);
10487 statement_t **anchor = &statement->compound.statements;
10488 bool only_decls_so_far = true;
10489 while (token.type != '}') {
10490 if (token.type == T_EOF) {
10491 errorf(&statement->base.source_position,
10492 "EOF while parsing compound statement");
10495 statement_t *sub_statement = intern_parse_statement();
10496 if (is_invalid_statement(sub_statement)) {
10497 /* an error occurred. if we are at an anchor, return */
10503 if (warning.declaration_after_statement) {
10504 if (sub_statement->kind != STATEMENT_DECLARATION) {
10505 only_decls_so_far = false;
10506 } else if (!only_decls_so_far) {
10507 warningf(&sub_statement->base.source_position,
10508 "ISO C90 forbids mixed declarations and code");
10512 *anchor = sub_statement;
10514 while (sub_statement->base.next != NULL)
10515 sub_statement = sub_statement->base.next;
10517 anchor = &sub_statement->base.next;
10521 /* look over all statements again to produce no effect warnings */
10522 if (warning.unused_value) {
10523 statement_t *sub_statement = statement->compound.statements;
10524 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10525 if (sub_statement->kind != STATEMENT_EXPRESSION)
10527 /* don't emit a warning for the last expression in an expression
10528 * statement as it has always an effect */
10529 if (inside_expression_statement && sub_statement->base.next == NULL)
10532 expression_t *expression = sub_statement->expression.expression;
10533 if (!expression_has_effect(expression)) {
10534 warningf(&expression->base.source_position,
10535 "statement has no effect");
10541 rem_anchor_token(T_while);
10542 rem_anchor_token(T_wchar_t);
10543 rem_anchor_token(T_volatile);
10544 rem_anchor_token(T_void);
10545 rem_anchor_token(T_using);
10546 rem_anchor_token(T_unsigned);
10547 rem_anchor_token(T_union);
10548 rem_anchor_token(T_typeof);
10549 rem_anchor_token(T_typename);
10550 rem_anchor_token(T_typeid);
10551 rem_anchor_token(T_typedef);
10552 rem_anchor_token(T_try);
10553 rem_anchor_token(T_true);
10554 rem_anchor_token(T_throw);
10555 rem_anchor_token(T_this);
10556 rem_anchor_token(T_template);
10557 rem_anchor_token(T_switch);
10558 rem_anchor_token(T_struct);
10559 rem_anchor_token(T_static_cast);
10560 rem_anchor_token(T_static);
10561 rem_anchor_token(T_sizeof);
10562 rem_anchor_token(T_signed);
10563 rem_anchor_token(T_short);
10564 rem_anchor_token(T_return);
10565 rem_anchor_token(T_restrict);
10566 rem_anchor_token(T_reinterpret_cast);
10567 rem_anchor_token(T_register);
10568 rem_anchor_token(T_operator);
10569 rem_anchor_token(T_new);
10570 rem_anchor_token(T_long);
10571 rem_anchor_token(T_int);
10572 rem_anchor_token(T_inline);
10573 rem_anchor_token(T_if);
10574 rem_anchor_token(T_goto);
10575 rem_anchor_token(T_for);
10576 rem_anchor_token(T_float);
10577 rem_anchor_token(T_false);
10578 rem_anchor_token(T_extern);
10579 rem_anchor_token(T_enum);
10580 rem_anchor_token(T_dynamic_cast);
10581 rem_anchor_token(T_do);
10582 rem_anchor_token(T_double);
10583 rem_anchor_token(T_delete);
10584 rem_anchor_token(T_default);
10585 rem_anchor_token(T_continue);
10586 rem_anchor_token(T_const_cast);
10587 rem_anchor_token(T_const);
10588 rem_anchor_token(T_class);
10589 rem_anchor_token(T_char);
10590 rem_anchor_token(T_case);
10591 rem_anchor_token(T_break);
10592 rem_anchor_token(T_bool);
10593 rem_anchor_token(T_auto);
10594 rem_anchor_token(T_asm);
10595 rem_anchor_token(T___thread);
10596 rem_anchor_token(T___real__);
10597 rem_anchor_token(T___label__);
10598 rem_anchor_token(T___imag__);
10599 rem_anchor_token(T___func__);
10600 rem_anchor_token(T___extension__);
10601 rem_anchor_token(T___builtin_va_start);
10602 rem_anchor_token(T___attribute__);
10603 rem_anchor_token(T___alignof__);
10604 rem_anchor_token(T___PRETTY_FUNCTION__);
10605 rem_anchor_token(T___FUNCTION__);
10606 rem_anchor_token(T__Imaginary);
10607 rem_anchor_token(T__Complex);
10608 rem_anchor_token(T__Bool);
10609 rem_anchor_token(T_WIDE_STRING_LITERAL);
10610 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10611 rem_anchor_token(T_STRING_LITERAL);
10612 rem_anchor_token(T_PLUSPLUS);
10613 rem_anchor_token(T_MINUSMINUS);
10614 rem_anchor_token(T_INTEGER);
10615 rem_anchor_token(T_IDENTIFIER);
10616 rem_anchor_token(T_FLOATINGPOINT);
10617 rem_anchor_token(T_COLONCOLON);
10618 rem_anchor_token(T_CHARACTER_CONSTANT);
10619 rem_anchor_token('~');
10620 rem_anchor_token('{');
10621 rem_anchor_token('-');
10622 rem_anchor_token('+');
10623 rem_anchor_token('*');
10624 rem_anchor_token('(');
10625 rem_anchor_token('&');
10626 rem_anchor_token('!');
10627 rem_anchor_token('}');
10628 assert(current_scope == &statement->compound.scope);
10629 scope_pop(old_scope);
10630 environment_pop_to(top);
10637 * Check for unused global static functions and variables
10639 static void check_unused_globals(void)
10641 if (!warning.unused_function && !warning.unused_variable)
10644 for (const entity_t *entity = file_scope->entities; entity != NULL;
10645 entity = entity->base.next) {
10646 if (!is_declaration(entity))
10649 const declaration_t *declaration = &entity->declaration;
10650 if (declaration->used ||
10651 declaration->modifiers & DM_UNUSED ||
10652 declaration->modifiers & DM_USED ||
10653 declaration->storage_class != STORAGE_CLASS_STATIC)
10656 type_t *const type = declaration->type;
10658 if (entity->kind == ENTITY_FUNCTION) {
10659 /* inhibit warning for static inline functions */
10660 if (entity->function.is_inline)
10663 s = entity->function.statement != NULL ? "defined" : "declared";
10668 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10669 type, declaration->base.symbol, s);
10673 static void parse_global_asm(void)
10675 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10678 expect('(', end_error);
10680 statement->asms.asm_text = parse_string_literals();
10681 statement->base.next = unit->global_asm;
10682 unit->global_asm = statement;
10684 expect(')', end_error);
10685 expect(';', end_error);
10690 static void parse_linkage_specification(void)
10694 const char *linkage = parse_string_literals().begin;
10696 linkage_kind_t old_linkage = current_linkage;
10697 linkage_kind_t new_linkage;
10698 if (strcmp(linkage, "C") == 0) {
10699 new_linkage = LINKAGE_C;
10700 } else if (strcmp(linkage, "C++") == 0) {
10701 new_linkage = LINKAGE_CXX;
10703 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10704 new_linkage = LINKAGE_INVALID;
10706 current_linkage = new_linkage;
10708 if (next_if('{')) {
10710 expect('}', end_error);
10716 assert(current_linkage == new_linkage);
10717 current_linkage = old_linkage;
10720 static void parse_external(void)
10722 switch (token.type) {
10723 DECLARATION_START_NO_EXTERN
10725 case T___extension__:
10726 /* tokens below are for implicit int */
10727 case '&': /* & x; -> int& x; (and error later, because C++ has no
10729 case '*': /* * x; -> int* x; */
10730 case '(': /* (x); -> int (x); */
10731 parse_external_declaration();
10735 if (look_ahead(1)->type == T_STRING_LITERAL) {
10736 parse_linkage_specification();
10738 parse_external_declaration();
10743 parse_global_asm();
10747 parse_namespace_definition();
10751 if (!strict_mode) {
10753 warningf(HERE, "stray ';' outside of function");
10760 errorf(HERE, "stray %K outside of function", &token);
10761 if (token.type == '(' || token.type == '{' || token.type == '[')
10762 eat_until_matching_token(token.type);
10768 static void parse_externals(void)
10770 add_anchor_token('}');
10771 add_anchor_token(T_EOF);
10774 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10775 unsigned char token_anchor_copy[T_LAST_TOKEN];
10776 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10779 while (token.type != T_EOF && token.type != '}') {
10781 bool anchor_leak = false;
10782 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10783 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10785 /* the anchor set and its copy differs */
10786 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10787 anchor_leak = true;
10790 if (in_gcc_extension) {
10791 /* an gcc extension scope was not closed */
10792 internal_errorf(HERE, "Leaked __extension__");
10793 anchor_leak = true;
10803 rem_anchor_token(T_EOF);
10804 rem_anchor_token('}');
10808 * Parse a translation unit.
10810 static void parse_translation_unit(void)
10812 add_anchor_token(T_EOF);
10817 if (token.type == T_EOF)
10820 errorf(HERE, "stray %K outside of function", &token);
10821 if (token.type == '(' || token.type == '{' || token.type == '[')
10822 eat_until_matching_token(token.type);
10827 void set_default_visibility(elf_visibility_tag_t visibility)
10829 default_visibility = visibility;
10835 * @return the translation unit or NULL if errors occurred.
10837 void start_parsing(void)
10839 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10840 label_stack = NEW_ARR_F(stack_entry_t, 0);
10841 diagnostic_count = 0;
10845 print_to_file(stderr);
10847 assert(unit == NULL);
10848 unit = allocate_ast_zero(sizeof(unit[0]));
10850 assert(file_scope == NULL);
10851 file_scope = &unit->scope;
10853 assert(current_scope == NULL);
10854 scope_push(&unit->scope);
10856 create_gnu_builtins();
10858 create_microsoft_intrinsics();
10861 translation_unit_t *finish_parsing(void)
10863 assert(current_scope == &unit->scope);
10866 assert(file_scope == &unit->scope);
10867 check_unused_globals();
10870 DEL_ARR_F(environment_stack);
10871 DEL_ARR_F(label_stack);
10873 translation_unit_t *result = unit;
10878 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10879 * are given length one. */
10880 static void complete_incomplete_arrays(void)
10882 size_t n = ARR_LEN(incomplete_arrays);
10883 for (size_t i = 0; i != n; ++i) {
10884 declaration_t *const decl = incomplete_arrays[i];
10885 type_t *const orig_type = decl->type;
10886 type_t *const type = skip_typeref(orig_type);
10888 if (!is_type_incomplete(type))
10891 if (warning.other) {
10892 warningf(&decl->base.source_position,
10893 "array '%#T' assumed to have one element",
10894 orig_type, decl->base.symbol);
10897 type_t *const new_type = duplicate_type(type);
10898 new_type->array.size_constant = true;
10899 new_type->array.has_implicit_size = true;
10900 new_type->array.size = 1;
10902 type_t *const result = identify_new_type(new_type);
10904 decl->type = result;
10908 void prepare_main_collect2(entity_t *entity)
10910 // create call to __main
10911 symbol_t *symbol = symbol_table_insert("__main");
10912 entity_t *subsubmain_ent
10913 = create_implicit_function(symbol, &builtin_source_position);
10915 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10916 type_t *ftype = subsubmain_ent->declaration.type;
10917 ref->base.source_position = builtin_source_position;
10918 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10919 ref->reference.entity = subsubmain_ent;
10921 expression_t *call = allocate_expression_zero(EXPR_CALL);
10922 call->base.source_position = builtin_source_position;
10923 call->base.type = type_void;
10924 call->call.function = ref;
10926 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10927 expr_statement->base.source_position = builtin_source_position;
10928 expr_statement->expression.expression = call;
10930 statement_t *statement = entity->function.statement;
10931 assert(statement->kind == STATEMENT_COMPOUND);
10932 compound_statement_t *compounds = &statement->compound;
10934 expr_statement->base.next = compounds->statements;
10935 compounds->statements = expr_statement;
10940 lookahead_bufpos = 0;
10941 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10944 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10945 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10946 parse_translation_unit();
10947 complete_incomplete_arrays();
10948 DEL_ARR_F(incomplete_arrays);
10949 incomplete_arrays = NULL;
10953 * Initialize the parser.
10955 void init_parser(void)
10957 sym_anonymous = symbol_table_insert("<anonymous>");
10959 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10961 init_expression_parsers();
10962 obstack_init(&temp_obst);
10966 * Terminate the parser.
10968 void exit_parser(void)
10970 obstack_free(&temp_obst, NULL);