2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const prev_parent = current_parent; \
116 ((void)(current_parent = (stmt)))
117 #define POP_PARENT ((void)(current_parent = prev_parent))
119 /** special symbol used for anonymous entities. */
120 static symbol_t *sym_anonymous = NULL;
122 /** The token anchor set */
123 static unsigned char token_anchor_set[T_LAST_TOKEN];
125 /** The current source position. */
126 #define HERE (&token.source_position)
128 /** true if we are in GCC mode. */
129 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
131 static statement_t *parse_compound_statement(bool inside_expression_statement);
132 static statement_t *parse_statement(void);
134 static expression_t *parse_subexpression(precedence_t);
135 static expression_t *parse_expression(void);
136 static type_t *parse_typename(void);
137 static void parse_externals(void);
138 static void parse_external(void);
140 static void parse_compound_type_entries(compound_t *compound_declaration);
142 static void check_call_argument(type_t *expected_type,
143 call_argument_t *argument, unsigned pos);
145 typedef enum declarator_flags_t {
147 DECL_MAY_BE_ABSTRACT = 1U << 0,
148 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
149 DECL_IS_PARAMETER = 1U << 2
150 } declarator_flags_t;
152 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
153 declarator_flags_t flags);
155 static void semantic_comparison(binary_expression_t *expression);
157 #define STORAGE_CLASSES \
158 STORAGE_CLASSES_NO_EXTERN \
161 #define STORAGE_CLASSES_NO_EXTERN \
168 #define TYPE_QUALIFIERS \
173 case T__forceinline: \
174 case T___attribute__:
176 #define COMPLEX_SPECIFIERS \
178 #define IMAGINARY_SPECIFIERS \
181 #define TYPE_SPECIFIERS \
183 case T___builtin_va_list: \
208 #define DECLARATION_START \
213 #define DECLARATION_START_NO_EXTERN \
214 STORAGE_CLASSES_NO_EXTERN \
218 #define TYPENAME_START \
222 #define EXPRESSION_START \
231 case T_CHARACTER_CONSTANT: \
232 case T_FLOATINGPOINT: \
233 case T_FLOATINGPOINT_HEXADECIMAL: \
235 case T_INTEGER_HEXADECIMAL: \
236 case T_INTEGER_OCTAL: \
239 case T_STRING_LITERAL: \
240 case T_WIDE_CHARACTER_CONSTANT: \
241 case T_WIDE_STRING_LITERAL: \
242 case T___FUNCDNAME__: \
243 case T___FUNCSIG__: \
244 case T___FUNCTION__: \
245 case T___PRETTY_FUNCTION__: \
246 case T___alignof__: \
247 case T___builtin_classify_type: \
248 case T___builtin_constant_p: \
249 case T___builtin_isgreater: \
250 case T___builtin_isgreaterequal: \
251 case T___builtin_isless: \
252 case T___builtin_islessequal: \
253 case T___builtin_islessgreater: \
254 case T___builtin_isunordered: \
255 case T___builtin_offsetof: \
256 case T___builtin_va_arg: \
257 case T___builtin_va_copy: \
258 case T___builtin_va_start: \
269 * Returns the size of a statement node.
271 * @param kind the statement kind
273 static size_t get_statement_struct_size(statement_kind_t kind)
275 static const size_t sizes[] = {
276 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
277 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
278 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
279 [STATEMENT_RETURN] = sizeof(return_statement_t),
280 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
281 [STATEMENT_IF] = sizeof(if_statement_t),
282 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
283 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
284 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
285 [STATEMENT_BREAK] = sizeof(statement_base_t),
286 [STATEMENT_GOTO] = sizeof(goto_statement_t),
287 [STATEMENT_LABEL] = sizeof(label_statement_t),
288 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
289 [STATEMENT_WHILE] = sizeof(while_statement_t),
290 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
291 [STATEMENT_FOR] = sizeof(for_statement_t),
292 [STATEMENT_ASM] = sizeof(asm_statement_t),
293 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
294 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
296 assert(kind < lengthof(sizes));
297 assert(sizes[kind] != 0);
302 * Returns the size of an expression node.
304 * @param kind the expression kind
306 static size_t get_expression_struct_size(expression_kind_t kind)
308 static const size_t sizes[] = {
309 [EXPR_INVALID] = sizeof(expression_base_t),
310 [EXPR_REFERENCE] = sizeof(reference_expression_t),
311 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
312 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
316 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
317 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
318 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
319 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
320 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
321 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
322 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
323 [EXPR_CALL] = sizeof(call_expression_t),
324 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
325 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
326 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
327 [EXPR_SELECT] = sizeof(select_expression_t),
328 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
329 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
330 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
331 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
332 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
333 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
334 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
335 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
336 [EXPR_VA_START] = sizeof(va_start_expression_t),
337 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
338 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
339 [EXPR_STATEMENT] = sizeof(statement_expression_t),
340 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
342 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
343 return sizes[EXPR_UNARY_FIRST];
345 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
346 return sizes[EXPR_BINARY_FIRST];
348 assert(kind < lengthof(sizes));
349 assert(sizes[kind] != 0);
354 * Allocate a statement node of given kind and initialize all
355 * fields with zero. Sets its source position to the position
356 * of the current token.
358 static statement_t *allocate_statement_zero(statement_kind_t kind)
360 size_t size = get_statement_struct_size(kind);
361 statement_t *res = allocate_ast_zero(size);
363 res->base.kind = kind;
364 res->base.parent = current_parent;
365 res->base.source_position = token.source_position;
370 * Allocate an expression node of given kind and initialize all
373 * @param kind the kind of the expression to allocate
375 static expression_t *allocate_expression_zero(expression_kind_t kind)
377 size_t size = get_expression_struct_size(kind);
378 expression_t *res = allocate_ast_zero(size);
380 res->base.kind = kind;
381 res->base.type = type_error_type;
382 res->base.source_position = token.source_position;
387 * Creates a new invalid expression at the source position
388 * of the current token.
390 static expression_t *create_invalid_expression(void)
392 return allocate_expression_zero(EXPR_INVALID);
396 * Creates a new invalid statement.
398 static statement_t *create_invalid_statement(void)
400 return allocate_statement_zero(STATEMENT_INVALID);
404 * Allocate a new empty statement.
406 static statement_t *create_empty_statement(void)
408 return allocate_statement_zero(STATEMENT_EMPTY);
411 static function_parameter_t *allocate_parameter(type_t *const type)
413 function_parameter_t *const param
414 = obstack_alloc(type_obst, sizeof(*param));
415 memset(param, 0, sizeof(*param));
421 * Returns the size of an initializer node.
423 * @param kind the initializer kind
425 static size_t get_initializer_size(initializer_kind_t kind)
427 static const size_t sizes[] = {
428 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
429 [INITIALIZER_STRING] = sizeof(initializer_string_t),
430 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
431 [INITIALIZER_LIST] = sizeof(initializer_list_t),
432 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
434 assert(kind < lengthof(sizes));
435 assert(sizes[kind] != 0);
440 * Allocate an initializer node of given kind and initialize all
443 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
445 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
452 * Returns the index of the top element of the environment stack.
454 static size_t environment_top(void)
456 return ARR_LEN(environment_stack);
460 * Returns the index of the top element of the global label stack.
462 static size_t label_top(void)
464 return ARR_LEN(label_stack);
468 * Return the next token.
470 static inline void next_token(void)
472 token = lookahead_buffer[lookahead_bufpos];
473 lookahead_buffer[lookahead_bufpos] = lexer_token;
476 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
479 print_token(stderr, &token);
480 fprintf(stderr, "\n");
484 static inline bool next_if(int const type)
486 if (token.type == type) {
495 * Return the next token with a given lookahead.
497 static inline const token_t *look_ahead(size_t num)
499 assert(0 < num && num <= MAX_LOOKAHEAD);
500 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
501 return &lookahead_buffer[pos];
505 * Adds a token type to the token type anchor set (a multi-set).
507 static void add_anchor_token(int token_type)
509 assert(0 <= token_type && token_type < T_LAST_TOKEN);
510 ++token_anchor_set[token_type];
514 * Set the number of tokens types of the given type
515 * to zero and return the old count.
517 static int save_and_reset_anchor_state(int token_type)
519 assert(0 <= token_type && token_type < T_LAST_TOKEN);
520 int count = token_anchor_set[token_type];
521 token_anchor_set[token_type] = 0;
526 * Restore the number of token types to the given count.
528 static void restore_anchor_state(int token_type, int count)
530 assert(0 <= token_type && token_type < T_LAST_TOKEN);
531 token_anchor_set[token_type] = count;
535 * Remove a token type from the token type anchor set (a multi-set).
537 static void rem_anchor_token(int token_type)
539 assert(0 <= token_type && token_type < T_LAST_TOKEN);
540 assert(token_anchor_set[token_type] != 0);
541 --token_anchor_set[token_type];
545 * Return true if the token type of the current token is
548 static bool at_anchor(void)
552 return token_anchor_set[token.type];
556 * Eat tokens until a matching token type is found.
558 static void eat_until_matching_token(int type)
562 case '(': end_token = ')'; break;
563 case '{': end_token = '}'; break;
564 case '[': end_token = ']'; break;
565 default: end_token = type; break;
568 unsigned parenthesis_count = 0;
569 unsigned brace_count = 0;
570 unsigned bracket_count = 0;
571 while (token.type != end_token ||
572 parenthesis_count != 0 ||
574 bracket_count != 0) {
575 switch (token.type) {
577 case '(': ++parenthesis_count; break;
578 case '{': ++brace_count; break;
579 case '[': ++bracket_count; break;
582 if (parenthesis_count > 0)
592 if (bracket_count > 0)
595 if (token.type == end_token &&
596 parenthesis_count == 0 &&
610 * Eat input tokens until an anchor is found.
612 static void eat_until_anchor(void)
614 while (token_anchor_set[token.type] == 0) {
615 if (token.type == '(' || token.type == '{' || token.type == '[')
616 eat_until_matching_token(token.type);
622 * Eat a whole block from input tokens.
624 static void eat_block(void)
626 eat_until_matching_token('{');
630 #define eat(token_type) (assert(token.type == (token_type)), next_token())
633 * Report a parse error because an expected token was not found.
636 #if defined __GNUC__ && __GNUC__ >= 4
637 __attribute__((sentinel))
639 void parse_error_expected(const char *message, ...)
641 if (message != NULL) {
642 errorf(HERE, "%s", message);
645 va_start(ap, message);
646 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
651 * Report an incompatible type.
653 static void type_error_incompatible(const char *msg,
654 const source_position_t *source_position, type_t *type1, type_t *type2)
656 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
661 * Expect the current token is the expected token.
662 * If not, generate an error, eat the current statement,
663 * and goto the error_label label.
665 #define expect(expected, error_label) \
667 if (UNLIKELY(token.type != (expected))) { \
668 parse_error_expected(NULL, (expected), NULL); \
669 add_anchor_token(expected); \
670 eat_until_anchor(); \
671 next_if((expected)); \
672 rem_anchor_token(expected); \
679 * Push a given scope on the scope stack and make it the
682 static scope_t *scope_push(scope_t *new_scope)
684 if (current_scope != NULL) {
685 new_scope->depth = current_scope->depth + 1;
688 scope_t *old_scope = current_scope;
689 current_scope = new_scope;
694 * Pop the current scope from the scope stack.
696 static void scope_pop(scope_t *old_scope)
698 current_scope = old_scope;
702 * Search an entity by its symbol in a given namespace.
704 static entity_t *get_entity(const symbol_t *const symbol,
705 namespace_tag_t namespc)
707 assert(namespc != NAMESPACE_INVALID);
708 entity_t *entity = symbol->entity;
709 for (; entity != NULL; entity = entity->base.symbol_next) {
710 if (entity->base.namespc == namespc)
717 /* §6.2.3:1 24) There is only one name space for tags even though three are
719 static entity_t *get_tag(symbol_t const *const symbol,
720 entity_kind_tag_t const kind)
722 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
723 if (entity != NULL && entity->kind != kind) {
725 "'%Y' defined as wrong kind of tag (previous definition %P)",
726 symbol, &entity->base.source_position);
733 * pushs an entity on the environment stack and links the corresponding symbol
736 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
738 symbol_t *symbol = entity->base.symbol;
739 entity_namespace_t namespc = entity->base.namespc;
740 assert(namespc != NAMESPACE_INVALID);
742 /* replace/add entity into entity list of the symbol */
745 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
750 /* replace an entry? */
751 if (iter->base.namespc == namespc) {
752 entity->base.symbol_next = iter->base.symbol_next;
758 /* remember old declaration */
760 entry.symbol = symbol;
761 entry.old_entity = iter;
762 entry.namespc = namespc;
763 ARR_APP1(stack_entry_t, *stack_ptr, entry);
767 * Push an entity on the environment stack.
769 static void environment_push(entity_t *entity)
771 assert(entity->base.source_position.input_name != NULL);
772 assert(entity->base.parent_scope != NULL);
773 stack_push(&environment_stack, entity);
777 * Push a declaration on the global label stack.
779 * @param declaration the declaration
781 static void label_push(entity_t *label)
783 /* we abuse the parameters scope as parent for the labels */
784 label->base.parent_scope = ¤t_function->parameters;
785 stack_push(&label_stack, label);
789 * pops symbols from the environment stack until @p new_top is the top element
791 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
793 stack_entry_t *stack = *stack_ptr;
794 size_t top = ARR_LEN(stack);
797 assert(new_top <= top);
801 for (i = top; i > new_top; --i) {
802 stack_entry_t *entry = &stack[i - 1];
804 entity_t *old_entity = entry->old_entity;
805 symbol_t *symbol = entry->symbol;
806 entity_namespace_t namespc = entry->namespc;
808 /* replace with old_entity/remove */
811 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
813 assert(iter != NULL);
814 /* replace an entry? */
815 if (iter->base.namespc == namespc)
819 /* restore definition from outer scopes (if there was one) */
820 if (old_entity != NULL) {
821 old_entity->base.symbol_next = iter->base.symbol_next;
822 *anchor = old_entity;
824 /* remove entry from list */
825 *anchor = iter->base.symbol_next;
829 ARR_SHRINKLEN(*stack_ptr, new_top);
833 * Pop all entries from the environment stack until the new_top
836 * @param new_top the new stack top
838 static void environment_pop_to(size_t new_top)
840 stack_pop_to(&environment_stack, new_top);
844 * Pop all entries from the global label stack until the new_top
847 * @param new_top the new stack top
849 static void label_pop_to(size_t new_top)
851 stack_pop_to(&label_stack, new_top);
854 static int get_akind_rank(atomic_type_kind_t akind)
860 * Return the type rank for an atomic type.
862 static int get_rank(const type_t *type)
864 assert(!is_typeref(type));
865 if (type->kind == TYPE_ENUM)
866 return get_akind_rank(type->enumt.akind);
868 assert(type->kind == TYPE_ATOMIC);
869 return get_akind_rank(type->atomic.akind);
873 * §6.3.1.1:2 Do integer promotion for a given type.
875 * @param type the type to promote
876 * @return the promoted type
878 static type_t *promote_integer(type_t *type)
880 if (type->kind == TYPE_BITFIELD)
881 type = type->bitfield.base_type;
883 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
890 * Create a cast expression.
892 * @param expression the expression to cast
893 * @param dest_type the destination type
895 static expression_t *create_cast_expression(expression_t *expression,
898 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
900 cast->unary.value = expression;
901 cast->base.type = dest_type;
907 * Check if a given expression represents a null pointer constant.
909 * @param expression the expression to check
911 static bool is_null_pointer_constant(const expression_t *expression)
913 /* skip void* cast */
914 if (expression->kind == EXPR_UNARY_CAST ||
915 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
916 type_t *const type = skip_typeref(expression->base.type);
917 if (types_compatible(type, type_void_ptr))
918 expression = expression->unary.value;
921 type_t *const type = skip_typeref(expression->base.type);
922 if (!is_type_integer(type))
924 switch (is_constant_expression(expression)) {
925 case EXPR_CLASS_ERROR: return true;
926 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
927 default: return false;
932 * Create an implicit cast expression.
934 * @param expression the expression to cast
935 * @param dest_type the destination type
937 static expression_t *create_implicit_cast(expression_t *expression,
940 type_t *const source_type = expression->base.type;
942 if (source_type == dest_type)
945 return create_cast_expression(expression, dest_type);
948 typedef enum assign_error_t {
950 ASSIGN_ERROR_INCOMPATIBLE,
951 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
952 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
953 ASSIGN_WARNING_POINTER_FROM_INT,
954 ASSIGN_WARNING_INT_FROM_POINTER
957 static void report_assign_error(assign_error_t error, type_t *orig_type_left,
958 const expression_t *const right,
960 const source_position_t *source_position)
962 type_t *const orig_type_right = right->base.type;
963 type_t *const type_left = skip_typeref(orig_type_left);
964 type_t *const type_right = skip_typeref(orig_type_right);
969 case ASSIGN_ERROR_INCOMPATIBLE:
970 errorf(source_position,
971 "destination type '%T' in %s is incompatible with type '%T'",
972 orig_type_left, context, orig_type_right);
975 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
977 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
978 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
980 /* the left type has all qualifiers from the right type */
981 unsigned missing_qualifiers
982 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
983 warningf(source_position,
984 "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type",
985 orig_type_left, context, orig_type_right, missing_qualifiers);
990 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
992 warningf(source_position,
993 "destination type '%T' in %s is incompatible with '%E' of type '%T'",
994 orig_type_left, context, right, orig_type_right);
998 case ASSIGN_WARNING_POINTER_FROM_INT:
1000 warningf(source_position,
1001 "%s makes pointer '%T' from integer '%T' without a cast",
1002 context, orig_type_left, orig_type_right);
1006 case ASSIGN_WARNING_INT_FROM_POINTER:
1007 if (warning.other) {
1008 warningf(source_position,
1009 "%s makes integer '%T' from pointer '%T' without a cast",
1010 context, orig_type_left, orig_type_right);
1015 panic("invalid error value");
1019 /** Implements the rules from §6.5.16.1 */
1020 static assign_error_t semantic_assign(type_t *orig_type_left,
1021 const expression_t *const right)
1023 type_t *const orig_type_right = right->base.type;
1024 type_t *const type_left = skip_typeref(orig_type_left);
1025 type_t *const type_right = skip_typeref(orig_type_right);
1027 if (is_type_pointer(type_left)) {
1028 if (is_null_pointer_constant(right)) {
1029 return ASSIGN_SUCCESS;
1030 } else if (is_type_pointer(type_right)) {
1031 type_t *points_to_left
1032 = skip_typeref(type_left->pointer.points_to);
1033 type_t *points_to_right
1034 = skip_typeref(type_right->pointer.points_to);
1035 assign_error_t res = ASSIGN_SUCCESS;
1037 /* the left type has all qualifiers from the right type */
1038 unsigned missing_qualifiers
1039 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1040 if (missing_qualifiers != 0) {
1041 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1044 points_to_left = get_unqualified_type(points_to_left);
1045 points_to_right = get_unqualified_type(points_to_right);
1047 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1050 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1051 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1052 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1055 if (!types_compatible(points_to_left, points_to_right)) {
1056 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1060 } else if (is_type_integer(type_right)) {
1061 return ASSIGN_WARNING_POINTER_FROM_INT;
1063 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1064 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1065 && is_type_pointer(type_right))) {
1066 return ASSIGN_SUCCESS;
1067 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1068 type_t *const unqual_type_left = get_unqualified_type(type_left);
1069 type_t *const unqual_type_right = get_unqualified_type(type_right);
1070 if (types_compatible(unqual_type_left, unqual_type_right)) {
1071 return ASSIGN_SUCCESS;
1073 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1074 return ASSIGN_WARNING_INT_FROM_POINTER;
1077 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1078 return ASSIGN_SUCCESS;
1080 return ASSIGN_ERROR_INCOMPATIBLE;
1083 static expression_t *parse_constant_expression(void)
1085 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1087 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1088 errorf(&result->base.source_position,
1089 "expression '%E' is not constant", result);
1095 static expression_t *parse_assignment_expression(void)
1097 return parse_subexpression(PREC_ASSIGNMENT);
1100 static void warn_string_concat(const source_position_t *pos)
1102 if (warning.traditional) {
1103 warningf(pos, "traditional C rejects string constant concatenation");
1107 static string_t parse_string_literals(void)
1109 assert(token.type == T_STRING_LITERAL);
1110 string_t result = token.literal;
1114 while (token.type == T_STRING_LITERAL) {
1115 warn_string_concat(&token.source_position);
1116 result = concat_strings(&result, &token.literal);
1124 * compare two string, ignoring double underscores on the second.
1126 static int strcmp_underscore(const char *s1, const char *s2)
1128 if (s2[0] == '_' && s2[1] == '_') {
1129 size_t len2 = strlen(s2);
1130 size_t len1 = strlen(s1);
1131 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1132 return strncmp(s1, s2+2, len2-4);
1136 return strcmp(s1, s2);
1139 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1141 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1142 attribute->kind = kind;
1147 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1150 * __attribute__ ( ( attribute-list ) )
1154 * attribute_list , attrib
1159 * any-word ( identifier )
1160 * any-word ( identifier , nonempty-expr-list )
1161 * any-word ( expr-list )
1163 * where the "identifier" must not be declared as a type, and
1164 * "any-word" may be any identifier (including one declared as a
1165 * type), a reserved word storage class specifier, type specifier or
1166 * type qualifier. ??? This still leaves out most reserved keywords
1167 * (following the old parser), shouldn't we include them, and why not
1168 * allow identifiers declared as types to start the arguments?
1170 * Matze: this all looks confusing and little systematic, so we're even less
1171 * strict and parse any list of things which are identifiers or
1172 * (assignment-)expressions.
1174 static attribute_argument_t *parse_attribute_arguments(void)
1176 attribute_argument_t *first = NULL;
1177 attribute_argument_t **anchor = &first;
1178 if (token.type != ')') do {
1179 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1181 /* is it an identifier */
1182 if (token.type == T_IDENTIFIER
1183 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1184 symbol_t *symbol = token.symbol;
1185 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1186 argument->v.symbol = symbol;
1189 /* must be an expression */
1190 expression_t *expression = parse_assignment_expression();
1192 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1193 argument->v.expression = expression;
1196 /* append argument */
1198 anchor = &argument->next;
1199 } while (next_if(','));
1200 expect(')', end_error);
1209 static attribute_t *parse_attribute_asm(void)
1213 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1215 expect('(', end_error);
1216 attribute->a.arguments = parse_attribute_arguments();
1223 static symbol_t *get_symbol_from_token(void)
1225 switch(token.type) {
1227 return token.symbol;
1256 /* maybe we need more tokens ... add them on demand */
1257 return get_token_symbol(&token);
1263 static attribute_t *parse_attribute_gnu_single(void)
1265 /* parse "any-word" */
1266 symbol_t *symbol = get_symbol_from_token();
1267 if (symbol == NULL) {
1268 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1272 const char *name = symbol->string;
1275 attribute_kind_t kind;
1276 for (kind = ATTRIBUTE_GNU_FIRST; kind <= ATTRIBUTE_GNU_LAST; ++kind) {
1277 const char *attribute_name = get_attribute_name(kind);
1278 if (attribute_name != NULL
1279 && strcmp_underscore(attribute_name, name) == 0)
1283 if (kind >= ATTRIBUTE_GNU_LAST) {
1284 if (warning.attribute) {
1285 warningf(HERE, "unknown attribute '%s' ignored", name);
1287 /* TODO: we should still save the attribute in the list... */
1288 kind = ATTRIBUTE_UNKNOWN;
1291 attribute_t *attribute = allocate_attribute_zero(kind);
1293 /* parse arguments */
1295 attribute->a.arguments = parse_attribute_arguments();
1300 static attribute_t *parse_attribute_gnu(void)
1302 attribute_t *first = NULL;
1303 attribute_t **anchor = &first;
1305 eat(T___attribute__);
1306 expect('(', end_error);
1307 expect('(', end_error);
1309 if (token.type != ')') do {
1310 attribute_t *attribute = parse_attribute_gnu_single();
1311 if (attribute == NULL)
1314 *anchor = attribute;
1315 anchor = &attribute->next;
1316 } while (next_if(','));
1317 expect(')', end_error);
1318 expect(')', end_error);
1324 /** Parse attributes. */
1325 static attribute_t *parse_attributes(attribute_t *first)
1327 attribute_t **anchor = &first;
1329 while (*anchor != NULL)
1330 anchor = &(*anchor)->next;
1332 attribute_t *attribute;
1333 switch (token.type) {
1334 case T___attribute__:
1335 attribute = parse_attribute_gnu();
1336 if (attribute == NULL)
1341 attribute = parse_attribute_asm();
1346 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1351 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1354 case T__forceinline:
1356 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1361 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1366 /* TODO record modifier */
1368 warningf(HERE, "Ignoring declaration modifier %K", &token);
1369 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1376 *anchor = attribute;
1377 anchor = &attribute->next;
1381 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1383 static entity_t *determine_lhs_ent(expression_t *const expr,
1386 switch (expr->kind) {
1387 case EXPR_REFERENCE: {
1388 entity_t *const entity = expr->reference.entity;
1389 /* we should only find variables as lvalues... */
1390 if (entity->base.kind != ENTITY_VARIABLE
1391 && entity->base.kind != ENTITY_PARAMETER)
1397 case EXPR_ARRAY_ACCESS: {
1398 expression_t *const ref = expr->array_access.array_ref;
1399 entity_t * ent = NULL;
1400 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1401 ent = determine_lhs_ent(ref, lhs_ent);
1404 mark_vars_read(expr->select.compound, lhs_ent);
1406 mark_vars_read(expr->array_access.index, lhs_ent);
1411 if (is_type_compound(skip_typeref(expr->base.type))) {
1412 return determine_lhs_ent(expr->select.compound, lhs_ent);
1414 mark_vars_read(expr->select.compound, lhs_ent);
1419 case EXPR_UNARY_DEREFERENCE: {
1420 expression_t *const val = expr->unary.value;
1421 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1423 return determine_lhs_ent(val->unary.value, lhs_ent);
1425 mark_vars_read(val, NULL);
1431 mark_vars_read(expr, NULL);
1436 #define ENT_ANY ((entity_t*)-1)
1439 * Mark declarations, which are read. This is used to detect variables, which
1443 * x is not marked as "read", because it is only read to calculate its own new
1447 * x and y are not detected as "not read", because multiple variables are
1450 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1452 switch (expr->kind) {
1453 case EXPR_REFERENCE: {
1454 entity_t *const entity = expr->reference.entity;
1455 if (entity->kind != ENTITY_VARIABLE
1456 && entity->kind != ENTITY_PARAMETER)
1459 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1460 if (entity->kind == ENTITY_VARIABLE) {
1461 entity->variable.read = true;
1463 entity->parameter.read = true;
1470 // TODO respect pure/const
1471 mark_vars_read(expr->call.function, NULL);
1472 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1473 mark_vars_read(arg->expression, NULL);
1477 case EXPR_CONDITIONAL:
1478 // TODO lhs_decl should depend on whether true/false have an effect
1479 mark_vars_read(expr->conditional.condition, NULL);
1480 if (expr->conditional.true_expression != NULL)
1481 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1482 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1486 if (lhs_ent == ENT_ANY
1487 && !is_type_compound(skip_typeref(expr->base.type)))
1489 mark_vars_read(expr->select.compound, lhs_ent);
1492 case EXPR_ARRAY_ACCESS: {
1493 expression_t *const ref = expr->array_access.array_ref;
1494 mark_vars_read(ref, lhs_ent);
1495 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1496 mark_vars_read(expr->array_access.index, lhs_ent);
1501 mark_vars_read(expr->va_arge.ap, lhs_ent);
1505 mark_vars_read(expr->va_copye.src, lhs_ent);
1508 case EXPR_UNARY_CAST:
1509 /* Special case: Use void cast to mark a variable as "read" */
1510 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1515 case EXPR_UNARY_THROW:
1516 if (expr->unary.value == NULL)
1519 case EXPR_UNARY_DEREFERENCE:
1520 case EXPR_UNARY_DELETE:
1521 case EXPR_UNARY_DELETE_ARRAY:
1522 if (lhs_ent == ENT_ANY)
1526 case EXPR_UNARY_NEGATE:
1527 case EXPR_UNARY_PLUS:
1528 case EXPR_UNARY_BITWISE_NEGATE:
1529 case EXPR_UNARY_NOT:
1530 case EXPR_UNARY_TAKE_ADDRESS:
1531 case EXPR_UNARY_POSTFIX_INCREMENT:
1532 case EXPR_UNARY_POSTFIX_DECREMENT:
1533 case EXPR_UNARY_PREFIX_INCREMENT:
1534 case EXPR_UNARY_PREFIX_DECREMENT:
1535 case EXPR_UNARY_CAST_IMPLICIT:
1536 case EXPR_UNARY_ASSUME:
1538 mark_vars_read(expr->unary.value, lhs_ent);
1541 case EXPR_BINARY_ADD:
1542 case EXPR_BINARY_SUB:
1543 case EXPR_BINARY_MUL:
1544 case EXPR_BINARY_DIV:
1545 case EXPR_BINARY_MOD:
1546 case EXPR_BINARY_EQUAL:
1547 case EXPR_BINARY_NOTEQUAL:
1548 case EXPR_BINARY_LESS:
1549 case EXPR_BINARY_LESSEQUAL:
1550 case EXPR_BINARY_GREATER:
1551 case EXPR_BINARY_GREATEREQUAL:
1552 case EXPR_BINARY_BITWISE_AND:
1553 case EXPR_BINARY_BITWISE_OR:
1554 case EXPR_BINARY_BITWISE_XOR:
1555 case EXPR_BINARY_LOGICAL_AND:
1556 case EXPR_BINARY_LOGICAL_OR:
1557 case EXPR_BINARY_SHIFTLEFT:
1558 case EXPR_BINARY_SHIFTRIGHT:
1559 case EXPR_BINARY_COMMA:
1560 case EXPR_BINARY_ISGREATER:
1561 case EXPR_BINARY_ISGREATEREQUAL:
1562 case EXPR_BINARY_ISLESS:
1563 case EXPR_BINARY_ISLESSEQUAL:
1564 case EXPR_BINARY_ISLESSGREATER:
1565 case EXPR_BINARY_ISUNORDERED:
1566 mark_vars_read(expr->binary.left, lhs_ent);
1567 mark_vars_read(expr->binary.right, lhs_ent);
1570 case EXPR_BINARY_ASSIGN:
1571 case EXPR_BINARY_MUL_ASSIGN:
1572 case EXPR_BINARY_DIV_ASSIGN:
1573 case EXPR_BINARY_MOD_ASSIGN:
1574 case EXPR_BINARY_ADD_ASSIGN:
1575 case EXPR_BINARY_SUB_ASSIGN:
1576 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1577 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1578 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1579 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1580 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1581 if (lhs_ent == ENT_ANY)
1583 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1584 mark_vars_read(expr->binary.right, lhs_ent);
1589 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1595 case EXPR_STRING_LITERAL:
1596 case EXPR_WIDE_STRING_LITERAL:
1597 case EXPR_COMPOUND_LITERAL: // TODO init?
1599 case EXPR_CLASSIFY_TYPE:
1602 case EXPR_BUILTIN_CONSTANT_P:
1603 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1605 case EXPR_STATEMENT: // TODO
1606 case EXPR_LABEL_ADDRESS:
1607 case EXPR_REFERENCE_ENUM_VALUE:
1611 panic("unhandled expression");
1614 static designator_t *parse_designation(void)
1616 designator_t *result = NULL;
1617 designator_t **anchor = &result;
1620 designator_t *designator;
1621 switch (token.type) {
1623 designator = allocate_ast_zero(sizeof(designator[0]));
1624 designator->source_position = token.source_position;
1626 add_anchor_token(']');
1627 designator->array_index = parse_constant_expression();
1628 rem_anchor_token(']');
1629 expect(']', end_error);
1632 designator = allocate_ast_zero(sizeof(designator[0]));
1633 designator->source_position = token.source_position;
1635 if (token.type != T_IDENTIFIER) {
1636 parse_error_expected("while parsing designator",
1637 T_IDENTIFIER, NULL);
1640 designator->symbol = token.symbol;
1644 expect('=', end_error);
1648 assert(designator != NULL);
1649 *anchor = designator;
1650 anchor = &designator->next;
1656 static initializer_t *initializer_from_string(array_type_t *const type,
1657 const string_t *const string)
1659 /* TODO: check len vs. size of array type */
1662 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1663 initializer->string.string = *string;
1668 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1669 const string_t *const string)
1671 /* TODO: check len vs. size of array type */
1674 initializer_t *const initializer =
1675 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1676 initializer->wide_string.string = *string;
1682 * Build an initializer from a given expression.
1684 static initializer_t *initializer_from_expression(type_t *orig_type,
1685 expression_t *expression)
1687 /* TODO check that expression is a constant expression */
1689 /* §6.7.8.14/15 char array may be initialized by string literals */
1690 type_t *type = skip_typeref(orig_type);
1691 type_t *expr_type_orig = expression->base.type;
1692 type_t *expr_type = skip_typeref(expr_type_orig);
1694 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1695 array_type_t *const array_type = &type->array;
1696 type_t *const element_type = skip_typeref(array_type->element_type);
1698 if (element_type->kind == TYPE_ATOMIC) {
1699 atomic_type_kind_t akind = element_type->atomic.akind;
1700 switch (expression->kind) {
1701 case EXPR_STRING_LITERAL:
1702 if (akind == ATOMIC_TYPE_CHAR
1703 || akind == ATOMIC_TYPE_SCHAR
1704 || akind == ATOMIC_TYPE_UCHAR) {
1705 return initializer_from_string(array_type,
1706 &expression->string_literal.value);
1710 case EXPR_WIDE_STRING_LITERAL: {
1711 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1712 if (get_unqualified_type(element_type) == bare_wchar_type) {
1713 return initializer_from_wide_string(array_type,
1714 &expression->string_literal.value);
1725 assign_error_t error = semantic_assign(type, expression);
1726 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1728 report_assign_error(error, type, expression, "initializer",
1729 &expression->base.source_position);
1731 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1732 result->value.value = create_implicit_cast(expression, type);
1738 * Checks if a given expression can be used as an constant initializer.
1740 static bool is_initializer_constant(const expression_t *expression)
1743 is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1744 is_address_constant(expression) != EXPR_CLASS_VARIABLE;
1748 * Parses an scalar initializer.
1750 * §6.7.8.11; eat {} without warning
1752 static initializer_t *parse_scalar_initializer(type_t *type,
1753 bool must_be_constant)
1755 /* there might be extra {} hierarchies */
1757 if (token.type == '{') {
1759 warningf(HERE, "extra curly braces around scalar initializer");
1763 } while (token.type == '{');
1766 expression_t *expression = parse_assignment_expression();
1767 mark_vars_read(expression, NULL);
1768 if (must_be_constant && !is_initializer_constant(expression)) {
1769 errorf(&expression->base.source_position,
1770 "initialisation expression '%E' is not constant",
1774 initializer_t *initializer = initializer_from_expression(type, expression);
1776 if (initializer == NULL) {
1777 errorf(&expression->base.source_position,
1778 "expression '%E' (type '%T') doesn't match expected type '%T'",
1779 expression, expression->base.type, type);
1784 bool additional_warning_displayed = false;
1785 while (braces > 0) {
1787 if (token.type != '}') {
1788 if (!additional_warning_displayed && warning.other) {
1789 warningf(HERE, "additional elements in scalar initializer");
1790 additional_warning_displayed = true;
1801 * An entry in the type path.
1803 typedef struct type_path_entry_t type_path_entry_t;
1804 struct type_path_entry_t {
1805 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1807 size_t index; /**< For array types: the current index. */
1808 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1813 * A type path expression a position inside compound or array types.
1815 typedef struct type_path_t type_path_t;
1816 struct type_path_t {
1817 type_path_entry_t *path; /**< An flexible array containing the current path. */
1818 type_t *top_type; /**< type of the element the path points */
1819 size_t max_index; /**< largest index in outermost array */
1823 * Prints a type path for debugging.
1825 static __attribute__((unused)) void debug_print_type_path(
1826 const type_path_t *path)
1828 size_t len = ARR_LEN(path->path);
1830 for (size_t i = 0; i < len; ++i) {
1831 const type_path_entry_t *entry = & path->path[i];
1833 type_t *type = skip_typeref(entry->type);
1834 if (is_type_compound(type)) {
1835 /* in gcc mode structs can have no members */
1836 if (entry->v.compound_entry == NULL) {
1840 fprintf(stderr, ".%s",
1841 entry->v.compound_entry->base.symbol->string);
1842 } else if (is_type_array(type)) {
1843 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1845 fprintf(stderr, "-INVALID-");
1848 if (path->top_type != NULL) {
1849 fprintf(stderr, " (");
1850 print_type(path->top_type);
1851 fprintf(stderr, ")");
1856 * Return the top type path entry, ie. in a path
1857 * (type).a.b returns the b.
1859 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1861 size_t len = ARR_LEN(path->path);
1863 return &path->path[len-1];
1867 * Enlarge the type path by an (empty) element.
1869 static type_path_entry_t *append_to_type_path(type_path_t *path)
1871 size_t len = ARR_LEN(path->path);
1872 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1874 type_path_entry_t *result = & path->path[len];
1875 memset(result, 0, sizeof(result[0]));
1880 * Descending into a sub-type. Enter the scope of the current top_type.
1882 static void descend_into_subtype(type_path_t *path)
1884 type_t *orig_top_type = path->top_type;
1885 type_t *top_type = skip_typeref(orig_top_type);
1887 type_path_entry_t *top = append_to_type_path(path);
1888 top->type = top_type;
1890 if (is_type_compound(top_type)) {
1891 compound_t *compound = top_type->compound.compound;
1892 entity_t *entry = compound->members.entities;
1894 if (entry != NULL) {
1895 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1896 top->v.compound_entry = &entry->declaration;
1897 path->top_type = entry->declaration.type;
1899 path->top_type = NULL;
1901 } else if (is_type_array(top_type)) {
1903 path->top_type = top_type->array.element_type;
1905 assert(!is_type_valid(top_type));
1910 * Pop an entry from the given type path, ie. returning from
1911 * (type).a.b to (type).a
1913 static void ascend_from_subtype(type_path_t *path)
1915 type_path_entry_t *top = get_type_path_top(path);
1917 path->top_type = top->type;
1919 size_t len = ARR_LEN(path->path);
1920 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1924 * Pop entries from the given type path until the given
1925 * path level is reached.
1927 static void ascend_to(type_path_t *path, size_t top_path_level)
1929 size_t len = ARR_LEN(path->path);
1931 while (len > top_path_level) {
1932 ascend_from_subtype(path);
1933 len = ARR_LEN(path->path);
1937 static bool walk_designator(type_path_t *path, const designator_t *designator,
1938 bool used_in_offsetof)
1940 for (; designator != NULL; designator = designator->next) {
1941 type_path_entry_t *top = get_type_path_top(path);
1942 type_t *orig_type = top->type;
1944 type_t *type = skip_typeref(orig_type);
1946 if (designator->symbol != NULL) {
1947 symbol_t *symbol = designator->symbol;
1948 if (!is_type_compound(type)) {
1949 if (is_type_valid(type)) {
1950 errorf(&designator->source_position,
1951 "'.%Y' designator used for non-compound type '%T'",
1955 top->type = type_error_type;
1956 top->v.compound_entry = NULL;
1957 orig_type = type_error_type;
1959 compound_t *compound = type->compound.compound;
1960 entity_t *iter = compound->members.entities;
1961 for (; iter != NULL; iter = iter->base.next) {
1962 if (iter->base.symbol == symbol) {
1967 errorf(&designator->source_position,
1968 "'%T' has no member named '%Y'", orig_type, symbol);
1971 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1972 if (used_in_offsetof) {
1973 type_t *real_type = skip_typeref(iter->declaration.type);
1974 if (real_type->kind == TYPE_BITFIELD) {
1975 errorf(&designator->source_position,
1976 "offsetof designator '%Y' must not specify bitfield",
1982 top->type = orig_type;
1983 top->v.compound_entry = &iter->declaration;
1984 orig_type = iter->declaration.type;
1987 expression_t *array_index = designator->array_index;
1988 assert(designator->array_index != NULL);
1990 if (!is_type_array(type)) {
1991 if (is_type_valid(type)) {
1992 errorf(&designator->source_position,
1993 "[%E] designator used for non-array type '%T'",
1994 array_index, orig_type);
1999 long index = fold_constant_to_int(array_index);
2000 if (!used_in_offsetof) {
2002 errorf(&designator->source_position,
2003 "array index [%E] must be positive", array_index);
2004 } else if (type->array.size_constant) {
2005 long array_size = type->array.size;
2006 if (index >= array_size) {
2007 errorf(&designator->source_position,
2008 "designator [%E] (%d) exceeds array size %d",
2009 array_index, index, array_size);
2014 top->type = orig_type;
2015 top->v.index = (size_t) index;
2016 orig_type = type->array.element_type;
2018 path->top_type = orig_type;
2020 if (designator->next != NULL) {
2021 descend_into_subtype(path);
2027 static void advance_current_object(type_path_t *path, size_t top_path_level)
2029 type_path_entry_t *top = get_type_path_top(path);
2031 type_t *type = skip_typeref(top->type);
2032 if (is_type_union(type)) {
2033 /* in unions only the first element is initialized */
2034 top->v.compound_entry = NULL;
2035 } else if (is_type_struct(type)) {
2036 declaration_t *entry = top->v.compound_entry;
2038 entity_t *next_entity = entry->base.next;
2039 if (next_entity != NULL) {
2040 assert(is_declaration(next_entity));
2041 entry = &next_entity->declaration;
2046 top->v.compound_entry = entry;
2047 if (entry != NULL) {
2048 path->top_type = entry->type;
2051 } else if (is_type_array(type)) {
2052 assert(is_type_array(type));
2056 if (!type->array.size_constant || top->v.index < type->array.size) {
2060 assert(!is_type_valid(type));
2064 /* we're past the last member of the current sub-aggregate, try if we
2065 * can ascend in the type hierarchy and continue with another subobject */
2066 size_t len = ARR_LEN(path->path);
2068 if (len > top_path_level) {
2069 ascend_from_subtype(path);
2070 advance_current_object(path, top_path_level);
2072 path->top_type = NULL;
2077 * skip any {...} blocks until a closing bracket is reached.
2079 static void skip_initializers(void)
2083 while (token.type != '}') {
2084 if (token.type == T_EOF)
2086 if (token.type == '{') {
2094 static initializer_t *create_empty_initializer(void)
2096 static initializer_t empty_initializer
2097 = { .list = { { INITIALIZER_LIST }, 0 } };
2098 return &empty_initializer;
2102 * Parse a part of an initialiser for a struct or union,
2104 static initializer_t *parse_sub_initializer(type_path_t *path,
2105 type_t *outer_type, size_t top_path_level,
2106 parse_initializer_env_t *env)
2108 if (token.type == '}') {
2109 /* empty initializer */
2110 return create_empty_initializer();
2113 type_t *orig_type = path->top_type;
2114 type_t *type = NULL;
2116 if (orig_type == NULL) {
2117 /* We are initializing an empty compound. */
2119 type = skip_typeref(orig_type);
2122 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2125 designator_t *designator = NULL;
2126 if (token.type == '.' || token.type == '[') {
2127 designator = parse_designation();
2128 goto finish_designator;
2129 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2130 /* GNU-style designator ("identifier: value") */
2131 designator = allocate_ast_zero(sizeof(designator[0]));
2132 designator->source_position = token.source_position;
2133 designator->symbol = token.symbol;
2138 /* reset path to toplevel, evaluate designator from there */
2139 ascend_to(path, top_path_level);
2140 if (!walk_designator(path, designator, false)) {
2141 /* can't continue after designation error */
2145 initializer_t *designator_initializer
2146 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2147 designator_initializer->designator.designator = designator;
2148 ARR_APP1(initializer_t*, initializers, designator_initializer);
2150 orig_type = path->top_type;
2151 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2156 if (token.type == '{') {
2157 if (type != NULL && is_type_scalar(type)) {
2158 sub = parse_scalar_initializer(type, env->must_be_constant);
2161 if (env->entity != NULL) {
2163 "extra brace group at end of initializer for '%Y'",
2164 env->entity->base.symbol);
2166 errorf(HERE, "extra brace group at end of initializer");
2171 descend_into_subtype(path);
2174 add_anchor_token('}');
2175 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2177 rem_anchor_token('}');
2180 ascend_from_subtype(path);
2181 expect('}', end_error);
2183 expect('}', end_error);
2184 goto error_parse_next;
2188 /* must be an expression */
2189 expression_t *expression = parse_assignment_expression();
2190 mark_vars_read(expression, NULL);
2192 if (env->must_be_constant && !is_initializer_constant(expression)) {
2193 errorf(&expression->base.source_position,
2194 "Initialisation expression '%E' is not constant",
2199 /* we are already outside, ... */
2200 if (outer_type == NULL)
2201 goto error_parse_next;
2202 type_t *const outer_type_skip = skip_typeref(outer_type);
2203 if (is_type_compound(outer_type_skip) &&
2204 !outer_type_skip->compound.compound->complete) {
2205 goto error_parse_next;
2210 /* handle { "string" } special case */
2211 if ((expression->kind == EXPR_STRING_LITERAL
2212 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2213 && outer_type != NULL) {
2214 sub = initializer_from_expression(outer_type, expression);
2217 if (token.type != '}' && warning.other) {
2218 warningf(HERE, "excessive elements in initializer for type '%T'",
2221 /* TODO: eat , ... */
2226 /* descend into subtypes until expression matches type */
2228 orig_type = path->top_type;
2229 type = skip_typeref(orig_type);
2231 sub = initializer_from_expression(orig_type, expression);
2235 if (!is_type_valid(type)) {
2238 if (is_type_scalar(type)) {
2239 errorf(&expression->base.source_position,
2240 "expression '%E' doesn't match expected type '%T'",
2241 expression, orig_type);
2245 descend_into_subtype(path);
2249 /* update largest index of top array */
2250 const type_path_entry_t *first = &path->path[0];
2251 type_t *first_type = first->type;
2252 first_type = skip_typeref(first_type);
2253 if (is_type_array(first_type)) {
2254 size_t index = first->v.index;
2255 if (index > path->max_index)
2256 path->max_index = index;
2260 /* append to initializers list */
2261 ARR_APP1(initializer_t*, initializers, sub);
2264 if (warning.other) {
2265 if (env->entity != NULL) {
2266 warningf(HERE, "excess elements in initializer for '%Y'",
2267 env->entity->base.symbol);
2269 warningf(HERE, "excess elements in initializer");
2275 if (token.type == '}') {
2278 expect(',', end_error);
2279 if (token.type == '}') {
2284 /* advance to the next declaration if we are not at the end */
2285 advance_current_object(path, top_path_level);
2286 orig_type = path->top_type;
2287 if (orig_type != NULL)
2288 type = skip_typeref(orig_type);
2294 size_t len = ARR_LEN(initializers);
2295 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2296 initializer_t *result = allocate_ast_zero(size);
2297 result->kind = INITIALIZER_LIST;
2298 result->list.len = len;
2299 memcpy(&result->list.initializers, initializers,
2300 len * sizeof(initializers[0]));
2302 DEL_ARR_F(initializers);
2303 ascend_to(path, top_path_level+1);
2308 skip_initializers();
2309 DEL_ARR_F(initializers);
2310 ascend_to(path, top_path_level+1);
2314 static expression_t *make_size_literal(size_t value)
2316 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2317 literal->base.type = type_size_t;
2320 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2321 literal->literal.value = make_string(buf);
2327 * Parses an initializer. Parsers either a compound literal
2328 * (env->declaration == NULL) or an initializer of a declaration.
2330 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2332 type_t *type = skip_typeref(env->type);
2333 size_t max_index = 0;
2334 initializer_t *result;
2336 if (is_type_scalar(type)) {
2337 result = parse_scalar_initializer(type, env->must_be_constant);
2338 } else if (token.type == '{') {
2342 memset(&path, 0, sizeof(path));
2343 path.top_type = env->type;
2344 path.path = NEW_ARR_F(type_path_entry_t, 0);
2346 descend_into_subtype(&path);
2348 add_anchor_token('}');
2349 result = parse_sub_initializer(&path, env->type, 1, env);
2350 rem_anchor_token('}');
2352 max_index = path.max_index;
2353 DEL_ARR_F(path.path);
2355 expect('}', end_error);
2358 /* parse_scalar_initializer() also works in this case: we simply
2359 * have an expression without {} around it */
2360 result = parse_scalar_initializer(type, env->must_be_constant);
2363 /* §6.7.8:22 array initializers for arrays with unknown size determine
2364 * the array type size */
2365 if (is_type_array(type) && type->array.size_expression == NULL
2366 && result != NULL) {
2368 switch (result->kind) {
2369 case INITIALIZER_LIST:
2370 assert(max_index != 0xdeadbeaf);
2371 size = max_index + 1;
2374 case INITIALIZER_STRING:
2375 size = result->string.string.size;
2378 case INITIALIZER_WIDE_STRING:
2379 size = result->wide_string.string.size;
2382 case INITIALIZER_DESIGNATOR:
2383 case INITIALIZER_VALUE:
2384 /* can happen for parse errors */
2389 internal_errorf(HERE, "invalid initializer type");
2392 type_t *new_type = duplicate_type(type);
2394 new_type->array.size_expression = make_size_literal(size);
2395 new_type->array.size_constant = true;
2396 new_type->array.has_implicit_size = true;
2397 new_type->array.size = size;
2398 env->type = new_type;
2404 static void append_entity(scope_t *scope, entity_t *entity)
2406 if (scope->last_entity != NULL) {
2407 scope->last_entity->base.next = entity;
2409 scope->entities = entity;
2411 entity->base.parent_entity = current_entity;
2412 scope->last_entity = entity;
2416 static compound_t *parse_compound_type_specifier(bool is_struct)
2418 source_position_t const pos = *HERE;
2419 eat(is_struct ? T_struct : T_union);
2421 symbol_t *symbol = NULL;
2422 entity_t *entity = NULL;
2423 attribute_t *attributes = NULL;
2425 if (token.type == T___attribute__) {
2426 attributes = parse_attributes(NULL);
2429 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2430 if (token.type == T_IDENTIFIER) {
2431 /* the compound has a name, check if we have seen it already */
2432 symbol = token.symbol;
2433 entity = get_tag(symbol, kind);
2436 if (entity != NULL) {
2437 if (entity->base.parent_scope != current_scope &&
2438 (token.type == '{' || token.type == ';')) {
2439 /* we're in an inner scope and have a definition. Shadow
2440 * existing definition in outer scope */
2442 } else if (entity->compound.complete && token.type == '{') {
2443 errorf(&pos, "multiple definitions of '%s %Y' (previous definition %P)",
2444 is_struct ? "struct" : "union", symbol,
2445 &entity->base.source_position);
2446 /* clear members in the hope to avoid further errors */
2447 entity->compound.members.entities = NULL;
2450 } else if (token.type != '{') {
2451 char const *const msg =
2452 is_struct ? "while parsing struct type specifier" :
2453 "while parsing union type specifier";
2454 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2459 if (entity == NULL) {
2460 entity = allocate_entity_zero(kind);
2462 entity->compound.alignment = 1;
2463 entity->base.namespc = NAMESPACE_TAG;
2464 entity->base.source_position = pos;
2465 entity->base.symbol = symbol;
2466 entity->base.parent_scope = current_scope;
2467 if (symbol != NULL) {
2468 environment_push(entity);
2470 append_entity(current_scope, entity);
2473 if (token.type == '{') {
2474 parse_compound_type_entries(&entity->compound);
2476 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2477 if (symbol == NULL) {
2478 assert(anonymous_entity == NULL);
2479 anonymous_entity = entity;
2483 if (attributes != NULL) {
2484 handle_entity_attributes(attributes, entity);
2487 return &entity->compound;
2490 static void parse_enum_entries(type_t *const enum_type)
2494 if (token.type == '}') {
2495 errorf(HERE, "empty enum not allowed");
2500 add_anchor_token('}');
2502 if (token.type != T_IDENTIFIER) {
2503 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2505 rem_anchor_token('}');
2509 entity_t *entity = allocate_entity_zero(ENTITY_ENUM_VALUE);
2510 entity->enum_value.enum_type = enum_type;
2511 entity->base.namespc = NAMESPACE_NORMAL;
2512 entity->base.symbol = token.symbol;
2513 entity->base.source_position = token.source_position;
2517 expression_t *value = parse_constant_expression();
2519 value = create_implicit_cast(value, enum_type);
2520 entity->enum_value.value = value;
2525 record_entity(entity, false);
2526 } while (next_if(',') && token.type != '}');
2527 rem_anchor_token('}');
2529 expect('}', end_error);
2535 static type_t *parse_enum_specifier(void)
2537 source_position_t const pos = *HERE;
2542 switch (token.type) {
2544 symbol = token.symbol;
2545 entity = get_tag(symbol, ENTITY_ENUM);
2548 if (entity != NULL) {
2549 if (entity->base.parent_scope != current_scope &&
2550 (token.type == '{' || token.type == ';')) {
2551 /* we're in an inner scope and have a definition. Shadow
2552 * existing definition in outer scope */
2554 } else if (entity->enume.complete && token.type == '{') {
2555 errorf(&pos, "multiple definitions of 'enum %Y' (previous definition %P)",
2556 symbol, &entity->base.source_position);
2567 parse_error_expected("while parsing enum type specifier",
2568 T_IDENTIFIER, '{', NULL);
2572 if (entity == NULL) {
2573 entity = allocate_entity_zero(ENTITY_ENUM);
2574 entity->base.namespc = NAMESPACE_TAG;
2575 entity->base.source_position = pos;
2576 entity->base.symbol = symbol;
2577 entity->base.parent_scope = current_scope;
2580 type_t *const type = allocate_type_zero(TYPE_ENUM);
2581 type->enumt.enume = &entity->enume;
2582 type->enumt.akind = ATOMIC_TYPE_INT;
2584 if (token.type == '{') {
2585 if (symbol != NULL) {
2586 environment_push(entity);
2588 append_entity(current_scope, entity);
2589 entity->enume.complete = true;
2591 parse_enum_entries(type);
2592 parse_attributes(NULL);
2594 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2595 if (symbol == NULL) {
2596 assert(anonymous_entity == NULL);
2597 anonymous_entity = entity;
2599 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2600 errorf(HERE, "'enum %Y' used before definition (incomplete enums are a GNU extension)",
2608 * if a symbol is a typedef to another type, return true
2610 static bool is_typedef_symbol(symbol_t *symbol)
2612 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2613 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2616 static type_t *parse_typeof(void)
2622 expect('(', end_error);
2623 add_anchor_token(')');
2625 expression_t *expression = NULL;
2627 bool old_type_prop = in_type_prop;
2628 bool old_gcc_extension = in_gcc_extension;
2629 in_type_prop = true;
2631 while (next_if(T___extension__)) {
2632 /* This can be a prefix to a typename or an expression. */
2633 in_gcc_extension = true;
2635 switch (token.type) {
2637 if (is_typedef_symbol(token.symbol)) {
2639 type = parse_typename();
2642 expression = parse_expression();
2643 type = revert_automatic_type_conversion(expression);
2647 in_type_prop = old_type_prop;
2648 in_gcc_extension = old_gcc_extension;
2650 rem_anchor_token(')');
2651 expect(')', end_error);
2653 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2654 typeof_type->typeoft.expression = expression;
2655 typeof_type->typeoft.typeof_type = type;
2662 typedef enum specifiers_t {
2663 SPECIFIER_SIGNED = 1 << 0,
2664 SPECIFIER_UNSIGNED = 1 << 1,
2665 SPECIFIER_LONG = 1 << 2,
2666 SPECIFIER_INT = 1 << 3,
2667 SPECIFIER_DOUBLE = 1 << 4,
2668 SPECIFIER_CHAR = 1 << 5,
2669 SPECIFIER_WCHAR_T = 1 << 6,
2670 SPECIFIER_SHORT = 1 << 7,
2671 SPECIFIER_LONG_LONG = 1 << 8,
2672 SPECIFIER_FLOAT = 1 << 9,
2673 SPECIFIER_BOOL = 1 << 10,
2674 SPECIFIER_VOID = 1 << 11,
2675 SPECIFIER_INT8 = 1 << 12,
2676 SPECIFIER_INT16 = 1 << 13,
2677 SPECIFIER_INT32 = 1 << 14,
2678 SPECIFIER_INT64 = 1 << 15,
2679 SPECIFIER_INT128 = 1 << 16,
2680 SPECIFIER_COMPLEX = 1 << 17,
2681 SPECIFIER_IMAGINARY = 1 << 18,
2684 static type_t *get_typedef_type(symbol_t *symbol)
2686 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2687 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2690 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2691 type->typedeft.typedefe = &entity->typedefe;
2696 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2698 expect('(', end_error);
2700 attribute_property_argument_t *property
2701 = allocate_ast_zero(sizeof(*property));
2704 if (token.type != T_IDENTIFIER) {
2705 parse_error_expected("while parsing property declspec",
2706 T_IDENTIFIER, NULL);
2711 symbol_t *symbol = token.symbol;
2713 if (strcmp(symbol->string, "put") == 0) {
2715 } else if (strcmp(symbol->string, "get") == 0) {
2718 errorf(HERE, "expected put or get in property declspec");
2721 expect('=', end_error);
2722 if (token.type != T_IDENTIFIER) {
2723 parse_error_expected("while parsing property declspec",
2724 T_IDENTIFIER, NULL);
2728 property->put_symbol = token.symbol;
2730 property->get_symbol = token.symbol;
2733 } while (next_if(','));
2735 attribute->a.property = property;
2737 expect(')', end_error);
2743 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2745 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2746 if (next_if(T_restrict)) {
2747 kind = ATTRIBUTE_MS_RESTRICT;
2748 } else if (token.type == T_IDENTIFIER) {
2749 const char *name = token.symbol->string;
2751 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2753 const char *attribute_name = get_attribute_name(k);
2754 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2760 if (kind == ATTRIBUTE_UNKNOWN && warning.attribute) {
2761 warningf(HERE, "unknown __declspec '%s' ignored", name);
2764 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2768 attribute_t *attribute = allocate_attribute_zero(kind);
2770 if (kind == ATTRIBUTE_MS_PROPERTY) {
2771 return parse_attribute_ms_property(attribute);
2774 /* parse arguments */
2776 attribute->a.arguments = parse_attribute_arguments();
2781 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2785 expect('(', end_error);
2790 add_anchor_token(')');
2792 attribute_t **anchor = &first;
2794 while (*anchor != NULL)
2795 anchor = &(*anchor)->next;
2797 attribute_t *attribute
2798 = parse_microsoft_extended_decl_modifier_single();
2799 if (attribute == NULL)
2802 *anchor = attribute;
2803 anchor = &attribute->next;
2804 } while (next_if(','));
2806 rem_anchor_token(')');
2807 expect(')', end_error);
2811 rem_anchor_token(')');
2815 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2817 entity_t *entity = allocate_entity_zero(kind);
2818 entity->base.namespc = NAMESPACE_NORMAL;
2819 entity->base.source_position = *HERE;
2820 entity->base.symbol = symbol;
2821 if (is_declaration(entity)) {
2822 entity->declaration.type = type_error_type;
2823 entity->declaration.implicit = true;
2824 } else if (kind == ENTITY_TYPEDEF) {
2825 entity->typedefe.type = type_error_type;
2826 entity->typedefe.builtin = true;
2828 if (kind != ENTITY_COMPOUND_MEMBER)
2829 record_entity(entity, false);
2833 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2835 type_t *type = NULL;
2836 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2837 unsigned type_specifiers = 0;
2838 bool newtype = false;
2839 bool saw_error = false;
2840 bool old_gcc_extension = in_gcc_extension;
2842 memset(specifiers, 0, sizeof(*specifiers));
2843 specifiers->source_position = token.source_position;
2846 specifiers->attributes = parse_attributes(specifiers->attributes);
2848 switch (token.type) {
2850 #define MATCH_STORAGE_CLASS(token, class) \
2852 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2853 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2855 specifiers->storage_class = class; \
2856 if (specifiers->thread_local) \
2857 goto check_thread_storage_class; \
2861 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2862 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2863 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2864 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2865 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2868 specifiers->attributes
2869 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2873 if (specifiers->thread_local) {
2874 errorf(HERE, "duplicate '__thread'");
2876 specifiers->thread_local = true;
2877 check_thread_storage_class:
2878 switch (specifiers->storage_class) {
2879 case STORAGE_CLASS_EXTERN:
2880 case STORAGE_CLASS_NONE:
2881 case STORAGE_CLASS_STATIC:
2885 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2886 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2887 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2888 wrong_thread_storage_class:
2889 errorf(HERE, "'__thread' used with '%s'", wrong);
2896 /* type qualifiers */
2897 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2899 qualifiers |= qualifier; \
2903 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2904 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2905 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2906 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2907 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2908 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2909 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2910 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2912 case T___extension__:
2914 in_gcc_extension = true;
2917 /* type specifiers */
2918 #define MATCH_SPECIFIER(token, specifier, name) \
2920 if (type_specifiers & specifier) { \
2921 errorf(HERE, "multiple " name " type specifiers given"); \
2923 type_specifiers |= specifier; \
2928 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2929 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2930 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2931 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2932 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2933 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2934 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2935 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2936 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2937 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2938 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2939 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2940 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2941 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2942 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2943 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2944 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2945 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2949 specifiers->is_inline = true;
2953 case T__forceinline:
2955 specifiers->modifiers |= DM_FORCEINLINE;
2960 if (type_specifiers & SPECIFIER_LONG_LONG) {
2961 errorf(HERE, "too many long type specifiers given");
2962 } else if (type_specifiers & SPECIFIER_LONG) {
2963 type_specifiers |= SPECIFIER_LONG_LONG;
2965 type_specifiers |= SPECIFIER_LONG;
2970 #define CHECK_DOUBLE_TYPE() \
2971 if ( type != NULL) \
2972 errorf(HERE, "multiple data types in declaration specifiers");
2975 CHECK_DOUBLE_TYPE();
2976 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2978 type->compound.compound = parse_compound_type_specifier(true);
2981 CHECK_DOUBLE_TYPE();
2982 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2983 type->compound.compound = parse_compound_type_specifier(false);
2986 CHECK_DOUBLE_TYPE();
2987 type = parse_enum_specifier();
2990 CHECK_DOUBLE_TYPE();
2991 type = parse_typeof();
2993 case T___builtin_va_list:
2994 CHECK_DOUBLE_TYPE();
2995 type = duplicate_type(type_valist);
2999 case T_IDENTIFIER: {
3000 /* only parse identifier if we haven't found a type yet */
3001 if (type != NULL || type_specifiers != 0) {
3002 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
3003 * declaration, so it doesn't generate errors about expecting '(' or
3005 switch (look_ahead(1)->type) {
3012 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
3016 errorf(HERE, "discarding stray %K in declaration specifier", &token);
3021 goto finish_specifiers;
3025 type_t *const typedef_type = get_typedef_type(token.symbol);
3026 if (typedef_type == NULL) {
3027 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
3028 * declaration, so it doesn't generate 'implicit int' followed by more
3029 * errors later on. */
3030 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
3036 errorf(HERE, "%K does not name a type", &token);
3039 create_error_entity(token.symbol, ENTITY_TYPEDEF);
3041 type = allocate_type_zero(TYPE_TYPEDEF);
3042 type->typedeft.typedefe = &entity->typedefe;
3050 goto finish_specifiers;
3055 type = typedef_type;
3059 /* function specifier */
3061 goto finish_specifiers;
3066 specifiers->attributes = parse_attributes(specifiers->attributes);
3068 in_gcc_extension = old_gcc_extension;
3070 if (type == NULL || (saw_error && type_specifiers != 0)) {
3071 atomic_type_kind_t atomic_type;
3073 /* match valid basic types */
3074 switch (type_specifiers) {
3075 case SPECIFIER_VOID:
3076 atomic_type = ATOMIC_TYPE_VOID;
3078 case SPECIFIER_WCHAR_T:
3079 atomic_type = ATOMIC_TYPE_WCHAR_T;
3081 case SPECIFIER_CHAR:
3082 atomic_type = ATOMIC_TYPE_CHAR;
3084 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3085 atomic_type = ATOMIC_TYPE_SCHAR;
3087 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3088 atomic_type = ATOMIC_TYPE_UCHAR;
3090 case SPECIFIER_SHORT:
3091 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3092 case SPECIFIER_SHORT | SPECIFIER_INT:
3093 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3094 atomic_type = ATOMIC_TYPE_SHORT;
3096 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3097 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3098 atomic_type = ATOMIC_TYPE_USHORT;
3101 case SPECIFIER_SIGNED:
3102 case SPECIFIER_SIGNED | SPECIFIER_INT:
3103 atomic_type = ATOMIC_TYPE_INT;
3105 case SPECIFIER_UNSIGNED:
3106 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3107 atomic_type = ATOMIC_TYPE_UINT;
3109 case SPECIFIER_LONG:
3110 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3111 case SPECIFIER_LONG | SPECIFIER_INT:
3112 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3113 atomic_type = ATOMIC_TYPE_LONG;
3115 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3116 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3117 atomic_type = ATOMIC_TYPE_ULONG;
3120 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3121 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3122 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3123 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3125 atomic_type = ATOMIC_TYPE_LONGLONG;
3126 goto warn_about_long_long;
3128 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3129 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3131 atomic_type = ATOMIC_TYPE_ULONGLONG;
3132 warn_about_long_long:
3133 if (warning.long_long) {
3134 warningf(&specifiers->source_position,
3135 "ISO C90 does not support 'long long'");
3139 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3140 atomic_type = unsigned_int8_type_kind;
3143 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3144 atomic_type = unsigned_int16_type_kind;
3147 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3148 atomic_type = unsigned_int32_type_kind;
3151 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3152 atomic_type = unsigned_int64_type_kind;
3155 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3156 atomic_type = unsigned_int128_type_kind;
3159 case SPECIFIER_INT8:
3160 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3161 atomic_type = int8_type_kind;
3164 case SPECIFIER_INT16:
3165 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3166 atomic_type = int16_type_kind;
3169 case SPECIFIER_INT32:
3170 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3171 atomic_type = int32_type_kind;
3174 case SPECIFIER_INT64:
3175 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3176 atomic_type = int64_type_kind;
3179 case SPECIFIER_INT128:
3180 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3181 atomic_type = int128_type_kind;
3184 case SPECIFIER_FLOAT:
3185 atomic_type = ATOMIC_TYPE_FLOAT;
3187 case SPECIFIER_DOUBLE:
3188 atomic_type = ATOMIC_TYPE_DOUBLE;
3190 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3191 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3193 case SPECIFIER_BOOL:
3194 atomic_type = ATOMIC_TYPE_BOOL;
3196 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3197 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3198 atomic_type = ATOMIC_TYPE_FLOAT;
3200 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3201 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3202 atomic_type = ATOMIC_TYPE_DOUBLE;
3204 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3205 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3206 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3209 /* invalid specifier combination, give an error message */
3210 if (type_specifiers == 0) {
3212 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3213 if (!(c_mode & _CXX) && !strict_mode) {
3214 if (warning.implicit_int) {
3215 warningf(HERE, "no type specifiers in declaration, using 'int'");
3217 atomic_type = ATOMIC_TYPE_INT;
3220 errorf(HERE, "no type specifiers given in declaration");
3223 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3224 (type_specifiers & SPECIFIER_UNSIGNED)) {
3225 errorf(HERE, "signed and unsigned specifiers given");
3226 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3227 errorf(HERE, "only integer types can be signed or unsigned");
3229 errorf(HERE, "multiple datatypes in declaration");
3234 if (type_specifiers & SPECIFIER_COMPLEX) {
3235 type = allocate_type_zero(TYPE_COMPLEX);
3236 type->complex.akind = atomic_type;
3237 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3238 type = allocate_type_zero(TYPE_IMAGINARY);
3239 type->imaginary.akind = atomic_type;
3241 type = allocate_type_zero(TYPE_ATOMIC);
3242 type->atomic.akind = atomic_type;
3245 } else if (type_specifiers != 0) {
3246 errorf(HERE, "multiple datatypes in declaration");
3249 /* FIXME: check type qualifiers here */
3250 type->base.qualifiers = qualifiers;
3253 type = identify_new_type(type);
3255 type = typehash_insert(type);
3258 if (specifiers->attributes != NULL)
3259 type = handle_type_attributes(specifiers->attributes, type);
3260 specifiers->type = type;
3264 specifiers->type = type_error_type;
3267 static type_qualifiers_t parse_type_qualifiers(void)
3269 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3272 switch (token.type) {
3273 /* type qualifiers */
3274 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3275 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3276 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3277 /* microsoft extended type modifiers */
3278 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3279 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3280 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3281 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3282 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3291 * Parses an K&R identifier list
3293 static void parse_identifier_list(scope_t *scope)
3296 entity_t *entity = allocate_entity_zero(ENTITY_PARAMETER);
3297 entity->base.source_position = token.source_position;
3298 entity->base.namespc = NAMESPACE_NORMAL;
3299 entity->base.symbol = token.symbol;
3300 /* a K&R parameter has no type, yet */
3304 append_entity(scope, entity);
3305 } while (next_if(',') && token.type == T_IDENTIFIER);
3308 static entity_t *parse_parameter(void)
3310 declaration_specifiers_t specifiers;
3311 parse_declaration_specifiers(&specifiers);
3313 entity_t *entity = parse_declarator(&specifiers,
3314 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3315 anonymous_entity = NULL;
3319 static void semantic_parameter_incomplete(const entity_t *entity)
3321 assert(entity->kind == ENTITY_PARAMETER);
3323 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3324 * list in a function declarator that is part of a
3325 * definition of that function shall not have
3326 * incomplete type. */
3327 type_t *type = skip_typeref(entity->declaration.type);
3328 if (is_type_incomplete(type)) {
3329 errorf(&entity->base.source_position,
3330 "parameter '%#T' has incomplete type",
3331 entity->declaration.type, entity->base.symbol);
3335 static bool has_parameters(void)
3337 /* func(void) is not a parameter */
3338 if (token.type == T_IDENTIFIER) {
3339 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3342 if (entity->kind != ENTITY_TYPEDEF)
3344 if (skip_typeref(entity->typedefe.type) != type_void)
3346 } else if (token.type != T_void) {
3349 if (look_ahead(1)->type != ')')
3356 * Parses function type parameters (and optionally creates variable_t entities
3357 * for them in a scope)
3359 static void parse_parameters(function_type_t *type, scope_t *scope)
3362 add_anchor_token(')');
3363 int saved_comma_state = save_and_reset_anchor_state(',');
3365 if (token.type == T_IDENTIFIER &&
3366 !is_typedef_symbol(token.symbol)) {
3367 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3368 if (la1_type == ',' || la1_type == ')') {
3369 type->kr_style_parameters = true;
3370 parse_identifier_list(scope);
3371 goto parameters_finished;
3375 if (token.type == ')') {
3376 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3377 if (!(c_mode & _CXX))
3378 type->unspecified_parameters = true;
3379 } else if (has_parameters()) {
3380 function_parameter_t **anchor = &type->parameters;
3382 switch (token.type) {
3385 type->variadic = true;
3386 goto parameters_finished;
3389 case T___extension__:
3392 entity_t *entity = parse_parameter();
3393 if (entity->kind == ENTITY_TYPEDEF) {
3394 errorf(&entity->base.source_position,
3395 "typedef not allowed as function parameter");
3398 assert(is_declaration(entity));
3400 semantic_parameter_incomplete(entity);
3402 function_parameter_t *const parameter =
3403 allocate_parameter(entity->declaration.type);
3405 if (scope != NULL) {
3406 append_entity(scope, entity);
3409 *anchor = parameter;
3410 anchor = ¶meter->next;
3415 goto parameters_finished;
3417 } while (next_if(','));
3420 parameters_finished:
3421 rem_anchor_token(')');
3422 expect(')', end_error);
3425 restore_anchor_state(',', saved_comma_state);
3428 typedef enum construct_type_kind_t {
3431 CONSTRUCT_REFERENCE,
3434 } construct_type_kind_t;
3436 typedef union construct_type_t construct_type_t;
3438 typedef struct construct_type_base_t {
3439 construct_type_kind_t kind;
3440 source_position_t pos;
3441 construct_type_t *next;
3442 } construct_type_base_t;
3444 typedef struct parsed_pointer_t {
3445 construct_type_base_t base;
3446 type_qualifiers_t type_qualifiers;
3447 variable_t *base_variable; /**< MS __based extension. */
3450 typedef struct parsed_reference_t {
3451 construct_type_base_t base;
3452 } parsed_reference_t;
3454 typedef struct construct_function_type_t {
3455 construct_type_base_t base;
3456 type_t *function_type;
3457 } construct_function_type_t;
3459 typedef struct parsed_array_t {
3460 construct_type_base_t base;
3461 type_qualifiers_t type_qualifiers;
3467 union construct_type_t {
3468 construct_type_kind_t kind;
3469 construct_type_base_t base;
3470 parsed_pointer_t pointer;
3471 parsed_reference_t reference;
3472 construct_function_type_t function;
3473 parsed_array_t array;
3476 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3478 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3479 memset(cons, 0, size);
3481 cons->base.pos = *HERE;
3486 static construct_type_t *parse_pointer_declarator(void)
3488 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3490 cons->pointer.type_qualifiers = parse_type_qualifiers();
3491 //cons->pointer.base_variable = base_variable;
3496 /* ISO/IEC 14882:1998(E) §8.3.2 */
3497 static construct_type_t *parse_reference_declarator(void)
3499 if (!(c_mode & _CXX))
3500 errorf(HERE, "references are only available for C++");
3502 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3509 static construct_type_t *parse_array_declarator(void)
3511 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3512 parsed_array_t *const array = &cons->array;
3515 add_anchor_token(']');
3517 bool is_static = next_if(T_static);
3519 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3522 is_static = next_if(T_static);
3524 array->type_qualifiers = type_qualifiers;
3525 array->is_static = is_static;
3527 expression_t *size = NULL;
3528 if (token.type == '*' && look_ahead(1)->type == ']') {
3529 array->is_variable = true;
3531 } else if (token.type != ']') {
3532 size = parse_assignment_expression();
3534 /* §6.7.5.2:1 Array size must have integer type */
3535 type_t *const orig_type = size->base.type;
3536 type_t *const type = skip_typeref(orig_type);
3537 if (!is_type_integer(type) && is_type_valid(type)) {
3538 errorf(&size->base.source_position,
3539 "array size '%E' must have integer type but has type '%T'",
3544 mark_vars_read(size, NULL);
3547 if (is_static && size == NULL)
3548 errorf(&array->base.pos, "static array parameters require a size");
3550 rem_anchor_token(']');
3551 expect(']', end_error);
3558 static construct_type_t *parse_function_declarator(scope_t *scope)
3560 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3562 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3563 function_type_t *ftype = &type->function;
3565 ftype->linkage = current_linkage;
3566 ftype->calling_convention = CC_DEFAULT;
3568 parse_parameters(ftype, scope);
3570 cons->function.function_type = type;
3575 typedef struct parse_declarator_env_t {
3576 bool may_be_abstract : 1;
3577 bool must_be_abstract : 1;
3578 decl_modifiers_t modifiers;
3580 source_position_t source_position;
3582 attribute_t *attributes;
3583 } parse_declarator_env_t;
3586 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3588 /* construct a single linked list of construct_type_t's which describe
3589 * how to construct the final declarator type */
3590 construct_type_t *first = NULL;
3591 construct_type_t **anchor = &first;
3593 env->attributes = parse_attributes(env->attributes);
3596 construct_type_t *type;
3597 //variable_t *based = NULL; /* MS __based extension */
3598 switch (token.type) {
3600 type = parse_reference_declarator();
3604 panic("based not supported anymore");
3609 type = parse_pointer_declarator();
3613 goto ptr_operator_end;
3617 anchor = &type->base.next;
3619 /* TODO: find out if this is correct */
3620 env->attributes = parse_attributes(env->attributes);
3624 construct_type_t *inner_types = NULL;
3626 switch (token.type) {
3628 if (env->must_be_abstract) {
3629 errorf(HERE, "no identifier expected in typename");
3631 env->symbol = token.symbol;
3632 env->source_position = token.source_position;
3638 /* Parenthesized declarator or function declarator? */
3639 token_t const *const la1 = look_ahead(1);
3640 switch (la1->type) {
3642 if (is_typedef_symbol(la1->symbol)) {
3644 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3645 * interpreted as ``function with no parameter specification'', rather
3646 * than redundant parentheses around the omitted identifier. */
3648 /* Function declarator. */
3649 if (!env->may_be_abstract) {
3650 errorf(HERE, "function declarator must have a name");
3657 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3658 /* Paranthesized declarator. */
3660 add_anchor_token(')');
3661 inner_types = parse_inner_declarator(env);
3662 if (inner_types != NULL) {
3663 /* All later declarators only modify the return type */
3664 env->must_be_abstract = true;
3666 rem_anchor_token(')');
3667 expect(')', end_error);
3675 if (env->may_be_abstract)
3677 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3682 construct_type_t **const p = anchor;
3685 construct_type_t *type;
3686 switch (token.type) {
3688 scope_t *scope = NULL;
3689 if (!env->must_be_abstract) {
3690 scope = &env->parameters;
3693 type = parse_function_declarator(scope);
3697 type = parse_array_declarator();
3700 goto declarator_finished;
3703 /* insert in the middle of the list (at p) */
3704 type->base.next = *p;
3707 anchor = &type->base.next;
3710 declarator_finished:
3711 /* append inner_types at the end of the list, we don't to set anchor anymore
3712 * as it's not needed anymore */
3713 *anchor = inner_types;
3720 static type_t *construct_declarator_type(construct_type_t *construct_list,
3723 construct_type_t *iter = construct_list;
3724 for (; iter != NULL; iter = iter->base.next) {
3725 source_position_t const* const pos = &iter->base.pos;
3726 switch (iter->kind) {
3727 case CONSTRUCT_INVALID:
3729 case CONSTRUCT_FUNCTION: {
3730 construct_function_type_t *function = &iter->function;
3731 type_t *function_type = function->function_type;
3733 function_type->function.return_type = type;
3735 type_t *skipped_return_type = skip_typeref(type);
3737 if (is_type_function(skipped_return_type)) {
3738 errorf(pos, "function returning function is not allowed");
3739 } else if (is_type_array(skipped_return_type)) {
3740 errorf(pos, "function returning array is not allowed");
3742 if (skipped_return_type->base.qualifiers != 0 && warning.other) {
3743 warningf(pos, "type qualifiers in return type of function type are meaningless");
3747 /* The function type was constructed earlier. Freeing it here will
3748 * destroy other types. */
3749 type = typehash_insert(function_type);
3753 case CONSTRUCT_POINTER: {
3754 if (is_type_reference(skip_typeref(type)))
3755 errorf(pos, "cannot declare a pointer to reference");
3757 parsed_pointer_t *pointer = &iter->pointer;
3758 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3762 case CONSTRUCT_REFERENCE:
3763 if (is_type_reference(skip_typeref(type)))
3764 errorf(pos, "cannot declare a reference to reference");
3766 type = make_reference_type(type);
3769 case CONSTRUCT_ARRAY: {
3770 if (is_type_reference(skip_typeref(type)))
3771 errorf(pos, "cannot declare an array of references");
3773 parsed_array_t *array = &iter->array;
3774 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3776 expression_t *size_expression = array->size;
3777 if (size_expression != NULL) {
3779 = create_implicit_cast(size_expression, type_size_t);
3782 array_type->base.qualifiers = array->type_qualifiers;
3783 array_type->array.element_type = type;
3784 array_type->array.is_static = array->is_static;
3785 array_type->array.is_variable = array->is_variable;
3786 array_type->array.size_expression = size_expression;
3788 if (size_expression != NULL) {
3789 switch (is_constant_expression(size_expression)) {
3790 case EXPR_CLASS_CONSTANT: {
3791 long const size = fold_constant_to_int(size_expression);
3792 array_type->array.size = size;
3793 array_type->array.size_constant = true;
3794 /* §6.7.5.2:1 If the expression is a constant expression, it shall
3795 * have a value greater than zero. */
3797 if (size < 0 || !GNU_MODE) {
3798 errorf(&size_expression->base.source_position,
3799 "size of array must be greater than zero");
3800 } else if (warning.other) {
3801 warningf(&size_expression->base.source_position,
3802 "zero length arrays are a GCC extension");
3808 case EXPR_CLASS_VARIABLE:
3809 array_type->array.is_vla = true;
3812 case EXPR_CLASS_ERROR:
3817 type_t *skipped_type = skip_typeref(type);
3819 if (is_type_incomplete(skipped_type)) {
3820 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3821 } else if (is_type_function(skipped_type)) {
3822 errorf(pos, "array of functions is not allowed");
3824 type = identify_new_type(array_type);
3828 internal_errorf(pos, "invalid type construction found");
3834 static type_t *automatic_type_conversion(type_t *orig_type);
3836 static type_t *semantic_parameter(const source_position_t *pos,
3838 const declaration_specifiers_t *specifiers,
3841 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3842 * shall be adjusted to ``qualified pointer to type'',
3844 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3845 * type'' shall be adjusted to ``pointer to function
3846 * returning type'', as in 6.3.2.1. */
3847 type = automatic_type_conversion(type);
3849 if (specifiers->is_inline && is_type_valid(type)) {
3850 errorf(pos, "parameter '%#T' declared 'inline'", type, symbol);
3853 /* §6.9.1:6 The declarations in the declaration list shall contain
3854 * no storage-class specifier other than register and no
3855 * initializations. */
3856 if (specifiers->thread_local || (
3857 specifiers->storage_class != STORAGE_CLASS_NONE &&
3858 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3860 errorf(pos, "invalid storage class for parameter '%#T'", type, symbol);
3863 /* delay test for incomplete type, because we might have (void)
3864 * which is legal but incomplete... */
3869 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3870 declarator_flags_t flags)
3872 parse_declarator_env_t env;
3873 memset(&env, 0, sizeof(env));
3874 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3876 construct_type_t *construct_type = parse_inner_declarator(&env);
3878 construct_declarator_type(construct_type, specifiers->type);
3879 type_t *type = skip_typeref(orig_type);
3881 if (construct_type != NULL) {
3882 obstack_free(&temp_obst, construct_type);
3885 attribute_t *attributes = parse_attributes(env.attributes);
3886 /* append (shared) specifier attribute behind attributes of this
3888 attribute_t **anchor = &attributes;
3889 while (*anchor != NULL)
3890 anchor = &(*anchor)->next;
3891 *anchor = specifiers->attributes;
3894 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3895 entity = allocate_entity_zero(ENTITY_TYPEDEF);
3896 entity->base.namespc = NAMESPACE_NORMAL;
3897 entity->base.symbol = env.symbol;
3898 entity->base.source_position = env.source_position;
3899 entity->typedefe.type = orig_type;
3901 if (anonymous_entity != NULL) {
3902 if (is_type_compound(type)) {
3903 assert(anonymous_entity->compound.alias == NULL);
3904 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3905 anonymous_entity->kind == ENTITY_UNION);
3906 anonymous_entity->compound.alias = entity;
3907 anonymous_entity = NULL;
3908 } else if (is_type_enum(type)) {
3909 assert(anonymous_entity->enume.alias == NULL);
3910 assert(anonymous_entity->kind == ENTITY_ENUM);
3911 anonymous_entity->enume.alias = entity;
3912 anonymous_entity = NULL;
3916 /* create a declaration type entity */
3917 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3918 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
3920 if (env.symbol != NULL) {
3921 if (specifiers->is_inline && is_type_valid(type)) {
3922 errorf(&env.source_position,
3923 "compound member '%Y' declared 'inline'", env.symbol);
3926 if (specifiers->thread_local ||
3927 specifiers->storage_class != STORAGE_CLASS_NONE) {
3928 errorf(&env.source_position,
3929 "compound member '%Y' must have no storage class",
3933 } else if (flags & DECL_IS_PARAMETER) {
3934 orig_type = semantic_parameter(&env.source_position, orig_type,
3935 specifiers, env.symbol);
3937 entity = allocate_entity_zero(ENTITY_PARAMETER);
3938 } else if (is_type_function(type)) {
3939 entity = allocate_entity_zero(ENTITY_FUNCTION);
3941 entity->function.is_inline = specifiers->is_inline;
3942 entity->function.elf_visibility = default_visibility;
3943 entity->function.parameters = env.parameters;
3945 if (env.symbol != NULL) {
3946 /* this needs fixes for C++ */
3947 bool in_function_scope = current_function != NULL;
3949 if (specifiers->thread_local || (
3950 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3951 specifiers->storage_class != STORAGE_CLASS_NONE &&
3952 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3954 errorf(&env.source_position,
3955 "invalid storage class for function '%Y'", env.symbol);
3959 entity = allocate_entity_zero(ENTITY_VARIABLE);
3961 entity->variable.elf_visibility = default_visibility;
3962 entity->variable.thread_local = specifiers->thread_local;
3964 if (env.symbol != NULL) {
3965 if (specifiers->is_inline && is_type_valid(type)) {
3966 errorf(&env.source_position,
3967 "variable '%Y' declared 'inline'", env.symbol);
3970 bool invalid_storage_class = false;
3971 if (current_scope == file_scope) {
3972 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3973 specifiers->storage_class != STORAGE_CLASS_NONE &&
3974 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3975 invalid_storage_class = true;
3978 if (specifiers->thread_local &&
3979 specifiers->storage_class == STORAGE_CLASS_NONE) {
3980 invalid_storage_class = true;
3983 if (invalid_storage_class) {
3984 errorf(&env.source_position,
3985 "invalid storage class for variable '%Y'", env.symbol);
3990 if (env.symbol != NULL) {
3991 entity->base.symbol = env.symbol;
3992 entity->base.source_position = env.source_position;
3994 entity->base.source_position = specifiers->source_position;
3996 entity->base.namespc = NAMESPACE_NORMAL;
3997 entity->declaration.type = orig_type;
3998 entity->declaration.alignment = get_type_alignment(orig_type);
3999 entity->declaration.modifiers = env.modifiers;
4000 entity->declaration.attributes = attributes;
4002 storage_class_t storage_class = specifiers->storage_class;
4003 entity->declaration.declared_storage_class = storage_class;
4005 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
4006 storage_class = STORAGE_CLASS_AUTO;
4007 entity->declaration.storage_class = storage_class;
4010 if (attributes != NULL) {
4011 handle_entity_attributes(attributes, entity);
4017 static type_t *parse_abstract_declarator(type_t *base_type)
4019 parse_declarator_env_t env;
4020 memset(&env, 0, sizeof(env));
4021 env.may_be_abstract = true;
4022 env.must_be_abstract = true;
4024 construct_type_t *construct_type = parse_inner_declarator(&env);
4026 type_t *result = construct_declarator_type(construct_type, base_type);
4027 if (construct_type != NULL) {
4028 obstack_free(&temp_obst, construct_type);
4030 result = handle_type_attributes(env.attributes, result);
4036 * Check if the declaration of main is suspicious. main should be a
4037 * function with external linkage, returning int, taking either zero
4038 * arguments, two, or three arguments of appropriate types, ie.
4040 * int main([ int argc, char **argv [, char **env ] ]).
4042 * @param decl the declaration to check
4043 * @param type the function type of the declaration
4045 static void check_main(const entity_t *entity)
4047 const source_position_t *pos = &entity->base.source_position;
4048 if (entity->kind != ENTITY_FUNCTION) {
4049 warningf(pos, "'main' is not a function");
4053 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
4054 warningf(pos, "'main' is normally a non-static function");
4057 type_t *type = skip_typeref(entity->declaration.type);
4058 assert(is_type_function(type));
4060 function_type_t *func_type = &type->function;
4061 if (!types_compatible(skip_typeref(func_type->return_type), type_int)) {
4062 warningf(pos, "return type of 'main' should be 'int', but is '%T'",
4063 func_type->return_type);
4065 const function_parameter_t *parm = func_type->parameters;
4067 type_t *const first_type = skip_typeref(parm->type);
4068 type_t *const first_type_unqual = get_unqualified_type(first_type);
4069 if (!types_compatible(first_type_unqual, type_int)) {
4071 "first argument of 'main' should be 'int', but is '%T'",
4076 type_t *const second_type = skip_typeref(parm->type);
4077 type_t *const second_type_unqual
4078 = get_unqualified_type(second_type);
4079 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4080 warningf(pos, "second argument of 'main' should be 'char**', but is '%T'",
4085 type_t *const third_type = skip_typeref(parm->type);
4086 type_t *const third_type_unqual
4087 = get_unqualified_type(third_type);
4088 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4089 warningf(pos, "third argument of 'main' should be 'char**', but is '%T'",
4094 goto warn_arg_count;
4098 warningf(pos, "'main' takes only zero, two or three arguments");
4104 * Check if a symbol is the equal to "main".
4106 static bool is_sym_main(const symbol_t *const sym)
4108 return strcmp(sym->string, "main") == 0;
4111 static void error_redefined_as_different_kind(const source_position_t *pos,
4112 const entity_t *old, entity_kind_t new_kind)
4114 errorf(pos, "redeclaration of %s '%Y' as %s (declared %P)",
4115 get_entity_kind_name(old->kind), old->base.symbol,
4116 get_entity_kind_name(new_kind), &old->base.source_position);
4119 static bool is_entity_valid(entity_t *const ent)
4121 if (is_declaration(ent)) {
4122 return is_type_valid(skip_typeref(ent->declaration.type));
4123 } else if (ent->kind == ENTITY_TYPEDEF) {
4124 return is_type_valid(skip_typeref(ent->typedefe.type));
4129 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4131 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4132 if (attributes_equal(tattr, attr))
4139 * test wether new_list contains any attributes not included in old_list
4141 static bool has_new_attributes(const attribute_t *old_list,
4142 const attribute_t *new_list)
4144 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4145 if (!contains_attribute(old_list, attr))
4152 * Merge in attributes from an attribute list (probably from a previous
4153 * declaration with the same name). Warning: destroys the old structure
4154 * of the attribute list - don't reuse attributes after this call.
4156 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4159 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4161 if (contains_attribute(decl->attributes, attr))
4164 /* move attribute to new declarations attributes list */
4165 attr->next = decl->attributes;
4166 decl->attributes = attr;
4171 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4172 * for various problems that occur for multiple definitions
4174 entity_t *record_entity(entity_t *entity, const bool is_definition)
4176 const symbol_t *const symbol = entity->base.symbol;
4177 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4178 const source_position_t *pos = &entity->base.source_position;
4180 /* can happen in error cases */
4184 entity_t *const previous_entity = get_entity(symbol, namespc);
4185 /* pushing the same entity twice will break the stack structure */
4186 assert(previous_entity != entity);
4188 if (entity->kind == ENTITY_FUNCTION) {
4189 type_t *const orig_type = entity->declaration.type;
4190 type_t *const type = skip_typeref(orig_type);
4192 assert(is_type_function(type));
4193 if (type->function.unspecified_parameters &&
4194 warning.strict_prototypes &&
4195 previous_entity == NULL) {
4196 warningf(pos, "function declaration '%#T' is not a prototype",
4200 if (warning.main && current_scope == file_scope
4201 && is_sym_main(symbol)) {
4206 if (is_declaration(entity) &&
4207 warning.nested_externs &&
4208 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4209 current_scope != file_scope) {
4210 warningf(pos, "nested extern declaration of '%#T'",
4211 entity->declaration.type, symbol);
4214 if (previous_entity != NULL) {
4215 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4216 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4217 assert(previous_entity->kind == ENTITY_PARAMETER);
4219 "declaration '%#T' redeclares the parameter '%#T' (declared %P)",
4220 entity->declaration.type, symbol,
4221 previous_entity->declaration.type, symbol,
4222 &previous_entity->base.source_position);
4226 if (previous_entity->base.parent_scope == current_scope) {
4227 if (previous_entity->kind != entity->kind) {
4228 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4229 error_redefined_as_different_kind(pos, previous_entity,
4234 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4235 errorf(pos, "redeclaration of enum entry '%Y' (declared %P)",
4236 symbol, &previous_entity->base.source_position);
4239 if (previous_entity->kind == ENTITY_TYPEDEF) {
4240 /* TODO: C++ allows this for exactly the same type */
4241 errorf(pos, "redefinition of typedef '%Y' (declared %P)",
4242 symbol, &previous_entity->base.source_position);
4246 /* at this point we should have only VARIABLES or FUNCTIONS */
4247 assert(is_declaration(previous_entity) && is_declaration(entity));
4249 declaration_t *const prev_decl = &previous_entity->declaration;
4250 declaration_t *const decl = &entity->declaration;
4252 /* can happen for K&R style declarations */
4253 if (prev_decl->type == NULL &&
4254 previous_entity->kind == ENTITY_PARAMETER &&
4255 entity->kind == ENTITY_PARAMETER) {
4256 prev_decl->type = decl->type;
4257 prev_decl->storage_class = decl->storage_class;
4258 prev_decl->declared_storage_class = decl->declared_storage_class;
4259 prev_decl->modifiers = decl->modifiers;
4260 return previous_entity;
4263 type_t *const orig_type = decl->type;
4264 assert(orig_type != NULL);
4265 type_t *const type = skip_typeref(orig_type);
4266 type_t *const prev_type = skip_typeref(prev_decl->type);
4268 if (!types_compatible(type, prev_type)) {
4270 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4271 orig_type, symbol, prev_decl->type, symbol,
4272 &previous_entity->base.source_position);
4274 unsigned old_storage_class = prev_decl->storage_class;
4276 if (warning.redundant_decls &&
4279 !(prev_decl->modifiers & DM_USED) &&
4280 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4281 warningf(&previous_entity->base.source_position,
4282 "unnecessary static forward declaration for '%#T'",
4283 prev_decl->type, symbol);
4286 storage_class_t new_storage_class = decl->storage_class;
4288 /* pretend no storage class means extern for function
4289 * declarations (except if the previous declaration is neither
4290 * none nor extern) */
4291 if (entity->kind == ENTITY_FUNCTION) {
4292 /* the previous declaration could have unspecified parameters or
4293 * be a typedef, so use the new type */
4294 if (prev_type->function.unspecified_parameters || is_definition)
4295 prev_decl->type = type;
4297 switch (old_storage_class) {
4298 case STORAGE_CLASS_NONE:
4299 old_storage_class = STORAGE_CLASS_EXTERN;
4302 case STORAGE_CLASS_EXTERN:
4303 if (is_definition) {
4304 if (warning.missing_prototypes &&
4305 prev_type->function.unspecified_parameters &&
4306 !is_sym_main(symbol)) {
4307 warningf(pos, "no previous prototype for '%#T'",
4310 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4311 new_storage_class = STORAGE_CLASS_EXTERN;
4318 } else if (is_type_incomplete(prev_type)) {
4319 prev_decl->type = type;
4322 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4323 new_storage_class == STORAGE_CLASS_EXTERN) {
4325 warn_redundant_declaration: ;
4327 = has_new_attributes(prev_decl->attributes,
4329 if (has_new_attrs) {
4330 merge_in_attributes(decl, prev_decl->attributes);
4331 } else if (!is_definition &&
4332 warning.redundant_decls &&
4333 is_type_valid(prev_type) &&
4334 strcmp(previous_entity->base.source_position.input_name,
4335 "<builtin>") != 0) {
4337 "redundant declaration for '%Y' (declared %P)",
4338 symbol, &previous_entity->base.source_position);
4340 } else if (current_function == NULL) {
4341 if (old_storage_class != STORAGE_CLASS_STATIC &&
4342 new_storage_class == STORAGE_CLASS_STATIC) {
4344 "static declaration of '%Y' follows non-static declaration (declared %P)",
4345 symbol, &previous_entity->base.source_position);
4346 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4347 prev_decl->storage_class = STORAGE_CLASS_NONE;
4348 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4350 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4352 goto error_redeclaration;
4353 goto warn_redundant_declaration;
4355 } else if (is_type_valid(prev_type)) {
4356 if (old_storage_class == new_storage_class) {
4357 error_redeclaration:
4358 errorf(pos, "redeclaration of '%Y' (declared %P)",
4359 symbol, &previous_entity->base.source_position);
4362 "redeclaration of '%Y' with different linkage (declared %P)",
4363 symbol, &previous_entity->base.source_position);
4368 prev_decl->modifiers |= decl->modifiers;
4369 if (entity->kind == ENTITY_FUNCTION) {
4370 previous_entity->function.is_inline |= entity->function.is_inline;
4372 return previous_entity;
4375 if (warning.shadow ||
4376 (warning.shadow_local && previous_entity->base.parent_scope != file_scope)) {
4377 warningf(pos, "%s '%Y' shadows %s (declared %P)",
4378 get_entity_kind_name(entity->kind), symbol,
4379 get_entity_kind_name(previous_entity->kind),
4380 &previous_entity->base.source_position);
4384 if (entity->kind == ENTITY_FUNCTION) {
4385 if (is_definition &&
4386 entity->declaration.storage_class != STORAGE_CLASS_STATIC) {
4387 if (warning.missing_prototypes && !is_sym_main(symbol)) {
4388 warningf(pos, "no previous prototype for '%#T'",
4389 entity->declaration.type, symbol);
4390 } else if (warning.missing_declarations && !is_sym_main(symbol)) {
4391 warningf(pos, "no previous declaration for '%#T'",
4392 entity->declaration.type, symbol);
4395 } else if (warning.missing_declarations &&
4396 entity->kind == ENTITY_VARIABLE &&
4397 current_scope == file_scope) {
4398 declaration_t *declaration = &entity->declaration;
4399 if (declaration->storage_class == STORAGE_CLASS_NONE) {
4400 warningf(pos, "no previous declaration for '%#T'",
4401 declaration->type, symbol);
4406 assert(entity->base.parent_scope == NULL);
4407 assert(current_scope != NULL);
4409 entity->base.parent_scope = current_scope;
4410 entity->base.namespc = NAMESPACE_NORMAL;
4411 environment_push(entity);
4412 append_entity(current_scope, entity);
4417 static void parser_error_multiple_definition(entity_t *entity,
4418 const source_position_t *source_position)
4420 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4421 entity->base.symbol, &entity->base.source_position);
4424 static bool is_declaration_specifier(const token_t *token,
4425 bool only_specifiers_qualifiers)
4427 switch (token->type) {
4432 return is_typedef_symbol(token->symbol);
4434 case T___extension__:
4436 return !only_specifiers_qualifiers;
4443 static void parse_init_declarator_rest(entity_t *entity)
4445 type_t *orig_type = type_error_type;
4447 if (entity->base.kind == ENTITY_TYPEDEF) {
4448 errorf(&entity->base.source_position,
4449 "typedef '%Y' is initialized (use __typeof__ instead)",
4450 entity->base.symbol);
4452 assert(is_declaration(entity));
4453 orig_type = entity->declaration.type;
4457 type_t *type = skip_typeref(orig_type);
4459 if (entity->kind == ENTITY_VARIABLE
4460 && entity->variable.initializer != NULL) {
4461 parser_error_multiple_definition(entity, HERE);
4464 declaration_t *const declaration = &entity->declaration;
4465 bool must_be_constant = false;
4466 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4467 entity->base.parent_scope == file_scope) {
4468 must_be_constant = true;
4471 if (is_type_function(type)) {
4472 errorf(&entity->base.source_position,
4473 "function '%#T' is initialized like a variable",
4474 orig_type, entity->base.symbol);
4475 orig_type = type_error_type;
4478 parse_initializer_env_t env;
4479 env.type = orig_type;
4480 env.must_be_constant = must_be_constant;
4481 env.entity = entity;
4482 current_init_decl = entity;
4484 initializer_t *initializer = parse_initializer(&env);
4485 current_init_decl = NULL;
4487 if (entity->kind == ENTITY_VARIABLE) {
4488 /* §6.7.5:22 array initializers for arrays with unknown size
4489 * determine the array type size */
4490 declaration->type = env.type;
4491 entity->variable.initializer = initializer;
4495 /* parse rest of a declaration without any declarator */
4496 static void parse_anonymous_declaration_rest(
4497 const declaration_specifiers_t *specifiers)
4500 anonymous_entity = NULL;
4502 if (warning.other) {
4503 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4504 specifiers->thread_local) {
4505 warningf(&specifiers->source_position,
4506 "useless storage class in empty declaration");
4509 type_t *type = specifiers->type;
4510 switch (type->kind) {
4511 case TYPE_COMPOUND_STRUCT:
4512 case TYPE_COMPOUND_UNION: {
4513 if (type->compound.compound->base.symbol == NULL) {
4514 warningf(&specifiers->source_position,
4515 "unnamed struct/union that defines no instances");
4524 warningf(&specifiers->source_position, "empty declaration");
4530 static void check_variable_type_complete(entity_t *ent)
4532 if (ent->kind != ENTITY_VARIABLE)
4535 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4536 * type for the object shall be complete [...] */
4537 declaration_t *decl = &ent->declaration;
4538 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4539 decl->storage_class == STORAGE_CLASS_STATIC)
4542 type_t *const orig_type = decl->type;
4543 type_t *const type = skip_typeref(orig_type);
4544 if (!is_type_incomplete(type))
4547 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4548 * are given length one. */
4549 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4550 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4554 errorf(&ent->base.source_position, "variable '%#T' has incomplete type",
4555 orig_type, ent->base.symbol);
4559 static void parse_declaration_rest(entity_t *ndeclaration,
4560 const declaration_specifiers_t *specifiers,
4561 parsed_declaration_func finished_declaration,
4562 declarator_flags_t flags)
4564 add_anchor_token(';');
4565 add_anchor_token(',');
4567 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4569 if (token.type == '=') {
4570 parse_init_declarator_rest(entity);
4571 } else if (entity->kind == ENTITY_VARIABLE) {
4572 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4573 * [...] where the extern specifier is explicitly used. */
4574 declaration_t *decl = &entity->declaration;
4575 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4576 type_t *type = decl->type;
4577 if (is_type_reference(skip_typeref(type))) {
4578 errorf(&entity->base.source_position,
4579 "reference '%#T' must be initialized",
4580 type, entity->base.symbol);
4585 check_variable_type_complete(entity);
4590 add_anchor_token('=');
4591 ndeclaration = parse_declarator(specifiers, flags);
4592 rem_anchor_token('=');
4594 expect(';', end_error);
4597 anonymous_entity = NULL;
4598 rem_anchor_token(';');
4599 rem_anchor_token(',');
4602 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4604 symbol_t *symbol = entity->base.symbol;
4605 if (symbol == NULL) {
4606 errorf(HERE, "anonymous declaration not valid as function parameter");
4610 assert(entity->base.namespc == NAMESPACE_NORMAL);
4611 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4612 if (previous_entity == NULL
4613 || previous_entity->base.parent_scope != current_scope) {
4614 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4619 if (is_definition) {
4620 errorf(HERE, "parameter '%Y' is initialised", entity->base.symbol);
4623 return record_entity(entity, false);
4626 static void parse_declaration(parsed_declaration_func finished_declaration,
4627 declarator_flags_t flags)
4629 add_anchor_token(';');
4630 declaration_specifiers_t specifiers;
4631 parse_declaration_specifiers(&specifiers);
4632 rem_anchor_token(';');
4634 if (token.type == ';') {
4635 parse_anonymous_declaration_rest(&specifiers);
4637 entity_t *entity = parse_declarator(&specifiers, flags);
4638 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4643 static type_t *get_default_promoted_type(type_t *orig_type)
4645 type_t *result = orig_type;
4647 type_t *type = skip_typeref(orig_type);
4648 if (is_type_integer(type)) {
4649 result = promote_integer(type);
4650 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4651 result = type_double;
4657 static void parse_kr_declaration_list(entity_t *entity)
4659 if (entity->kind != ENTITY_FUNCTION)
4662 type_t *type = skip_typeref(entity->declaration.type);
4663 assert(is_type_function(type));
4664 if (!type->function.kr_style_parameters)
4667 add_anchor_token('{');
4669 /* push function parameters */
4670 size_t const top = environment_top();
4671 scope_t *old_scope = scope_push(&entity->function.parameters);
4673 entity_t *parameter = entity->function.parameters.entities;
4674 for ( ; parameter != NULL; parameter = parameter->base.next) {
4675 assert(parameter->base.parent_scope == NULL);
4676 parameter->base.parent_scope = current_scope;
4677 environment_push(parameter);
4680 /* parse declaration list */
4682 switch (token.type) {
4684 case T___extension__:
4685 /* This covers symbols, which are no type, too, and results in
4686 * better error messages. The typical cases are misspelled type
4687 * names and missing includes. */
4689 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4697 /* pop function parameters */
4698 assert(current_scope == &entity->function.parameters);
4699 scope_pop(old_scope);
4700 environment_pop_to(top);
4702 /* update function type */
4703 type_t *new_type = duplicate_type(type);
4705 function_parameter_t *parameters = NULL;
4706 function_parameter_t **anchor = ¶meters;
4708 /* did we have an earlier prototype? */
4709 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4710 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4713 function_parameter_t *proto_parameter = NULL;
4714 if (proto_type != NULL) {
4715 type_t *proto_type_type = proto_type->declaration.type;
4716 proto_parameter = proto_type_type->function.parameters;
4717 /* If a K&R function definition has a variadic prototype earlier, then
4718 * make the function definition variadic, too. This should conform to
4719 * §6.7.5.3:15 and §6.9.1:8. */
4720 new_type->function.variadic = proto_type_type->function.variadic;
4722 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4724 new_type->function.unspecified_parameters = true;
4727 bool need_incompatible_warning = false;
4728 parameter = entity->function.parameters.entities;
4729 for (; parameter != NULL; parameter = parameter->base.next,
4731 proto_parameter == NULL ? NULL : proto_parameter->next) {
4732 if (parameter->kind != ENTITY_PARAMETER)
4735 type_t *parameter_type = parameter->declaration.type;
4736 if (parameter_type == NULL) {
4738 errorf(HERE, "no type specified for function parameter '%Y'",
4739 parameter->base.symbol);
4740 parameter_type = type_error_type;
4742 if (warning.implicit_int) {
4743 warningf(HERE, "no type specified for function parameter '%Y', using 'int'",
4744 parameter->base.symbol);
4746 parameter_type = type_int;
4748 parameter->declaration.type = parameter_type;
4751 semantic_parameter_incomplete(parameter);
4753 /* we need the default promoted types for the function type */
4754 type_t *not_promoted = parameter_type;
4755 parameter_type = get_default_promoted_type(parameter_type);
4757 /* gcc special: if the type of the prototype matches the unpromoted
4758 * type don't promote */
4759 if (!strict_mode && proto_parameter != NULL) {
4760 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4761 type_t *promo_skip = skip_typeref(parameter_type);
4762 type_t *param_skip = skip_typeref(not_promoted);
4763 if (!types_compatible(proto_p_type, promo_skip)
4764 && types_compatible(proto_p_type, param_skip)) {
4766 need_incompatible_warning = true;
4767 parameter_type = not_promoted;
4770 function_parameter_t *const parameter
4771 = allocate_parameter(parameter_type);
4773 *anchor = parameter;
4774 anchor = ¶meter->next;
4777 new_type->function.parameters = parameters;
4778 new_type = identify_new_type(new_type);
4780 if (warning.other && need_incompatible_warning) {
4781 type_t *proto_type_type = proto_type->declaration.type;
4783 "declaration '%#T' is incompatible with '%#T' (declared %P)",
4784 proto_type_type, proto_type->base.symbol,
4785 new_type, entity->base.symbol,
4786 &proto_type->base.source_position);
4789 entity->declaration.type = new_type;
4791 rem_anchor_token('{');
4794 static bool first_err = true;
4797 * When called with first_err set, prints the name of the current function,
4800 static void print_in_function(void)
4804 diagnosticf("%s: In function '%Y':\n",
4805 current_function->base.base.source_position.input_name,
4806 current_function->base.base.symbol);
4811 * Check if all labels are defined in the current function.
4812 * Check if all labels are used in the current function.
4814 static void check_labels(void)
4816 for (const goto_statement_t *goto_statement = goto_first;
4817 goto_statement != NULL;
4818 goto_statement = goto_statement->next) {
4819 /* skip computed gotos */
4820 if (goto_statement->expression != NULL)
4823 label_t *label = goto_statement->label;
4826 if (label->base.source_position.input_name == NULL) {
4827 print_in_function();
4828 errorf(&goto_statement->base.source_position,
4829 "label '%Y' used but not defined", label->base.symbol);
4833 if (warning.unused_label) {
4834 for (const label_statement_t *label_statement = label_first;
4835 label_statement != NULL;
4836 label_statement = label_statement->next) {
4837 label_t *label = label_statement->label;
4839 if (! label->used) {
4840 print_in_function();
4841 warningf(&label_statement->base.source_position,
4842 "label '%Y' defined but not used", label->base.symbol);
4848 static void warn_unused_entity(entity_t *entity, entity_t *last)
4850 entity_t const *const end = last != NULL ? last->base.next : NULL;
4851 for (; entity != end; entity = entity->base.next) {
4852 if (!is_declaration(entity))
4855 declaration_t *declaration = &entity->declaration;
4856 if (declaration->implicit)
4859 if (!declaration->used) {
4860 print_in_function();
4861 const char *what = get_entity_kind_name(entity->kind);
4862 warningf(&entity->base.source_position, "%s '%Y' is unused",
4863 what, entity->base.symbol);
4864 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4865 print_in_function();
4866 const char *what = get_entity_kind_name(entity->kind);
4867 warningf(&entity->base.source_position, "%s '%Y' is never read",
4868 what, entity->base.symbol);
4873 static void check_unused_variables(statement_t *const stmt, void *const env)
4877 switch (stmt->kind) {
4878 case STATEMENT_DECLARATION: {
4879 declaration_statement_t const *const decls = &stmt->declaration;
4880 warn_unused_entity(decls->declarations_begin,
4881 decls->declarations_end);
4886 warn_unused_entity(stmt->fors.scope.entities, NULL);
4895 * Check declarations of current_function for unused entities.
4897 static void check_declarations(void)
4899 if (warning.unused_parameter) {
4900 const scope_t *scope = ¤t_function->parameters;
4902 /* do not issue unused warnings for main */
4903 if (!is_sym_main(current_function->base.base.symbol)) {
4904 warn_unused_entity(scope->entities, NULL);
4907 if (warning.unused_variable) {
4908 walk_statements(current_function->statement, check_unused_variables,
4913 static int determine_truth(expression_t const* const cond)
4916 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4917 fold_constant_to_bool(cond) ? 1 :
4921 static void check_reachable(statement_t *);
4922 static bool reaches_end;
4924 static bool expression_returns(expression_t const *const expr)
4926 switch (expr->kind) {
4928 expression_t const *const func = expr->call.function;
4929 if (func->kind == EXPR_REFERENCE) {
4930 entity_t *entity = func->reference.entity;
4931 if (entity->kind == ENTITY_FUNCTION
4932 && entity->declaration.modifiers & DM_NORETURN)
4936 if (!expression_returns(func))
4939 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4940 if (!expression_returns(arg->expression))
4947 case EXPR_REFERENCE:
4948 case EXPR_REFERENCE_ENUM_VALUE:
4950 case EXPR_STRING_LITERAL:
4951 case EXPR_WIDE_STRING_LITERAL:
4952 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4953 case EXPR_LABEL_ADDRESS:
4954 case EXPR_CLASSIFY_TYPE:
4955 case EXPR_SIZEOF: // TODO handle obscure VLA case
4958 case EXPR_BUILTIN_CONSTANT_P:
4959 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4964 case EXPR_STATEMENT: {
4965 bool old_reaches_end = reaches_end;
4966 reaches_end = false;
4967 check_reachable(expr->statement.statement);
4968 bool returns = reaches_end;
4969 reaches_end = old_reaches_end;
4973 case EXPR_CONDITIONAL:
4974 // TODO handle constant expression
4976 if (!expression_returns(expr->conditional.condition))
4979 if (expr->conditional.true_expression != NULL
4980 && expression_returns(expr->conditional.true_expression))
4983 return expression_returns(expr->conditional.false_expression);
4986 return expression_returns(expr->select.compound);
4988 case EXPR_ARRAY_ACCESS:
4990 expression_returns(expr->array_access.array_ref) &&
4991 expression_returns(expr->array_access.index);
4994 return expression_returns(expr->va_starte.ap);
4997 return expression_returns(expr->va_arge.ap);
5000 return expression_returns(expr->va_copye.src);
5002 EXPR_UNARY_CASES_MANDATORY
5003 return expression_returns(expr->unary.value);
5005 case EXPR_UNARY_THROW:
5009 // TODO handle constant lhs of && and ||
5011 expression_returns(expr->binary.left) &&
5012 expression_returns(expr->binary.right);
5018 panic("unhandled expression");
5021 static bool initializer_returns(initializer_t const *const init)
5023 switch (init->kind) {
5024 case INITIALIZER_VALUE:
5025 return expression_returns(init->value.value);
5027 case INITIALIZER_LIST: {
5028 initializer_t * const* i = init->list.initializers;
5029 initializer_t * const* const end = i + init->list.len;
5030 bool returns = true;
5031 for (; i != end; ++i) {
5032 if (!initializer_returns(*i))
5038 case INITIALIZER_STRING:
5039 case INITIALIZER_WIDE_STRING:
5040 case INITIALIZER_DESIGNATOR: // designators have no payload
5043 panic("unhandled initializer");
5046 static bool noreturn_candidate;
5048 static void check_reachable(statement_t *const stmt)
5050 if (stmt->base.reachable)
5052 if (stmt->kind != STATEMENT_DO_WHILE)
5053 stmt->base.reachable = true;
5055 statement_t *last = stmt;
5057 switch (stmt->kind) {
5058 case STATEMENT_INVALID:
5059 case STATEMENT_EMPTY:
5061 next = stmt->base.next;
5064 case STATEMENT_DECLARATION: {
5065 declaration_statement_t const *const decl = &stmt->declaration;
5066 entity_t const * ent = decl->declarations_begin;
5067 entity_t const *const last = decl->declarations_end;
5069 for (;; ent = ent->base.next) {
5070 if (ent->kind == ENTITY_VARIABLE &&
5071 ent->variable.initializer != NULL &&
5072 !initializer_returns(ent->variable.initializer)) {
5079 next = stmt->base.next;
5083 case STATEMENT_COMPOUND:
5084 next = stmt->compound.statements;
5086 next = stmt->base.next;
5089 case STATEMENT_RETURN: {
5090 expression_t const *const val = stmt->returns.value;
5091 if (val == NULL || expression_returns(val))
5092 noreturn_candidate = false;
5096 case STATEMENT_IF: {
5097 if_statement_t const *const ifs = &stmt->ifs;
5098 expression_t const *const cond = ifs->condition;
5100 if (!expression_returns(cond))
5103 int const val = determine_truth(cond);
5106 check_reachable(ifs->true_statement);
5111 if (ifs->false_statement != NULL) {
5112 check_reachable(ifs->false_statement);
5116 next = stmt->base.next;
5120 case STATEMENT_SWITCH: {
5121 switch_statement_t const *const switchs = &stmt->switchs;
5122 expression_t const *const expr = switchs->expression;
5124 if (!expression_returns(expr))
5127 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
5128 long const val = fold_constant_to_int(expr);
5129 case_label_statement_t * defaults = NULL;
5130 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5131 if (i->expression == NULL) {
5136 if (i->first_case <= val && val <= i->last_case) {
5137 check_reachable((statement_t*)i);
5142 if (defaults != NULL) {
5143 check_reachable((statement_t*)defaults);
5147 bool has_default = false;
5148 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5149 if (i->expression == NULL)
5152 check_reachable((statement_t*)i);
5159 next = stmt->base.next;
5163 case STATEMENT_EXPRESSION: {
5164 /* Check for noreturn function call */
5165 expression_t const *const expr = stmt->expression.expression;
5166 if (!expression_returns(expr))
5169 next = stmt->base.next;
5173 case STATEMENT_CONTINUE:
5174 for (statement_t *parent = stmt;;) {
5175 parent = parent->base.parent;
5176 if (parent == NULL) /* continue not within loop */
5180 switch (parent->kind) {
5181 case STATEMENT_WHILE: goto continue_while;
5182 case STATEMENT_DO_WHILE: goto continue_do_while;
5183 case STATEMENT_FOR: goto continue_for;
5189 case STATEMENT_BREAK:
5190 for (statement_t *parent = stmt;;) {
5191 parent = parent->base.parent;
5192 if (parent == NULL) /* break not within loop/switch */
5195 switch (parent->kind) {
5196 case STATEMENT_SWITCH:
5197 case STATEMENT_WHILE:
5198 case STATEMENT_DO_WHILE:
5201 next = parent->base.next;
5202 goto found_break_parent;
5210 case STATEMENT_GOTO:
5211 if (stmt->gotos.expression) {
5212 if (!expression_returns(stmt->gotos.expression))
5215 statement_t *parent = stmt->base.parent;
5216 if (parent == NULL) /* top level goto */
5220 next = stmt->gotos.label->statement;
5221 if (next == NULL) /* missing label */
5226 case STATEMENT_LABEL:
5227 next = stmt->label.statement;
5230 case STATEMENT_CASE_LABEL:
5231 next = stmt->case_label.statement;
5234 case STATEMENT_WHILE: {
5235 while_statement_t const *const whiles = &stmt->whiles;
5236 expression_t const *const cond = whiles->condition;
5238 if (!expression_returns(cond))
5241 int const val = determine_truth(cond);
5244 check_reachable(whiles->body);
5249 next = stmt->base.next;
5253 case STATEMENT_DO_WHILE:
5254 next = stmt->do_while.body;
5257 case STATEMENT_FOR: {
5258 for_statement_t *const fors = &stmt->fors;
5260 if (fors->condition_reachable)
5262 fors->condition_reachable = true;
5264 expression_t const *const cond = fors->condition;
5269 } else if (expression_returns(cond)) {
5270 val = determine_truth(cond);
5276 check_reachable(fors->body);
5281 next = stmt->base.next;
5285 case STATEMENT_MS_TRY: {
5286 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5287 check_reachable(ms_try->try_statement);
5288 next = ms_try->final_statement;
5292 case STATEMENT_LEAVE: {
5293 statement_t *parent = stmt;
5295 parent = parent->base.parent;
5296 if (parent == NULL) /* __leave not within __try */
5299 if (parent->kind == STATEMENT_MS_TRY) {
5301 next = parent->ms_try.final_statement;
5309 panic("invalid statement kind");
5312 while (next == NULL) {
5313 next = last->base.parent;
5315 noreturn_candidate = false;
5317 type_t *const type = skip_typeref(current_function->base.type);
5318 assert(is_type_function(type));
5319 type_t *const ret = skip_typeref(type->function.return_type);
5320 if (warning.return_type &&
5321 !is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5322 is_type_valid(ret) &&
5323 !is_sym_main(current_function->base.base.symbol)) {
5324 warningf(&stmt->base.source_position,
5325 "control reaches end of non-void function");
5330 switch (next->kind) {
5331 case STATEMENT_INVALID:
5332 case STATEMENT_EMPTY:
5333 case STATEMENT_DECLARATION:
5334 case STATEMENT_EXPRESSION:
5336 case STATEMENT_RETURN:
5337 case STATEMENT_CONTINUE:
5338 case STATEMENT_BREAK:
5339 case STATEMENT_GOTO:
5340 case STATEMENT_LEAVE:
5341 panic("invalid control flow in function");
5343 case STATEMENT_COMPOUND:
5344 if (next->compound.stmt_expr) {
5350 case STATEMENT_SWITCH:
5351 case STATEMENT_LABEL:
5352 case STATEMENT_CASE_LABEL:
5354 next = next->base.next;
5357 case STATEMENT_WHILE: {
5359 if (next->base.reachable)
5361 next->base.reachable = true;
5363 while_statement_t const *const whiles = &next->whiles;
5364 expression_t const *const cond = whiles->condition;
5366 if (!expression_returns(cond))
5369 int const val = determine_truth(cond);
5372 check_reachable(whiles->body);
5378 next = next->base.next;
5382 case STATEMENT_DO_WHILE: {
5384 if (next->base.reachable)
5386 next->base.reachable = true;
5388 do_while_statement_t const *const dw = &next->do_while;
5389 expression_t const *const cond = dw->condition;
5391 if (!expression_returns(cond))
5394 int const val = determine_truth(cond);
5397 check_reachable(dw->body);
5403 next = next->base.next;
5407 case STATEMENT_FOR: {
5409 for_statement_t *const fors = &next->fors;
5411 fors->step_reachable = true;
5413 if (fors->condition_reachable)
5415 fors->condition_reachable = true;
5417 expression_t const *const cond = fors->condition;
5422 } else if (expression_returns(cond)) {
5423 val = determine_truth(cond);
5429 check_reachable(fors->body);
5435 next = next->base.next;
5439 case STATEMENT_MS_TRY:
5441 next = next->ms_try.final_statement;
5446 check_reachable(next);
5449 static void check_unreachable(statement_t* const stmt, void *const env)
5453 switch (stmt->kind) {
5454 case STATEMENT_DO_WHILE:
5455 if (!stmt->base.reachable) {
5456 expression_t const *const cond = stmt->do_while.condition;
5457 if (determine_truth(cond) >= 0) {
5458 warningf(&cond->base.source_position,
5459 "condition of do-while-loop is unreachable");
5464 case STATEMENT_FOR: {
5465 for_statement_t const* const fors = &stmt->fors;
5467 // if init and step are unreachable, cond is unreachable, too
5468 if (!stmt->base.reachable && !fors->step_reachable) {
5469 warningf(&stmt->base.source_position, "statement is unreachable");
5471 if (!stmt->base.reachable && fors->initialisation != NULL) {
5472 warningf(&fors->initialisation->base.source_position,
5473 "initialisation of for-statement is unreachable");
5476 if (!fors->condition_reachable && fors->condition != NULL) {
5477 warningf(&fors->condition->base.source_position,
5478 "condition of for-statement is unreachable");
5481 if (!fors->step_reachable && fors->step != NULL) {
5482 warningf(&fors->step->base.source_position,
5483 "step of for-statement is unreachable");
5489 case STATEMENT_COMPOUND:
5490 if (stmt->compound.statements != NULL)
5492 goto warn_unreachable;
5494 case STATEMENT_DECLARATION: {
5495 /* Only warn if there is at least one declarator with an initializer.
5496 * This typically occurs in switch statements. */
5497 declaration_statement_t const *const decl = &stmt->declaration;
5498 entity_t const * ent = decl->declarations_begin;
5499 entity_t const *const last = decl->declarations_end;
5501 for (;; ent = ent->base.next) {
5502 if (ent->kind == ENTITY_VARIABLE &&
5503 ent->variable.initializer != NULL) {
5504 goto warn_unreachable;
5514 if (!stmt->base.reachable)
5515 warningf(&stmt->base.source_position, "statement is unreachable");
5520 static void parse_external_declaration(void)
5522 /* function-definitions and declarations both start with declaration
5524 add_anchor_token(';');
5525 declaration_specifiers_t specifiers;
5526 parse_declaration_specifiers(&specifiers);
5527 rem_anchor_token(';');
5529 /* must be a declaration */
5530 if (token.type == ';') {
5531 parse_anonymous_declaration_rest(&specifiers);
5535 add_anchor_token(',');
5536 add_anchor_token('=');
5537 add_anchor_token(';');
5538 add_anchor_token('{');
5540 /* declarator is common to both function-definitions and declarations */
5541 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5543 rem_anchor_token('{');
5544 rem_anchor_token(';');
5545 rem_anchor_token('=');
5546 rem_anchor_token(',');
5548 /* must be a declaration */
5549 switch (token.type) {
5553 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5558 /* must be a function definition */
5559 parse_kr_declaration_list(ndeclaration);
5561 if (token.type != '{') {
5562 parse_error_expected("while parsing function definition", '{', NULL);
5563 eat_until_matching_token(';');
5567 assert(is_declaration(ndeclaration));
5568 type_t *const orig_type = ndeclaration->declaration.type;
5569 type_t * type = skip_typeref(orig_type);
5571 if (!is_type_function(type)) {
5572 if (is_type_valid(type)) {
5573 errorf(HERE, "declarator '%#T' has a body but is not a function type",
5574 type, ndeclaration->base.symbol);
5578 } else if (is_typeref(orig_type)) {
5580 errorf(&ndeclaration->base.source_position,
5581 "type of function definition '%#T' is a typedef",
5582 orig_type, ndeclaration->base.symbol);
5585 if (warning.aggregate_return &&
5586 is_type_compound(skip_typeref(type->function.return_type))) {
5587 warningf(&ndeclaration->base.source_position, "function '%Y' returns an aggregate",
5588 ndeclaration->base.symbol);
5590 if (warning.traditional && !type->function.unspecified_parameters) {
5591 warningf(&ndeclaration->base.source_position, "traditional C rejects ISO C style function definition of function '%Y'",
5592 ndeclaration->base.symbol);
5594 if (warning.old_style_definition && type->function.unspecified_parameters) {
5595 warningf(&ndeclaration->base.source_position, "old-style function definition '%Y'",
5596 ndeclaration->base.symbol);
5599 /* §6.7.5.3:14 a function definition with () means no
5600 * parameters (and not unspecified parameters) */
5601 if (type->function.unspecified_parameters &&
5602 type->function.parameters == NULL) {
5603 type_t *copy = duplicate_type(type);
5604 copy->function.unspecified_parameters = false;
5605 type = identify_new_type(copy);
5607 ndeclaration->declaration.type = type;
5610 entity_t *const entity = record_entity(ndeclaration, true);
5611 assert(entity->kind == ENTITY_FUNCTION);
5612 assert(ndeclaration->kind == ENTITY_FUNCTION);
5614 function_t *const function = &entity->function;
5615 if (ndeclaration != entity) {
5616 function->parameters = ndeclaration->function.parameters;
5618 assert(is_declaration(entity));
5619 type = skip_typeref(entity->declaration.type);
5621 /* push function parameters and switch scope */
5622 size_t const top = environment_top();
5623 scope_t *old_scope = scope_push(&function->parameters);
5625 entity_t *parameter = function->parameters.entities;
5626 for (; parameter != NULL; parameter = parameter->base.next) {
5627 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5628 parameter->base.parent_scope = current_scope;
5630 assert(parameter->base.parent_scope == NULL
5631 || parameter->base.parent_scope == current_scope);
5632 parameter->base.parent_scope = current_scope;
5633 if (parameter->base.symbol == NULL) {
5634 errorf(¶meter->base.source_position, "parameter name omitted");
5637 environment_push(parameter);
5640 if (function->statement != NULL) {
5641 parser_error_multiple_definition(entity, HERE);
5644 /* parse function body */
5645 int label_stack_top = label_top();
5646 function_t *old_current_function = current_function;
5647 entity_t *old_current_entity = current_entity;
5648 current_function = function;
5649 current_entity = entity;
5650 current_parent = NULL;
5653 goto_anchor = &goto_first;
5655 label_anchor = &label_first;
5657 statement_t *const body = parse_compound_statement(false);
5658 function->statement = body;
5661 check_declarations();
5662 if (warning.return_type ||
5663 warning.unreachable_code ||
5664 (warning.missing_noreturn
5665 && !(function->base.modifiers & DM_NORETURN))) {
5666 noreturn_candidate = true;
5667 check_reachable(body);
5668 if (warning.unreachable_code)
5669 walk_statements(body, check_unreachable, NULL);
5670 if (warning.missing_noreturn &&
5671 noreturn_candidate &&
5672 !(function->base.modifiers & DM_NORETURN)) {
5673 warningf(&body->base.source_position,
5674 "function '%#T' is candidate for attribute 'noreturn'",
5675 type, entity->base.symbol);
5679 assert(current_parent == NULL);
5680 assert(current_function == function);
5681 assert(current_entity == entity);
5682 current_entity = old_current_entity;
5683 current_function = old_current_function;
5684 label_pop_to(label_stack_top);
5687 assert(current_scope == &function->parameters);
5688 scope_pop(old_scope);
5689 environment_pop_to(top);
5692 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5693 source_position_t *source_position,
5694 const symbol_t *symbol)
5696 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5698 type->bitfield.base_type = base_type;
5699 type->bitfield.size_expression = size;
5702 type_t *skipped_type = skip_typeref(base_type);
5703 if (!is_type_integer(skipped_type)) {
5704 errorf(HERE, "bitfield base type '%T' is not an integer type",
5708 bit_size = get_type_size(base_type) * 8;
5711 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5712 long v = fold_constant_to_int(size);
5713 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5716 errorf(source_position, "negative width in bit-field '%Y'",
5718 } else if (v == 0 && symbol != NULL) {
5719 errorf(source_position, "zero width for bit-field '%Y'",
5721 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5722 errorf(source_position, "width of '%Y' exceeds its type",
5725 type->bitfield.bit_size = v;
5732 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5734 entity_t *iter = compound->members.entities;
5735 for (; iter != NULL; iter = iter->base.next) {
5736 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5739 if (iter->base.symbol == symbol) {
5741 } else if (iter->base.symbol == NULL) {
5742 /* search in anonymous structs and unions */
5743 type_t *type = skip_typeref(iter->declaration.type);
5744 if (is_type_compound(type)) {
5745 if (find_compound_entry(type->compound.compound, symbol)
5756 static void check_deprecated(const source_position_t *source_position,
5757 const entity_t *entity)
5759 if (!warning.deprecated_declarations)
5761 if (!is_declaration(entity))
5763 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5766 char const *const prefix = get_entity_kind_name(entity->kind);
5767 const char *deprecated_string
5768 = get_deprecated_string(entity->declaration.attributes);
5769 if (deprecated_string != NULL) {
5770 warningf(source_position, "%s '%Y' is deprecated (declared %P): \"%s\"",
5771 prefix, entity->base.symbol, &entity->base.source_position,
5774 warningf(source_position, "%s '%Y' is deprecated (declared %P)", prefix,
5775 entity->base.symbol, &entity->base.source_position);
5780 static expression_t *create_select(const source_position_t *pos,
5782 type_qualifiers_t qualifiers,
5785 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5787 check_deprecated(pos, entry);
5789 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5790 select->select.compound = addr;
5791 select->select.compound_entry = entry;
5793 type_t *entry_type = entry->declaration.type;
5794 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5796 /* we always do the auto-type conversions; the & and sizeof parser contains
5797 * code to revert this! */
5798 select->base.type = automatic_type_conversion(res_type);
5799 if (res_type->kind == TYPE_BITFIELD) {
5800 select->base.type = res_type->bitfield.base_type;
5807 * Find entry with symbol in compound. Search anonymous structs and unions and
5808 * creates implicit select expressions for them.
5809 * Returns the adress for the innermost compound.
5811 static expression_t *find_create_select(const source_position_t *pos,
5813 type_qualifiers_t qualifiers,
5814 compound_t *compound, symbol_t *symbol)
5816 entity_t *iter = compound->members.entities;
5817 for (; iter != NULL; iter = iter->base.next) {
5818 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5821 symbol_t *iter_symbol = iter->base.symbol;
5822 if (iter_symbol == NULL) {
5823 type_t *type = iter->declaration.type;
5824 if (type->kind != TYPE_COMPOUND_STRUCT
5825 && type->kind != TYPE_COMPOUND_UNION)
5828 compound_t *sub_compound = type->compound.compound;
5830 if (find_compound_entry(sub_compound, symbol) == NULL)
5833 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5834 sub_addr->base.source_position = *pos;
5835 sub_addr->select.implicit = true;
5836 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5840 if (iter_symbol == symbol) {
5841 return create_select(pos, addr, qualifiers, iter);
5848 static void parse_compound_declarators(compound_t *compound,
5849 const declaration_specifiers_t *specifiers)
5854 if (token.type == ':') {
5855 source_position_t source_position = *HERE;
5858 type_t *base_type = specifiers->type;
5859 expression_t *size = parse_constant_expression();
5861 type_t *type = make_bitfield_type(base_type, size,
5862 &source_position, NULL);
5864 attribute_t *attributes = parse_attributes(NULL);
5865 attribute_t **anchor = &attributes;
5866 while (*anchor != NULL)
5867 anchor = &(*anchor)->next;
5868 *anchor = specifiers->attributes;
5870 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER);
5871 entity->base.namespc = NAMESPACE_NORMAL;
5872 entity->base.source_position = source_position;
5873 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5874 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5875 entity->declaration.type = type;
5876 entity->declaration.attributes = attributes;
5878 if (attributes != NULL) {
5879 handle_entity_attributes(attributes, entity);
5881 append_entity(&compound->members, entity);
5883 entity = parse_declarator(specifiers,
5884 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5885 if (entity->kind == ENTITY_TYPEDEF) {
5886 errorf(&entity->base.source_position,
5887 "typedef not allowed as compound member");
5889 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5891 /* make sure we don't define a symbol multiple times */
5892 symbol_t *symbol = entity->base.symbol;
5893 if (symbol != NULL) {
5894 entity_t *prev = find_compound_entry(compound, symbol);
5896 errorf(&entity->base.source_position,
5897 "multiple declarations of symbol '%Y' (declared %P)",
5898 symbol, &prev->base.source_position);
5902 if (token.type == ':') {
5903 source_position_t source_position = *HERE;
5905 expression_t *size = parse_constant_expression();
5907 type_t *type = entity->declaration.type;
5908 type_t *bitfield_type = make_bitfield_type(type, size,
5909 &source_position, entity->base.symbol);
5911 attribute_t *attributes = parse_attributes(NULL);
5912 entity->declaration.type = bitfield_type;
5913 handle_entity_attributes(attributes, entity);
5915 type_t *orig_type = entity->declaration.type;
5916 type_t *type = skip_typeref(orig_type);
5917 if (is_type_function(type)) {
5918 errorf(&entity->base.source_position,
5919 "compound member '%Y' must not have function type '%T'",
5920 entity->base.symbol, orig_type);
5921 } else if (is_type_incomplete(type)) {
5922 /* §6.7.2.1:16 flexible array member */
5923 if (!is_type_array(type) ||
5924 token.type != ';' ||
5925 look_ahead(1)->type != '}') {
5926 errorf(&entity->base.source_position,
5927 "compound member '%Y' has incomplete type '%T'",
5928 entity->base.symbol, orig_type);
5933 append_entity(&compound->members, entity);
5936 } while (next_if(','));
5937 expect(';', end_error);
5940 anonymous_entity = NULL;
5943 static void parse_compound_type_entries(compound_t *compound)
5946 add_anchor_token('}');
5948 while (token.type != '}') {
5949 if (token.type == T_EOF) {
5950 errorf(HERE, "EOF while parsing struct");
5953 declaration_specifiers_t specifiers;
5954 parse_declaration_specifiers(&specifiers);
5955 parse_compound_declarators(compound, &specifiers);
5957 rem_anchor_token('}');
5961 compound->complete = true;
5964 static type_t *parse_typename(void)
5966 declaration_specifiers_t specifiers;
5967 parse_declaration_specifiers(&specifiers);
5968 if (specifiers.storage_class != STORAGE_CLASS_NONE
5969 || specifiers.thread_local) {
5970 /* TODO: improve error message, user does probably not know what a
5971 * storage class is...
5973 errorf(HERE, "typename must not have a storage class");
5976 type_t *result = parse_abstract_declarator(specifiers.type);
5984 typedef expression_t* (*parse_expression_function)(void);
5985 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5987 typedef struct expression_parser_function_t expression_parser_function_t;
5988 struct expression_parser_function_t {
5989 parse_expression_function parser;
5990 precedence_t infix_precedence;
5991 parse_expression_infix_function infix_parser;
5994 expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5997 * Prints an error message if an expression was expected but not read
5999 static expression_t *expected_expression_error(void)
6001 /* skip the error message if the error token was read */
6002 if (token.type != T_ERROR) {
6003 errorf(HERE, "expected expression, got token %K", &token);
6007 return create_invalid_expression();
6010 static type_t *get_string_type(void)
6012 return warning.write_strings ? type_const_char_ptr : type_char_ptr;
6015 static type_t *get_wide_string_type(void)
6017 return warning.write_strings ? type_const_wchar_t_ptr : type_wchar_t_ptr;
6021 * Parse a string constant.
6023 static expression_t *parse_string_literal(void)
6025 source_position_t begin = token.source_position;
6026 string_t res = token.literal;
6027 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
6030 while (token.type == T_STRING_LITERAL
6031 || token.type == T_WIDE_STRING_LITERAL) {
6032 warn_string_concat(&token.source_position);
6033 res = concat_strings(&res, &token.literal);
6035 is_wide |= token.type == T_WIDE_STRING_LITERAL;
6038 expression_t *literal;
6040 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
6041 literal->base.type = get_wide_string_type();
6043 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
6044 literal->base.type = get_string_type();
6046 literal->base.source_position = begin;
6047 literal->literal.value = res;
6053 * Parse a boolean constant.
6055 static expression_t *parse_boolean_literal(bool value)
6057 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
6058 literal->base.source_position = token.source_position;
6059 literal->base.type = type_bool;
6060 literal->literal.value.begin = value ? "true" : "false";
6061 literal->literal.value.size = value ? 4 : 5;
6067 static void warn_traditional_suffix(void)
6069 if (!warning.traditional)
6071 warningf(&token.source_position, "traditional C rejects the '%Y' suffix",
6075 static void check_integer_suffix(void)
6077 symbol_t *suffix = token.symbol;
6081 bool not_traditional = false;
6082 const char *c = suffix->string;
6083 if (*c == 'l' || *c == 'L') {
6086 not_traditional = true;
6088 if (*c == 'u' || *c == 'U') {
6091 } else if (*c == 'u' || *c == 'U') {
6092 not_traditional = true;
6095 } else if (*c == 'u' || *c == 'U') {
6096 not_traditional = true;
6098 if (*c == 'l' || *c == 'L') {
6106 errorf(&token.source_position,
6107 "invalid suffix '%s' on integer constant", suffix->string);
6108 } else if (not_traditional) {
6109 warn_traditional_suffix();
6113 static type_t *check_floatingpoint_suffix(void)
6115 symbol_t *suffix = token.symbol;
6116 type_t *type = type_double;
6120 bool not_traditional = false;
6121 const char *c = suffix->string;
6122 if (*c == 'f' || *c == 'F') {
6125 } else if (*c == 'l' || *c == 'L') {
6127 type = type_long_double;
6130 errorf(&token.source_position,
6131 "invalid suffix '%s' on floatingpoint constant", suffix->string);
6132 } else if (not_traditional) {
6133 warn_traditional_suffix();
6140 * Parse an integer constant.
6142 static expression_t *parse_number_literal(void)
6144 expression_kind_t kind;
6147 switch (token.type) {
6149 kind = EXPR_LITERAL_INTEGER;
6150 check_integer_suffix();
6153 case T_INTEGER_OCTAL:
6154 kind = EXPR_LITERAL_INTEGER_OCTAL;
6155 check_integer_suffix();
6158 case T_INTEGER_HEXADECIMAL:
6159 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
6160 check_integer_suffix();
6163 case T_FLOATINGPOINT:
6164 kind = EXPR_LITERAL_FLOATINGPOINT;
6165 type = check_floatingpoint_suffix();
6167 case T_FLOATINGPOINT_HEXADECIMAL:
6168 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6169 type = check_floatingpoint_suffix();
6172 panic("unexpected token type in parse_number_literal");
6175 expression_t *literal = allocate_expression_zero(kind);
6176 literal->base.source_position = token.source_position;
6177 literal->base.type = type;
6178 literal->literal.value = token.literal;
6179 literal->literal.suffix = token.symbol;
6182 /* integer type depends on the size of the number and the size
6183 * representable by the types. The backend/codegeneration has to determine
6186 determine_literal_type(&literal->literal);
6191 * Parse a character constant.
6193 static expression_t *parse_character_constant(void)
6195 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6196 literal->base.source_position = token.source_position;
6197 literal->base.type = c_mode & _CXX ? type_char : type_int;
6198 literal->literal.value = token.literal;
6200 size_t len = literal->literal.value.size;
6202 if (!GNU_MODE && !(c_mode & _C99)) {
6203 errorf(HERE, "more than 1 character in character constant");
6204 } else if (warning.multichar) {
6205 literal->base.type = type_int;
6206 warningf(HERE, "multi-character character constant");
6215 * Parse a wide character constant.
6217 static expression_t *parse_wide_character_constant(void)
6219 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6220 literal->base.source_position = token.source_position;
6221 literal->base.type = type_int;
6222 literal->literal.value = token.literal;
6224 size_t len = wstrlen(&literal->literal.value);
6226 warningf(HERE, "multi-character character constant");
6233 static entity_t *create_implicit_function(symbol_t *symbol,
6234 const source_position_t *source_position)
6236 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6237 ntype->function.return_type = type_int;
6238 ntype->function.unspecified_parameters = true;
6239 ntype->function.linkage = LINKAGE_C;
6240 type_t *type = identify_new_type(ntype);
6242 entity_t *entity = allocate_entity_zero(ENTITY_FUNCTION);
6243 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6244 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6245 entity->declaration.type = type;
6246 entity->declaration.implicit = true;
6247 entity->base.namespc = NAMESPACE_NORMAL;
6248 entity->base.symbol = symbol;
6249 entity->base.source_position = *source_position;
6251 if (current_scope != NULL) {
6252 bool strict_prototypes_old = warning.strict_prototypes;
6253 warning.strict_prototypes = false;
6254 record_entity(entity, false);
6255 warning.strict_prototypes = strict_prototypes_old;
6262 * Performs automatic type cast as described in §6.3.2.1.
6264 * @param orig_type the original type
6266 static type_t *automatic_type_conversion(type_t *orig_type)
6268 type_t *type = skip_typeref(orig_type);
6269 if (is_type_array(type)) {
6270 array_type_t *array_type = &type->array;
6271 type_t *element_type = array_type->element_type;
6272 unsigned qualifiers = array_type->base.qualifiers;
6274 return make_pointer_type(element_type, qualifiers);
6277 if (is_type_function(type)) {
6278 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6285 * reverts the automatic casts of array to pointer types and function
6286 * to function-pointer types as defined §6.3.2.1
6288 type_t *revert_automatic_type_conversion(const expression_t *expression)
6290 switch (expression->kind) {
6291 case EXPR_REFERENCE: {
6292 entity_t *entity = expression->reference.entity;
6293 if (is_declaration(entity)) {
6294 return entity->declaration.type;
6295 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6296 return entity->enum_value.enum_type;
6298 panic("no declaration or enum in reference");
6303 entity_t *entity = expression->select.compound_entry;
6304 assert(is_declaration(entity));
6305 type_t *type = entity->declaration.type;
6306 return get_qualified_type(type,
6307 expression->base.type->base.qualifiers);
6310 case EXPR_UNARY_DEREFERENCE: {
6311 const expression_t *const value = expression->unary.value;
6312 type_t *const type = skip_typeref(value->base.type);
6313 if (!is_type_pointer(type))
6314 return type_error_type;
6315 return type->pointer.points_to;
6318 case EXPR_ARRAY_ACCESS: {
6319 const expression_t *array_ref = expression->array_access.array_ref;
6320 type_t *type_left = skip_typeref(array_ref->base.type);
6321 if (!is_type_pointer(type_left))
6322 return type_error_type;
6323 return type_left->pointer.points_to;
6326 case EXPR_STRING_LITERAL: {
6327 size_t size = expression->string_literal.value.size;
6328 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6331 case EXPR_WIDE_STRING_LITERAL: {
6332 size_t size = wstrlen(&expression->string_literal.value);
6333 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6336 case EXPR_COMPOUND_LITERAL:
6337 return expression->compound_literal.type;
6342 return expression->base.type;
6346 * Find an entity matching a symbol in a scope.
6347 * Uses current scope if scope is NULL
6349 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6350 namespace_tag_t namespc)
6352 if (scope == NULL) {
6353 return get_entity(symbol, namespc);
6356 /* we should optimize here, if scope grows above a certain size we should
6357 construct a hashmap here... */
6358 entity_t *entity = scope->entities;
6359 for ( ; entity != NULL; entity = entity->base.next) {
6360 if (entity->base.symbol == symbol && entity->base.namespc == namespc)
6367 static entity_t *parse_qualified_identifier(void)
6369 /* namespace containing the symbol */
6371 source_position_t pos;
6372 const scope_t *lookup_scope = NULL;
6374 if (next_if(T_COLONCOLON))
6375 lookup_scope = &unit->scope;
6379 if (token.type != T_IDENTIFIER) {
6380 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6381 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6383 symbol = token.symbol;
6388 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6390 if (!next_if(T_COLONCOLON))
6393 switch (entity->kind) {
6394 case ENTITY_NAMESPACE:
6395 lookup_scope = &entity->namespacee.members;
6400 lookup_scope = &entity->compound.members;
6403 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6404 symbol, get_entity_kind_name(entity->kind));
6409 if (entity == NULL) {
6410 if (!strict_mode && token.type == '(') {
6411 /* an implicitly declared function */
6412 if (warning.error_implicit_function_declaration) {
6413 errorf(&pos, "implicit declaration of function '%Y'", symbol);
6414 } else if (warning.implicit_function_declaration) {
6415 warningf(&pos, "implicit declaration of function '%Y'", symbol);
6418 entity = create_implicit_function(symbol, &pos);
6420 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6421 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6428 /* skip further qualifications */
6429 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6431 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6434 static expression_t *parse_reference(void)
6436 source_position_t const pos = token.source_position;
6437 entity_t *const entity = parse_qualified_identifier();
6440 if (is_declaration(entity)) {
6441 orig_type = entity->declaration.type;
6442 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6443 orig_type = entity->enum_value.enum_type;
6445 panic("expected declaration or enum value in reference");
6448 /* we always do the auto-type conversions; the & and sizeof parser contains
6449 * code to revert this! */
6450 type_t *type = automatic_type_conversion(orig_type);
6452 expression_kind_t kind = EXPR_REFERENCE;
6453 if (entity->kind == ENTITY_ENUM_VALUE)
6454 kind = EXPR_REFERENCE_ENUM_VALUE;
6456 expression_t *expression = allocate_expression_zero(kind);
6457 expression->base.source_position = pos;
6458 expression->base.type = type;
6459 expression->reference.entity = entity;
6461 /* this declaration is used */
6462 if (is_declaration(entity)) {
6463 entity->declaration.used = true;
6466 if (entity->base.parent_scope != file_scope
6467 && (current_function != NULL
6468 && entity->base.parent_scope->depth < current_function->parameters.depth)
6469 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6470 if (entity->kind == ENTITY_VARIABLE) {
6471 /* access of a variable from an outer function */
6472 entity->variable.address_taken = true;
6473 } else if (entity->kind == ENTITY_PARAMETER) {
6474 entity->parameter.address_taken = true;
6476 current_function->need_closure = true;
6479 check_deprecated(HERE, entity);
6481 if (warning.init_self && entity == current_init_decl && !in_type_prop
6482 && entity->kind == ENTITY_VARIABLE) {
6483 current_init_decl = NULL;
6484 warningf(&pos, "variable '%#T' is initialized by itself",
6485 entity->declaration.type, entity->base.symbol);
6491 static bool semantic_cast(expression_t *cast)
6493 expression_t *expression = cast->unary.value;
6494 type_t *orig_dest_type = cast->base.type;
6495 type_t *orig_type_right = expression->base.type;
6496 type_t const *dst_type = skip_typeref(orig_dest_type);
6497 type_t const *src_type = skip_typeref(orig_type_right);
6498 source_position_t const *pos = &cast->base.source_position;
6500 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6501 if (dst_type == type_void)
6504 /* only integer and pointer can be casted to pointer */
6505 if (is_type_pointer(dst_type) &&
6506 !is_type_pointer(src_type) &&
6507 !is_type_integer(src_type) &&
6508 is_type_valid(src_type)) {
6509 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6513 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6514 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6518 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6519 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6523 if (warning.cast_qual &&
6524 is_type_pointer(src_type) &&
6525 is_type_pointer(dst_type)) {
6526 type_t *src = skip_typeref(src_type->pointer.points_to);
6527 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6528 unsigned missing_qualifiers =
6529 src->base.qualifiers & ~dst->base.qualifiers;
6530 if (missing_qualifiers != 0) {
6532 "cast discards qualifiers '%Q' in pointer target type of '%T'",
6533 missing_qualifiers, orig_type_right);
6539 static expression_t *parse_compound_literal(type_t *type)
6541 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6543 parse_initializer_env_t env;
6546 env.must_be_constant = false;
6547 initializer_t *initializer = parse_initializer(&env);
6550 expression->compound_literal.initializer = initializer;
6551 expression->compound_literal.type = type;
6552 expression->base.type = automatic_type_conversion(type);
6558 * Parse a cast expression.
6560 static expression_t *parse_cast(void)
6562 source_position_t source_position = token.source_position;
6565 add_anchor_token(')');
6567 type_t *type = parse_typename();
6569 rem_anchor_token(')');
6570 expect(')', end_error);
6572 if (token.type == '{') {
6573 return parse_compound_literal(type);
6576 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6577 cast->base.source_position = source_position;
6579 expression_t *value = parse_subexpression(PREC_CAST);
6580 cast->base.type = type;
6581 cast->unary.value = value;
6583 if (! semantic_cast(cast)) {
6584 /* TODO: record the error in the AST. else it is impossible to detect it */
6589 return create_invalid_expression();
6593 * Parse a statement expression.
6595 static expression_t *parse_statement_expression(void)
6597 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6600 add_anchor_token(')');
6602 statement_t *statement = parse_compound_statement(true);
6603 statement->compound.stmt_expr = true;
6604 expression->statement.statement = statement;
6606 /* find last statement and use its type */
6607 type_t *type = type_void;
6608 const statement_t *stmt = statement->compound.statements;
6610 while (stmt->base.next != NULL)
6611 stmt = stmt->base.next;
6613 if (stmt->kind == STATEMENT_EXPRESSION) {
6614 type = stmt->expression.expression->base.type;
6616 } else if (warning.other) {
6617 warningf(&expression->base.source_position, "empty statement expression ({})");
6619 expression->base.type = type;
6621 rem_anchor_token(')');
6622 expect(')', end_error);
6629 * Parse a parenthesized expression.
6631 static expression_t *parse_parenthesized_expression(void)
6633 token_t const* const la1 = look_ahead(1);
6634 switch (la1->type) {
6636 /* gcc extension: a statement expression */
6637 return parse_statement_expression();
6640 if (is_typedef_symbol(la1->symbol)) {
6643 return parse_cast();
6648 add_anchor_token(')');
6649 expression_t *result = parse_expression();
6650 result->base.parenthesized = true;
6651 rem_anchor_token(')');
6652 expect(')', end_error);
6658 static expression_t *parse_function_keyword(void)
6662 if (current_function == NULL) {
6663 errorf(HERE, "'__func__' used outside of a function");
6666 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6667 expression->base.type = type_char_ptr;
6668 expression->funcname.kind = FUNCNAME_FUNCTION;
6675 static expression_t *parse_pretty_function_keyword(void)
6677 if (current_function == NULL) {
6678 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6681 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6682 expression->base.type = type_char_ptr;
6683 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6685 eat(T___PRETTY_FUNCTION__);
6690 static expression_t *parse_funcsig_keyword(void)
6692 if (current_function == NULL) {
6693 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6696 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6697 expression->base.type = type_char_ptr;
6698 expression->funcname.kind = FUNCNAME_FUNCSIG;
6705 static expression_t *parse_funcdname_keyword(void)
6707 if (current_function == NULL) {
6708 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6711 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6712 expression->base.type = type_char_ptr;
6713 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6715 eat(T___FUNCDNAME__);
6720 static designator_t *parse_designator(void)
6722 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6723 result->source_position = *HERE;
6725 if (token.type != T_IDENTIFIER) {
6726 parse_error_expected("while parsing member designator",
6727 T_IDENTIFIER, NULL);
6730 result->symbol = token.symbol;
6733 designator_t *last_designator = result;
6736 if (token.type != T_IDENTIFIER) {
6737 parse_error_expected("while parsing member designator",
6738 T_IDENTIFIER, NULL);
6741 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6742 designator->source_position = *HERE;
6743 designator->symbol = token.symbol;
6746 last_designator->next = designator;
6747 last_designator = designator;
6751 add_anchor_token(']');
6752 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6753 designator->source_position = *HERE;
6754 designator->array_index = parse_expression();
6755 rem_anchor_token(']');
6756 expect(']', end_error);
6757 if (designator->array_index == NULL) {
6761 last_designator->next = designator;
6762 last_designator = designator;
6774 * Parse the __builtin_offsetof() expression.
6776 static expression_t *parse_offsetof(void)
6778 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6779 expression->base.type = type_size_t;
6781 eat(T___builtin_offsetof);
6783 expect('(', end_error);
6784 add_anchor_token(',');
6785 type_t *type = parse_typename();
6786 rem_anchor_token(',');
6787 expect(',', end_error);
6788 add_anchor_token(')');
6789 designator_t *designator = parse_designator();
6790 rem_anchor_token(')');
6791 expect(')', end_error);
6793 expression->offsetofe.type = type;
6794 expression->offsetofe.designator = designator;
6797 memset(&path, 0, sizeof(path));
6798 path.top_type = type;
6799 path.path = NEW_ARR_F(type_path_entry_t, 0);
6801 descend_into_subtype(&path);
6803 if (!walk_designator(&path, designator, true)) {
6804 return create_invalid_expression();
6807 DEL_ARR_F(path.path);
6811 return create_invalid_expression();
6815 * Parses a _builtin_va_start() expression.
6817 static expression_t *parse_va_start(void)
6819 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6821 eat(T___builtin_va_start);
6823 expect('(', end_error);
6824 add_anchor_token(',');
6825 expression->va_starte.ap = parse_assignment_expression();
6826 rem_anchor_token(',');
6827 expect(',', end_error);
6828 expression_t *const expr = parse_assignment_expression();
6829 if (expr->kind == EXPR_REFERENCE) {
6830 entity_t *const entity = expr->reference.entity;
6831 if (!current_function->base.type->function.variadic) {
6832 errorf(&expr->base.source_position,
6833 "'va_start' used in non-variadic function");
6834 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6835 entity->base.next != NULL ||
6836 entity->kind != ENTITY_PARAMETER) {
6837 errorf(&expr->base.source_position,
6838 "second argument of 'va_start' must be last parameter of the current function");
6840 expression->va_starte.parameter = &entity->variable;
6842 expect(')', end_error);
6845 expect(')', end_error);
6847 return create_invalid_expression();
6851 * Parses a __builtin_va_arg() expression.
6853 static expression_t *parse_va_arg(void)
6855 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6857 eat(T___builtin_va_arg);
6859 expect('(', end_error);
6861 ap.expression = parse_assignment_expression();
6862 expression->va_arge.ap = ap.expression;
6863 check_call_argument(type_valist, &ap, 1);
6865 expect(',', end_error);
6866 expression->base.type = parse_typename();
6867 expect(')', end_error);
6871 return create_invalid_expression();
6875 * Parses a __builtin_va_copy() expression.
6877 static expression_t *parse_va_copy(void)
6879 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6881 eat(T___builtin_va_copy);
6883 expect('(', end_error);
6884 expression_t *dst = parse_assignment_expression();
6885 assign_error_t error = semantic_assign(type_valist, dst);
6886 report_assign_error(error, type_valist, dst, "call argument 1",
6887 &dst->base.source_position);
6888 expression->va_copye.dst = dst;
6890 expect(',', end_error);
6892 call_argument_t src;
6893 src.expression = parse_assignment_expression();
6894 check_call_argument(type_valist, &src, 2);
6895 expression->va_copye.src = src.expression;
6896 expect(')', end_error);
6900 return create_invalid_expression();
6904 * Parses a __builtin_constant_p() expression.
6906 static expression_t *parse_builtin_constant(void)
6908 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6910 eat(T___builtin_constant_p);
6912 expect('(', end_error);
6913 add_anchor_token(')');
6914 expression->builtin_constant.value = parse_assignment_expression();
6915 rem_anchor_token(')');
6916 expect(')', end_error);
6917 expression->base.type = type_int;
6921 return create_invalid_expression();
6925 * Parses a __builtin_types_compatible_p() expression.
6927 static expression_t *parse_builtin_types_compatible(void)
6929 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6931 eat(T___builtin_types_compatible_p);
6933 expect('(', end_error);
6934 add_anchor_token(')');
6935 add_anchor_token(',');
6936 expression->builtin_types_compatible.left = parse_typename();
6937 rem_anchor_token(',');
6938 expect(',', end_error);
6939 expression->builtin_types_compatible.right = parse_typename();
6940 rem_anchor_token(')');
6941 expect(')', end_error);
6942 expression->base.type = type_int;
6946 return create_invalid_expression();
6950 * Parses a __builtin_is_*() compare expression.
6952 static expression_t *parse_compare_builtin(void)
6954 expression_t *expression;
6956 switch (token.type) {
6957 case T___builtin_isgreater:
6958 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6960 case T___builtin_isgreaterequal:
6961 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6963 case T___builtin_isless:
6964 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6966 case T___builtin_islessequal:
6967 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6969 case T___builtin_islessgreater:
6970 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6972 case T___builtin_isunordered:
6973 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6976 internal_errorf(HERE, "invalid compare builtin found");
6978 expression->base.source_position = *HERE;
6981 expect('(', end_error);
6982 expression->binary.left = parse_assignment_expression();
6983 expect(',', end_error);
6984 expression->binary.right = parse_assignment_expression();
6985 expect(')', end_error);
6987 type_t *const orig_type_left = expression->binary.left->base.type;
6988 type_t *const orig_type_right = expression->binary.right->base.type;
6990 type_t *const type_left = skip_typeref(orig_type_left);
6991 type_t *const type_right = skip_typeref(orig_type_right);
6992 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6993 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6994 type_error_incompatible("invalid operands in comparison",
6995 &expression->base.source_position, orig_type_left, orig_type_right);
6998 semantic_comparison(&expression->binary);
7003 return create_invalid_expression();
7007 * Parses a MS assume() expression.
7009 static expression_t *parse_assume(void)
7011 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
7015 expect('(', end_error);
7016 add_anchor_token(')');
7017 expression->unary.value = parse_assignment_expression();
7018 rem_anchor_token(')');
7019 expect(')', end_error);
7021 expression->base.type = type_void;
7024 return create_invalid_expression();
7028 * Return the declaration for a given label symbol or create a new one.
7030 * @param symbol the symbol of the label
7032 static label_t *get_label(symbol_t *symbol)
7035 assert(current_function != NULL);
7037 label = get_entity(symbol, NAMESPACE_LABEL);
7038 /* if we found a local label, we already created the declaration */
7039 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
7040 if (label->base.parent_scope != current_scope) {
7041 assert(label->base.parent_scope->depth < current_scope->depth);
7042 current_function->goto_to_outer = true;
7044 return &label->label;
7047 label = get_entity(symbol, NAMESPACE_LABEL);
7048 /* if we found a label in the same function, then we already created the
7051 && label->base.parent_scope == ¤t_function->parameters) {
7052 return &label->label;
7055 /* otherwise we need to create a new one */
7056 label = allocate_entity_zero(ENTITY_LABEL);
7057 label->base.namespc = NAMESPACE_LABEL;
7058 label->base.symbol = symbol;
7062 return &label->label;
7066 * Parses a GNU && label address expression.
7068 static expression_t *parse_label_address(void)
7070 source_position_t source_position = token.source_position;
7072 if (token.type != T_IDENTIFIER) {
7073 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
7076 symbol_t *symbol = token.symbol;
7079 label_t *label = get_label(symbol);
7081 label->address_taken = true;
7083 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
7084 expression->base.source_position = source_position;
7086 /* label address is threaten as a void pointer */
7087 expression->base.type = type_void_ptr;
7088 expression->label_address.label = label;
7091 return create_invalid_expression();
7095 * Parse a microsoft __noop expression.
7097 static expression_t *parse_noop_expression(void)
7099 /* the result is a (int)0 */
7100 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
7101 literal->base.type = type_int;
7102 literal->base.source_position = token.source_position;
7103 literal->literal.value.begin = "__noop";
7104 literal->literal.value.size = 6;
7108 if (token.type == '(') {
7109 /* parse arguments */
7111 add_anchor_token(')');
7112 add_anchor_token(',');
7114 if (token.type != ')') do {
7115 (void)parse_assignment_expression();
7116 } while (next_if(','));
7118 rem_anchor_token(',');
7119 rem_anchor_token(')');
7120 expect(')', end_error);
7127 * Parses a primary expression.
7129 static expression_t *parse_primary_expression(void)
7131 switch (token.type) {
7132 case T_false: return parse_boolean_literal(false);
7133 case T_true: return parse_boolean_literal(true);
7135 case T_INTEGER_OCTAL:
7136 case T_INTEGER_HEXADECIMAL:
7137 case T_FLOATINGPOINT:
7138 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
7139 case T_CHARACTER_CONSTANT: return parse_character_constant();
7140 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
7141 case T_STRING_LITERAL:
7142 case T_WIDE_STRING_LITERAL: return parse_string_literal();
7143 case T___FUNCTION__:
7144 case T___func__: return parse_function_keyword();
7145 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
7146 case T___FUNCSIG__: return parse_funcsig_keyword();
7147 case T___FUNCDNAME__: return parse_funcdname_keyword();
7148 case T___builtin_offsetof: return parse_offsetof();
7149 case T___builtin_va_start: return parse_va_start();
7150 case T___builtin_va_arg: return parse_va_arg();
7151 case T___builtin_va_copy: return parse_va_copy();
7152 case T___builtin_isgreater:
7153 case T___builtin_isgreaterequal:
7154 case T___builtin_isless:
7155 case T___builtin_islessequal:
7156 case T___builtin_islessgreater:
7157 case T___builtin_isunordered: return parse_compare_builtin();
7158 case T___builtin_constant_p: return parse_builtin_constant();
7159 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
7160 case T__assume: return parse_assume();
7163 return parse_label_address();
7166 case '(': return parse_parenthesized_expression();
7167 case T___noop: return parse_noop_expression();
7169 /* Gracefully handle type names while parsing expressions. */
7171 return parse_reference();
7173 if (!is_typedef_symbol(token.symbol)) {
7174 return parse_reference();
7178 source_position_t const pos = *HERE;
7179 type_t const *const type = parse_typename();
7180 errorf(&pos, "encountered type '%T' while parsing expression", type);
7181 return create_invalid_expression();
7185 errorf(HERE, "unexpected token %K, expected an expression", &token);
7187 return create_invalid_expression();
7190 static expression_t *parse_array_expression(expression_t *left)
7192 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
7193 array_access_expression_t *const arr = &expr->array_access;
7196 add_anchor_token(']');
7198 expression_t *const inside = parse_expression();
7200 type_t *const orig_type_left = left->base.type;
7201 type_t *const orig_type_inside = inside->base.type;
7203 type_t *const type_left = skip_typeref(orig_type_left);
7204 type_t *const type_inside = skip_typeref(orig_type_inside);
7210 if (is_type_pointer(type_left)) {
7213 idx_type = type_inside;
7214 res_type = type_left->pointer.points_to;
7216 } else if (is_type_pointer(type_inside)) {
7217 arr->flipped = true;
7220 idx_type = type_left;
7221 res_type = type_inside->pointer.points_to;
7223 res_type = automatic_type_conversion(res_type);
7224 if (!is_type_integer(idx_type)) {
7225 errorf(&idx->base.source_position, "array subscript must have integer type");
7226 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR) && warning.char_subscripts) {
7227 warningf(&idx->base.source_position, "array subscript has char type");
7230 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7232 "array access on object with non-pointer types '%T', '%T'",
7233 orig_type_left, orig_type_inside);
7235 res_type = type_error_type;
7240 arr->array_ref = ref;
7242 arr->base.type = res_type;
7244 rem_anchor_token(']');
7245 expect(']', end_error);
7250 static expression_t *parse_typeprop(expression_kind_t const kind)
7252 expression_t *tp_expression = allocate_expression_zero(kind);
7253 tp_expression->base.type = type_size_t;
7255 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7257 /* we only refer to a type property, mark this case */
7258 bool old = in_type_prop;
7259 in_type_prop = true;
7262 expression_t *expression;
7263 if (token.type == '(' && is_declaration_specifier(look_ahead(1), true)) {
7265 add_anchor_token(')');
7266 orig_type = parse_typename();
7267 rem_anchor_token(')');
7268 expect(')', end_error);
7270 if (token.type == '{') {
7271 /* It was not sizeof(type) after all. It is sizeof of an expression
7272 * starting with a compound literal */
7273 expression = parse_compound_literal(orig_type);
7274 goto typeprop_expression;
7277 expression = parse_subexpression(PREC_UNARY);
7279 typeprop_expression:
7280 tp_expression->typeprop.tp_expression = expression;
7282 orig_type = revert_automatic_type_conversion(expression);
7283 expression->base.type = orig_type;
7286 tp_expression->typeprop.type = orig_type;
7287 type_t const* const type = skip_typeref(orig_type);
7288 char const* wrong_type = NULL;
7289 if (is_type_incomplete(type)) {
7290 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7291 wrong_type = "incomplete";
7292 } else if (type->kind == TYPE_FUNCTION) {
7294 /* function types are allowed (and return 1) */
7295 if (warning.other) {
7296 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7297 warningf(&tp_expression->base.source_position,
7298 "%s expression with function argument returns invalid result", what);
7301 wrong_type = "function";
7304 if (is_type_incomplete(type))
7305 wrong_type = "incomplete";
7307 if (type->kind == TYPE_BITFIELD)
7308 wrong_type = "bitfield";
7310 if (wrong_type != NULL) {
7311 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7312 errorf(&tp_expression->base.source_position,
7313 "operand of %s expression must not be of %s type '%T'",
7314 what, wrong_type, orig_type);
7319 return tp_expression;
7322 static expression_t *parse_sizeof(void)
7324 return parse_typeprop(EXPR_SIZEOF);
7327 static expression_t *parse_alignof(void)
7329 return parse_typeprop(EXPR_ALIGNOF);
7332 static expression_t *parse_select_expression(expression_t *addr)
7334 assert(token.type == '.' || token.type == T_MINUSGREATER);
7335 bool select_left_arrow = (token.type == T_MINUSGREATER);
7336 source_position_t const pos = *HERE;
7339 if (token.type != T_IDENTIFIER) {
7340 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7341 return create_invalid_expression();
7343 symbol_t *symbol = token.symbol;
7346 type_t *const orig_type = addr->base.type;
7347 type_t *const type = skip_typeref(orig_type);
7350 bool saw_error = false;
7351 if (is_type_pointer(type)) {
7352 if (!select_left_arrow) {
7354 "request for member '%Y' in something not a struct or union, but '%T'",
7358 type_left = skip_typeref(type->pointer.points_to);
7360 if (select_left_arrow && is_type_valid(type)) {
7361 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7367 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7368 type_left->kind != TYPE_COMPOUND_UNION) {
7370 if (is_type_valid(type_left) && !saw_error) {
7372 "request for member '%Y' in something not a struct or union, but '%T'",
7375 return create_invalid_expression();
7378 compound_t *compound = type_left->compound.compound;
7379 if (!compound->complete) {
7380 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7382 return create_invalid_expression();
7385 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7386 expression_t *result =
7387 find_create_select(&pos, addr, qualifiers, compound, symbol);
7389 if (result == NULL) {
7390 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7391 return create_invalid_expression();
7397 static void check_call_argument(type_t *expected_type,
7398 call_argument_t *argument, unsigned pos)
7400 type_t *expected_type_skip = skip_typeref(expected_type);
7401 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7402 expression_t *arg_expr = argument->expression;
7403 type_t *arg_type = skip_typeref(arg_expr->base.type);
7405 /* handle transparent union gnu extension */
7406 if (is_type_union(expected_type_skip)
7407 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7408 compound_t *union_decl = expected_type_skip->compound.compound;
7409 type_t *best_type = NULL;
7410 entity_t *entry = union_decl->members.entities;
7411 for ( ; entry != NULL; entry = entry->base.next) {
7412 assert(is_declaration(entry));
7413 type_t *decl_type = entry->declaration.type;
7414 error = semantic_assign(decl_type, arg_expr);
7415 if (error == ASSIGN_ERROR_INCOMPATIBLE
7416 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7419 if (error == ASSIGN_SUCCESS) {
7420 best_type = decl_type;
7421 } else if (best_type == NULL) {
7422 best_type = decl_type;
7426 if (best_type != NULL) {
7427 expected_type = best_type;
7431 error = semantic_assign(expected_type, arg_expr);
7432 argument->expression = create_implicit_cast(arg_expr, expected_type);
7434 if (error != ASSIGN_SUCCESS) {
7435 /* report exact scope in error messages (like "in argument 3") */
7437 snprintf(buf, sizeof(buf), "call argument %u", pos);
7438 report_assign_error(error, expected_type, arg_expr, buf,
7439 &arg_expr->base.source_position);
7440 } else if (warning.traditional || warning.conversion) {
7441 type_t *const promoted_type = get_default_promoted_type(arg_type);
7442 if (!types_compatible(expected_type_skip, promoted_type) &&
7443 !types_compatible(expected_type_skip, type_void_ptr) &&
7444 !types_compatible(type_void_ptr, promoted_type)) {
7445 /* Deliberately show the skipped types in this warning */
7446 warningf(&arg_expr->base.source_position,
7447 "passing call argument %u as '%T' rather than '%T' due to prototype",
7448 pos, expected_type_skip, promoted_type);
7454 * Handle the semantic restrictions of builtin calls
7456 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7457 switch (call->function->reference.entity->function.btk) {
7458 case bk_gnu_builtin_return_address:
7459 case bk_gnu_builtin_frame_address: {
7460 /* argument must be constant */
7461 call_argument_t *argument = call->arguments;
7463 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7464 errorf(&call->base.source_position,
7465 "argument of '%Y' must be a constant expression",
7466 call->function->reference.entity->base.symbol);
7470 case bk_gnu_builtin_object_size:
7471 if (call->arguments == NULL)
7474 call_argument_t *arg = call->arguments->next;
7475 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7476 errorf(&call->base.source_position,
7477 "second argument of '%Y' must be a constant expression",
7478 call->function->reference.entity->base.symbol);
7481 case bk_gnu_builtin_prefetch:
7482 /* second and third argument must be constant if existent */
7483 if (call->arguments == NULL)
7485 call_argument_t *rw = call->arguments->next;
7486 call_argument_t *locality = NULL;
7489 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7490 errorf(&call->base.source_position,
7491 "second argument of '%Y' must be a constant expression",
7492 call->function->reference.entity->base.symbol);
7494 locality = rw->next;
7496 if (locality != NULL) {
7497 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7498 errorf(&call->base.source_position,
7499 "third argument of '%Y' must be a constant expression",
7500 call->function->reference.entity->base.symbol);
7502 locality = rw->next;
7511 * Parse a call expression, ie. expression '( ... )'.
7513 * @param expression the function address
7515 static expression_t *parse_call_expression(expression_t *expression)
7517 expression_t *result = allocate_expression_zero(EXPR_CALL);
7518 call_expression_t *call = &result->call;
7519 call->function = expression;
7521 type_t *const orig_type = expression->base.type;
7522 type_t *const type = skip_typeref(orig_type);
7524 function_type_t *function_type = NULL;
7525 if (is_type_pointer(type)) {
7526 type_t *const to_type = skip_typeref(type->pointer.points_to);
7528 if (is_type_function(to_type)) {
7529 function_type = &to_type->function;
7530 call->base.type = function_type->return_type;
7534 if (function_type == NULL && is_type_valid(type)) {
7536 "called object '%E' (type '%T') is not a pointer to a function",
7537 expression, orig_type);
7540 /* parse arguments */
7542 add_anchor_token(')');
7543 add_anchor_token(',');
7545 if (token.type != ')') {
7546 call_argument_t **anchor = &call->arguments;
7548 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7549 argument->expression = parse_assignment_expression();
7552 anchor = &argument->next;
7553 } while (next_if(','));
7555 rem_anchor_token(',');
7556 rem_anchor_token(')');
7557 expect(')', end_error);
7559 if (function_type == NULL)
7562 /* check type and count of call arguments */
7563 function_parameter_t *parameter = function_type->parameters;
7564 call_argument_t *argument = call->arguments;
7565 if (!function_type->unspecified_parameters) {
7566 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7567 parameter = parameter->next, argument = argument->next) {
7568 check_call_argument(parameter->type, argument, ++pos);
7571 if (parameter != NULL) {
7572 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7573 } else if (argument != NULL && !function_type->variadic) {
7574 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7578 /* do default promotion for other arguments */
7579 for (; argument != NULL; argument = argument->next) {
7580 type_t *type = argument->expression->base.type;
7581 if (!is_type_object(skip_typeref(type))) {
7582 errorf(&argument->expression->base.source_position,
7583 "call argument '%E' must not be void", argument->expression);
7586 type = get_default_promoted_type(type);
7588 argument->expression
7589 = create_implicit_cast(argument->expression, type);
7594 if (warning.aggregate_return &&
7595 is_type_compound(skip_typeref(function_type->return_type))) {
7596 warningf(&expression->base.source_position,
7597 "function call has aggregate value");
7600 if (expression->kind == EXPR_REFERENCE) {
7601 reference_expression_t *reference = &expression->reference;
7602 if (reference->entity->kind == ENTITY_FUNCTION &&
7603 reference->entity->function.btk != bk_none)
7604 handle_builtin_argument_restrictions(call);
7611 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7613 static bool same_compound_type(const type_t *type1, const type_t *type2)
7616 is_type_compound(type1) &&
7617 type1->kind == type2->kind &&
7618 type1->compound.compound == type2->compound.compound;
7621 static expression_t const *get_reference_address(expression_t const *expr)
7623 bool regular_take_address = true;
7625 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7626 expr = expr->unary.value;
7628 regular_take_address = false;
7631 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7634 expr = expr->unary.value;
7637 if (expr->kind != EXPR_REFERENCE)
7640 /* special case for functions which are automatically converted to a
7641 * pointer to function without an extra TAKE_ADDRESS operation */
7642 if (!regular_take_address &&
7643 expr->reference.entity->kind != ENTITY_FUNCTION) {
7650 static void warn_reference_address_as_bool(expression_t const* expr)
7652 if (!warning.address)
7655 expr = get_reference_address(expr);
7657 warningf(&expr->base.source_position,
7658 "the address of '%Y' will always evaluate as 'true'",
7659 expr->reference.entity->base.symbol);
7663 static void warn_assignment_in_condition(const expression_t *const expr)
7665 if (!warning.parentheses)
7667 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7669 if (expr->base.parenthesized)
7671 warningf(&expr->base.source_position,
7672 "suggest parentheses around assignment used as truth value");
7675 static void semantic_condition(expression_t const *const expr,
7676 char const *const context)
7678 type_t *const type = skip_typeref(expr->base.type);
7679 if (is_type_scalar(type)) {
7680 warn_reference_address_as_bool(expr);
7681 warn_assignment_in_condition(expr);
7682 } else if (is_type_valid(type)) {
7683 errorf(&expr->base.source_position,
7684 "%s must have scalar type", context);
7689 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7691 * @param expression the conditional expression
7693 static expression_t *parse_conditional_expression(expression_t *expression)
7695 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7697 conditional_expression_t *conditional = &result->conditional;
7698 conditional->condition = expression;
7701 add_anchor_token(':');
7703 /* §6.5.15:2 The first operand shall have scalar type. */
7704 semantic_condition(expression, "condition of conditional operator");
7706 expression_t *true_expression = expression;
7707 bool gnu_cond = false;
7708 if (GNU_MODE && token.type == ':') {
7711 true_expression = parse_expression();
7713 rem_anchor_token(':');
7714 expect(':', end_error);
7716 expression_t *false_expression =
7717 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7719 type_t *const orig_true_type = true_expression->base.type;
7720 type_t *const orig_false_type = false_expression->base.type;
7721 type_t *const true_type = skip_typeref(orig_true_type);
7722 type_t *const false_type = skip_typeref(orig_false_type);
7725 type_t *result_type;
7726 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7727 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7728 /* ISO/IEC 14882:1998(E) §5.16:2 */
7729 if (true_expression->kind == EXPR_UNARY_THROW) {
7730 result_type = false_type;
7731 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7732 result_type = true_type;
7734 if (warning.other && (
7735 !is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7736 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)
7738 warningf(&conditional->base.source_position,
7739 "ISO C forbids conditional expression with only one void side");
7741 result_type = type_void;
7743 } else if (is_type_arithmetic(true_type)
7744 && is_type_arithmetic(false_type)) {
7745 result_type = semantic_arithmetic(true_type, false_type);
7746 } else if (same_compound_type(true_type, false_type)) {
7747 /* just take 1 of the 2 types */
7748 result_type = true_type;
7749 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7750 type_t *pointer_type;
7752 expression_t *other_expression;
7753 if (is_type_pointer(true_type) &&
7754 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7755 pointer_type = true_type;
7756 other_type = false_type;
7757 other_expression = false_expression;
7759 pointer_type = false_type;
7760 other_type = true_type;
7761 other_expression = true_expression;
7764 if (is_null_pointer_constant(other_expression)) {
7765 result_type = pointer_type;
7766 } else if (is_type_pointer(other_type)) {
7767 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7768 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7771 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7772 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7774 } else if (types_compatible(get_unqualified_type(to1),
7775 get_unqualified_type(to2))) {
7778 if (warning.other) {
7779 warningf(&conditional->base.source_position,
7780 "pointer types '%T' and '%T' in conditional expression are incompatible",
7781 true_type, false_type);
7786 type_t *const type =
7787 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7788 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7789 } else if (is_type_integer(other_type)) {
7790 if (warning.other) {
7791 warningf(&conditional->base.source_position,
7792 "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7794 result_type = pointer_type;
7796 if (is_type_valid(other_type)) {
7797 type_error_incompatible("while parsing conditional",
7798 &expression->base.source_position, true_type, false_type);
7800 result_type = type_error_type;
7803 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7804 type_error_incompatible("while parsing conditional",
7805 &conditional->base.source_position, true_type,
7808 result_type = type_error_type;
7811 conditional->true_expression
7812 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7813 conditional->false_expression
7814 = create_implicit_cast(false_expression, result_type);
7815 conditional->base.type = result_type;
7820 * Parse an extension expression.
7822 static expression_t *parse_extension(void)
7824 eat(T___extension__);
7826 bool old_gcc_extension = in_gcc_extension;
7827 in_gcc_extension = true;
7828 expression_t *expression = parse_subexpression(PREC_UNARY);
7829 in_gcc_extension = old_gcc_extension;
7834 * Parse a __builtin_classify_type() expression.
7836 static expression_t *parse_builtin_classify_type(void)
7838 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7839 result->base.type = type_int;
7841 eat(T___builtin_classify_type);
7843 expect('(', end_error);
7844 add_anchor_token(')');
7845 expression_t *expression = parse_expression();
7846 rem_anchor_token(')');
7847 expect(')', end_error);
7848 result->classify_type.type_expression = expression;
7852 return create_invalid_expression();
7856 * Parse a delete expression
7857 * ISO/IEC 14882:1998(E) §5.3.5
7859 static expression_t *parse_delete(void)
7861 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7862 result->base.type = type_void;
7867 result->kind = EXPR_UNARY_DELETE_ARRAY;
7868 expect(']', end_error);
7872 expression_t *const value = parse_subexpression(PREC_CAST);
7873 result->unary.value = value;
7875 type_t *const type = skip_typeref(value->base.type);
7876 if (!is_type_pointer(type)) {
7877 if (is_type_valid(type)) {
7878 errorf(&value->base.source_position,
7879 "operand of delete must have pointer type");
7881 } else if (warning.other &&
7882 is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7883 warningf(&value->base.source_position,
7884 "deleting 'void*' is undefined");
7891 * Parse a throw expression
7892 * ISO/IEC 14882:1998(E) §15:1
7894 static expression_t *parse_throw(void)
7896 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7897 result->base.type = type_void;
7901 expression_t *value = NULL;
7902 switch (token.type) {
7904 value = parse_assignment_expression();
7905 /* ISO/IEC 14882:1998(E) §15.1:3 */
7906 type_t *const orig_type = value->base.type;
7907 type_t *const type = skip_typeref(orig_type);
7908 if (is_type_incomplete(type)) {
7909 errorf(&value->base.source_position,
7910 "cannot throw object of incomplete type '%T'", orig_type);
7911 } else if (is_type_pointer(type)) {
7912 type_t *const points_to = skip_typeref(type->pointer.points_to);
7913 if (is_type_incomplete(points_to) &&
7914 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7915 errorf(&value->base.source_position,
7916 "cannot throw pointer to incomplete type '%T'", orig_type);
7924 result->unary.value = value;
7929 static bool check_pointer_arithmetic(const source_position_t *source_position,
7930 type_t *pointer_type,
7931 type_t *orig_pointer_type)
7933 type_t *points_to = pointer_type->pointer.points_to;
7934 points_to = skip_typeref(points_to);
7936 if (is_type_incomplete(points_to)) {
7937 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7938 errorf(source_position,
7939 "arithmetic with pointer to incomplete type '%T' not allowed",
7942 } else if (warning.pointer_arith) {
7943 warningf(source_position,
7944 "pointer of type '%T' used in arithmetic",
7947 } else if (is_type_function(points_to)) {
7949 errorf(source_position,
7950 "arithmetic with pointer to function type '%T' not allowed",
7953 } else if (warning.pointer_arith) {
7954 warningf(source_position,
7955 "pointer to a function '%T' used in arithmetic",
7962 static bool is_lvalue(const expression_t *expression)
7964 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7965 switch (expression->kind) {
7966 case EXPR_ARRAY_ACCESS:
7967 case EXPR_COMPOUND_LITERAL:
7968 case EXPR_REFERENCE:
7970 case EXPR_UNARY_DEREFERENCE:
7974 type_t *type = skip_typeref(expression->base.type);
7976 /* ISO/IEC 14882:1998(E) §3.10:3 */
7977 is_type_reference(type) ||
7978 /* Claim it is an lvalue, if the type is invalid. There was a parse
7979 * error before, which maybe prevented properly recognizing it as
7981 !is_type_valid(type);
7986 static void semantic_incdec(unary_expression_t *expression)
7988 type_t *const orig_type = expression->value->base.type;
7989 type_t *const type = skip_typeref(orig_type);
7990 if (is_type_pointer(type)) {
7991 if (!check_pointer_arithmetic(&expression->base.source_position,
7995 } else if (!is_type_real(type) && is_type_valid(type)) {
7996 /* TODO: improve error message */
7997 errorf(&expression->base.source_position,
7998 "operation needs an arithmetic or pointer type");
8001 if (!is_lvalue(expression->value)) {
8002 /* TODO: improve error message */
8003 errorf(&expression->base.source_position, "lvalue required as operand");
8005 expression->base.type = orig_type;
8008 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
8010 type_t *const orig_type = expression->value->base.type;
8011 type_t *const type = skip_typeref(orig_type);
8012 if (!is_type_arithmetic(type)) {
8013 if (is_type_valid(type)) {
8014 /* TODO: improve error message */
8015 errorf(&expression->base.source_position,
8016 "operation needs an arithmetic type");
8021 expression->base.type = orig_type;
8024 static void semantic_unexpr_plus(unary_expression_t *expression)
8026 semantic_unexpr_arithmetic(expression);
8027 if (warning.traditional)
8028 warningf(&expression->base.source_position,
8029 "traditional C rejects the unary plus operator");
8032 static void semantic_not(unary_expression_t *expression)
8034 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
8035 semantic_condition(expression->value, "operand of !");
8036 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8039 static void semantic_unexpr_integer(unary_expression_t *expression)
8041 type_t *const orig_type = expression->value->base.type;
8042 type_t *const type = skip_typeref(orig_type);
8043 if (!is_type_integer(type)) {
8044 if (is_type_valid(type)) {
8045 errorf(&expression->base.source_position,
8046 "operand of ~ must be of integer type");
8051 expression->base.type = orig_type;
8054 static void semantic_dereference(unary_expression_t *expression)
8056 type_t *const orig_type = expression->value->base.type;
8057 type_t *const type = skip_typeref(orig_type);
8058 if (!is_type_pointer(type)) {
8059 if (is_type_valid(type)) {
8060 errorf(&expression->base.source_position,
8061 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
8066 type_t *result_type = type->pointer.points_to;
8067 result_type = automatic_type_conversion(result_type);
8068 expression->base.type = result_type;
8072 * Record that an address is taken (expression represents an lvalue).
8074 * @param expression the expression
8075 * @param may_be_register if true, the expression might be an register
8077 static void set_address_taken(expression_t *expression, bool may_be_register)
8079 if (expression->kind != EXPR_REFERENCE)
8082 entity_t *const entity = expression->reference.entity;
8084 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
8087 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
8088 && !may_be_register) {
8089 errorf(&expression->base.source_position,
8090 "address of register %s '%Y' requested",
8091 get_entity_kind_name(entity->kind), entity->base.symbol);
8094 if (entity->kind == ENTITY_VARIABLE) {
8095 entity->variable.address_taken = true;
8097 assert(entity->kind == ENTITY_PARAMETER);
8098 entity->parameter.address_taken = true;
8103 * Check the semantic of the address taken expression.
8105 static void semantic_take_addr(unary_expression_t *expression)
8107 expression_t *value = expression->value;
8108 value->base.type = revert_automatic_type_conversion(value);
8110 type_t *orig_type = value->base.type;
8111 type_t *type = skip_typeref(orig_type);
8112 if (!is_type_valid(type))
8116 if (!is_lvalue(value)) {
8117 errorf(&expression->base.source_position, "'&' requires an lvalue");
8119 if (type->kind == TYPE_BITFIELD) {
8120 errorf(&expression->base.source_position,
8121 "'&' not allowed on object with bitfield type '%T'",
8125 set_address_taken(value, false);
8127 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
8130 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
8131 static expression_t *parse_##unexpression_type(void) \
8133 expression_t *unary_expression \
8134 = allocate_expression_zero(unexpression_type); \
8136 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
8138 sfunc(&unary_expression->unary); \
8140 return unary_expression; \
8143 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
8144 semantic_unexpr_arithmetic)
8145 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
8146 semantic_unexpr_plus)
8147 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
8149 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
8150 semantic_dereference)
8151 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
8153 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
8154 semantic_unexpr_integer)
8155 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
8157 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
8160 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
8162 static expression_t *parse_##unexpression_type(expression_t *left) \
8164 expression_t *unary_expression \
8165 = allocate_expression_zero(unexpression_type); \
8167 unary_expression->unary.value = left; \
8169 sfunc(&unary_expression->unary); \
8171 return unary_expression; \
8174 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
8175 EXPR_UNARY_POSTFIX_INCREMENT,
8177 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
8178 EXPR_UNARY_POSTFIX_DECREMENT,
8181 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
8183 /* TODO: handle complex + imaginary types */
8185 type_left = get_unqualified_type(type_left);
8186 type_right = get_unqualified_type(type_right);
8188 /* §6.3.1.8 Usual arithmetic conversions */
8189 if (type_left == type_long_double || type_right == type_long_double) {
8190 return type_long_double;
8191 } else if (type_left == type_double || type_right == type_double) {
8193 } else if (type_left == type_float || type_right == type_float) {
8197 type_left = promote_integer(type_left);
8198 type_right = promote_integer(type_right);
8200 if (type_left == type_right)
8203 bool const signed_left = is_type_signed(type_left);
8204 bool const signed_right = is_type_signed(type_right);
8205 int const rank_left = get_rank(type_left);
8206 int const rank_right = get_rank(type_right);
8208 if (signed_left == signed_right)
8209 return rank_left >= rank_right ? type_left : type_right;
8218 u_rank = rank_right;
8219 u_type = type_right;
8221 s_rank = rank_right;
8222 s_type = type_right;
8227 if (u_rank >= s_rank)
8230 /* casting rank to atomic_type_kind is a bit hacky, but makes things
8232 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
8233 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8237 case ATOMIC_TYPE_INT: return type_unsigned_int;
8238 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8239 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8241 default: panic("invalid atomic type");
8246 * Check the semantic restrictions for a binary expression.
8248 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8250 expression_t *const left = expression->left;
8251 expression_t *const right = expression->right;
8252 type_t *const orig_type_left = left->base.type;
8253 type_t *const orig_type_right = right->base.type;
8254 type_t *const type_left = skip_typeref(orig_type_left);
8255 type_t *const type_right = skip_typeref(orig_type_right);
8257 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8258 /* TODO: improve error message */
8259 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8260 errorf(&expression->base.source_position,
8261 "operation needs arithmetic types");
8266 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8267 expression->left = create_implicit_cast(left, arithmetic_type);
8268 expression->right = create_implicit_cast(right, arithmetic_type);
8269 expression->base.type = arithmetic_type;
8272 static void semantic_binexpr_integer(binary_expression_t *const expression)
8274 expression_t *const left = expression->left;
8275 expression_t *const right = expression->right;
8276 type_t *const orig_type_left = left->base.type;
8277 type_t *const orig_type_right = right->base.type;
8278 type_t *const type_left = skip_typeref(orig_type_left);
8279 type_t *const type_right = skip_typeref(orig_type_right);
8281 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8282 /* TODO: improve error message */
8283 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8284 errorf(&expression->base.source_position,
8285 "operation needs integer types");
8290 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8291 expression->left = create_implicit_cast(left, result_type);
8292 expression->right = create_implicit_cast(right, result_type);
8293 expression->base.type = result_type;
8296 static void warn_div_by_zero(binary_expression_t const *const expression)
8298 if (!warning.div_by_zero ||
8299 !is_type_integer(expression->base.type))
8302 expression_t const *const right = expression->right;
8303 /* The type of the right operand can be different for /= */
8304 if (is_type_integer(right->base.type) &&
8305 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8306 !fold_constant_to_bool(right)) {
8307 warningf(&expression->base.source_position, "division by zero");
8312 * Check the semantic restrictions for a div/mod expression.
8314 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8316 semantic_binexpr_arithmetic(expression);
8317 warn_div_by_zero(expression);
8320 static void warn_addsub_in_shift(const expression_t *const expr)
8322 if (expr->base.parenthesized)
8326 switch (expr->kind) {
8327 case EXPR_BINARY_ADD: op = '+'; break;
8328 case EXPR_BINARY_SUB: op = '-'; break;
8332 warningf(&expr->base.source_position,
8333 "suggest parentheses around '%c' inside shift", op);
8336 static bool semantic_shift(binary_expression_t *expression)
8338 expression_t *const left = expression->left;
8339 expression_t *const right = expression->right;
8340 type_t *const orig_type_left = left->base.type;
8341 type_t *const orig_type_right = right->base.type;
8342 type_t * type_left = skip_typeref(orig_type_left);
8343 type_t * type_right = skip_typeref(orig_type_right);
8345 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8346 /* TODO: improve error message */
8347 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8348 errorf(&expression->base.source_position,
8349 "operands of shift operation must have integer types");
8354 type_left = promote_integer(type_left);
8356 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8357 long count = fold_constant_to_int(right);
8359 warningf(&right->base.source_position,
8360 "shift count must be non-negative");
8361 } else if ((unsigned long)count >=
8362 get_atomic_type_size(type_left->atomic.akind) * 8) {
8363 warningf(&right->base.source_position,
8364 "shift count must be less than type width");
8368 type_right = promote_integer(type_right);
8369 expression->right = create_implicit_cast(right, type_right);
8374 static void semantic_shift_op(binary_expression_t *expression)
8376 expression_t *const left = expression->left;
8377 expression_t *const right = expression->right;
8379 if (!semantic_shift(expression))
8382 if (warning.parentheses) {
8383 warn_addsub_in_shift(left);
8384 warn_addsub_in_shift(right);
8387 type_t *const orig_type_left = left->base.type;
8388 type_t * type_left = skip_typeref(orig_type_left);
8390 type_left = promote_integer(type_left);
8391 expression->left = create_implicit_cast(left, type_left);
8392 expression->base.type = type_left;
8395 static void semantic_add(binary_expression_t *expression)
8397 expression_t *const left = expression->left;
8398 expression_t *const right = expression->right;
8399 type_t *const orig_type_left = left->base.type;
8400 type_t *const orig_type_right = right->base.type;
8401 type_t *const type_left = skip_typeref(orig_type_left);
8402 type_t *const type_right = skip_typeref(orig_type_right);
8405 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8406 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8407 expression->left = create_implicit_cast(left, arithmetic_type);
8408 expression->right = create_implicit_cast(right, arithmetic_type);
8409 expression->base.type = arithmetic_type;
8410 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8411 check_pointer_arithmetic(&expression->base.source_position,
8412 type_left, orig_type_left);
8413 expression->base.type = type_left;
8414 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8415 check_pointer_arithmetic(&expression->base.source_position,
8416 type_right, orig_type_right);
8417 expression->base.type = type_right;
8418 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8419 errorf(&expression->base.source_position,
8420 "invalid operands to binary + ('%T', '%T')",
8421 orig_type_left, orig_type_right);
8425 static void semantic_sub(binary_expression_t *expression)
8427 expression_t *const left = expression->left;
8428 expression_t *const right = expression->right;
8429 type_t *const orig_type_left = left->base.type;
8430 type_t *const orig_type_right = right->base.type;
8431 type_t *const type_left = skip_typeref(orig_type_left);
8432 type_t *const type_right = skip_typeref(orig_type_right);
8433 source_position_t const *const pos = &expression->base.source_position;
8436 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8437 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8438 expression->left = create_implicit_cast(left, arithmetic_type);
8439 expression->right = create_implicit_cast(right, arithmetic_type);
8440 expression->base.type = arithmetic_type;
8441 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8442 check_pointer_arithmetic(&expression->base.source_position,
8443 type_left, orig_type_left);
8444 expression->base.type = type_left;
8445 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8446 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8447 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8448 if (!types_compatible(unqual_left, unqual_right)) {
8450 "subtracting pointers to incompatible types '%T' and '%T'",
8451 orig_type_left, orig_type_right);
8452 } else if (!is_type_object(unqual_left)) {
8453 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8454 errorf(pos, "subtracting pointers to non-object types '%T'",
8456 } else if (warning.other) {
8457 warningf(pos, "subtracting pointers to void");
8460 expression->base.type = type_ptrdiff_t;
8461 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8462 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8463 orig_type_left, orig_type_right);
8467 static void warn_string_literal_address(expression_t const* expr)
8469 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8470 expr = expr->unary.value;
8471 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8473 expr = expr->unary.value;
8476 if (expr->kind == EXPR_STRING_LITERAL
8477 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8478 warningf(&expr->base.source_position,
8479 "comparison with string literal results in unspecified behaviour");
8483 static void warn_comparison_in_comparison(const expression_t *const expr)
8485 if (expr->base.parenthesized)
8487 switch (expr->base.kind) {
8488 case EXPR_BINARY_LESS:
8489 case EXPR_BINARY_GREATER:
8490 case EXPR_BINARY_LESSEQUAL:
8491 case EXPR_BINARY_GREATEREQUAL:
8492 case EXPR_BINARY_NOTEQUAL:
8493 case EXPR_BINARY_EQUAL:
8494 warningf(&expr->base.source_position,
8495 "comparisons like 'x <= y < z' do not have their mathematical meaning");
8502 static bool maybe_negative(expression_t const *const expr)
8504 switch (is_constant_expression(expr)) {
8505 case EXPR_CLASS_ERROR: return false;
8506 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8507 default: return true;
8512 * Check the semantics of comparison expressions.
8514 * @param expression The expression to check.
8516 static void semantic_comparison(binary_expression_t *expression)
8518 expression_t *left = expression->left;
8519 expression_t *right = expression->right;
8521 if (warning.address) {
8522 warn_string_literal_address(left);
8523 warn_string_literal_address(right);
8525 expression_t const* const func_left = get_reference_address(left);
8526 if (func_left != NULL && is_null_pointer_constant(right)) {
8527 warningf(&expression->base.source_position,
8528 "the address of '%Y' will never be NULL",
8529 func_left->reference.entity->base.symbol);
8532 expression_t const* const func_right = get_reference_address(right);
8533 if (func_right != NULL && is_null_pointer_constant(right)) {
8534 warningf(&expression->base.source_position,
8535 "the address of '%Y' will never be NULL",
8536 func_right->reference.entity->base.symbol);
8540 if (warning.parentheses) {
8541 warn_comparison_in_comparison(left);
8542 warn_comparison_in_comparison(right);
8545 type_t *orig_type_left = left->base.type;
8546 type_t *orig_type_right = right->base.type;
8547 type_t *type_left = skip_typeref(orig_type_left);
8548 type_t *type_right = skip_typeref(orig_type_right);
8550 /* TODO non-arithmetic types */
8551 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8552 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8554 /* test for signed vs unsigned compares */
8555 if (warning.sign_compare && is_type_integer(arithmetic_type)) {
8556 bool const signed_left = is_type_signed(type_left);
8557 bool const signed_right = is_type_signed(type_right);
8558 if (signed_left != signed_right) {
8559 /* FIXME long long needs better const folding magic */
8560 /* TODO check whether constant value can be represented by other type */
8561 if ((signed_left && maybe_negative(left)) ||
8562 (signed_right && maybe_negative(right))) {
8563 warningf(&expression->base.source_position,
8564 "comparison between signed and unsigned");
8569 expression->left = create_implicit_cast(left, arithmetic_type);
8570 expression->right = create_implicit_cast(right, arithmetic_type);
8571 expression->base.type = arithmetic_type;
8572 if (warning.float_equal &&
8573 (expression->base.kind == EXPR_BINARY_EQUAL ||
8574 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8575 is_type_float(arithmetic_type)) {
8576 warningf(&expression->base.source_position,
8577 "comparing floating point with == or != is unsafe");
8579 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8580 /* TODO check compatibility */
8581 } else if (is_type_pointer(type_left)) {
8582 expression->right = create_implicit_cast(right, type_left);
8583 } else if (is_type_pointer(type_right)) {
8584 expression->left = create_implicit_cast(left, type_right);
8585 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8586 type_error_incompatible("invalid operands in comparison",
8587 &expression->base.source_position,
8588 type_left, type_right);
8590 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8594 * Checks if a compound type has constant fields.
8596 static bool has_const_fields(const compound_type_t *type)
8598 compound_t *compound = type->compound;
8599 entity_t *entry = compound->members.entities;
8601 for (; entry != NULL; entry = entry->base.next) {
8602 if (!is_declaration(entry))
8605 const type_t *decl_type = skip_typeref(entry->declaration.type);
8606 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8613 static bool is_valid_assignment_lhs(expression_t const* const left)
8615 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8616 type_t *const type_left = skip_typeref(orig_type_left);
8618 if (!is_lvalue(left)) {
8619 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8624 if (left->kind == EXPR_REFERENCE
8625 && left->reference.entity->kind == ENTITY_FUNCTION) {
8626 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8630 if (is_type_array(type_left)) {
8631 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8634 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8635 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8639 if (is_type_incomplete(type_left)) {
8640 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8641 left, orig_type_left);
8644 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8645 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8646 left, orig_type_left);
8653 static void semantic_arithmetic_assign(binary_expression_t *expression)
8655 expression_t *left = expression->left;
8656 expression_t *right = expression->right;
8657 type_t *orig_type_left = left->base.type;
8658 type_t *orig_type_right = right->base.type;
8660 if (!is_valid_assignment_lhs(left))
8663 type_t *type_left = skip_typeref(orig_type_left);
8664 type_t *type_right = skip_typeref(orig_type_right);
8666 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8667 /* TODO: improve error message */
8668 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8669 errorf(&expression->base.source_position,
8670 "operation needs arithmetic types");
8675 /* combined instructions are tricky. We can't create an implicit cast on
8676 * the left side, because we need the uncasted form for the store.
8677 * The ast2firm pass has to know that left_type must be right_type
8678 * for the arithmetic operation and create a cast by itself */
8679 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8680 expression->right = create_implicit_cast(right, arithmetic_type);
8681 expression->base.type = type_left;
8684 static void semantic_divmod_assign(binary_expression_t *expression)
8686 semantic_arithmetic_assign(expression);
8687 warn_div_by_zero(expression);
8690 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8692 expression_t *const left = expression->left;
8693 expression_t *const right = expression->right;
8694 type_t *const orig_type_left = left->base.type;
8695 type_t *const orig_type_right = right->base.type;
8696 type_t *const type_left = skip_typeref(orig_type_left);
8697 type_t *const type_right = skip_typeref(orig_type_right);
8699 if (!is_valid_assignment_lhs(left))
8702 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8703 /* combined instructions are tricky. We can't create an implicit cast on
8704 * the left side, because we need the uncasted form for the store.
8705 * The ast2firm pass has to know that left_type must be right_type
8706 * for the arithmetic operation and create a cast by itself */
8707 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8708 expression->right = create_implicit_cast(right, arithmetic_type);
8709 expression->base.type = type_left;
8710 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8711 check_pointer_arithmetic(&expression->base.source_position,
8712 type_left, orig_type_left);
8713 expression->base.type = type_left;
8714 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8715 errorf(&expression->base.source_position,
8716 "incompatible types '%T' and '%T' in assignment",
8717 orig_type_left, orig_type_right);
8721 static void semantic_integer_assign(binary_expression_t *expression)
8723 expression_t *left = expression->left;
8724 expression_t *right = expression->right;
8725 type_t *orig_type_left = left->base.type;
8726 type_t *orig_type_right = right->base.type;
8728 if (!is_valid_assignment_lhs(left))
8731 type_t *type_left = skip_typeref(orig_type_left);
8732 type_t *type_right = skip_typeref(orig_type_right);
8734 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8735 /* TODO: improve error message */
8736 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8737 errorf(&expression->base.source_position,
8738 "operation needs integer types");
8743 /* combined instructions are tricky. We can't create an implicit cast on
8744 * the left side, because we need the uncasted form for the store.
8745 * The ast2firm pass has to know that left_type must be right_type
8746 * for the arithmetic operation and create a cast by itself */
8747 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8748 expression->right = create_implicit_cast(right, arithmetic_type);
8749 expression->base.type = type_left;
8752 static void semantic_shift_assign(binary_expression_t *expression)
8754 expression_t *left = expression->left;
8756 if (!is_valid_assignment_lhs(left))
8759 if (!semantic_shift(expression))
8762 expression->base.type = skip_typeref(left->base.type);
8765 static void warn_logical_and_within_or(const expression_t *const expr)
8767 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8769 if (expr->base.parenthesized)
8771 warningf(&expr->base.source_position,
8772 "suggest parentheses around && within ||");
8776 * Check the semantic restrictions of a logical expression.
8778 static void semantic_logical_op(binary_expression_t *expression)
8780 /* §6.5.13:2 Each of the operands shall have scalar type.
8781 * §6.5.14:2 Each of the operands shall have scalar type. */
8782 semantic_condition(expression->left, "left operand of logical operator");
8783 semantic_condition(expression->right, "right operand of logical operator");
8784 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR &&
8785 warning.parentheses) {
8786 warn_logical_and_within_or(expression->left);
8787 warn_logical_and_within_or(expression->right);
8789 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8793 * Check the semantic restrictions of a binary assign expression.
8795 static void semantic_binexpr_assign(binary_expression_t *expression)
8797 expression_t *left = expression->left;
8798 type_t *orig_type_left = left->base.type;
8800 if (!is_valid_assignment_lhs(left))
8803 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8804 report_assign_error(error, orig_type_left, expression->right,
8805 "assignment", &left->base.source_position);
8806 expression->right = create_implicit_cast(expression->right, orig_type_left);
8807 expression->base.type = orig_type_left;
8811 * Determine if the outermost operation (or parts thereof) of the given
8812 * expression has no effect in order to generate a warning about this fact.
8813 * Therefore in some cases this only examines some of the operands of the
8814 * expression (see comments in the function and examples below).
8816 * f() + 23; // warning, because + has no effect
8817 * x || f(); // no warning, because x controls execution of f()
8818 * x ? y : f(); // warning, because y has no effect
8819 * (void)x; // no warning to be able to suppress the warning
8820 * This function can NOT be used for an "expression has definitely no effect"-
8822 static bool expression_has_effect(const expression_t *const expr)
8824 switch (expr->kind) {
8825 case EXPR_UNKNOWN: break;
8826 case EXPR_INVALID: return true; /* do NOT warn */
8827 case EXPR_REFERENCE: return false;
8828 case EXPR_REFERENCE_ENUM_VALUE: return false;
8829 case EXPR_LABEL_ADDRESS: return false;
8831 /* suppress the warning for microsoft __noop operations */
8832 case EXPR_LITERAL_MS_NOOP: return true;
8833 case EXPR_LITERAL_BOOLEAN:
8834 case EXPR_LITERAL_CHARACTER:
8835 case EXPR_LITERAL_WIDE_CHARACTER:
8836 case EXPR_LITERAL_INTEGER:
8837 case EXPR_LITERAL_INTEGER_OCTAL:
8838 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8839 case EXPR_LITERAL_FLOATINGPOINT:
8840 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8841 case EXPR_STRING_LITERAL: return false;
8842 case EXPR_WIDE_STRING_LITERAL: return false;
8845 const call_expression_t *const call = &expr->call;
8846 if (call->function->kind != EXPR_REFERENCE)
8849 switch (call->function->reference.entity->function.btk) {
8850 /* FIXME: which builtins have no effect? */
8851 default: return true;
8855 /* Generate the warning if either the left or right hand side of a
8856 * conditional expression has no effect */
8857 case EXPR_CONDITIONAL: {
8858 conditional_expression_t const *const cond = &expr->conditional;
8859 expression_t const *const t = cond->true_expression;
8861 (t == NULL || expression_has_effect(t)) &&
8862 expression_has_effect(cond->false_expression);
8865 case EXPR_SELECT: return false;
8866 case EXPR_ARRAY_ACCESS: return false;
8867 case EXPR_SIZEOF: return false;
8868 case EXPR_CLASSIFY_TYPE: return false;
8869 case EXPR_ALIGNOF: return false;
8871 case EXPR_FUNCNAME: return false;
8872 case EXPR_BUILTIN_CONSTANT_P: return false;
8873 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8874 case EXPR_OFFSETOF: return false;
8875 case EXPR_VA_START: return true;
8876 case EXPR_VA_ARG: return true;
8877 case EXPR_VA_COPY: return true;
8878 case EXPR_STATEMENT: return true; // TODO
8879 case EXPR_COMPOUND_LITERAL: return false;
8881 case EXPR_UNARY_NEGATE: return false;
8882 case EXPR_UNARY_PLUS: return false;
8883 case EXPR_UNARY_BITWISE_NEGATE: return false;
8884 case EXPR_UNARY_NOT: return false;
8885 case EXPR_UNARY_DEREFERENCE: return false;
8886 case EXPR_UNARY_TAKE_ADDRESS: return false;
8887 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8888 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8889 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8890 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8892 /* Treat void casts as if they have an effect in order to being able to
8893 * suppress the warning */
8894 case EXPR_UNARY_CAST: {
8895 type_t *const type = skip_typeref(expr->base.type);
8896 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8899 case EXPR_UNARY_CAST_IMPLICIT: return true;
8900 case EXPR_UNARY_ASSUME: return true;
8901 case EXPR_UNARY_DELETE: return true;
8902 case EXPR_UNARY_DELETE_ARRAY: return true;
8903 case EXPR_UNARY_THROW: return true;
8905 case EXPR_BINARY_ADD: return false;
8906 case EXPR_BINARY_SUB: return false;
8907 case EXPR_BINARY_MUL: return false;
8908 case EXPR_BINARY_DIV: return false;
8909 case EXPR_BINARY_MOD: return false;
8910 case EXPR_BINARY_EQUAL: return false;
8911 case EXPR_BINARY_NOTEQUAL: return false;
8912 case EXPR_BINARY_LESS: return false;
8913 case EXPR_BINARY_LESSEQUAL: return false;
8914 case EXPR_BINARY_GREATER: return false;
8915 case EXPR_BINARY_GREATEREQUAL: return false;
8916 case EXPR_BINARY_BITWISE_AND: return false;
8917 case EXPR_BINARY_BITWISE_OR: return false;
8918 case EXPR_BINARY_BITWISE_XOR: return false;
8919 case EXPR_BINARY_SHIFTLEFT: return false;
8920 case EXPR_BINARY_SHIFTRIGHT: return false;
8921 case EXPR_BINARY_ASSIGN: return true;
8922 case EXPR_BINARY_MUL_ASSIGN: return true;
8923 case EXPR_BINARY_DIV_ASSIGN: return true;
8924 case EXPR_BINARY_MOD_ASSIGN: return true;
8925 case EXPR_BINARY_ADD_ASSIGN: return true;
8926 case EXPR_BINARY_SUB_ASSIGN: return true;
8927 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8928 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8929 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8930 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8931 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8933 /* Only examine the right hand side of && and ||, because the left hand
8934 * side already has the effect of controlling the execution of the right
8936 case EXPR_BINARY_LOGICAL_AND:
8937 case EXPR_BINARY_LOGICAL_OR:
8938 /* Only examine the right hand side of a comma expression, because the left
8939 * hand side has a separate warning */
8940 case EXPR_BINARY_COMMA:
8941 return expression_has_effect(expr->binary.right);
8943 case EXPR_BINARY_ISGREATER: return false;
8944 case EXPR_BINARY_ISGREATEREQUAL: return false;
8945 case EXPR_BINARY_ISLESS: return false;
8946 case EXPR_BINARY_ISLESSEQUAL: return false;
8947 case EXPR_BINARY_ISLESSGREATER: return false;
8948 case EXPR_BINARY_ISUNORDERED: return false;
8951 internal_errorf(HERE, "unexpected expression");
8954 static void semantic_comma(binary_expression_t *expression)
8956 if (warning.unused_value) {
8957 const expression_t *const left = expression->left;
8958 if (!expression_has_effect(left)) {
8959 warningf(&left->base.source_position,
8960 "left-hand operand of comma expression has no effect");
8963 expression->base.type = expression->right->base.type;
8967 * @param prec_r precedence of the right operand
8969 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8970 static expression_t *parse_##binexpression_type(expression_t *left) \
8972 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8973 binexpr->binary.left = left; \
8976 expression_t *right = parse_subexpression(prec_r); \
8978 binexpr->binary.right = right; \
8979 sfunc(&binexpr->binary); \
8984 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8985 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8986 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8987 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8988 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8989 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8990 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8991 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8992 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8993 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8994 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8995 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8996 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8997 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8998 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8999 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
9000 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
9001 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
9002 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
9003 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9004 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
9005 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
9006 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9007 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
9008 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9009 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
9010 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9011 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9012 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
9013 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
9016 static expression_t *parse_subexpression(precedence_t precedence)
9018 if (token.type < 0) {
9019 return expected_expression_error();
9022 expression_parser_function_t *parser
9023 = &expression_parsers[token.type];
9024 source_position_t source_position = token.source_position;
9027 if (parser->parser != NULL) {
9028 left = parser->parser();
9030 left = parse_primary_expression();
9032 assert(left != NULL);
9033 left->base.source_position = source_position;
9036 if (token.type < 0) {
9037 return expected_expression_error();
9040 parser = &expression_parsers[token.type];
9041 if (parser->infix_parser == NULL)
9043 if (parser->infix_precedence < precedence)
9046 left = parser->infix_parser(left);
9048 assert(left != NULL);
9049 assert(left->kind != EXPR_UNKNOWN);
9050 left->base.source_position = source_position;
9057 * Parse an expression.
9059 static expression_t *parse_expression(void)
9061 return parse_subexpression(PREC_EXPRESSION);
9065 * Register a parser for a prefix-like operator.
9067 * @param parser the parser function
9068 * @param token_type the token type of the prefix token
9070 static void register_expression_parser(parse_expression_function parser,
9073 expression_parser_function_t *entry = &expression_parsers[token_type];
9075 if (entry->parser != NULL) {
9076 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9077 panic("trying to register multiple expression parsers for a token");
9079 entry->parser = parser;
9083 * Register a parser for an infix operator with given precedence.
9085 * @param parser the parser function
9086 * @param token_type the token type of the infix operator
9087 * @param precedence the precedence of the operator
9089 static void register_infix_parser(parse_expression_infix_function parser,
9090 int token_type, precedence_t precedence)
9092 expression_parser_function_t *entry = &expression_parsers[token_type];
9094 if (entry->infix_parser != NULL) {
9095 diagnosticf("for token '%k'\n", (token_type_t)token_type);
9096 panic("trying to register multiple infix expression parsers for a "
9099 entry->infix_parser = parser;
9100 entry->infix_precedence = precedence;
9104 * Initialize the expression parsers.
9106 static void init_expression_parsers(void)
9108 memset(&expression_parsers, 0, sizeof(expression_parsers));
9110 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
9111 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
9112 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
9113 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
9114 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
9115 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
9116 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
9117 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
9118 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
9119 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
9120 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
9121 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
9122 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
9123 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
9124 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
9125 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
9126 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
9127 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
9128 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
9129 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
9130 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
9131 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
9132 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
9133 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
9134 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
9135 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
9136 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
9137 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
9138 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
9139 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
9140 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
9141 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
9142 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
9143 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
9144 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
9145 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
9146 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
9148 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
9149 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
9150 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
9151 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
9152 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
9153 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
9154 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
9155 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
9156 register_expression_parser(parse_sizeof, T_sizeof);
9157 register_expression_parser(parse_alignof, T___alignof__);
9158 register_expression_parser(parse_extension, T___extension__);
9159 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
9160 register_expression_parser(parse_delete, T_delete);
9161 register_expression_parser(parse_throw, T_throw);
9165 * Parse a asm statement arguments specification.
9167 static asm_argument_t *parse_asm_arguments(bool is_out)
9169 asm_argument_t *result = NULL;
9170 asm_argument_t **anchor = &result;
9172 while (token.type == T_STRING_LITERAL || token.type == '[') {
9173 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
9174 memset(argument, 0, sizeof(argument[0]));
9177 if (token.type != T_IDENTIFIER) {
9178 parse_error_expected("while parsing asm argument",
9179 T_IDENTIFIER, NULL);
9182 argument->symbol = token.symbol;
9184 expect(']', end_error);
9187 argument->constraints = parse_string_literals();
9188 expect('(', end_error);
9189 add_anchor_token(')');
9190 expression_t *expression = parse_expression();
9191 rem_anchor_token(')');
9193 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
9194 * change size or type representation (e.g. int -> long is ok, but
9195 * int -> float is not) */
9196 if (expression->kind == EXPR_UNARY_CAST) {
9197 type_t *const type = expression->base.type;
9198 type_kind_t const kind = type->kind;
9199 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
9202 if (kind == TYPE_ATOMIC) {
9203 atomic_type_kind_t const akind = type->atomic.akind;
9204 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9205 size = get_atomic_type_size(akind);
9207 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9208 size = get_atomic_type_size(get_intptr_kind());
9212 expression_t *const value = expression->unary.value;
9213 type_t *const value_type = value->base.type;
9214 type_kind_t const value_kind = value_type->kind;
9216 unsigned value_flags;
9217 unsigned value_size;
9218 if (value_kind == TYPE_ATOMIC) {
9219 atomic_type_kind_t const value_akind = value_type->atomic.akind;
9220 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
9221 value_size = get_atomic_type_size(value_akind);
9222 } else if (value_kind == TYPE_POINTER) {
9223 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
9224 value_size = get_atomic_type_size(get_intptr_kind());
9229 if (value_flags != flags || value_size != size)
9233 } while (expression->kind == EXPR_UNARY_CAST);
9237 if (!is_lvalue(expression)) {
9238 errorf(&expression->base.source_position,
9239 "asm output argument is not an lvalue");
9242 if (argument->constraints.begin[0] == '=')
9243 determine_lhs_ent(expression, NULL);
9245 mark_vars_read(expression, NULL);
9247 mark_vars_read(expression, NULL);
9249 argument->expression = expression;
9250 expect(')', end_error);
9252 set_address_taken(expression, true);
9255 anchor = &argument->next;
9267 * Parse a asm statement clobber specification.
9269 static asm_clobber_t *parse_asm_clobbers(void)
9271 asm_clobber_t *result = NULL;
9272 asm_clobber_t **anchor = &result;
9274 while (token.type == T_STRING_LITERAL) {
9275 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9276 clobber->clobber = parse_string_literals();
9279 anchor = &clobber->next;
9289 * Parse an asm statement.
9291 static statement_t *parse_asm_statement(void)
9293 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9294 asm_statement_t *asm_statement = &statement->asms;
9298 if (next_if(T_volatile))
9299 asm_statement->is_volatile = true;
9301 expect('(', end_error);
9302 add_anchor_token(')');
9303 if (token.type != T_STRING_LITERAL) {
9304 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9307 asm_statement->asm_text = parse_string_literals();
9309 add_anchor_token(':');
9310 if (!next_if(':')) {
9311 rem_anchor_token(':');
9315 asm_statement->outputs = parse_asm_arguments(true);
9316 if (!next_if(':')) {
9317 rem_anchor_token(':');
9321 asm_statement->inputs = parse_asm_arguments(false);
9322 if (!next_if(':')) {
9323 rem_anchor_token(':');
9326 rem_anchor_token(':');
9328 asm_statement->clobbers = parse_asm_clobbers();
9331 rem_anchor_token(')');
9332 expect(')', end_error);
9333 expect(';', end_error);
9335 if (asm_statement->outputs == NULL) {
9336 /* GCC: An 'asm' instruction without any output operands will be treated
9337 * identically to a volatile 'asm' instruction. */
9338 asm_statement->is_volatile = true;
9343 return create_invalid_statement();
9346 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9348 statement_t *inner_stmt;
9349 switch (token.type) {
9351 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9352 inner_stmt = create_invalid_statement();
9356 if (label->kind == STATEMENT_LABEL) {
9357 /* Eat an empty statement here, to avoid the warning about an empty
9358 * statement after a label. label:; is commonly used to have a label
9359 * before a closing brace. */
9360 inner_stmt = create_empty_statement();
9367 inner_stmt = parse_statement();
9368 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9369 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9370 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9378 * Parse a case statement.
9380 static statement_t *parse_case_statement(void)
9382 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9383 source_position_t *const pos = &statement->base.source_position;
9387 expression_t *const expression = parse_expression();
9388 statement->case_label.expression = expression;
9389 expression_classification_t const expr_class = is_constant_expression(expression);
9390 if (expr_class != EXPR_CLASS_CONSTANT) {
9391 if (expr_class != EXPR_CLASS_ERROR) {
9392 errorf(pos, "case label does not reduce to an integer constant");
9394 statement->case_label.is_bad = true;
9396 long const val = fold_constant_to_int(expression);
9397 statement->case_label.first_case = val;
9398 statement->case_label.last_case = val;
9402 if (next_if(T_DOTDOTDOT)) {
9403 expression_t *const end_range = parse_expression();
9404 statement->case_label.end_range = end_range;
9405 expression_classification_t const end_class = is_constant_expression(end_range);
9406 if (end_class != EXPR_CLASS_CONSTANT) {
9407 if (end_class != EXPR_CLASS_ERROR) {
9408 errorf(pos, "case range does not reduce to an integer constant");
9410 statement->case_label.is_bad = true;
9412 long const val = fold_constant_to_int(end_range);
9413 statement->case_label.last_case = val;
9415 if (warning.other && val < statement->case_label.first_case) {
9416 statement->case_label.is_empty_range = true;
9417 warningf(pos, "empty range specified");
9423 PUSH_PARENT(statement);
9425 expect(':', end_error);
9428 if (current_switch != NULL) {
9429 if (! statement->case_label.is_bad) {
9430 /* Check for duplicate case values */
9431 case_label_statement_t *c = &statement->case_label;
9432 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9433 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9436 if (c->last_case < l->first_case || c->first_case > l->last_case)
9439 errorf(pos, "duplicate case value (previously used %P)",
9440 &l->base.source_position);
9444 /* link all cases into the switch statement */
9445 if (current_switch->last_case == NULL) {
9446 current_switch->first_case = &statement->case_label;
9448 current_switch->last_case->next = &statement->case_label;
9450 current_switch->last_case = &statement->case_label;
9452 errorf(pos, "case label not within a switch statement");
9455 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9462 * Parse a default statement.
9464 static statement_t *parse_default_statement(void)
9466 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9470 PUSH_PARENT(statement);
9472 expect(':', end_error);
9475 if (current_switch != NULL) {
9476 const case_label_statement_t *def_label = current_switch->default_label;
9477 if (def_label != NULL) {
9478 errorf(HERE, "multiple default labels in one switch (previous declared %P)",
9479 &def_label->base.source_position);
9481 current_switch->default_label = &statement->case_label;
9483 /* link all cases into the switch statement */
9484 if (current_switch->last_case == NULL) {
9485 current_switch->first_case = &statement->case_label;
9487 current_switch->last_case->next = &statement->case_label;
9489 current_switch->last_case = &statement->case_label;
9492 errorf(&statement->base.source_position,
9493 "'default' label not within a switch statement");
9496 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9503 * Parse a label statement.
9505 static statement_t *parse_label_statement(void)
9507 assert(token.type == T_IDENTIFIER);
9508 symbol_t *symbol = token.symbol;
9509 label_t *label = get_label(symbol);
9511 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9512 statement->label.label = label;
9516 PUSH_PARENT(statement);
9518 /* if statement is already set then the label is defined twice,
9519 * otherwise it was just mentioned in a goto/local label declaration so far
9521 if (label->statement != NULL) {
9522 errorf(HERE, "duplicate label '%Y' (declared %P)",
9523 symbol, &label->base.source_position);
9525 label->base.source_position = token.source_position;
9526 label->statement = statement;
9531 statement->label.statement = parse_label_inner_statement(statement, "label");
9533 /* remember the labels in a list for later checking */
9534 *label_anchor = &statement->label;
9535 label_anchor = &statement->label.next;
9542 * Parse an if statement.
9544 static statement_t *parse_if(void)
9546 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9550 PUSH_PARENT(statement);
9552 add_anchor_token('{');
9554 expect('(', end_error);
9555 add_anchor_token(')');
9556 expression_t *const expr = parse_expression();
9557 statement->ifs.condition = expr;
9558 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9560 semantic_condition(expr, "condition of 'if'-statment");
9561 mark_vars_read(expr, NULL);
9562 rem_anchor_token(')');
9563 expect(')', end_error);
9566 rem_anchor_token('{');
9568 add_anchor_token(T_else);
9569 statement_t *const true_stmt = parse_statement();
9570 statement->ifs.true_statement = true_stmt;
9571 rem_anchor_token(T_else);
9573 if (next_if(T_else)) {
9574 statement->ifs.false_statement = parse_statement();
9575 } else if (warning.parentheses &&
9576 true_stmt->kind == STATEMENT_IF &&
9577 true_stmt->ifs.false_statement != NULL) {
9578 warningf(&true_stmt->base.source_position,
9579 "suggest explicit braces to avoid ambiguous 'else'");
9587 * Check that all enums are handled in a switch.
9589 * @param statement the switch statement to check
9591 static void check_enum_cases(const switch_statement_t *statement)
9593 const type_t *type = skip_typeref(statement->expression->base.type);
9594 if (! is_type_enum(type))
9596 const enum_type_t *enumt = &type->enumt;
9598 /* if we have a default, no warnings */
9599 if (statement->default_label != NULL)
9602 /* FIXME: calculation of value should be done while parsing */
9603 /* TODO: quadratic algorithm here. Change to an n log n one */
9604 long last_value = -1;
9605 const entity_t *entry = enumt->enume->base.next;
9606 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9607 entry = entry->base.next) {
9608 const expression_t *expression = entry->enum_value.value;
9609 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9611 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9612 if (l->expression == NULL)
9614 if (l->first_case <= value && value <= l->last_case) {
9620 warningf(&statement->base.source_position,
9621 "enumeration value '%Y' not handled in switch",
9622 entry->base.symbol);
9629 * Parse a switch statement.
9631 static statement_t *parse_switch(void)
9633 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9637 PUSH_PARENT(statement);
9639 expect('(', end_error);
9640 add_anchor_token(')');
9641 expression_t *const expr = parse_expression();
9642 mark_vars_read(expr, NULL);
9643 type_t * type = skip_typeref(expr->base.type);
9644 if (is_type_integer(type)) {
9645 type = promote_integer(type);
9646 if (warning.traditional) {
9647 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9648 warningf(&expr->base.source_position,
9649 "'%T' switch expression not converted to '%T' in ISO C",
9653 } else if (is_type_valid(type)) {
9654 errorf(&expr->base.source_position,
9655 "switch quantity is not an integer, but '%T'", type);
9656 type = type_error_type;
9658 statement->switchs.expression = create_implicit_cast(expr, type);
9659 expect(')', end_error);
9660 rem_anchor_token(')');
9662 switch_statement_t *rem = current_switch;
9663 current_switch = &statement->switchs;
9664 statement->switchs.body = parse_statement();
9665 current_switch = rem;
9667 if (warning.switch_default &&
9668 statement->switchs.default_label == NULL) {
9669 warningf(&statement->base.source_position, "switch has no default case");
9671 if (warning.switch_enum)
9672 check_enum_cases(&statement->switchs);
9678 return create_invalid_statement();
9681 static statement_t *parse_loop_body(statement_t *const loop)
9683 statement_t *const rem = current_loop;
9684 current_loop = loop;
9686 statement_t *const body = parse_statement();
9693 * Parse a while statement.
9695 static statement_t *parse_while(void)
9697 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9701 PUSH_PARENT(statement);
9703 expect('(', end_error);
9704 add_anchor_token(')');
9705 expression_t *const cond = parse_expression();
9706 statement->whiles.condition = cond;
9707 /* §6.8.5:2 The controlling expression of an iteration statement shall
9708 * have scalar type. */
9709 semantic_condition(cond, "condition of 'while'-statement");
9710 mark_vars_read(cond, NULL);
9711 rem_anchor_token(')');
9712 expect(')', end_error);
9714 statement->whiles.body = parse_loop_body(statement);
9720 return create_invalid_statement();
9724 * Parse a do statement.
9726 static statement_t *parse_do(void)
9728 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9732 PUSH_PARENT(statement);
9734 add_anchor_token(T_while);
9735 statement->do_while.body = parse_loop_body(statement);
9736 rem_anchor_token(T_while);
9738 expect(T_while, end_error);
9739 expect('(', end_error);
9740 add_anchor_token(')');
9741 expression_t *const cond = parse_expression();
9742 statement->do_while.condition = cond;
9743 /* §6.8.5:2 The controlling expression of an iteration statement shall
9744 * have scalar type. */
9745 semantic_condition(cond, "condition of 'do-while'-statement");
9746 mark_vars_read(cond, NULL);
9747 rem_anchor_token(')');
9748 expect(')', end_error);
9749 expect(';', end_error);
9755 return create_invalid_statement();
9759 * Parse a for statement.
9761 static statement_t *parse_for(void)
9763 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9767 expect('(', end_error1);
9768 add_anchor_token(')');
9770 PUSH_PARENT(statement);
9772 size_t const top = environment_top();
9773 scope_t *old_scope = scope_push(&statement->fors.scope);
9775 bool old_gcc_extension = in_gcc_extension;
9776 while (next_if(T___extension__)) {
9777 in_gcc_extension = true;
9781 } else if (is_declaration_specifier(&token, false)) {
9782 parse_declaration(record_entity, DECL_FLAGS_NONE);
9784 add_anchor_token(';');
9785 expression_t *const init = parse_expression();
9786 statement->fors.initialisation = init;
9787 mark_vars_read(init, ENT_ANY);
9788 if (warning.unused_value && !expression_has_effect(init)) {
9789 warningf(&init->base.source_position,
9790 "initialisation of 'for'-statement has no effect");
9792 rem_anchor_token(';');
9793 expect(';', end_error2);
9795 in_gcc_extension = old_gcc_extension;
9797 if (token.type != ';') {
9798 add_anchor_token(';');
9799 expression_t *const cond = parse_expression();
9800 statement->fors.condition = cond;
9801 /* §6.8.5:2 The controlling expression of an iteration statement
9802 * shall have scalar type. */
9803 semantic_condition(cond, "condition of 'for'-statement");
9804 mark_vars_read(cond, NULL);
9805 rem_anchor_token(';');
9807 expect(';', end_error2);
9808 if (token.type != ')') {
9809 expression_t *const step = parse_expression();
9810 statement->fors.step = step;
9811 mark_vars_read(step, ENT_ANY);
9812 if (warning.unused_value && !expression_has_effect(step)) {
9813 warningf(&step->base.source_position,
9814 "step of 'for'-statement has no effect");
9817 expect(')', end_error2);
9818 rem_anchor_token(')');
9819 statement->fors.body = parse_loop_body(statement);
9821 assert(current_scope == &statement->fors.scope);
9822 scope_pop(old_scope);
9823 environment_pop_to(top);
9830 rem_anchor_token(')');
9831 assert(current_scope == &statement->fors.scope);
9832 scope_pop(old_scope);
9833 environment_pop_to(top);
9837 return create_invalid_statement();
9841 * Parse a goto statement.
9843 static statement_t *parse_goto(void)
9845 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9848 if (GNU_MODE && next_if('*')) {
9849 expression_t *expression = parse_expression();
9850 mark_vars_read(expression, NULL);
9852 /* Argh: although documentation says the expression must be of type void*,
9853 * gcc accepts anything that can be casted into void* without error */
9854 type_t *type = expression->base.type;
9856 if (type != type_error_type) {
9857 if (!is_type_pointer(type) && !is_type_integer(type)) {
9858 errorf(&expression->base.source_position,
9859 "cannot convert to a pointer type");
9860 } else if (warning.other && type != type_void_ptr) {
9861 warningf(&expression->base.source_position,
9862 "type of computed goto expression should be 'void*' not '%T'", type);
9864 expression = create_implicit_cast(expression, type_void_ptr);
9867 statement->gotos.expression = expression;
9868 } else if (token.type == T_IDENTIFIER) {
9869 symbol_t *symbol = token.symbol;
9871 statement->gotos.label = get_label(symbol);
9874 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9876 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9878 return create_invalid_statement();
9881 /* remember the goto's in a list for later checking */
9882 *goto_anchor = &statement->gotos;
9883 goto_anchor = &statement->gotos.next;
9885 expect(';', end_error);
9892 * Parse a continue statement.
9894 static statement_t *parse_continue(void)
9896 if (current_loop == NULL) {
9897 errorf(HERE, "continue statement not within loop");
9900 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9903 expect(';', end_error);
9910 * Parse a break statement.
9912 static statement_t *parse_break(void)
9914 if (current_switch == NULL && current_loop == NULL) {
9915 errorf(HERE, "break statement not within loop or switch");
9918 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9921 expect(';', end_error);
9928 * Parse a __leave statement.
9930 static statement_t *parse_leave_statement(void)
9932 if (current_try == NULL) {
9933 errorf(HERE, "__leave statement not within __try");
9936 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9939 expect(';', end_error);
9946 * Check if a given entity represents a local variable.
9948 static bool is_local_variable(const entity_t *entity)
9950 if (entity->kind != ENTITY_VARIABLE)
9953 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9954 case STORAGE_CLASS_AUTO:
9955 case STORAGE_CLASS_REGISTER: {
9956 const type_t *type = skip_typeref(entity->declaration.type);
9957 if (is_type_function(type)) {
9969 * Check if a given expression represents a local variable.
9971 static bool expression_is_local_variable(const expression_t *expression)
9973 if (expression->base.kind != EXPR_REFERENCE) {
9976 const entity_t *entity = expression->reference.entity;
9977 return is_local_variable(entity);
9981 * Check if a given expression represents a local variable and
9982 * return its declaration then, else return NULL.
9984 entity_t *expression_is_variable(const expression_t *expression)
9986 if (expression->base.kind != EXPR_REFERENCE) {
9989 entity_t *entity = expression->reference.entity;
9990 if (entity->kind != ENTITY_VARIABLE)
9997 * Parse a return statement.
9999 static statement_t *parse_return(void)
10003 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
10005 expression_t *return_value = NULL;
10006 if (token.type != ';') {
10007 return_value = parse_expression();
10008 mark_vars_read(return_value, NULL);
10011 const type_t *const func_type = skip_typeref(current_function->base.type);
10012 assert(is_type_function(func_type));
10013 type_t *const return_type = skip_typeref(func_type->function.return_type);
10015 source_position_t const *const pos = &statement->base.source_position;
10016 if (return_value != NULL) {
10017 type_t *return_value_type = skip_typeref(return_value->base.type);
10019 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10020 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
10021 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
10022 /* Only warn in C mode, because GCC does the same */
10023 if (c_mode & _CXX || strict_mode) {
10025 "'return' with a value, in function returning 'void'");
10026 } else if (warning.other) {
10028 "'return' with a value, in function returning 'void'");
10030 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10031 /* Only warn in C mode, because GCC does the same */
10034 "'return' with expression in function returning 'void'");
10035 } else if (warning.other) {
10037 "'return' with expression in function returning 'void'");
10041 assign_error_t error = semantic_assign(return_type, return_value);
10042 report_assign_error(error, return_type, return_value, "'return'",
10045 return_value = create_implicit_cast(return_value, return_type);
10046 /* check for returning address of a local var */
10047 if (warning.other && return_value != NULL
10048 && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
10049 const expression_t *expression = return_value->unary.value;
10050 if (expression_is_local_variable(expression)) {
10051 warningf(pos, "function returns address of local variable");
10054 } else if (warning.other && !is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
10055 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
10056 if (c_mode & _CXX || strict_mode) {
10058 "'return' without value, in function returning non-void");
10061 "'return' without value, in function returning non-void");
10064 statement->returns.value = return_value;
10066 expect(';', end_error);
10073 * Parse a declaration statement.
10075 static statement_t *parse_declaration_statement(void)
10077 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10079 entity_t *before = current_scope->last_entity;
10081 parse_external_declaration();
10083 parse_declaration(record_entity, DECL_FLAGS_NONE);
10086 declaration_statement_t *const decl = &statement->declaration;
10087 entity_t *const begin =
10088 before != NULL ? before->base.next : current_scope->entities;
10089 decl->declarations_begin = begin;
10090 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
10096 * Parse an expression statement, ie. expr ';'.
10098 static statement_t *parse_expression_statement(void)
10100 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10102 expression_t *const expr = parse_expression();
10103 statement->expression.expression = expr;
10104 mark_vars_read(expr, ENT_ANY);
10106 expect(';', end_error);
10113 * Parse a microsoft __try { } __finally { } or
10114 * __try{ } __except() { }
10116 static statement_t *parse_ms_try_statment(void)
10118 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
10121 PUSH_PARENT(statement);
10123 ms_try_statement_t *rem = current_try;
10124 current_try = &statement->ms_try;
10125 statement->ms_try.try_statement = parse_compound_statement(false);
10130 if (next_if(T___except)) {
10131 expect('(', end_error);
10132 add_anchor_token(')');
10133 expression_t *const expr = parse_expression();
10134 mark_vars_read(expr, NULL);
10135 type_t * type = skip_typeref(expr->base.type);
10136 if (is_type_integer(type)) {
10137 type = promote_integer(type);
10138 } else if (is_type_valid(type)) {
10139 errorf(&expr->base.source_position,
10140 "__expect expression is not an integer, but '%T'", type);
10141 type = type_error_type;
10143 statement->ms_try.except_expression = create_implicit_cast(expr, type);
10144 rem_anchor_token(')');
10145 expect(')', end_error);
10146 statement->ms_try.final_statement = parse_compound_statement(false);
10147 } else if (next_if(T__finally)) {
10148 statement->ms_try.final_statement = parse_compound_statement(false);
10150 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
10151 return create_invalid_statement();
10155 return create_invalid_statement();
10158 static statement_t *parse_empty_statement(void)
10160 if (warning.empty_statement) {
10161 warningf(HERE, "statement is empty");
10163 statement_t *const statement = create_empty_statement();
10168 static statement_t *parse_local_label_declaration(void)
10170 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
10174 entity_t *begin = NULL;
10175 entity_t *end = NULL;
10176 entity_t **anchor = &begin;
10178 if (token.type != T_IDENTIFIER) {
10179 parse_error_expected("while parsing local label declaration",
10180 T_IDENTIFIER, NULL);
10183 symbol_t *symbol = token.symbol;
10184 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
10185 if (entity != NULL && entity->base.parent_scope == current_scope) {
10186 errorf(HERE, "multiple definitions of '__label__ %Y' (previous definition %P)",
10187 symbol, &entity->base.source_position);
10189 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL);
10191 entity->base.parent_scope = current_scope;
10192 entity->base.namespc = NAMESPACE_LABEL;
10193 entity->base.source_position = token.source_position;
10194 entity->base.symbol = symbol;
10197 anchor = &entity->base.next;
10200 environment_push(entity);
10203 } while (next_if(','));
10204 expect(';', end_error);
10206 statement->declaration.declarations_begin = begin;
10207 statement->declaration.declarations_end = end;
10211 static void parse_namespace_definition(void)
10215 entity_t *entity = NULL;
10216 symbol_t *symbol = NULL;
10218 if (token.type == T_IDENTIFIER) {
10219 symbol = token.symbol;
10222 entity = get_entity(symbol, NAMESPACE_NORMAL);
10224 && entity->kind != ENTITY_NAMESPACE
10225 && entity->base.parent_scope == current_scope) {
10226 if (is_entity_valid(entity)) {
10227 error_redefined_as_different_kind(&token.source_position,
10228 entity, ENTITY_NAMESPACE);
10234 if (entity == NULL) {
10235 entity = allocate_entity_zero(ENTITY_NAMESPACE);
10236 entity->base.symbol = symbol;
10237 entity->base.source_position = token.source_position;
10238 entity->base.namespc = NAMESPACE_NORMAL;
10239 entity->base.parent_scope = current_scope;
10242 if (token.type == '=') {
10243 /* TODO: parse namespace alias */
10244 panic("namespace alias definition not supported yet");
10247 environment_push(entity);
10248 append_entity(current_scope, entity);
10250 size_t const top = environment_top();
10251 scope_t *old_scope = scope_push(&entity->namespacee.members);
10253 entity_t *old_current_entity = current_entity;
10254 current_entity = entity;
10256 expect('{', end_error);
10258 expect('}', end_error);
10261 assert(current_scope == &entity->namespacee.members);
10262 assert(current_entity == entity);
10263 current_entity = old_current_entity;
10264 scope_pop(old_scope);
10265 environment_pop_to(top);
10269 * Parse a statement.
10270 * There's also parse_statement() which additionally checks for
10271 * "statement has no effect" warnings
10273 static statement_t *intern_parse_statement(void)
10275 statement_t *statement = NULL;
10277 /* declaration or statement */
10278 add_anchor_token(';');
10279 switch (token.type) {
10280 case T_IDENTIFIER: {
10281 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
10282 if (la1_type == ':') {
10283 statement = parse_label_statement();
10284 } else if (is_typedef_symbol(token.symbol)) {
10285 statement = parse_declaration_statement();
10287 /* it's an identifier, the grammar says this must be an
10288 * expression statement. However it is common that users mistype
10289 * declaration types, so we guess a bit here to improve robustness
10290 * for incorrect programs */
10291 switch (la1_type) {
10294 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10296 statement = parse_expression_statement();
10300 statement = parse_declaration_statement();
10308 case T___extension__:
10309 /* This can be a prefix to a declaration or an expression statement.
10310 * We simply eat it now and parse the rest with tail recursion. */
10311 while (next_if(T___extension__)) {}
10312 bool old_gcc_extension = in_gcc_extension;
10313 in_gcc_extension = true;
10314 statement = intern_parse_statement();
10315 in_gcc_extension = old_gcc_extension;
10319 statement = parse_declaration_statement();
10323 statement = parse_local_label_declaration();
10326 case ';': statement = parse_empty_statement(); break;
10327 case '{': statement = parse_compound_statement(false); break;
10328 case T___leave: statement = parse_leave_statement(); break;
10329 case T___try: statement = parse_ms_try_statment(); break;
10330 case T_asm: statement = parse_asm_statement(); break;
10331 case T_break: statement = parse_break(); break;
10332 case T_case: statement = parse_case_statement(); break;
10333 case T_continue: statement = parse_continue(); break;
10334 case T_default: statement = parse_default_statement(); break;
10335 case T_do: statement = parse_do(); break;
10336 case T_for: statement = parse_for(); break;
10337 case T_goto: statement = parse_goto(); break;
10338 case T_if: statement = parse_if(); break;
10339 case T_return: statement = parse_return(); break;
10340 case T_switch: statement = parse_switch(); break;
10341 case T_while: statement = parse_while(); break;
10344 statement = parse_expression_statement();
10348 errorf(HERE, "unexpected token %K while parsing statement", &token);
10349 statement = create_invalid_statement();
10354 rem_anchor_token(';');
10356 assert(statement != NULL
10357 && statement->base.source_position.input_name != NULL);
10363 * parse a statement and emits "statement has no effect" warning if needed
10364 * (This is really a wrapper around intern_parse_statement with check for 1
10365 * single warning. It is needed, because for statement expressions we have
10366 * to avoid the warning on the last statement)
10368 static statement_t *parse_statement(void)
10370 statement_t *statement = intern_parse_statement();
10372 if (statement->kind == STATEMENT_EXPRESSION && warning.unused_value) {
10373 expression_t *expression = statement->expression.expression;
10374 if (!expression_has_effect(expression)) {
10375 warningf(&expression->base.source_position,
10376 "statement has no effect");
10384 * Parse a compound statement.
10386 static statement_t *parse_compound_statement(bool inside_expression_statement)
10388 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10390 PUSH_PARENT(statement);
10393 add_anchor_token('}');
10394 /* tokens, which can start a statement */
10395 /* TODO MS, __builtin_FOO */
10396 add_anchor_token('!');
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(T_CHARACTER_CONSTANT);
10405 add_anchor_token(T_COLONCOLON);
10406 add_anchor_token(T_FLOATINGPOINT);
10407 add_anchor_token(T_IDENTIFIER);
10408 add_anchor_token(T_INTEGER);
10409 add_anchor_token(T_MINUSMINUS);
10410 add_anchor_token(T_PLUSPLUS);
10411 add_anchor_token(T_STRING_LITERAL);
10412 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10413 add_anchor_token(T_WIDE_STRING_LITERAL);
10414 add_anchor_token(T__Bool);
10415 add_anchor_token(T__Complex);
10416 add_anchor_token(T__Imaginary);
10417 add_anchor_token(T___FUNCTION__);
10418 add_anchor_token(T___PRETTY_FUNCTION__);
10419 add_anchor_token(T___alignof__);
10420 add_anchor_token(T___attribute__);
10421 add_anchor_token(T___builtin_va_start);
10422 add_anchor_token(T___extension__);
10423 add_anchor_token(T___func__);
10424 add_anchor_token(T___imag__);
10425 add_anchor_token(T___label__);
10426 add_anchor_token(T___real__);
10427 add_anchor_token(T___thread);
10428 add_anchor_token(T_asm);
10429 add_anchor_token(T_auto);
10430 add_anchor_token(T_bool);
10431 add_anchor_token(T_break);
10432 add_anchor_token(T_case);
10433 add_anchor_token(T_char);
10434 add_anchor_token(T_class);
10435 add_anchor_token(T_const);
10436 add_anchor_token(T_const_cast);
10437 add_anchor_token(T_continue);
10438 add_anchor_token(T_default);
10439 add_anchor_token(T_delete);
10440 add_anchor_token(T_double);
10441 add_anchor_token(T_do);
10442 add_anchor_token(T_dynamic_cast);
10443 add_anchor_token(T_enum);
10444 add_anchor_token(T_extern);
10445 add_anchor_token(T_false);
10446 add_anchor_token(T_float);
10447 add_anchor_token(T_for);
10448 add_anchor_token(T_goto);
10449 add_anchor_token(T_if);
10450 add_anchor_token(T_inline);
10451 add_anchor_token(T_int);
10452 add_anchor_token(T_long);
10453 add_anchor_token(T_new);
10454 add_anchor_token(T_operator);
10455 add_anchor_token(T_register);
10456 add_anchor_token(T_reinterpret_cast);
10457 add_anchor_token(T_restrict);
10458 add_anchor_token(T_return);
10459 add_anchor_token(T_short);
10460 add_anchor_token(T_signed);
10461 add_anchor_token(T_sizeof);
10462 add_anchor_token(T_static);
10463 add_anchor_token(T_static_cast);
10464 add_anchor_token(T_struct);
10465 add_anchor_token(T_switch);
10466 add_anchor_token(T_template);
10467 add_anchor_token(T_this);
10468 add_anchor_token(T_throw);
10469 add_anchor_token(T_true);
10470 add_anchor_token(T_try);
10471 add_anchor_token(T_typedef);
10472 add_anchor_token(T_typeid);
10473 add_anchor_token(T_typename);
10474 add_anchor_token(T_typeof);
10475 add_anchor_token(T_union);
10476 add_anchor_token(T_unsigned);
10477 add_anchor_token(T_using);
10478 add_anchor_token(T_void);
10479 add_anchor_token(T_volatile);
10480 add_anchor_token(T_wchar_t);
10481 add_anchor_token(T_while);
10483 size_t const top = environment_top();
10484 scope_t *old_scope = scope_push(&statement->compound.scope);
10486 statement_t **anchor = &statement->compound.statements;
10487 bool only_decls_so_far = true;
10488 while (token.type != '}') {
10489 if (token.type == T_EOF) {
10490 errorf(&statement->base.source_position,
10491 "EOF while parsing compound statement");
10494 statement_t *sub_statement = intern_parse_statement();
10495 if (is_invalid_statement(sub_statement)) {
10496 /* an error occurred. if we are at an anchor, return */
10502 if (warning.declaration_after_statement) {
10503 if (sub_statement->kind != STATEMENT_DECLARATION) {
10504 only_decls_so_far = false;
10505 } else if (!only_decls_so_far) {
10506 warningf(&sub_statement->base.source_position,
10507 "ISO C90 forbids mixed declarations and code");
10511 *anchor = sub_statement;
10513 while (sub_statement->base.next != NULL)
10514 sub_statement = sub_statement->base.next;
10516 anchor = &sub_statement->base.next;
10520 /* look over all statements again to produce no effect warnings */
10521 if (warning.unused_value) {
10522 statement_t *sub_statement = statement->compound.statements;
10523 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10524 if (sub_statement->kind != STATEMENT_EXPRESSION)
10526 /* don't emit a warning for the last expression in an expression
10527 * statement as it has always an effect */
10528 if (inside_expression_statement && sub_statement->base.next == NULL)
10531 expression_t *expression = sub_statement->expression.expression;
10532 if (!expression_has_effect(expression)) {
10533 warningf(&expression->base.source_position,
10534 "statement has no effect");
10540 rem_anchor_token(T_while);
10541 rem_anchor_token(T_wchar_t);
10542 rem_anchor_token(T_volatile);
10543 rem_anchor_token(T_void);
10544 rem_anchor_token(T_using);
10545 rem_anchor_token(T_unsigned);
10546 rem_anchor_token(T_union);
10547 rem_anchor_token(T_typeof);
10548 rem_anchor_token(T_typename);
10549 rem_anchor_token(T_typeid);
10550 rem_anchor_token(T_typedef);
10551 rem_anchor_token(T_try);
10552 rem_anchor_token(T_true);
10553 rem_anchor_token(T_throw);
10554 rem_anchor_token(T_this);
10555 rem_anchor_token(T_template);
10556 rem_anchor_token(T_switch);
10557 rem_anchor_token(T_struct);
10558 rem_anchor_token(T_static_cast);
10559 rem_anchor_token(T_static);
10560 rem_anchor_token(T_sizeof);
10561 rem_anchor_token(T_signed);
10562 rem_anchor_token(T_short);
10563 rem_anchor_token(T_return);
10564 rem_anchor_token(T_restrict);
10565 rem_anchor_token(T_reinterpret_cast);
10566 rem_anchor_token(T_register);
10567 rem_anchor_token(T_operator);
10568 rem_anchor_token(T_new);
10569 rem_anchor_token(T_long);
10570 rem_anchor_token(T_int);
10571 rem_anchor_token(T_inline);
10572 rem_anchor_token(T_if);
10573 rem_anchor_token(T_goto);
10574 rem_anchor_token(T_for);
10575 rem_anchor_token(T_float);
10576 rem_anchor_token(T_false);
10577 rem_anchor_token(T_extern);
10578 rem_anchor_token(T_enum);
10579 rem_anchor_token(T_dynamic_cast);
10580 rem_anchor_token(T_do);
10581 rem_anchor_token(T_double);
10582 rem_anchor_token(T_delete);
10583 rem_anchor_token(T_default);
10584 rem_anchor_token(T_continue);
10585 rem_anchor_token(T_const_cast);
10586 rem_anchor_token(T_const);
10587 rem_anchor_token(T_class);
10588 rem_anchor_token(T_char);
10589 rem_anchor_token(T_case);
10590 rem_anchor_token(T_break);
10591 rem_anchor_token(T_bool);
10592 rem_anchor_token(T_auto);
10593 rem_anchor_token(T_asm);
10594 rem_anchor_token(T___thread);
10595 rem_anchor_token(T___real__);
10596 rem_anchor_token(T___label__);
10597 rem_anchor_token(T___imag__);
10598 rem_anchor_token(T___func__);
10599 rem_anchor_token(T___extension__);
10600 rem_anchor_token(T___builtin_va_start);
10601 rem_anchor_token(T___attribute__);
10602 rem_anchor_token(T___alignof__);
10603 rem_anchor_token(T___PRETTY_FUNCTION__);
10604 rem_anchor_token(T___FUNCTION__);
10605 rem_anchor_token(T__Imaginary);
10606 rem_anchor_token(T__Complex);
10607 rem_anchor_token(T__Bool);
10608 rem_anchor_token(T_WIDE_STRING_LITERAL);
10609 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10610 rem_anchor_token(T_STRING_LITERAL);
10611 rem_anchor_token(T_PLUSPLUS);
10612 rem_anchor_token(T_MINUSMINUS);
10613 rem_anchor_token(T_INTEGER);
10614 rem_anchor_token(T_IDENTIFIER);
10615 rem_anchor_token(T_FLOATINGPOINT);
10616 rem_anchor_token(T_COLONCOLON);
10617 rem_anchor_token(T_CHARACTER_CONSTANT);
10618 rem_anchor_token('~');
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 assert(current_scope == &statement->compound.scope);
10628 scope_pop(old_scope);
10629 environment_pop_to(top);
10636 * Check for unused global static functions and variables
10638 static void check_unused_globals(void)
10640 if (!warning.unused_function && !warning.unused_variable)
10643 for (const entity_t *entity = file_scope->entities; entity != NULL;
10644 entity = entity->base.next) {
10645 if (!is_declaration(entity))
10648 const declaration_t *declaration = &entity->declaration;
10649 if (declaration->used ||
10650 declaration->modifiers & DM_UNUSED ||
10651 declaration->modifiers & DM_USED ||
10652 declaration->storage_class != STORAGE_CLASS_STATIC)
10655 type_t *const type = declaration->type;
10657 if (entity->kind == ENTITY_FUNCTION) {
10658 /* inhibit warning for static inline functions */
10659 if (entity->function.is_inline)
10662 s = entity->function.statement != NULL ? "defined" : "declared";
10667 warningf(&declaration->base.source_position, "'%#T' %s but not used",
10668 type, declaration->base.symbol, s);
10672 static void parse_global_asm(void)
10674 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10677 expect('(', end_error);
10679 statement->asms.asm_text = parse_string_literals();
10680 statement->base.next = unit->global_asm;
10681 unit->global_asm = statement;
10683 expect(')', end_error);
10684 expect(';', end_error);
10689 static void parse_linkage_specification(void)
10693 const char *linkage = parse_string_literals().begin;
10695 linkage_kind_t old_linkage = current_linkage;
10696 linkage_kind_t new_linkage;
10697 if (strcmp(linkage, "C") == 0) {
10698 new_linkage = LINKAGE_C;
10699 } else if (strcmp(linkage, "C++") == 0) {
10700 new_linkage = LINKAGE_CXX;
10702 errorf(HERE, "linkage string \"%s\" not recognized", linkage);
10703 new_linkage = LINKAGE_INVALID;
10705 current_linkage = new_linkage;
10707 if (next_if('{')) {
10709 expect('}', end_error);
10715 assert(current_linkage == new_linkage);
10716 current_linkage = old_linkage;
10719 static void parse_external(void)
10721 switch (token.type) {
10722 DECLARATION_START_NO_EXTERN
10724 case T___extension__:
10725 /* tokens below are for implicit int */
10726 case '&': /* & x; -> int& x; (and error later, because C++ has no
10728 case '*': /* * x; -> int* x; */
10729 case '(': /* (x); -> int (x); */
10730 parse_external_declaration();
10734 if (look_ahead(1)->type == T_STRING_LITERAL) {
10735 parse_linkage_specification();
10737 parse_external_declaration();
10742 parse_global_asm();
10746 parse_namespace_definition();
10750 if (!strict_mode) {
10752 warningf(HERE, "stray ';' outside of function");
10759 errorf(HERE, "stray %K outside of function", &token);
10760 if (token.type == '(' || token.type == '{' || token.type == '[')
10761 eat_until_matching_token(token.type);
10767 static void parse_externals(void)
10769 add_anchor_token('}');
10770 add_anchor_token(T_EOF);
10773 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10774 unsigned char token_anchor_copy[T_LAST_TOKEN];
10775 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10778 while (token.type != T_EOF && token.type != '}') {
10780 bool anchor_leak = false;
10781 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10782 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10784 /* the anchor set and its copy differs */
10785 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10786 anchor_leak = true;
10789 if (in_gcc_extension) {
10790 /* an gcc extension scope was not closed */
10791 internal_errorf(HERE, "Leaked __extension__");
10792 anchor_leak = true;
10802 rem_anchor_token(T_EOF);
10803 rem_anchor_token('}');
10807 * Parse a translation unit.
10809 static void parse_translation_unit(void)
10811 add_anchor_token(T_EOF);
10816 if (token.type == T_EOF)
10819 errorf(HERE, "stray %K outside of function", &token);
10820 if (token.type == '(' || token.type == '{' || token.type == '[')
10821 eat_until_matching_token(token.type);
10826 void set_default_visibility(elf_visibility_tag_t visibility)
10828 default_visibility = visibility;
10834 * @return the translation unit or NULL if errors occurred.
10836 void start_parsing(void)
10838 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10839 label_stack = NEW_ARR_F(stack_entry_t, 0);
10840 diagnostic_count = 0;
10844 print_to_file(stderr);
10846 assert(unit == NULL);
10847 unit = allocate_ast_zero(sizeof(unit[0]));
10849 assert(file_scope == NULL);
10850 file_scope = &unit->scope;
10852 assert(current_scope == NULL);
10853 scope_push(&unit->scope);
10855 create_gnu_builtins();
10857 create_microsoft_intrinsics();
10860 translation_unit_t *finish_parsing(void)
10862 assert(current_scope == &unit->scope);
10865 assert(file_scope == &unit->scope);
10866 check_unused_globals();
10869 DEL_ARR_F(environment_stack);
10870 DEL_ARR_F(label_stack);
10872 translation_unit_t *result = unit;
10877 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10878 * are given length one. */
10879 static void complete_incomplete_arrays(void)
10881 size_t n = ARR_LEN(incomplete_arrays);
10882 for (size_t i = 0; i != n; ++i) {
10883 declaration_t *const decl = incomplete_arrays[i];
10884 type_t *const orig_type = decl->type;
10885 type_t *const type = skip_typeref(orig_type);
10887 if (!is_type_incomplete(type))
10890 if (warning.other) {
10891 warningf(&decl->base.source_position,
10892 "array '%#T' assumed to have one element",
10893 orig_type, decl->base.symbol);
10896 type_t *const new_type = duplicate_type(type);
10897 new_type->array.size_constant = true;
10898 new_type->array.has_implicit_size = true;
10899 new_type->array.size = 1;
10901 type_t *const result = identify_new_type(new_type);
10903 decl->type = result;
10907 void prepare_main_collect2(entity_t *entity)
10909 // create call to __main
10910 symbol_t *symbol = symbol_table_insert("__main");
10911 entity_t *subsubmain_ent
10912 = create_implicit_function(symbol, &builtin_source_position);
10914 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10915 type_t *ftype = subsubmain_ent->declaration.type;
10916 ref->base.source_position = builtin_source_position;
10917 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10918 ref->reference.entity = subsubmain_ent;
10920 expression_t *call = allocate_expression_zero(EXPR_CALL);
10921 call->base.source_position = builtin_source_position;
10922 call->base.type = type_void;
10923 call->call.function = ref;
10925 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10926 expr_statement->base.source_position = builtin_source_position;
10927 expr_statement->expression.expression = call;
10929 statement_t *statement = entity->function.statement;
10930 assert(statement->kind == STATEMENT_COMPOUND);
10931 compound_statement_t *compounds = &statement->compound;
10933 expr_statement->base.next = compounds->statements;
10934 compounds->statements = expr_statement;
10939 lookahead_bufpos = 0;
10940 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10943 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10944 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10945 parse_translation_unit();
10946 complete_incomplete_arrays();
10947 DEL_ARR_F(incomplete_arrays);
10948 incomplete_arrays = NULL;
10952 * Initialize the parser.
10954 void init_parser(void)
10956 sym_anonymous = symbol_table_insert("<anonymous>");
10958 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10960 init_expression_parsers();
10961 obstack_init(&temp_obst);
10965 * Terminate the parser.
10967 void exit_parser(void)
10969 obstack_free(&temp_obst, NULL);