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 EXPRESSION_START \
227 case T_CHARACTER_CONSTANT: \
228 case T_FLOATINGPOINT: \
229 case T_FLOATINGPOINT_HEXADECIMAL: \
231 case T_INTEGER_HEXADECIMAL: \
232 case T_INTEGER_OCTAL: \
235 case T_STRING_LITERAL: \
236 case T_WIDE_CHARACTER_CONSTANT: \
237 case T_WIDE_STRING_LITERAL: \
238 case T___FUNCDNAME__: \
239 case T___FUNCSIG__: \
240 case T___FUNCTION__: \
241 case T___PRETTY_FUNCTION__: \
242 case T___alignof__: \
243 case T___builtin_classify_type: \
244 case T___builtin_constant_p: \
245 case T___builtin_isgreater: \
246 case T___builtin_isgreaterequal: \
247 case T___builtin_isless: \
248 case T___builtin_islessequal: \
249 case T___builtin_islessgreater: \
250 case T___builtin_isunordered: \
251 case T___builtin_offsetof: \
252 case T___builtin_va_arg: \
253 case T___builtin_va_copy: \
254 case T___builtin_va_start: \
265 * Returns the size of a statement node.
267 * @param kind the statement kind
269 static size_t get_statement_struct_size(statement_kind_t kind)
271 static const size_t sizes[] = {
272 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
273 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
274 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
275 [STATEMENT_RETURN] = sizeof(return_statement_t),
276 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
277 [STATEMENT_IF] = sizeof(if_statement_t),
278 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
279 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
280 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
281 [STATEMENT_BREAK] = sizeof(statement_base_t),
282 [STATEMENT_GOTO] = sizeof(goto_statement_t),
283 [STATEMENT_LABEL] = sizeof(label_statement_t),
284 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
285 [STATEMENT_WHILE] = sizeof(while_statement_t),
286 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
287 [STATEMENT_FOR] = sizeof(for_statement_t),
288 [STATEMENT_ASM] = sizeof(asm_statement_t),
289 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
290 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
292 assert((size_t)kind < lengthof(sizes));
293 assert(sizes[kind] != 0);
298 * Returns the size of an expression node.
300 * @param kind the expression kind
302 static size_t get_expression_struct_size(expression_kind_t kind)
304 static const size_t sizes[] = {
305 [EXPR_INVALID] = sizeof(expression_base_t),
306 [EXPR_REFERENCE] = sizeof(reference_expression_t),
307 [EXPR_REFERENCE_ENUM_VALUE] = sizeof(reference_expression_t),
308 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
309 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
310 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
311 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
312 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
313 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
314 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
315 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
316 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
317 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
318 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
319 [EXPR_CALL] = sizeof(call_expression_t),
320 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
321 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
322 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
323 [EXPR_SELECT] = sizeof(select_expression_t),
324 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
325 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
326 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
327 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
328 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
329 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
330 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
331 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
332 [EXPR_VA_START] = sizeof(va_start_expression_t),
333 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
334 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
335 [EXPR_STATEMENT] = sizeof(statement_expression_t),
336 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
338 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
339 return sizes[EXPR_UNARY_FIRST];
341 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
342 return sizes[EXPR_BINARY_FIRST];
344 assert((size_t)kind < lengthof(sizes));
345 assert(sizes[kind] != 0);
350 * Allocate a statement node of given kind and initialize all
351 * fields with zero. Sets its source position to the position
352 * of the current token.
354 static statement_t *allocate_statement_zero(statement_kind_t kind)
356 size_t size = get_statement_struct_size(kind);
357 statement_t *res = allocate_ast_zero(size);
359 res->base.kind = kind;
360 res->base.parent = current_parent;
361 res->base.source_position = token.source_position;
366 * Allocate an expression node of given kind and initialize all
369 * @param kind the kind of the expression to allocate
371 static expression_t *allocate_expression_zero(expression_kind_t kind)
373 size_t size = get_expression_struct_size(kind);
374 expression_t *res = allocate_ast_zero(size);
376 res->base.kind = kind;
377 res->base.type = type_error_type;
378 res->base.source_position = token.source_position;
383 * Creates a new invalid expression at the source position
384 * of the current token.
386 static expression_t *create_invalid_expression(void)
388 return allocate_expression_zero(EXPR_INVALID);
392 * Creates a new invalid statement.
394 static statement_t *create_invalid_statement(void)
396 return allocate_statement_zero(STATEMENT_INVALID);
400 * Allocate a new empty statement.
402 static statement_t *create_empty_statement(void)
404 return allocate_statement_zero(STATEMENT_EMPTY);
408 * Returns the size of an initializer node.
410 * @param kind the initializer kind
412 static size_t get_initializer_size(initializer_kind_t kind)
414 static const size_t sizes[] = {
415 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
416 [INITIALIZER_STRING] = sizeof(initializer_string_t),
417 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
418 [INITIALIZER_LIST] = sizeof(initializer_list_t),
419 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
421 assert((size_t)kind < lengthof(sizes));
422 assert(sizes[kind] != 0);
427 * Allocate an initializer node of given kind and initialize all
430 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
432 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
439 * Returns the index of the top element of the environment stack.
441 static size_t environment_top(void)
443 return ARR_LEN(environment_stack);
447 * Returns the index of the top element of the global label stack.
449 static size_t label_top(void)
451 return ARR_LEN(label_stack);
455 * Return the next token.
457 static inline void next_token(void)
459 token = lookahead_buffer[lookahead_bufpos];
460 lookahead_buffer[lookahead_bufpos] = lexer_token;
463 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
466 print_token(stderr, &token);
467 fprintf(stderr, "\n");
471 static inline bool next_if(int const type)
473 if (token.type == type) {
482 * Return the next token with a given lookahead.
484 static inline const token_t *look_ahead(size_t num)
486 assert(0 < num && num <= MAX_LOOKAHEAD);
487 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
488 return &lookahead_buffer[pos];
492 * Adds a token type to the token type anchor set (a multi-set).
494 static void add_anchor_token(int token_type)
496 assert(0 <= token_type && token_type < T_LAST_TOKEN);
497 ++token_anchor_set[token_type];
501 * Set the number of tokens types of the given type
502 * to zero and return the old count.
504 static int save_and_reset_anchor_state(int token_type)
506 assert(0 <= token_type && token_type < T_LAST_TOKEN);
507 int count = token_anchor_set[token_type];
508 token_anchor_set[token_type] = 0;
513 * Restore the number of token types to the given count.
515 static void restore_anchor_state(int token_type, int count)
517 assert(0 <= token_type && token_type < T_LAST_TOKEN);
518 token_anchor_set[token_type] = count;
522 * Remove a token type from the token type anchor set (a multi-set).
524 static void rem_anchor_token(int token_type)
526 assert(0 <= token_type && token_type < T_LAST_TOKEN);
527 assert(token_anchor_set[token_type] != 0);
528 --token_anchor_set[token_type];
532 * Return true if the token type of the current token is
535 static bool at_anchor(void)
539 return token_anchor_set[token.type];
543 * Eat tokens until a matching token type is found.
545 static void eat_until_matching_token(int type)
549 case '(': end_token = ')'; break;
550 case '{': end_token = '}'; break;
551 case '[': end_token = ']'; break;
552 default: end_token = type; break;
555 unsigned parenthesis_count = 0;
556 unsigned brace_count = 0;
557 unsigned bracket_count = 0;
558 while (token.type != end_token ||
559 parenthesis_count != 0 ||
561 bracket_count != 0) {
562 switch (token.type) {
564 case '(': ++parenthesis_count; break;
565 case '{': ++brace_count; break;
566 case '[': ++bracket_count; break;
569 if (parenthesis_count > 0)
579 if (bracket_count > 0)
582 if (token.type == end_token &&
583 parenthesis_count == 0 &&
597 * Eat input tokens until an anchor is found.
599 static void eat_until_anchor(void)
601 while (token_anchor_set[token.type] == 0) {
602 if (token.type == '(' || token.type == '{' || token.type == '[')
603 eat_until_matching_token(token.type);
609 * Eat a whole block from input tokens.
611 static void eat_block(void)
613 eat_until_matching_token('{');
617 #define eat(token_type) (assert(token.type == (token_type)), next_token())
620 * Report a parse error because an expected token was not found.
623 #if defined __GNUC__ && __GNUC__ >= 4
624 __attribute__((sentinel))
626 void parse_error_expected(const char *message, ...)
628 if (message != NULL) {
629 errorf(HERE, "%s", message);
632 va_start(ap, message);
633 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
638 * Report an incompatible type.
640 static void type_error_incompatible(const char *msg,
641 const source_position_t *source_position, type_t *type1, type_t *type2)
643 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
648 * Expect the current token is the expected token.
649 * If not, generate an error, eat the current statement,
650 * and goto the error_label label.
652 #define expect(expected, error_label) \
654 if (UNLIKELY(token.type != (expected))) { \
655 parse_error_expected(NULL, (expected), NULL); \
656 add_anchor_token(expected); \
657 eat_until_anchor(); \
658 next_if((expected)); \
659 rem_anchor_token(expected); \
666 * Push a given scope on the scope stack and make it the
669 static scope_t *scope_push(scope_t *new_scope)
671 if (current_scope != NULL) {
672 new_scope->depth = current_scope->depth + 1;
675 scope_t *old_scope = current_scope;
676 current_scope = new_scope;
681 * Pop the current scope from the scope stack.
683 static void scope_pop(scope_t *old_scope)
685 current_scope = old_scope;
689 * Search an entity by its symbol in a given namespace.
691 static entity_t *get_entity(const symbol_t *const symbol,
692 namespace_tag_t namespc)
694 assert(namespc != NAMESPACE_INVALID);
695 entity_t *entity = symbol->entity;
696 for (; entity != NULL; entity = entity->base.symbol_next) {
697 if ((namespace_tag_t)entity->base.namespc == namespc)
704 /* §6.2.3:1 24) There is only one name space for tags even though three are
706 static entity_t *get_tag(symbol_t const *const symbol,
707 entity_kind_tag_t const kind)
709 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
710 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
712 "'%Y' defined as wrong kind of tag (previous definition %P)",
713 symbol, &entity->base.source_position);
720 * pushs an entity on the environment stack and links the corresponding symbol
723 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
725 symbol_t *symbol = entity->base.symbol;
726 entity_namespace_t namespc = entity->base.namespc;
727 assert(namespc != NAMESPACE_INVALID);
729 /* replace/add entity into entity list of the symbol */
732 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
737 /* replace an entry? */
738 if (iter->base.namespc == namespc) {
739 entity->base.symbol_next = iter->base.symbol_next;
745 /* remember old declaration */
747 entry.symbol = symbol;
748 entry.old_entity = iter;
749 entry.namespc = namespc;
750 ARR_APP1(stack_entry_t, *stack_ptr, entry);
754 * Push an entity on the environment stack.
756 static void environment_push(entity_t *entity)
758 assert(entity->base.source_position.input_name != NULL);
759 assert(entity->base.parent_scope != NULL);
760 stack_push(&environment_stack, entity);
764 * Push a declaration on the global label stack.
766 * @param declaration the declaration
768 static void label_push(entity_t *label)
770 /* we abuse the parameters scope as parent for the labels */
771 label->base.parent_scope = ¤t_function->parameters;
772 stack_push(&label_stack, label);
776 * pops symbols from the environment stack until @p new_top is the top element
778 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
780 stack_entry_t *stack = *stack_ptr;
781 size_t top = ARR_LEN(stack);
784 assert(new_top <= top);
788 for (i = top; i > new_top; --i) {
789 stack_entry_t *entry = &stack[i - 1];
791 entity_t *old_entity = entry->old_entity;
792 symbol_t *symbol = entry->symbol;
793 entity_namespace_t namespc = entry->namespc;
795 /* replace with old_entity/remove */
798 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
800 assert(iter != NULL);
801 /* replace an entry? */
802 if (iter->base.namespc == namespc)
806 /* restore definition from outer scopes (if there was one) */
807 if (old_entity != NULL) {
808 old_entity->base.symbol_next = iter->base.symbol_next;
809 *anchor = old_entity;
811 /* remove entry from list */
812 *anchor = iter->base.symbol_next;
816 ARR_SHRINKLEN(*stack_ptr, new_top);
820 * Pop all entries from the environment stack until the new_top
823 * @param new_top the new stack top
825 static void environment_pop_to(size_t new_top)
827 stack_pop_to(&environment_stack, new_top);
831 * Pop all entries from the global label stack until the new_top
834 * @param new_top the new stack top
836 static void label_pop_to(size_t new_top)
838 stack_pop_to(&label_stack, new_top);
841 static int get_akind_rank(atomic_type_kind_t akind)
847 * Return the type rank for an atomic type.
849 static int get_rank(const type_t *type)
851 assert(!is_typeref(type));
852 if (type->kind == TYPE_ENUM)
853 return get_akind_rank(type->enumt.akind);
855 assert(type->kind == TYPE_ATOMIC);
856 return get_akind_rank(type->atomic.akind);
860 * §6.3.1.1:2 Do integer promotion for a given type.
862 * @param type the type to promote
863 * @return the promoted type
865 static type_t *promote_integer(type_t *type)
867 if (type->kind == TYPE_BITFIELD)
868 type = type->bitfield.base_type;
870 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
877 * Create a cast expression.
879 * @param expression the expression to cast
880 * @param dest_type the destination type
882 static expression_t *create_cast_expression(expression_t *expression,
885 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
887 cast->unary.value = expression;
888 cast->base.type = dest_type;
894 * Check if a given expression represents a null pointer constant.
896 * @param expression the expression to check
898 static bool is_null_pointer_constant(const expression_t *expression)
900 /* skip void* cast */
901 if (expression->kind == EXPR_UNARY_CAST ||
902 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
903 type_t *const type = skip_typeref(expression->base.type);
904 if (types_compatible(type, type_void_ptr))
905 expression = expression->unary.value;
908 type_t *const type = skip_typeref(expression->base.type);
909 if (!is_type_integer(type))
911 switch (is_constant_expression(expression)) {
912 case EXPR_CLASS_ERROR: return true;
913 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
914 default: return false;
919 * Create an implicit cast expression.
921 * @param expression the expression to cast
922 * @param dest_type the destination type
924 static expression_t *create_implicit_cast(expression_t *expression,
927 type_t *const source_type = expression->base.type;
929 if (source_type == dest_type)
932 return create_cast_expression(expression, dest_type);
935 typedef enum assign_error_t {
937 ASSIGN_ERROR_INCOMPATIBLE,
938 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
939 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
940 ASSIGN_WARNING_POINTER_FROM_INT,
941 ASSIGN_WARNING_INT_FROM_POINTER
944 static void report_assign_error(assign_error_t error, type_t *orig_type_left, expression_t const *const right, char const *const context, source_position_t const *const pos)
946 type_t *const orig_type_right = right->base.type;
947 type_t *const type_left = skip_typeref(orig_type_left);
948 type_t *const type_right = skip_typeref(orig_type_right);
953 case ASSIGN_ERROR_INCOMPATIBLE:
954 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
957 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
958 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
959 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
961 /* the left type has all qualifiers from the right type */
962 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
963 warningf(WARN_OTHER, pos, "destination type '%T' in %s from type '%T' lacks qualifiers '%Q' in pointer target type", orig_type_left, context, orig_type_right, missing_qualifiers);
967 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
968 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
971 case ASSIGN_WARNING_POINTER_FROM_INT:
972 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
975 case ASSIGN_WARNING_INT_FROM_POINTER:
976 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
980 panic("invalid error value");
984 /** Implements the rules from §6.5.16.1 */
985 static assign_error_t semantic_assign(type_t *orig_type_left,
986 const expression_t *const right)
988 type_t *const orig_type_right = right->base.type;
989 type_t *const type_left = skip_typeref(orig_type_left);
990 type_t *const type_right = skip_typeref(orig_type_right);
992 if (is_type_pointer(type_left)) {
993 if (is_null_pointer_constant(right)) {
994 return ASSIGN_SUCCESS;
995 } else if (is_type_pointer(type_right)) {
996 type_t *points_to_left
997 = skip_typeref(type_left->pointer.points_to);
998 type_t *points_to_right
999 = skip_typeref(type_right->pointer.points_to);
1000 assign_error_t res = ASSIGN_SUCCESS;
1002 /* the left type has all qualifiers from the right type */
1003 unsigned missing_qualifiers
1004 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1005 if (missing_qualifiers != 0) {
1006 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1009 points_to_left = get_unqualified_type(points_to_left);
1010 points_to_right = get_unqualified_type(points_to_right);
1012 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1015 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1016 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1017 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1020 if (!types_compatible(points_to_left, points_to_right)) {
1021 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1025 } else if (is_type_integer(type_right)) {
1026 return ASSIGN_WARNING_POINTER_FROM_INT;
1028 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1029 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1030 && is_type_pointer(type_right))) {
1031 return ASSIGN_SUCCESS;
1032 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1033 type_t *const unqual_type_left = get_unqualified_type(type_left);
1034 type_t *const unqual_type_right = get_unqualified_type(type_right);
1035 if (types_compatible(unqual_type_left, unqual_type_right)) {
1036 return ASSIGN_SUCCESS;
1038 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1039 return ASSIGN_WARNING_INT_FROM_POINTER;
1042 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1043 return ASSIGN_SUCCESS;
1045 return ASSIGN_ERROR_INCOMPATIBLE;
1048 static expression_t *parse_constant_expression(void)
1050 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1052 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1053 errorf(&result->base.source_position,
1054 "expression '%E' is not constant", result);
1060 static expression_t *parse_assignment_expression(void)
1062 return parse_subexpression(PREC_ASSIGNMENT);
1065 static void warn_string_concat(const source_position_t *pos)
1067 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1070 static string_t parse_string_literals(void)
1072 assert(token.type == T_STRING_LITERAL);
1073 string_t result = token.literal;
1077 while (token.type == T_STRING_LITERAL) {
1078 warn_string_concat(&token.source_position);
1079 result = concat_strings(&result, &token.literal);
1087 * compare two string, ignoring double underscores on the second.
1089 static int strcmp_underscore(const char *s1, const char *s2)
1091 if (s2[0] == '_' && s2[1] == '_') {
1092 size_t len2 = strlen(s2);
1093 size_t len1 = strlen(s1);
1094 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1095 return strncmp(s1, s2+2, len2-4);
1099 return strcmp(s1, s2);
1102 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1104 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1105 attribute->kind = kind;
1106 attribute->source_position = *HERE;
1111 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1114 * __attribute__ ( ( attribute-list ) )
1118 * attribute_list , attrib
1123 * any-word ( identifier )
1124 * any-word ( identifier , nonempty-expr-list )
1125 * any-word ( expr-list )
1127 * where the "identifier" must not be declared as a type, and
1128 * "any-word" may be any identifier (including one declared as a
1129 * type), a reserved word storage class specifier, type specifier or
1130 * type qualifier. ??? This still leaves out most reserved keywords
1131 * (following the old parser), shouldn't we include them, and why not
1132 * allow identifiers declared as types to start the arguments?
1134 * Matze: this all looks confusing and little systematic, so we're even less
1135 * strict and parse any list of things which are identifiers or
1136 * (assignment-)expressions.
1138 static attribute_argument_t *parse_attribute_arguments(void)
1140 attribute_argument_t *first = NULL;
1141 attribute_argument_t **anchor = &first;
1142 if (token.type != ')') do {
1143 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1145 /* is it an identifier */
1146 if (token.type == T_IDENTIFIER
1147 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1148 symbol_t *symbol = token.symbol;
1149 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1150 argument->v.symbol = symbol;
1153 /* must be an expression */
1154 expression_t *expression = parse_assignment_expression();
1156 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1157 argument->v.expression = expression;
1160 /* append argument */
1162 anchor = &argument->next;
1163 } while (next_if(','));
1164 expect(')', end_error);
1173 static attribute_t *parse_attribute_asm(void)
1177 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1179 expect('(', end_error);
1180 attribute->a.arguments = parse_attribute_arguments();
1187 static symbol_t *get_symbol_from_token(void)
1189 switch(token.type) {
1191 return token.symbol;
1220 /* maybe we need more tokens ... add them on demand */
1221 return get_token_symbol(&token);
1227 static attribute_t *parse_attribute_gnu_single(void)
1229 /* parse "any-word" */
1230 symbol_t *symbol = get_symbol_from_token();
1231 if (symbol == NULL) {
1232 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1236 attribute_kind_t kind;
1237 char const *const name = symbol->string;
1238 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1239 if (kind > ATTRIBUTE_GNU_LAST) {
1240 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1241 /* TODO: we should still save the attribute in the list... */
1242 kind = ATTRIBUTE_UNKNOWN;
1246 const char *attribute_name = get_attribute_name(kind);
1247 if (attribute_name != NULL
1248 && strcmp_underscore(attribute_name, name) == 0)
1254 attribute_t *attribute = allocate_attribute_zero(kind);
1256 /* parse arguments */
1258 attribute->a.arguments = parse_attribute_arguments();
1263 static attribute_t *parse_attribute_gnu(void)
1265 attribute_t *first = NULL;
1266 attribute_t **anchor = &first;
1268 eat(T___attribute__);
1269 expect('(', end_error);
1270 expect('(', end_error);
1272 if (token.type != ')') do {
1273 attribute_t *attribute = parse_attribute_gnu_single();
1274 if (attribute == NULL)
1277 *anchor = attribute;
1278 anchor = &attribute->next;
1279 } while (next_if(','));
1280 expect(')', end_error);
1281 expect(')', end_error);
1287 /** Parse attributes. */
1288 static attribute_t *parse_attributes(attribute_t *first)
1290 attribute_t **anchor = &first;
1292 while (*anchor != NULL)
1293 anchor = &(*anchor)->next;
1295 attribute_t *attribute;
1296 switch (token.type) {
1297 case T___attribute__:
1298 attribute = parse_attribute_gnu();
1299 if (attribute == NULL)
1304 attribute = parse_attribute_asm();
1309 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1314 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1317 case T__forceinline:
1319 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1324 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1328 /* TODO record modifier */
1329 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1331 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1338 *anchor = attribute;
1339 anchor = &attribute->next;
1343 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1345 static entity_t *determine_lhs_ent(expression_t *const expr,
1348 switch (expr->kind) {
1349 case EXPR_REFERENCE: {
1350 entity_t *const entity = expr->reference.entity;
1351 /* we should only find variables as lvalues... */
1352 if (entity->base.kind != ENTITY_VARIABLE
1353 && entity->base.kind != ENTITY_PARAMETER)
1359 case EXPR_ARRAY_ACCESS: {
1360 expression_t *const ref = expr->array_access.array_ref;
1361 entity_t * ent = NULL;
1362 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1363 ent = determine_lhs_ent(ref, lhs_ent);
1366 mark_vars_read(expr->select.compound, lhs_ent);
1368 mark_vars_read(expr->array_access.index, lhs_ent);
1373 if (is_type_compound(skip_typeref(expr->base.type))) {
1374 return determine_lhs_ent(expr->select.compound, lhs_ent);
1376 mark_vars_read(expr->select.compound, lhs_ent);
1381 case EXPR_UNARY_DEREFERENCE: {
1382 expression_t *const val = expr->unary.value;
1383 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1385 return determine_lhs_ent(val->unary.value, lhs_ent);
1387 mark_vars_read(val, NULL);
1393 mark_vars_read(expr, NULL);
1398 #define ENT_ANY ((entity_t*)-1)
1401 * Mark declarations, which are read. This is used to detect variables, which
1405 * x is not marked as "read", because it is only read to calculate its own new
1409 * x and y are not detected as "not read", because multiple variables are
1412 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1414 switch (expr->kind) {
1415 case EXPR_REFERENCE: {
1416 entity_t *const entity = expr->reference.entity;
1417 if (entity->kind != ENTITY_VARIABLE
1418 && entity->kind != ENTITY_PARAMETER)
1421 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1422 if (entity->kind == ENTITY_VARIABLE) {
1423 entity->variable.read = true;
1425 entity->parameter.read = true;
1432 // TODO respect pure/const
1433 mark_vars_read(expr->call.function, NULL);
1434 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1435 mark_vars_read(arg->expression, NULL);
1439 case EXPR_CONDITIONAL:
1440 // TODO lhs_decl should depend on whether true/false have an effect
1441 mark_vars_read(expr->conditional.condition, NULL);
1442 if (expr->conditional.true_expression != NULL)
1443 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1444 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1448 if (lhs_ent == ENT_ANY
1449 && !is_type_compound(skip_typeref(expr->base.type)))
1451 mark_vars_read(expr->select.compound, lhs_ent);
1454 case EXPR_ARRAY_ACCESS: {
1455 expression_t *const ref = expr->array_access.array_ref;
1456 mark_vars_read(ref, lhs_ent);
1457 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1458 mark_vars_read(expr->array_access.index, lhs_ent);
1463 mark_vars_read(expr->va_arge.ap, lhs_ent);
1467 mark_vars_read(expr->va_copye.src, lhs_ent);
1470 case EXPR_UNARY_CAST:
1471 /* Special case: Use void cast to mark a variable as "read" */
1472 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1477 case EXPR_UNARY_THROW:
1478 if (expr->unary.value == NULL)
1481 case EXPR_UNARY_DEREFERENCE:
1482 case EXPR_UNARY_DELETE:
1483 case EXPR_UNARY_DELETE_ARRAY:
1484 if (lhs_ent == ENT_ANY)
1488 case EXPR_UNARY_NEGATE:
1489 case EXPR_UNARY_PLUS:
1490 case EXPR_UNARY_BITWISE_NEGATE:
1491 case EXPR_UNARY_NOT:
1492 case EXPR_UNARY_TAKE_ADDRESS:
1493 case EXPR_UNARY_POSTFIX_INCREMENT:
1494 case EXPR_UNARY_POSTFIX_DECREMENT:
1495 case EXPR_UNARY_PREFIX_INCREMENT:
1496 case EXPR_UNARY_PREFIX_DECREMENT:
1497 case EXPR_UNARY_CAST_IMPLICIT:
1498 case EXPR_UNARY_ASSUME:
1500 mark_vars_read(expr->unary.value, lhs_ent);
1503 case EXPR_BINARY_ADD:
1504 case EXPR_BINARY_SUB:
1505 case EXPR_BINARY_MUL:
1506 case EXPR_BINARY_DIV:
1507 case EXPR_BINARY_MOD:
1508 case EXPR_BINARY_EQUAL:
1509 case EXPR_BINARY_NOTEQUAL:
1510 case EXPR_BINARY_LESS:
1511 case EXPR_BINARY_LESSEQUAL:
1512 case EXPR_BINARY_GREATER:
1513 case EXPR_BINARY_GREATEREQUAL:
1514 case EXPR_BINARY_BITWISE_AND:
1515 case EXPR_BINARY_BITWISE_OR:
1516 case EXPR_BINARY_BITWISE_XOR:
1517 case EXPR_BINARY_LOGICAL_AND:
1518 case EXPR_BINARY_LOGICAL_OR:
1519 case EXPR_BINARY_SHIFTLEFT:
1520 case EXPR_BINARY_SHIFTRIGHT:
1521 case EXPR_BINARY_COMMA:
1522 case EXPR_BINARY_ISGREATER:
1523 case EXPR_BINARY_ISGREATEREQUAL:
1524 case EXPR_BINARY_ISLESS:
1525 case EXPR_BINARY_ISLESSEQUAL:
1526 case EXPR_BINARY_ISLESSGREATER:
1527 case EXPR_BINARY_ISUNORDERED:
1528 mark_vars_read(expr->binary.left, lhs_ent);
1529 mark_vars_read(expr->binary.right, lhs_ent);
1532 case EXPR_BINARY_ASSIGN:
1533 case EXPR_BINARY_MUL_ASSIGN:
1534 case EXPR_BINARY_DIV_ASSIGN:
1535 case EXPR_BINARY_MOD_ASSIGN:
1536 case EXPR_BINARY_ADD_ASSIGN:
1537 case EXPR_BINARY_SUB_ASSIGN:
1538 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1539 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1540 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1541 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1542 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1543 if (lhs_ent == ENT_ANY)
1545 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1546 mark_vars_read(expr->binary.right, lhs_ent);
1551 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1557 case EXPR_STRING_LITERAL:
1558 case EXPR_WIDE_STRING_LITERAL:
1559 case EXPR_COMPOUND_LITERAL: // TODO init?
1561 case EXPR_CLASSIFY_TYPE:
1564 case EXPR_BUILTIN_CONSTANT_P:
1565 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1567 case EXPR_STATEMENT: // TODO
1568 case EXPR_LABEL_ADDRESS:
1569 case EXPR_REFERENCE_ENUM_VALUE:
1573 panic("unhandled expression");
1576 static designator_t *parse_designation(void)
1578 designator_t *result = NULL;
1579 designator_t **anchor = &result;
1582 designator_t *designator;
1583 switch (token.type) {
1585 designator = allocate_ast_zero(sizeof(designator[0]));
1586 designator->source_position = token.source_position;
1588 add_anchor_token(']');
1589 designator->array_index = parse_constant_expression();
1590 rem_anchor_token(']');
1591 expect(']', end_error);
1594 designator = allocate_ast_zero(sizeof(designator[0]));
1595 designator->source_position = token.source_position;
1597 if (token.type != T_IDENTIFIER) {
1598 parse_error_expected("while parsing designator",
1599 T_IDENTIFIER, NULL);
1602 designator->symbol = token.symbol;
1606 expect('=', end_error);
1610 assert(designator != NULL);
1611 *anchor = designator;
1612 anchor = &designator->next;
1618 static initializer_t *initializer_from_string(array_type_t *const type,
1619 const string_t *const string)
1621 /* TODO: check len vs. size of array type */
1624 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1625 initializer->string.string = *string;
1630 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1631 const string_t *const string)
1633 /* TODO: check len vs. size of array type */
1636 initializer_t *const initializer =
1637 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1638 initializer->wide_string.string = *string;
1644 * Build an initializer from a given expression.
1646 static initializer_t *initializer_from_expression(type_t *orig_type,
1647 expression_t *expression)
1649 /* TODO check that expression is a constant expression */
1651 /* §6.7.8.14/15 char array may be initialized by string literals */
1652 type_t *type = skip_typeref(orig_type);
1653 type_t *expr_type_orig = expression->base.type;
1654 type_t *expr_type = skip_typeref(expr_type_orig);
1656 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1657 array_type_t *const array_type = &type->array;
1658 type_t *const element_type = skip_typeref(array_type->element_type);
1660 if (element_type->kind == TYPE_ATOMIC) {
1661 atomic_type_kind_t akind = element_type->atomic.akind;
1662 switch (expression->kind) {
1663 case EXPR_STRING_LITERAL:
1664 if (akind == ATOMIC_TYPE_CHAR
1665 || akind == ATOMIC_TYPE_SCHAR
1666 || akind == ATOMIC_TYPE_UCHAR) {
1667 return initializer_from_string(array_type,
1668 &expression->string_literal.value);
1672 case EXPR_WIDE_STRING_LITERAL: {
1673 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1674 if (get_unqualified_type(element_type) == bare_wchar_type) {
1675 return initializer_from_wide_string(array_type,
1676 &expression->string_literal.value);
1687 assign_error_t error = semantic_assign(type, expression);
1688 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1690 report_assign_error(error, type, expression, "initializer",
1691 &expression->base.source_position);
1693 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1694 result->value.value = create_implicit_cast(expression, type);
1700 * Checks if a given expression can be used as a constant initializer.
1702 static bool is_initializer_constant(const expression_t *expression)
1704 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1705 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1709 * Parses an scalar initializer.
1711 * §6.7.8.11; eat {} without warning
1713 static initializer_t *parse_scalar_initializer(type_t *type,
1714 bool must_be_constant)
1716 /* there might be extra {} hierarchies */
1718 if (token.type == '{') {
1719 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1723 } while (token.type == '{');
1726 expression_t *expression = parse_assignment_expression();
1727 mark_vars_read(expression, NULL);
1728 if (must_be_constant && !is_initializer_constant(expression)) {
1729 errorf(&expression->base.source_position,
1730 "initialisation expression '%E' is not constant",
1734 initializer_t *initializer = initializer_from_expression(type, expression);
1736 if (initializer == NULL) {
1737 errorf(&expression->base.source_position,
1738 "expression '%E' (type '%T') doesn't match expected type '%T'",
1739 expression, expression->base.type, type);
1744 bool additional_warning_displayed = false;
1745 while (braces > 0) {
1747 if (token.type != '}') {
1748 if (!additional_warning_displayed) {
1749 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1750 additional_warning_displayed = true;
1761 * An entry in the type path.
1763 typedef struct type_path_entry_t type_path_entry_t;
1764 struct type_path_entry_t {
1765 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1767 size_t index; /**< For array types: the current index. */
1768 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1773 * A type path expression a position inside compound or array types.
1775 typedef struct type_path_t type_path_t;
1776 struct type_path_t {
1777 type_path_entry_t *path; /**< An flexible array containing the current path. */
1778 type_t *top_type; /**< type of the element the path points */
1779 size_t max_index; /**< largest index in outermost array */
1783 * Prints a type path for debugging.
1785 static __attribute__((unused)) void debug_print_type_path(
1786 const type_path_t *path)
1788 size_t len = ARR_LEN(path->path);
1790 for (size_t i = 0; i < len; ++i) {
1791 const type_path_entry_t *entry = & path->path[i];
1793 type_t *type = skip_typeref(entry->type);
1794 if (is_type_compound(type)) {
1795 /* in gcc mode structs can have no members */
1796 if (entry->v.compound_entry == NULL) {
1800 fprintf(stderr, ".%s",
1801 entry->v.compound_entry->base.symbol->string);
1802 } else if (is_type_array(type)) {
1803 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1805 fprintf(stderr, "-INVALID-");
1808 if (path->top_type != NULL) {
1809 fprintf(stderr, " (");
1810 print_type(path->top_type);
1811 fprintf(stderr, ")");
1816 * Return the top type path entry, ie. in a path
1817 * (type).a.b returns the b.
1819 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1821 size_t len = ARR_LEN(path->path);
1823 return &path->path[len-1];
1827 * Enlarge the type path by an (empty) element.
1829 static type_path_entry_t *append_to_type_path(type_path_t *path)
1831 size_t len = ARR_LEN(path->path);
1832 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1834 type_path_entry_t *result = & path->path[len];
1835 memset(result, 0, sizeof(result[0]));
1840 * Descending into a sub-type. Enter the scope of the current top_type.
1842 static void descend_into_subtype(type_path_t *path)
1844 type_t *orig_top_type = path->top_type;
1845 type_t *top_type = skip_typeref(orig_top_type);
1847 type_path_entry_t *top = append_to_type_path(path);
1848 top->type = top_type;
1850 if (is_type_compound(top_type)) {
1851 compound_t *compound = top_type->compound.compound;
1852 entity_t *entry = compound->members.entities;
1854 if (entry != NULL) {
1855 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1856 top->v.compound_entry = &entry->declaration;
1857 path->top_type = entry->declaration.type;
1859 path->top_type = NULL;
1861 } else if (is_type_array(top_type)) {
1863 path->top_type = top_type->array.element_type;
1865 assert(!is_type_valid(top_type));
1870 * Pop an entry from the given type path, ie. returning from
1871 * (type).a.b to (type).a
1873 static void ascend_from_subtype(type_path_t *path)
1875 type_path_entry_t *top = get_type_path_top(path);
1877 path->top_type = top->type;
1879 size_t len = ARR_LEN(path->path);
1880 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1884 * Pop entries from the given type path until the given
1885 * path level is reached.
1887 static void ascend_to(type_path_t *path, size_t top_path_level)
1889 size_t len = ARR_LEN(path->path);
1891 while (len > top_path_level) {
1892 ascend_from_subtype(path);
1893 len = ARR_LEN(path->path);
1897 static bool walk_designator(type_path_t *path, const designator_t *designator,
1898 bool used_in_offsetof)
1900 for (; designator != NULL; designator = designator->next) {
1901 type_path_entry_t *top = get_type_path_top(path);
1902 type_t *orig_type = top->type;
1904 type_t *type = skip_typeref(orig_type);
1906 if (designator->symbol != NULL) {
1907 symbol_t *symbol = designator->symbol;
1908 if (!is_type_compound(type)) {
1909 if (is_type_valid(type)) {
1910 errorf(&designator->source_position,
1911 "'.%Y' designator used for non-compound type '%T'",
1915 top->type = type_error_type;
1916 top->v.compound_entry = NULL;
1917 orig_type = type_error_type;
1919 compound_t *compound = type->compound.compound;
1920 entity_t *iter = compound->members.entities;
1921 for (; iter != NULL; iter = iter->base.next) {
1922 if (iter->base.symbol == symbol) {
1927 errorf(&designator->source_position,
1928 "'%T' has no member named '%Y'", orig_type, symbol);
1931 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1932 if (used_in_offsetof) {
1933 type_t *real_type = skip_typeref(iter->declaration.type);
1934 if (real_type->kind == TYPE_BITFIELD) {
1935 errorf(&designator->source_position,
1936 "offsetof designator '%Y' must not specify bitfield",
1942 top->type = orig_type;
1943 top->v.compound_entry = &iter->declaration;
1944 orig_type = iter->declaration.type;
1947 expression_t *array_index = designator->array_index;
1948 assert(designator->array_index != NULL);
1950 if (!is_type_array(type)) {
1951 if (is_type_valid(type)) {
1952 errorf(&designator->source_position,
1953 "[%E] designator used for non-array type '%T'",
1954 array_index, orig_type);
1959 long index = fold_constant_to_int(array_index);
1960 if (!used_in_offsetof) {
1962 errorf(&designator->source_position,
1963 "array index [%E] must be positive", array_index);
1964 } else if (type->array.size_constant) {
1965 long array_size = type->array.size;
1966 if (index >= array_size) {
1967 errorf(&designator->source_position,
1968 "designator [%E] (%d) exceeds array size %d",
1969 array_index, index, array_size);
1974 top->type = orig_type;
1975 top->v.index = (size_t) index;
1976 orig_type = type->array.element_type;
1978 path->top_type = orig_type;
1980 if (designator->next != NULL) {
1981 descend_into_subtype(path);
1987 static void advance_current_object(type_path_t *path, size_t top_path_level)
1989 type_path_entry_t *top = get_type_path_top(path);
1991 type_t *type = skip_typeref(top->type);
1992 if (is_type_union(type)) {
1993 /* in unions only the first element is initialized */
1994 top->v.compound_entry = NULL;
1995 } else if (is_type_struct(type)) {
1996 declaration_t *entry = top->v.compound_entry;
1998 entity_t *next_entity = entry->base.next;
1999 if (next_entity != NULL) {
2000 assert(is_declaration(next_entity));
2001 entry = &next_entity->declaration;
2006 top->v.compound_entry = entry;
2007 if (entry != NULL) {
2008 path->top_type = entry->type;
2011 } else if (is_type_array(type)) {
2012 assert(is_type_array(type));
2016 if (!type->array.size_constant || top->v.index < type->array.size) {
2020 assert(!is_type_valid(type));
2024 /* we're past the last member of the current sub-aggregate, try if we
2025 * can ascend in the type hierarchy and continue with another subobject */
2026 size_t len = ARR_LEN(path->path);
2028 if (len > top_path_level) {
2029 ascend_from_subtype(path);
2030 advance_current_object(path, top_path_level);
2032 path->top_type = NULL;
2037 * skip any {...} blocks until a closing bracket is reached.
2039 static void skip_initializers(void)
2043 while (token.type != '}') {
2044 if (token.type == T_EOF)
2046 if (token.type == '{') {
2054 static initializer_t *create_empty_initializer(void)
2056 static initializer_t empty_initializer
2057 = { .list = { { INITIALIZER_LIST }, 0 } };
2058 return &empty_initializer;
2062 * Parse a part of an initialiser for a struct or union,
2064 static initializer_t *parse_sub_initializer(type_path_t *path,
2065 type_t *outer_type, size_t top_path_level,
2066 parse_initializer_env_t *env)
2068 if (token.type == '}') {
2069 /* empty initializer */
2070 return create_empty_initializer();
2073 type_t *orig_type = path->top_type;
2074 type_t *type = NULL;
2076 if (orig_type == NULL) {
2077 /* We are initializing an empty compound. */
2079 type = skip_typeref(orig_type);
2082 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2085 designator_t *designator = NULL;
2086 if (token.type == '.' || token.type == '[') {
2087 designator = parse_designation();
2088 goto finish_designator;
2089 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2090 /* GNU-style designator ("identifier: value") */
2091 designator = allocate_ast_zero(sizeof(designator[0]));
2092 designator->source_position = token.source_position;
2093 designator->symbol = token.symbol;
2098 /* reset path to toplevel, evaluate designator from there */
2099 ascend_to(path, top_path_level);
2100 if (!walk_designator(path, designator, false)) {
2101 /* can't continue after designation error */
2105 initializer_t *designator_initializer
2106 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2107 designator_initializer->designator.designator = designator;
2108 ARR_APP1(initializer_t*, initializers, designator_initializer);
2110 orig_type = path->top_type;
2111 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2116 if (token.type == '{') {
2117 if (type != NULL && is_type_scalar(type)) {
2118 sub = parse_scalar_initializer(type, env->must_be_constant);
2121 if (env->entity != NULL) {
2123 "extra brace group at end of initializer for '%Y'",
2124 env->entity->base.symbol);
2126 errorf(HERE, "extra brace group at end of initializer");
2131 descend_into_subtype(path);
2134 add_anchor_token('}');
2135 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2137 rem_anchor_token('}');
2140 ascend_from_subtype(path);
2141 expect('}', end_error);
2143 expect('}', end_error);
2144 goto error_parse_next;
2148 /* must be an expression */
2149 expression_t *expression = parse_assignment_expression();
2150 mark_vars_read(expression, NULL);
2152 if (env->must_be_constant && !is_initializer_constant(expression)) {
2153 errorf(&expression->base.source_position,
2154 "Initialisation expression '%E' is not constant",
2159 /* we are already outside, ... */
2160 if (outer_type == NULL)
2161 goto error_parse_next;
2162 type_t *const outer_type_skip = skip_typeref(outer_type);
2163 if (is_type_compound(outer_type_skip) &&
2164 !outer_type_skip->compound.compound->complete) {
2165 goto error_parse_next;
2168 source_position_t const* const pos = &expression->base.source_position;
2169 if (env->entity != NULL) {
2170 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2172 warningf(WARN_OTHER, pos, "excess elements in initializer");
2174 goto error_parse_next;
2177 /* handle { "string" } special case */
2178 if ((expression->kind == EXPR_STRING_LITERAL
2179 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2180 && outer_type != NULL) {
2181 sub = initializer_from_expression(outer_type, expression);
2184 if (token.type != '}') {
2185 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2187 /* TODO: eat , ... */
2192 /* descend into subtypes until expression matches type */
2194 orig_type = path->top_type;
2195 type = skip_typeref(orig_type);
2197 sub = initializer_from_expression(orig_type, expression);
2201 if (!is_type_valid(type)) {
2204 if (is_type_scalar(type)) {
2205 errorf(&expression->base.source_position,
2206 "expression '%E' doesn't match expected type '%T'",
2207 expression, orig_type);
2211 descend_into_subtype(path);
2215 /* update largest index of top array */
2216 const type_path_entry_t *first = &path->path[0];
2217 type_t *first_type = first->type;
2218 first_type = skip_typeref(first_type);
2219 if (is_type_array(first_type)) {
2220 size_t index = first->v.index;
2221 if (index > path->max_index)
2222 path->max_index = index;
2225 /* append to initializers list */
2226 ARR_APP1(initializer_t*, initializers, sub);
2229 if (token.type == '}') {
2232 expect(',', end_error);
2233 if (token.type == '}') {
2238 /* advance to the next declaration if we are not at the end */
2239 advance_current_object(path, top_path_level);
2240 orig_type = path->top_type;
2241 if (orig_type != NULL)
2242 type = skip_typeref(orig_type);
2248 size_t len = ARR_LEN(initializers);
2249 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2250 initializer_t *result = allocate_ast_zero(size);
2251 result->kind = INITIALIZER_LIST;
2252 result->list.len = len;
2253 memcpy(&result->list.initializers, initializers,
2254 len * sizeof(initializers[0]));
2256 DEL_ARR_F(initializers);
2257 ascend_to(path, top_path_level+1);
2262 skip_initializers();
2263 DEL_ARR_F(initializers);
2264 ascend_to(path, top_path_level+1);
2268 static expression_t *make_size_literal(size_t value)
2270 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2271 literal->base.type = type_size_t;
2274 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2275 literal->literal.value = make_string(buf);
2281 * Parses an initializer. Parsers either a compound literal
2282 * (env->declaration == NULL) or an initializer of a declaration.
2284 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2286 type_t *type = skip_typeref(env->type);
2287 size_t max_index = 0;
2288 initializer_t *result;
2290 if (is_type_scalar(type)) {
2291 result = parse_scalar_initializer(type, env->must_be_constant);
2292 } else if (token.type == '{') {
2296 memset(&path, 0, sizeof(path));
2297 path.top_type = env->type;
2298 path.path = NEW_ARR_F(type_path_entry_t, 0);
2300 descend_into_subtype(&path);
2302 add_anchor_token('}');
2303 result = parse_sub_initializer(&path, env->type, 1, env);
2304 rem_anchor_token('}');
2306 max_index = path.max_index;
2307 DEL_ARR_F(path.path);
2309 expect('}', end_error);
2312 /* parse_scalar_initializer() also works in this case: we simply
2313 * have an expression without {} around it */
2314 result = parse_scalar_initializer(type, env->must_be_constant);
2317 /* §6.7.8:22 array initializers for arrays with unknown size determine
2318 * the array type size */
2319 if (is_type_array(type) && type->array.size_expression == NULL
2320 && result != NULL) {
2322 switch (result->kind) {
2323 case INITIALIZER_LIST:
2324 assert(max_index != 0xdeadbeaf);
2325 size = max_index + 1;
2328 case INITIALIZER_STRING:
2329 size = result->string.string.size;
2332 case INITIALIZER_WIDE_STRING:
2333 size = result->wide_string.string.size;
2336 case INITIALIZER_DESIGNATOR:
2337 case INITIALIZER_VALUE:
2338 /* can happen for parse errors */
2343 internal_errorf(HERE, "invalid initializer type");
2346 type_t *new_type = duplicate_type(type);
2348 new_type->array.size_expression = make_size_literal(size);
2349 new_type->array.size_constant = true;
2350 new_type->array.has_implicit_size = true;
2351 new_type->array.size = size;
2352 env->type = new_type;
2358 static void append_entity(scope_t *scope, entity_t *entity)
2360 if (scope->last_entity != NULL) {
2361 scope->last_entity->base.next = entity;
2363 scope->entities = entity;
2365 entity->base.parent_entity = current_entity;
2366 scope->last_entity = entity;
2370 static compound_t *parse_compound_type_specifier(bool is_struct)
2372 source_position_t const pos = *HERE;
2373 eat(is_struct ? T_struct : T_union);
2375 symbol_t *symbol = NULL;
2376 entity_t *entity = NULL;
2377 attribute_t *attributes = NULL;
2379 if (token.type == T___attribute__) {
2380 attributes = parse_attributes(NULL);
2383 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2384 if (token.type == T_IDENTIFIER) {
2385 /* the compound has a name, check if we have seen it already */
2386 symbol = token.symbol;
2387 entity = get_tag(symbol, kind);
2390 if (entity != NULL) {
2391 if (entity->base.parent_scope != current_scope &&
2392 (token.type == '{' || token.type == ';')) {
2393 /* we're in an inner scope and have a definition. Shadow
2394 * existing definition in outer scope */
2396 } else if (entity->compound.complete && token.type == '{') {
2397 source_position_t const *const ppos = &entity->base.source_position;
2398 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2399 /* clear members in the hope to avoid further errors */
2400 entity->compound.members.entities = NULL;
2403 } else if (token.type != '{') {
2404 char const *const msg =
2405 is_struct ? "while parsing struct type specifier" :
2406 "while parsing union type specifier";
2407 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2412 if (entity == NULL) {
2413 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2414 entity->compound.alignment = 1;
2415 entity->base.source_position = pos;
2416 entity->base.parent_scope = current_scope;
2417 if (symbol != NULL) {
2418 environment_push(entity);
2420 append_entity(current_scope, entity);
2423 if (token.type == '{') {
2424 parse_compound_type_entries(&entity->compound);
2426 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2427 if (symbol == NULL) {
2428 assert(anonymous_entity == NULL);
2429 anonymous_entity = entity;
2433 if (attributes != NULL) {
2434 handle_entity_attributes(attributes, entity);
2437 return &entity->compound;
2440 static void parse_enum_entries(type_t *const enum_type)
2444 if (token.type == '}') {
2445 errorf(HERE, "empty enum not allowed");
2450 add_anchor_token('}');
2452 if (token.type != T_IDENTIFIER) {
2453 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2455 rem_anchor_token('}');
2459 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, token.symbol);
2460 entity->enum_value.enum_type = enum_type;
2461 entity->base.source_position = token.source_position;
2465 expression_t *value = parse_constant_expression();
2467 value = create_implicit_cast(value, enum_type);
2468 entity->enum_value.value = value;
2473 record_entity(entity, false);
2474 } while (next_if(',') && token.type != '}');
2475 rem_anchor_token('}');
2477 expect('}', end_error);
2483 static type_t *parse_enum_specifier(void)
2485 source_position_t const pos = *HERE;
2490 switch (token.type) {
2492 symbol = token.symbol;
2493 entity = get_tag(symbol, ENTITY_ENUM);
2496 if (entity != NULL) {
2497 if (entity->base.parent_scope != current_scope &&
2498 (token.type == '{' || token.type == ';')) {
2499 /* we're in an inner scope and have a definition. Shadow
2500 * existing definition in outer scope */
2502 } else if (entity->enume.complete && token.type == '{') {
2503 source_position_t const *const ppos = &entity->base.source_position;
2504 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2515 parse_error_expected("while parsing enum type specifier",
2516 T_IDENTIFIER, '{', NULL);
2520 if (entity == NULL) {
2521 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2522 entity->base.source_position = pos;
2523 entity->base.parent_scope = current_scope;
2526 type_t *const type = allocate_type_zero(TYPE_ENUM);
2527 type->enumt.enume = &entity->enume;
2528 type->enumt.akind = ATOMIC_TYPE_INT;
2530 if (token.type == '{') {
2531 if (symbol != NULL) {
2532 environment_push(entity);
2534 append_entity(current_scope, entity);
2535 entity->enume.complete = true;
2537 parse_enum_entries(type);
2538 parse_attributes(NULL);
2540 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2541 if (symbol == NULL) {
2542 assert(anonymous_entity == NULL);
2543 anonymous_entity = entity;
2545 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2546 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2553 * if a symbol is a typedef to another type, return true
2555 static bool is_typedef_symbol(symbol_t *symbol)
2557 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2558 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2561 static type_t *parse_typeof(void)
2567 expect('(', end_error);
2568 add_anchor_token(')');
2570 expression_t *expression = NULL;
2572 bool old_type_prop = in_type_prop;
2573 bool old_gcc_extension = in_gcc_extension;
2574 in_type_prop = true;
2576 while (next_if(T___extension__)) {
2577 /* This can be a prefix to a typename or an expression. */
2578 in_gcc_extension = true;
2580 switch (token.type) {
2582 if (is_typedef_symbol(token.symbol)) {
2584 type = parse_typename();
2587 expression = parse_expression();
2588 type = revert_automatic_type_conversion(expression);
2592 in_type_prop = old_type_prop;
2593 in_gcc_extension = old_gcc_extension;
2595 rem_anchor_token(')');
2596 expect(')', end_error);
2598 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2599 typeof_type->typeoft.expression = expression;
2600 typeof_type->typeoft.typeof_type = type;
2607 typedef enum specifiers_t {
2608 SPECIFIER_SIGNED = 1 << 0,
2609 SPECIFIER_UNSIGNED = 1 << 1,
2610 SPECIFIER_LONG = 1 << 2,
2611 SPECIFIER_INT = 1 << 3,
2612 SPECIFIER_DOUBLE = 1 << 4,
2613 SPECIFIER_CHAR = 1 << 5,
2614 SPECIFIER_WCHAR_T = 1 << 6,
2615 SPECIFIER_SHORT = 1 << 7,
2616 SPECIFIER_LONG_LONG = 1 << 8,
2617 SPECIFIER_FLOAT = 1 << 9,
2618 SPECIFIER_BOOL = 1 << 10,
2619 SPECIFIER_VOID = 1 << 11,
2620 SPECIFIER_INT8 = 1 << 12,
2621 SPECIFIER_INT16 = 1 << 13,
2622 SPECIFIER_INT32 = 1 << 14,
2623 SPECIFIER_INT64 = 1 << 15,
2624 SPECIFIER_INT128 = 1 << 16,
2625 SPECIFIER_COMPLEX = 1 << 17,
2626 SPECIFIER_IMAGINARY = 1 << 18,
2629 static type_t *get_typedef_type(symbol_t *symbol)
2631 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2632 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2635 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2636 type->typedeft.typedefe = &entity->typedefe;
2641 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2643 expect('(', end_error);
2645 attribute_property_argument_t *property
2646 = allocate_ast_zero(sizeof(*property));
2649 if (token.type != T_IDENTIFIER) {
2650 parse_error_expected("while parsing property declspec",
2651 T_IDENTIFIER, NULL);
2656 symbol_t *symbol = token.symbol;
2657 if (strcmp(symbol->string, "put") == 0) {
2658 prop = &property->put_symbol;
2659 } else if (strcmp(symbol->string, "get") == 0) {
2660 prop = &property->get_symbol;
2662 errorf(HERE, "expected put or get in property declspec");
2666 expect('=', end_error);
2667 if (token.type != T_IDENTIFIER) {
2668 parse_error_expected("while parsing property declspec",
2669 T_IDENTIFIER, NULL);
2673 *prop = token.symbol;
2675 } while (next_if(','));
2677 attribute->a.property = property;
2679 expect(')', end_error);
2685 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2687 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2688 if (next_if(T_restrict)) {
2689 kind = ATTRIBUTE_MS_RESTRICT;
2690 } else if (token.type == T_IDENTIFIER) {
2691 const char *name = token.symbol->string;
2692 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2694 const char *attribute_name = get_attribute_name(k);
2695 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2701 if (kind == ATTRIBUTE_UNKNOWN) {
2702 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2706 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2710 attribute_t *attribute = allocate_attribute_zero(kind);
2712 if (kind == ATTRIBUTE_MS_PROPERTY) {
2713 return parse_attribute_ms_property(attribute);
2716 /* parse arguments */
2718 attribute->a.arguments = parse_attribute_arguments();
2723 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2727 expect('(', end_error);
2732 add_anchor_token(')');
2734 attribute_t **anchor = &first;
2736 while (*anchor != NULL)
2737 anchor = &(*anchor)->next;
2739 attribute_t *attribute
2740 = parse_microsoft_extended_decl_modifier_single();
2741 if (attribute == NULL)
2744 *anchor = attribute;
2745 anchor = &attribute->next;
2746 } while (next_if(','));
2748 rem_anchor_token(')');
2749 expect(')', end_error);
2753 rem_anchor_token(')');
2757 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2759 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2760 entity->base.source_position = *HERE;
2761 if (is_declaration(entity)) {
2762 entity->declaration.type = type_error_type;
2763 entity->declaration.implicit = true;
2764 } else if (kind == ENTITY_TYPEDEF) {
2765 entity->typedefe.type = type_error_type;
2766 entity->typedefe.builtin = true;
2768 if (kind != ENTITY_COMPOUND_MEMBER)
2769 record_entity(entity, false);
2773 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2775 type_t *type = NULL;
2776 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2777 unsigned type_specifiers = 0;
2778 bool newtype = false;
2779 bool saw_error = false;
2780 bool old_gcc_extension = in_gcc_extension;
2782 memset(specifiers, 0, sizeof(*specifiers));
2783 specifiers->source_position = token.source_position;
2786 specifiers->attributes = parse_attributes(specifiers->attributes);
2788 switch (token.type) {
2790 #define MATCH_STORAGE_CLASS(token, class) \
2792 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2793 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2795 specifiers->storage_class = class; \
2796 if (specifiers->thread_local) \
2797 goto check_thread_storage_class; \
2801 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2802 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2803 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2804 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2805 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2808 specifiers->attributes
2809 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2813 if (specifiers->thread_local) {
2814 errorf(HERE, "duplicate '__thread'");
2816 specifiers->thread_local = true;
2817 check_thread_storage_class:
2818 switch (specifiers->storage_class) {
2819 case STORAGE_CLASS_EXTERN:
2820 case STORAGE_CLASS_NONE:
2821 case STORAGE_CLASS_STATIC:
2825 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2826 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2827 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2828 wrong_thread_storage_class:
2829 errorf(HERE, "'__thread' used with '%s'", wrong);
2836 /* type qualifiers */
2837 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2839 qualifiers |= qualifier; \
2843 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2844 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2845 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2846 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2847 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2848 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2849 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2850 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2852 case T___extension__:
2854 in_gcc_extension = true;
2857 /* type specifiers */
2858 #define MATCH_SPECIFIER(token, specifier, name) \
2860 if (type_specifiers & specifier) { \
2861 errorf(HERE, "multiple " name " type specifiers given"); \
2863 type_specifiers |= specifier; \
2868 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2869 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2870 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2871 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2872 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2873 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2874 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2875 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2876 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2877 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2878 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2879 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2880 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2881 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2882 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2883 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2884 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2885 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2889 specifiers->is_inline = true;
2893 case T__forceinline:
2895 specifiers->modifiers |= DM_FORCEINLINE;
2900 if (type_specifiers & SPECIFIER_LONG_LONG) {
2901 errorf(HERE, "too many long type specifiers given");
2902 } else if (type_specifiers & SPECIFIER_LONG) {
2903 type_specifiers |= SPECIFIER_LONG_LONG;
2905 type_specifiers |= SPECIFIER_LONG;
2910 #define CHECK_DOUBLE_TYPE() \
2911 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2914 CHECK_DOUBLE_TYPE();
2915 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2917 type->compound.compound = parse_compound_type_specifier(true);
2920 CHECK_DOUBLE_TYPE();
2921 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2922 type->compound.compound = parse_compound_type_specifier(false);
2925 CHECK_DOUBLE_TYPE();
2926 type = parse_enum_specifier();
2929 CHECK_DOUBLE_TYPE();
2930 type = parse_typeof();
2932 case T___builtin_va_list:
2933 CHECK_DOUBLE_TYPE();
2934 type = duplicate_type(type_valist);
2938 case T_IDENTIFIER: {
2939 /* only parse identifier if we haven't found a type yet */
2940 if (type != NULL || type_specifiers != 0) {
2941 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2942 * declaration, so it doesn't generate errors about expecting '(' or
2944 switch (look_ahead(1)->type) {
2951 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2955 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2960 goto finish_specifiers;
2964 type_t *const typedef_type = get_typedef_type(token.symbol);
2965 if (typedef_type == NULL) {
2966 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2967 * declaration, so it doesn't generate 'implicit int' followed by more
2968 * errors later on. */
2969 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2975 errorf(HERE, "%K does not name a type", &token);
2978 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2980 type = allocate_type_zero(TYPE_TYPEDEF);
2981 type->typedeft.typedefe = &entity->typedefe;
2989 goto finish_specifiers;
2994 type = typedef_type;
2998 /* function specifier */
3000 goto finish_specifiers;
3005 specifiers->attributes = parse_attributes(specifiers->attributes);
3007 in_gcc_extension = old_gcc_extension;
3009 if (type == NULL || (saw_error && type_specifiers != 0)) {
3010 atomic_type_kind_t atomic_type;
3012 /* match valid basic types */
3013 switch (type_specifiers) {
3014 case SPECIFIER_VOID:
3015 atomic_type = ATOMIC_TYPE_VOID;
3017 case SPECIFIER_WCHAR_T:
3018 atomic_type = ATOMIC_TYPE_WCHAR_T;
3020 case SPECIFIER_CHAR:
3021 atomic_type = ATOMIC_TYPE_CHAR;
3023 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3024 atomic_type = ATOMIC_TYPE_SCHAR;
3026 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3027 atomic_type = ATOMIC_TYPE_UCHAR;
3029 case SPECIFIER_SHORT:
3030 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3031 case SPECIFIER_SHORT | SPECIFIER_INT:
3032 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3033 atomic_type = ATOMIC_TYPE_SHORT;
3035 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3036 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3037 atomic_type = ATOMIC_TYPE_USHORT;
3040 case SPECIFIER_SIGNED:
3041 case SPECIFIER_SIGNED | SPECIFIER_INT:
3042 atomic_type = ATOMIC_TYPE_INT;
3044 case SPECIFIER_UNSIGNED:
3045 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3046 atomic_type = ATOMIC_TYPE_UINT;
3048 case SPECIFIER_LONG:
3049 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3050 case SPECIFIER_LONG | SPECIFIER_INT:
3051 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3052 atomic_type = ATOMIC_TYPE_LONG;
3054 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3055 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3056 atomic_type = ATOMIC_TYPE_ULONG;
3059 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3060 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3061 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3062 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3064 atomic_type = ATOMIC_TYPE_LONGLONG;
3065 goto warn_about_long_long;
3067 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3068 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3070 atomic_type = ATOMIC_TYPE_ULONGLONG;
3071 warn_about_long_long:
3072 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3075 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3076 atomic_type = unsigned_int8_type_kind;
3079 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3080 atomic_type = unsigned_int16_type_kind;
3083 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3084 atomic_type = unsigned_int32_type_kind;
3087 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3088 atomic_type = unsigned_int64_type_kind;
3091 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3092 atomic_type = unsigned_int128_type_kind;
3095 case SPECIFIER_INT8:
3096 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3097 atomic_type = int8_type_kind;
3100 case SPECIFIER_INT16:
3101 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3102 atomic_type = int16_type_kind;
3105 case SPECIFIER_INT32:
3106 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3107 atomic_type = int32_type_kind;
3110 case SPECIFIER_INT64:
3111 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3112 atomic_type = int64_type_kind;
3115 case SPECIFIER_INT128:
3116 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3117 atomic_type = int128_type_kind;
3120 case SPECIFIER_FLOAT:
3121 atomic_type = ATOMIC_TYPE_FLOAT;
3123 case SPECIFIER_DOUBLE:
3124 atomic_type = ATOMIC_TYPE_DOUBLE;
3126 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3127 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3129 case SPECIFIER_BOOL:
3130 atomic_type = ATOMIC_TYPE_BOOL;
3132 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3133 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3134 atomic_type = ATOMIC_TYPE_FLOAT;
3136 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3137 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3138 atomic_type = ATOMIC_TYPE_DOUBLE;
3140 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3141 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3142 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3145 /* invalid specifier combination, give an error message */
3146 source_position_t const* const pos = &specifiers->source_position;
3147 if (type_specifiers == 0) {
3149 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3150 if (!(c_mode & _CXX) && !strict_mode) {
3151 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3152 atomic_type = ATOMIC_TYPE_INT;
3155 errorf(pos, "no type specifiers given in declaration");
3158 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3159 (type_specifiers & SPECIFIER_UNSIGNED)) {
3160 errorf(pos, "signed and unsigned specifiers given");
3161 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3162 errorf(pos, "only integer types can be signed or unsigned");
3164 errorf(pos, "multiple datatypes in declaration");
3170 if (type_specifiers & SPECIFIER_COMPLEX) {
3171 type = allocate_type_zero(TYPE_COMPLEX);
3172 type->complex.akind = atomic_type;
3173 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3174 type = allocate_type_zero(TYPE_IMAGINARY);
3175 type->imaginary.akind = atomic_type;
3177 type = allocate_type_zero(TYPE_ATOMIC);
3178 type->atomic.akind = atomic_type;
3181 } else if (type_specifiers != 0) {
3182 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3185 /* FIXME: check type qualifiers here */
3186 type->base.qualifiers = qualifiers;
3189 type = identify_new_type(type);
3191 type = typehash_insert(type);
3194 if (specifiers->attributes != NULL)
3195 type = handle_type_attributes(specifiers->attributes, type);
3196 specifiers->type = type;
3200 specifiers->type = type_error_type;
3203 static type_qualifiers_t parse_type_qualifiers(void)
3205 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3208 switch (token.type) {
3209 /* type qualifiers */
3210 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3211 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3212 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3213 /* microsoft extended type modifiers */
3214 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3215 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3216 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3217 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3218 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3227 * Parses an K&R identifier list
3229 static void parse_identifier_list(scope_t *scope)
3232 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3233 entity->base.source_position = token.source_position;
3234 /* a K&R parameter has no type, yet */
3238 append_entity(scope, entity);
3239 } while (next_if(',') && token.type == T_IDENTIFIER);
3242 static entity_t *parse_parameter(void)
3244 declaration_specifiers_t specifiers;
3245 parse_declaration_specifiers(&specifiers);
3247 entity_t *entity = parse_declarator(&specifiers,
3248 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3249 anonymous_entity = NULL;
3253 static void semantic_parameter_incomplete(const entity_t *entity)
3255 assert(entity->kind == ENTITY_PARAMETER);
3257 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3258 * list in a function declarator that is part of a
3259 * definition of that function shall not have
3260 * incomplete type. */
3261 type_t *type = skip_typeref(entity->declaration.type);
3262 if (is_type_incomplete(type)) {
3263 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3267 static bool has_parameters(void)
3269 /* func(void) is not a parameter */
3270 if (token.type == T_IDENTIFIER) {
3271 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3274 if (entity->kind != ENTITY_TYPEDEF)
3276 if (skip_typeref(entity->typedefe.type) != type_void)
3278 } else if (token.type != T_void) {
3281 if (look_ahead(1)->type != ')')
3288 * Parses function type parameters (and optionally creates variable_t entities
3289 * for them in a scope)
3291 static void parse_parameters(function_type_t *type, scope_t *scope)
3294 add_anchor_token(')');
3295 int saved_comma_state = save_and_reset_anchor_state(',');
3297 if (token.type == T_IDENTIFIER &&
3298 !is_typedef_symbol(token.symbol)) {
3299 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3300 if (la1_type == ',' || la1_type == ')') {
3301 type->kr_style_parameters = true;
3302 parse_identifier_list(scope);
3303 goto parameters_finished;
3307 if (token.type == ')') {
3308 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3309 if (!(c_mode & _CXX))
3310 type->unspecified_parameters = true;
3311 } else if (has_parameters()) {
3312 function_parameter_t **anchor = &type->parameters;
3314 switch (token.type) {
3317 type->variadic = true;
3318 goto parameters_finished;
3321 case T___extension__:
3324 entity_t *entity = parse_parameter();
3325 if (entity->kind == ENTITY_TYPEDEF) {
3326 errorf(&entity->base.source_position,
3327 "typedef not allowed as function parameter");
3330 assert(is_declaration(entity));
3332 semantic_parameter_incomplete(entity);
3334 function_parameter_t *const parameter =
3335 allocate_parameter(entity->declaration.type);
3337 if (scope != NULL) {
3338 append_entity(scope, entity);
3341 *anchor = parameter;
3342 anchor = ¶meter->next;
3347 goto parameters_finished;
3349 } while (next_if(','));
3352 parameters_finished:
3353 rem_anchor_token(')');
3354 expect(')', end_error);
3357 restore_anchor_state(',', saved_comma_state);
3360 typedef enum construct_type_kind_t {
3363 CONSTRUCT_REFERENCE,
3366 } construct_type_kind_t;
3368 typedef union construct_type_t construct_type_t;
3370 typedef struct construct_type_base_t {
3371 construct_type_kind_t kind;
3372 source_position_t pos;
3373 construct_type_t *next;
3374 } construct_type_base_t;
3376 typedef struct parsed_pointer_t {
3377 construct_type_base_t base;
3378 type_qualifiers_t type_qualifiers;
3379 variable_t *base_variable; /**< MS __based extension. */
3382 typedef struct parsed_reference_t {
3383 construct_type_base_t base;
3384 } parsed_reference_t;
3386 typedef struct construct_function_type_t {
3387 construct_type_base_t base;
3388 type_t *function_type;
3389 } construct_function_type_t;
3391 typedef struct parsed_array_t {
3392 construct_type_base_t base;
3393 type_qualifiers_t type_qualifiers;
3399 union construct_type_t {
3400 construct_type_kind_t kind;
3401 construct_type_base_t base;
3402 parsed_pointer_t pointer;
3403 parsed_reference_t reference;
3404 construct_function_type_t function;
3405 parsed_array_t array;
3408 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3410 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3411 memset(cons, 0, size);
3413 cons->base.pos = *HERE;
3418 static construct_type_t *parse_pointer_declarator(void)
3420 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3422 cons->pointer.type_qualifiers = parse_type_qualifiers();
3423 //cons->pointer.base_variable = base_variable;
3428 /* ISO/IEC 14882:1998(E) §8.3.2 */
3429 static construct_type_t *parse_reference_declarator(void)
3431 if (!(c_mode & _CXX))
3432 errorf(HERE, "references are only available for C++");
3434 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3441 static construct_type_t *parse_array_declarator(void)
3443 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3444 parsed_array_t *const array = &cons->array;
3447 add_anchor_token(']');
3449 bool is_static = next_if(T_static);
3451 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3454 is_static = next_if(T_static);
3456 array->type_qualifiers = type_qualifiers;
3457 array->is_static = is_static;
3459 expression_t *size = NULL;
3460 if (token.type == '*' && look_ahead(1)->type == ']') {
3461 array->is_variable = true;
3463 } else if (token.type != ']') {
3464 size = parse_assignment_expression();
3466 /* §6.7.5.2:1 Array size must have integer type */
3467 type_t *const orig_type = size->base.type;
3468 type_t *const type = skip_typeref(orig_type);
3469 if (!is_type_integer(type) && is_type_valid(type)) {
3470 errorf(&size->base.source_position,
3471 "array size '%E' must have integer type but has type '%T'",
3476 mark_vars_read(size, NULL);
3479 if (is_static && size == NULL)
3480 errorf(&array->base.pos, "static array parameters require a size");
3482 rem_anchor_token(']');
3483 expect(']', end_error);
3490 static construct_type_t *parse_function_declarator(scope_t *scope)
3492 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3494 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3495 function_type_t *ftype = &type->function;
3497 ftype->linkage = current_linkage;
3498 ftype->calling_convention = CC_DEFAULT;
3500 parse_parameters(ftype, scope);
3502 cons->function.function_type = type;
3507 typedef struct parse_declarator_env_t {
3508 bool may_be_abstract : 1;
3509 bool must_be_abstract : 1;
3510 decl_modifiers_t modifiers;
3512 source_position_t source_position;
3514 attribute_t *attributes;
3515 } parse_declarator_env_t;
3518 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3520 /* construct a single linked list of construct_type_t's which describe
3521 * how to construct the final declarator type */
3522 construct_type_t *first = NULL;
3523 construct_type_t **anchor = &first;
3525 env->attributes = parse_attributes(env->attributes);
3528 construct_type_t *type;
3529 //variable_t *based = NULL; /* MS __based extension */
3530 switch (token.type) {
3532 type = parse_reference_declarator();
3536 panic("based not supported anymore");
3541 type = parse_pointer_declarator();
3545 goto ptr_operator_end;
3549 anchor = &type->base.next;
3551 /* TODO: find out if this is correct */
3552 env->attributes = parse_attributes(env->attributes);
3556 construct_type_t *inner_types = NULL;
3558 switch (token.type) {
3560 if (env->must_be_abstract) {
3561 errorf(HERE, "no identifier expected in typename");
3563 env->symbol = token.symbol;
3564 env->source_position = token.source_position;
3570 /* Parenthesized declarator or function declarator? */
3571 token_t const *const la1 = look_ahead(1);
3572 switch (la1->type) {
3574 if (is_typedef_symbol(la1->symbol)) {
3576 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3577 * interpreted as ``function with no parameter specification'', rather
3578 * than redundant parentheses around the omitted identifier. */
3580 /* Function declarator. */
3581 if (!env->may_be_abstract) {
3582 errorf(HERE, "function declarator must have a name");
3589 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3590 /* Paranthesized declarator. */
3592 add_anchor_token(')');
3593 inner_types = parse_inner_declarator(env);
3594 if (inner_types != NULL) {
3595 /* All later declarators only modify the return type */
3596 env->must_be_abstract = true;
3598 rem_anchor_token(')');
3599 expect(')', end_error);
3607 if (env->may_be_abstract)
3609 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3614 construct_type_t **const p = anchor;
3617 construct_type_t *type;
3618 switch (token.type) {
3620 scope_t *scope = NULL;
3621 if (!env->must_be_abstract) {
3622 scope = &env->parameters;
3625 type = parse_function_declarator(scope);
3629 type = parse_array_declarator();
3632 goto declarator_finished;
3635 /* insert in the middle of the list (at p) */
3636 type->base.next = *p;
3639 anchor = &type->base.next;
3642 declarator_finished:
3643 /* append inner_types at the end of the list, we don't to set anchor anymore
3644 * as it's not needed anymore */
3645 *anchor = inner_types;
3652 static type_t *construct_declarator_type(construct_type_t *construct_list,
3655 construct_type_t *iter = construct_list;
3656 for (; iter != NULL; iter = iter->base.next) {
3657 source_position_t const* const pos = &iter->base.pos;
3658 switch (iter->kind) {
3659 case CONSTRUCT_INVALID:
3661 case CONSTRUCT_FUNCTION: {
3662 construct_function_type_t *function = &iter->function;
3663 type_t *function_type = function->function_type;
3665 function_type->function.return_type = type;
3667 type_t *skipped_return_type = skip_typeref(type);
3669 if (is_type_function(skipped_return_type)) {
3670 errorf(pos, "function returning function is not allowed");
3671 } else if (is_type_array(skipped_return_type)) {
3672 errorf(pos, "function returning array is not allowed");
3674 if (skipped_return_type->base.qualifiers != 0) {
3675 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3679 /* The function type was constructed earlier. Freeing it here will
3680 * destroy other types. */
3681 type = typehash_insert(function_type);
3685 case CONSTRUCT_POINTER: {
3686 if (is_type_reference(skip_typeref(type)))
3687 errorf(pos, "cannot declare a pointer to reference");
3689 parsed_pointer_t *pointer = &iter->pointer;
3690 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3694 case CONSTRUCT_REFERENCE:
3695 if (is_type_reference(skip_typeref(type)))
3696 errorf(pos, "cannot declare a reference to reference");
3698 type = make_reference_type(type);
3701 case CONSTRUCT_ARRAY: {
3702 if (is_type_reference(skip_typeref(type)))
3703 errorf(pos, "cannot declare an array of references");
3705 parsed_array_t *array = &iter->array;
3706 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3708 expression_t *size_expression = array->size;
3709 if (size_expression != NULL) {
3711 = create_implicit_cast(size_expression, type_size_t);
3714 array_type->base.qualifiers = array->type_qualifiers;
3715 array_type->array.element_type = type;
3716 array_type->array.is_static = array->is_static;
3717 array_type->array.is_variable = array->is_variable;
3718 array_type->array.size_expression = size_expression;
3720 if (size_expression != NULL) {
3721 switch (is_constant_expression(size_expression)) {
3722 case EXPR_CLASS_CONSTANT: {
3723 long const size = fold_constant_to_int(size_expression);
3724 array_type->array.size = size;
3725 array_type->array.size_constant = true;
3726 /* §6.7.5.2:1 If the expression is a constant expression,
3727 * it shall have a value greater than zero. */
3729 errorf(&size_expression->base.source_position,
3730 "size of array must be greater than zero");
3731 } else if (size == 0 && !GNU_MODE) {
3732 errorf(&size_expression->base.source_position,
3733 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3738 case EXPR_CLASS_VARIABLE:
3739 array_type->array.is_vla = true;
3742 case EXPR_CLASS_ERROR:
3747 type_t *skipped_type = skip_typeref(type);
3749 if (is_type_incomplete(skipped_type)) {
3750 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3751 } else if (is_type_function(skipped_type)) {
3752 errorf(pos, "array of functions is not allowed");
3754 type = identify_new_type(array_type);
3758 internal_errorf(pos, "invalid type construction found");
3764 static type_t *automatic_type_conversion(type_t *orig_type);
3766 static type_t *semantic_parameter(const source_position_t *pos,
3768 const declaration_specifiers_t *specifiers,
3769 entity_t const *const param)
3771 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3772 * shall be adjusted to ``qualified pointer to type'',
3774 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3775 * type'' shall be adjusted to ``pointer to function
3776 * returning type'', as in 6.3.2.1. */
3777 type = automatic_type_conversion(type);
3779 if (specifiers->is_inline && is_type_valid(type)) {
3780 errorf(pos, "'%N' declared 'inline'", param);
3783 /* §6.9.1:6 The declarations in the declaration list shall contain
3784 * no storage-class specifier other than register and no
3785 * initializations. */
3786 if (specifiers->thread_local || (
3787 specifiers->storage_class != STORAGE_CLASS_NONE &&
3788 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3790 errorf(pos, "invalid storage class for '%N'", param);
3793 /* delay test for incomplete type, because we might have (void)
3794 * which is legal but incomplete... */
3799 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3800 declarator_flags_t flags)
3802 parse_declarator_env_t env;
3803 memset(&env, 0, sizeof(env));
3804 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3806 construct_type_t *construct_type = parse_inner_declarator(&env);
3808 construct_declarator_type(construct_type, specifiers->type);
3809 type_t *type = skip_typeref(orig_type);
3811 if (construct_type != NULL) {
3812 obstack_free(&temp_obst, construct_type);
3815 attribute_t *attributes = parse_attributes(env.attributes);
3816 /* append (shared) specifier attribute behind attributes of this
3818 attribute_t **anchor = &attributes;
3819 while (*anchor != NULL)
3820 anchor = &(*anchor)->next;
3821 *anchor = specifiers->attributes;
3824 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3825 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3826 entity->base.source_position = env.source_position;
3827 entity->typedefe.type = orig_type;
3829 if (anonymous_entity != NULL) {
3830 if (is_type_compound(type)) {
3831 assert(anonymous_entity->compound.alias == NULL);
3832 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3833 anonymous_entity->kind == ENTITY_UNION);
3834 anonymous_entity->compound.alias = entity;
3835 anonymous_entity = NULL;
3836 } else if (is_type_enum(type)) {
3837 assert(anonymous_entity->enume.alias == NULL);
3838 assert(anonymous_entity->kind == ENTITY_ENUM);
3839 anonymous_entity->enume.alias = entity;
3840 anonymous_entity = NULL;
3844 /* create a declaration type entity */
3845 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3846 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3848 if (env.symbol != NULL) {
3849 if (specifiers->is_inline && is_type_valid(type)) {
3850 errorf(&env.source_position,
3851 "compound member '%Y' declared 'inline'", env.symbol);
3854 if (specifiers->thread_local ||
3855 specifiers->storage_class != STORAGE_CLASS_NONE) {
3856 errorf(&env.source_position,
3857 "compound member '%Y' must have no storage class",
3861 } else if (flags & DECL_IS_PARAMETER) {
3862 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3863 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3864 } else if (is_type_function(type)) {
3865 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3866 entity->function.is_inline = specifiers->is_inline;
3867 entity->function.elf_visibility = default_visibility;
3868 entity->function.parameters = env.parameters;
3870 if (env.symbol != NULL) {
3871 /* this needs fixes for C++ */
3872 bool in_function_scope = current_function != NULL;
3874 if (specifiers->thread_local || (
3875 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3876 specifiers->storage_class != STORAGE_CLASS_NONE &&
3877 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3879 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3883 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3884 entity->variable.elf_visibility = default_visibility;
3885 entity->variable.thread_local = specifiers->thread_local;
3887 if (env.symbol != NULL) {
3888 if (specifiers->is_inline && is_type_valid(type)) {
3889 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3892 bool invalid_storage_class = false;
3893 if (current_scope == file_scope) {
3894 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3895 specifiers->storage_class != STORAGE_CLASS_NONE &&
3896 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3897 invalid_storage_class = true;
3900 if (specifiers->thread_local &&
3901 specifiers->storage_class == STORAGE_CLASS_NONE) {
3902 invalid_storage_class = true;
3905 if (invalid_storage_class) {
3906 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3911 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3912 entity->declaration.type = orig_type;
3913 entity->declaration.alignment = get_type_alignment(orig_type);
3914 entity->declaration.modifiers = env.modifiers;
3915 entity->declaration.attributes = attributes;
3917 storage_class_t storage_class = specifiers->storage_class;
3918 entity->declaration.declared_storage_class = storage_class;
3920 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3921 storage_class = STORAGE_CLASS_AUTO;
3922 entity->declaration.storage_class = storage_class;
3925 if (attributes != NULL) {
3926 handle_entity_attributes(attributes, entity);
3932 static type_t *parse_abstract_declarator(type_t *base_type)
3934 parse_declarator_env_t env;
3935 memset(&env, 0, sizeof(env));
3936 env.may_be_abstract = true;
3937 env.must_be_abstract = true;
3939 construct_type_t *construct_type = parse_inner_declarator(&env);
3941 type_t *result = construct_declarator_type(construct_type, base_type);
3942 if (construct_type != NULL) {
3943 obstack_free(&temp_obst, construct_type);
3945 result = handle_type_attributes(env.attributes, result);
3951 * Check if the declaration of main is suspicious. main should be a
3952 * function with external linkage, returning int, taking either zero
3953 * arguments, two, or three arguments of appropriate types, ie.
3955 * int main([ int argc, char **argv [, char **env ] ]).
3957 * @param decl the declaration to check
3958 * @param type the function type of the declaration
3960 static void check_main(const entity_t *entity)
3962 const source_position_t *pos = &entity->base.source_position;
3963 if (entity->kind != ENTITY_FUNCTION) {
3964 warningf(WARN_MAIN, pos, "'main' is not a function");
3968 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3969 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3972 type_t *type = skip_typeref(entity->declaration.type);
3973 assert(is_type_function(type));
3975 function_type_t const *const func_type = &type->function;
3976 type_t *const ret_type = func_type->return_type;
3977 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3978 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3980 const function_parameter_t *parm = func_type->parameters;
3982 type_t *const first_type = skip_typeref(parm->type);
3983 type_t *const first_type_unqual = get_unqualified_type(first_type);
3984 if (!types_compatible(first_type_unqual, type_int)) {
3985 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3989 type_t *const second_type = skip_typeref(parm->type);
3990 type_t *const second_type_unqual
3991 = get_unqualified_type(second_type);
3992 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3993 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3997 type_t *const third_type = skip_typeref(parm->type);
3998 type_t *const third_type_unqual
3999 = get_unqualified_type(third_type);
4000 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4001 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
4005 goto warn_arg_count;
4009 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4015 * Check if a symbol is the equal to "main".
4017 static bool is_sym_main(const symbol_t *const sym)
4019 return strcmp(sym->string, "main") == 0;
4022 static void error_redefined_as_different_kind(const source_position_t *pos,
4023 const entity_t *old, entity_kind_t new_kind)
4025 char const *const what = get_entity_kind_name(new_kind);
4026 source_position_t const *const ppos = &old->base.source_position;
4027 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4030 static bool is_entity_valid(entity_t *const ent)
4032 if (is_declaration(ent)) {
4033 return is_type_valid(skip_typeref(ent->declaration.type));
4034 } else if (ent->kind == ENTITY_TYPEDEF) {
4035 return is_type_valid(skip_typeref(ent->typedefe.type));
4040 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4042 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4043 if (attributes_equal(tattr, attr))
4050 * test wether new_list contains any attributes not included in old_list
4052 static bool has_new_attributes(const attribute_t *old_list,
4053 const attribute_t *new_list)
4055 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4056 if (!contains_attribute(old_list, attr))
4063 * Merge in attributes from an attribute list (probably from a previous
4064 * declaration with the same name). Warning: destroys the old structure
4065 * of the attribute list - don't reuse attributes after this call.
4067 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4070 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4072 if (contains_attribute(decl->attributes, attr))
4075 /* move attribute to new declarations attributes list */
4076 attr->next = decl->attributes;
4077 decl->attributes = attr;
4082 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4083 * for various problems that occur for multiple definitions
4085 entity_t *record_entity(entity_t *entity, const bool is_definition)
4087 const symbol_t *const symbol = entity->base.symbol;
4088 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4089 const source_position_t *pos = &entity->base.source_position;
4091 /* can happen in error cases */
4095 entity_t *const previous_entity = get_entity(symbol, namespc);
4096 /* pushing the same entity twice will break the stack structure */
4097 assert(previous_entity != entity);
4099 if (entity->kind == ENTITY_FUNCTION) {
4100 type_t *const orig_type = entity->declaration.type;
4101 type_t *const type = skip_typeref(orig_type);
4103 assert(is_type_function(type));
4104 if (type->function.unspecified_parameters &&
4105 previous_entity == NULL &&
4106 !entity->declaration.implicit) {
4107 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4110 if (current_scope == file_scope && is_sym_main(symbol)) {
4115 if (is_declaration(entity) &&
4116 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4117 current_scope != file_scope &&
4118 !entity->declaration.implicit) {
4119 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4122 if (previous_entity != NULL) {
4123 source_position_t const *const ppos = &previous_entity->base.source_position;
4125 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4126 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4127 assert(previous_entity->kind == ENTITY_PARAMETER);
4128 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4132 if (previous_entity->base.parent_scope == current_scope) {
4133 if (previous_entity->kind != entity->kind) {
4134 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4135 error_redefined_as_different_kind(pos, previous_entity,
4140 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4141 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4144 if (previous_entity->kind == ENTITY_TYPEDEF) {
4145 /* TODO: C++ allows this for exactly the same type */
4146 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4150 /* at this point we should have only VARIABLES or FUNCTIONS */
4151 assert(is_declaration(previous_entity) && is_declaration(entity));
4153 declaration_t *const prev_decl = &previous_entity->declaration;
4154 declaration_t *const decl = &entity->declaration;
4156 /* can happen for K&R style declarations */
4157 if (prev_decl->type == NULL &&
4158 previous_entity->kind == ENTITY_PARAMETER &&
4159 entity->kind == ENTITY_PARAMETER) {
4160 prev_decl->type = decl->type;
4161 prev_decl->storage_class = decl->storage_class;
4162 prev_decl->declared_storage_class = decl->declared_storage_class;
4163 prev_decl->modifiers = decl->modifiers;
4164 return previous_entity;
4167 type_t *const type = skip_typeref(decl->type);
4168 type_t *const prev_type = skip_typeref(prev_decl->type);
4170 if (!types_compatible(type, prev_type)) {
4171 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4173 unsigned old_storage_class = prev_decl->storage_class;
4175 if (is_definition &&
4177 !(prev_decl->modifiers & DM_USED) &&
4178 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4179 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4182 storage_class_t new_storage_class = decl->storage_class;
4184 /* pretend no storage class means extern for function
4185 * declarations (except if the previous declaration is neither
4186 * none nor extern) */
4187 if (entity->kind == ENTITY_FUNCTION) {
4188 /* the previous declaration could have unspecified parameters or
4189 * be a typedef, so use the new type */
4190 if (prev_type->function.unspecified_parameters || is_definition)
4191 prev_decl->type = type;
4193 switch (old_storage_class) {
4194 case STORAGE_CLASS_NONE:
4195 old_storage_class = STORAGE_CLASS_EXTERN;
4198 case STORAGE_CLASS_EXTERN:
4199 if (is_definition) {
4200 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4201 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4203 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4204 new_storage_class = STORAGE_CLASS_EXTERN;
4211 } else if (is_type_incomplete(prev_type)) {
4212 prev_decl->type = type;
4215 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4216 new_storage_class == STORAGE_CLASS_EXTERN) {
4218 warn_redundant_declaration: ;
4220 = has_new_attributes(prev_decl->attributes,
4222 if (has_new_attrs) {
4223 merge_in_attributes(decl, prev_decl->attributes);
4224 } else if (!is_definition &&
4225 is_type_valid(prev_type) &&
4226 strcmp(ppos->input_name, "<builtin>") != 0) {
4227 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4229 } else if (current_function == NULL) {
4230 if (old_storage_class != STORAGE_CLASS_STATIC &&
4231 new_storage_class == STORAGE_CLASS_STATIC) {
4232 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4233 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4234 prev_decl->storage_class = STORAGE_CLASS_NONE;
4235 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4237 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4239 goto error_redeclaration;
4240 goto warn_redundant_declaration;
4242 } else if (is_type_valid(prev_type)) {
4243 if (old_storage_class == new_storage_class) {
4244 error_redeclaration:
4245 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4247 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4252 prev_decl->modifiers |= decl->modifiers;
4253 if (entity->kind == ENTITY_FUNCTION) {
4254 previous_entity->function.is_inline |= entity->function.is_inline;
4256 return previous_entity;
4260 if (is_warn_on(why = WARN_SHADOW) ||
4261 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4262 char const *const what = get_entity_kind_name(previous_entity->kind);
4263 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4267 if (entity->kind == ENTITY_FUNCTION) {
4268 if (is_definition &&
4269 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4270 !is_sym_main(symbol)) {
4271 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4272 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4274 goto warn_missing_declaration;
4277 } else if (entity->kind == ENTITY_VARIABLE) {
4278 if (current_scope == file_scope &&
4279 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4280 !entity->declaration.implicit) {
4281 warn_missing_declaration:
4282 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4287 assert(entity->base.parent_scope == NULL);
4288 assert(current_scope != NULL);
4290 entity->base.parent_scope = current_scope;
4291 environment_push(entity);
4292 append_entity(current_scope, entity);
4297 static void parser_error_multiple_definition(entity_t *entity,
4298 const source_position_t *source_position)
4300 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4301 entity->base.symbol, &entity->base.source_position);
4304 static bool is_declaration_specifier(const token_t *token)
4306 switch (token->type) {
4310 return is_typedef_symbol(token->symbol);
4317 static void parse_init_declarator_rest(entity_t *entity)
4319 type_t *orig_type = type_error_type;
4321 if (entity->base.kind == ENTITY_TYPEDEF) {
4322 source_position_t const *const pos = &entity->base.source_position;
4323 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4325 assert(is_declaration(entity));
4326 orig_type = entity->declaration.type;
4329 type_t *type = skip_typeref(orig_type);
4331 if (entity->kind == ENTITY_VARIABLE
4332 && entity->variable.initializer != NULL) {
4333 parser_error_multiple_definition(entity, HERE);
4337 declaration_t *const declaration = &entity->declaration;
4338 bool must_be_constant = false;
4339 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4340 entity->base.parent_scope == file_scope) {
4341 must_be_constant = true;
4344 if (is_type_function(type)) {
4345 source_position_t const *const pos = &entity->base.source_position;
4346 errorf(pos, "'%N' is initialized like a variable", entity);
4347 orig_type = type_error_type;
4350 parse_initializer_env_t env;
4351 env.type = orig_type;
4352 env.must_be_constant = must_be_constant;
4353 env.entity = entity;
4354 current_init_decl = entity;
4356 initializer_t *initializer = parse_initializer(&env);
4357 current_init_decl = NULL;
4359 if (entity->kind == ENTITY_VARIABLE) {
4360 /* §6.7.5:22 array initializers for arrays with unknown size
4361 * determine the array type size */
4362 declaration->type = env.type;
4363 entity->variable.initializer = initializer;
4367 /* parse rest of a declaration without any declarator */
4368 static void parse_anonymous_declaration_rest(
4369 const declaration_specifiers_t *specifiers)
4372 anonymous_entity = NULL;
4374 source_position_t const *const pos = &specifiers->source_position;
4375 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4376 specifiers->thread_local) {
4377 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4380 type_t *type = specifiers->type;
4381 switch (type->kind) {
4382 case TYPE_COMPOUND_STRUCT:
4383 case TYPE_COMPOUND_UNION: {
4384 if (type->compound.compound->base.symbol == NULL) {
4385 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4394 warningf(WARN_OTHER, pos, "empty declaration");
4399 static void check_variable_type_complete(entity_t *ent)
4401 if (ent->kind != ENTITY_VARIABLE)
4404 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4405 * type for the object shall be complete [...] */
4406 declaration_t *decl = &ent->declaration;
4407 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4408 decl->storage_class == STORAGE_CLASS_STATIC)
4411 type_t *const type = skip_typeref(decl->type);
4412 if (!is_type_incomplete(type))
4415 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4416 * are given length one. */
4417 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4418 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4422 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4426 static void parse_declaration_rest(entity_t *ndeclaration,
4427 const declaration_specifiers_t *specifiers,
4428 parsed_declaration_func finished_declaration,
4429 declarator_flags_t flags)
4431 add_anchor_token(';');
4432 add_anchor_token(',');
4434 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4436 if (token.type == '=') {
4437 parse_init_declarator_rest(entity);
4438 } else if (entity->kind == ENTITY_VARIABLE) {
4439 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4440 * [...] where the extern specifier is explicitly used. */
4441 declaration_t *decl = &entity->declaration;
4442 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4443 type_t *type = decl->type;
4444 if (is_type_reference(skip_typeref(type))) {
4445 source_position_t const *const pos = &entity->base.source_position;
4446 errorf(pos, "reference '%#N' must be initialized", entity);
4451 check_variable_type_complete(entity);
4456 add_anchor_token('=');
4457 ndeclaration = parse_declarator(specifiers, flags);
4458 rem_anchor_token('=');
4460 expect(';', end_error);
4463 anonymous_entity = NULL;
4464 rem_anchor_token(';');
4465 rem_anchor_token(',');
4468 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4470 symbol_t *symbol = entity->base.symbol;
4474 assert(entity->base.namespc == NAMESPACE_NORMAL);
4475 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4476 if (previous_entity == NULL
4477 || previous_entity->base.parent_scope != current_scope) {
4478 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4483 if (is_definition) {
4484 errorf(HERE, "'%N' is initialised", entity);
4487 return record_entity(entity, false);
4490 static void parse_declaration(parsed_declaration_func finished_declaration,
4491 declarator_flags_t flags)
4493 add_anchor_token(';');
4494 declaration_specifiers_t specifiers;
4495 parse_declaration_specifiers(&specifiers);
4496 rem_anchor_token(';');
4498 if (token.type == ';') {
4499 parse_anonymous_declaration_rest(&specifiers);
4501 entity_t *entity = parse_declarator(&specifiers, flags);
4502 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4507 static type_t *get_default_promoted_type(type_t *orig_type)
4509 type_t *result = orig_type;
4511 type_t *type = skip_typeref(orig_type);
4512 if (is_type_integer(type)) {
4513 result = promote_integer(type);
4514 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4515 result = type_double;
4521 static void parse_kr_declaration_list(entity_t *entity)
4523 if (entity->kind != ENTITY_FUNCTION)
4526 type_t *type = skip_typeref(entity->declaration.type);
4527 assert(is_type_function(type));
4528 if (!type->function.kr_style_parameters)
4531 add_anchor_token('{');
4533 /* push function parameters */
4534 size_t const top = environment_top();
4535 scope_t *old_scope = scope_push(&entity->function.parameters);
4537 entity_t *parameter = entity->function.parameters.entities;
4538 for ( ; parameter != NULL; parameter = parameter->base.next) {
4539 assert(parameter->base.parent_scope == NULL);
4540 parameter->base.parent_scope = current_scope;
4541 environment_push(parameter);
4544 /* parse declaration list */
4546 switch (token.type) {
4548 case T___extension__:
4549 /* This covers symbols, which are no type, too, and results in
4550 * better error messages. The typical cases are misspelled type
4551 * names and missing includes. */
4553 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4561 /* pop function parameters */
4562 assert(current_scope == &entity->function.parameters);
4563 scope_pop(old_scope);
4564 environment_pop_to(top);
4566 /* update function type */
4567 type_t *new_type = duplicate_type(type);
4569 function_parameter_t *parameters = NULL;
4570 function_parameter_t **anchor = ¶meters;
4572 /* did we have an earlier prototype? */
4573 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4574 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4577 function_parameter_t *proto_parameter = NULL;
4578 if (proto_type != NULL) {
4579 type_t *proto_type_type = proto_type->declaration.type;
4580 proto_parameter = proto_type_type->function.parameters;
4581 /* If a K&R function definition has a variadic prototype earlier, then
4582 * make the function definition variadic, too. This should conform to
4583 * §6.7.5.3:15 and §6.9.1:8. */
4584 new_type->function.variadic = proto_type_type->function.variadic;
4586 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4588 new_type->function.unspecified_parameters = true;
4591 bool need_incompatible_warning = false;
4592 parameter = entity->function.parameters.entities;
4593 for (; parameter != NULL; parameter = parameter->base.next,
4595 proto_parameter == NULL ? NULL : proto_parameter->next) {
4596 if (parameter->kind != ENTITY_PARAMETER)
4599 type_t *parameter_type = parameter->declaration.type;
4600 if (parameter_type == NULL) {
4601 source_position_t const* const pos = ¶meter->base.source_position;
4603 errorf(pos, "no type specified for function '%N'", parameter);
4604 parameter_type = type_error_type;
4606 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4607 parameter_type = type_int;
4609 parameter->declaration.type = parameter_type;
4612 semantic_parameter_incomplete(parameter);
4614 /* we need the default promoted types for the function type */
4615 type_t *not_promoted = parameter_type;
4616 parameter_type = get_default_promoted_type(parameter_type);
4618 /* gcc special: if the type of the prototype matches the unpromoted
4619 * type don't promote */
4620 if (!strict_mode && proto_parameter != NULL) {
4621 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4622 type_t *promo_skip = skip_typeref(parameter_type);
4623 type_t *param_skip = skip_typeref(not_promoted);
4624 if (!types_compatible(proto_p_type, promo_skip)
4625 && types_compatible(proto_p_type, param_skip)) {
4627 need_incompatible_warning = true;
4628 parameter_type = not_promoted;
4631 function_parameter_t *const function_parameter
4632 = allocate_parameter(parameter_type);
4634 *anchor = function_parameter;
4635 anchor = &function_parameter->next;
4638 new_type->function.parameters = parameters;
4639 new_type = identify_new_type(new_type);
4641 if (need_incompatible_warning) {
4642 symbol_t const *const sym = entity->base.symbol;
4643 source_position_t const *const pos = &entity->base.source_position;
4644 source_position_t const *const ppos = &proto_type->base.source_position;
4645 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4647 entity->declaration.type = new_type;
4649 rem_anchor_token('{');
4652 static bool first_err = true;
4655 * When called with first_err set, prints the name of the current function,
4658 static void print_in_function(void)
4662 char const *const file = current_function->base.base.source_position.input_name;
4663 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4668 * Check if all labels are defined in the current function.
4669 * Check if all labels are used in the current function.
4671 static void check_labels(void)
4673 for (const goto_statement_t *goto_statement = goto_first;
4674 goto_statement != NULL;
4675 goto_statement = goto_statement->next) {
4676 /* skip computed gotos */
4677 if (goto_statement->expression != NULL)
4680 label_t *label = goto_statement->label;
4681 if (label->base.source_position.input_name == NULL) {
4682 print_in_function();
4683 source_position_t const *const pos = &goto_statement->base.source_position;
4684 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4688 if (is_warn_on(WARN_UNUSED_LABEL)) {
4689 for (const label_statement_t *label_statement = label_first;
4690 label_statement != NULL;
4691 label_statement = label_statement->next) {
4692 label_t *label = label_statement->label;
4694 if (! label->used) {
4695 print_in_function();
4696 source_position_t const *const pos = &label_statement->base.source_position;
4697 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4703 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4705 entity_t const *const end = last != NULL ? last->base.next : NULL;
4706 for (; entity != end; entity = entity->base.next) {
4707 if (!is_declaration(entity))
4710 declaration_t *declaration = &entity->declaration;
4711 if (declaration->implicit)
4714 if (!declaration->used) {
4715 print_in_function();
4716 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4717 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4718 print_in_function();
4719 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4724 static void check_unused_variables(statement_t *const stmt, void *const env)
4728 switch (stmt->kind) {
4729 case STATEMENT_DECLARATION: {
4730 declaration_statement_t const *const decls = &stmt->declaration;
4731 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4736 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4745 * Check declarations of current_function for unused entities.
4747 static void check_declarations(void)
4749 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4750 const scope_t *scope = ¤t_function->parameters;
4752 /* do not issue unused warnings for main */
4753 if (!is_sym_main(current_function->base.base.symbol)) {
4754 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4757 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4758 walk_statements(current_function->statement, check_unused_variables,
4763 static int determine_truth(expression_t const* const cond)
4766 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4767 fold_constant_to_bool(cond) ? 1 :
4771 static void check_reachable(statement_t *);
4772 static bool reaches_end;
4774 static bool expression_returns(expression_t const *const expr)
4776 switch (expr->kind) {
4778 expression_t const *const func = expr->call.function;
4779 if (func->kind == EXPR_REFERENCE) {
4780 entity_t *entity = func->reference.entity;
4781 if (entity->kind == ENTITY_FUNCTION
4782 && entity->declaration.modifiers & DM_NORETURN)
4786 if (!expression_returns(func))
4789 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4790 if (!expression_returns(arg->expression))
4797 case EXPR_REFERENCE:
4798 case EXPR_REFERENCE_ENUM_VALUE:
4800 case EXPR_STRING_LITERAL:
4801 case EXPR_WIDE_STRING_LITERAL:
4802 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4803 case EXPR_LABEL_ADDRESS:
4804 case EXPR_CLASSIFY_TYPE:
4805 case EXPR_SIZEOF: // TODO handle obscure VLA case
4808 case EXPR_BUILTIN_CONSTANT_P:
4809 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4814 case EXPR_STATEMENT: {
4815 bool old_reaches_end = reaches_end;
4816 reaches_end = false;
4817 check_reachable(expr->statement.statement);
4818 bool returns = reaches_end;
4819 reaches_end = old_reaches_end;
4823 case EXPR_CONDITIONAL:
4824 // TODO handle constant expression
4826 if (!expression_returns(expr->conditional.condition))
4829 if (expr->conditional.true_expression != NULL
4830 && expression_returns(expr->conditional.true_expression))
4833 return expression_returns(expr->conditional.false_expression);
4836 return expression_returns(expr->select.compound);
4838 case EXPR_ARRAY_ACCESS:
4840 expression_returns(expr->array_access.array_ref) &&
4841 expression_returns(expr->array_access.index);
4844 return expression_returns(expr->va_starte.ap);
4847 return expression_returns(expr->va_arge.ap);
4850 return expression_returns(expr->va_copye.src);
4852 EXPR_UNARY_CASES_MANDATORY
4853 return expression_returns(expr->unary.value);
4855 case EXPR_UNARY_THROW:
4859 // TODO handle constant lhs of && and ||
4861 expression_returns(expr->binary.left) &&
4862 expression_returns(expr->binary.right);
4868 panic("unhandled expression");
4871 static bool initializer_returns(initializer_t const *const init)
4873 switch (init->kind) {
4874 case INITIALIZER_VALUE:
4875 return expression_returns(init->value.value);
4877 case INITIALIZER_LIST: {
4878 initializer_t * const* i = init->list.initializers;
4879 initializer_t * const* const end = i + init->list.len;
4880 bool returns = true;
4881 for (; i != end; ++i) {
4882 if (!initializer_returns(*i))
4888 case INITIALIZER_STRING:
4889 case INITIALIZER_WIDE_STRING:
4890 case INITIALIZER_DESIGNATOR: // designators have no payload
4893 panic("unhandled initializer");
4896 static bool noreturn_candidate;
4898 static void check_reachable(statement_t *const stmt)
4900 if (stmt->base.reachable)
4902 if (stmt->kind != STATEMENT_DO_WHILE)
4903 stmt->base.reachable = true;
4905 statement_t *last = stmt;
4907 switch (stmt->kind) {
4908 case STATEMENT_INVALID:
4909 case STATEMENT_EMPTY:
4911 next = stmt->base.next;
4914 case STATEMENT_DECLARATION: {
4915 declaration_statement_t const *const decl = &stmt->declaration;
4916 entity_t const * ent = decl->declarations_begin;
4917 entity_t const *const last_decl = decl->declarations_end;
4919 for (;; ent = ent->base.next) {
4920 if (ent->kind == ENTITY_VARIABLE &&
4921 ent->variable.initializer != NULL &&
4922 !initializer_returns(ent->variable.initializer)) {
4925 if (ent == last_decl)
4929 next = stmt->base.next;
4933 case STATEMENT_COMPOUND:
4934 next = stmt->compound.statements;
4936 next = stmt->base.next;
4939 case STATEMENT_RETURN: {
4940 expression_t const *const val = stmt->returns.value;
4941 if (val == NULL || expression_returns(val))
4942 noreturn_candidate = false;
4946 case STATEMENT_IF: {
4947 if_statement_t const *const ifs = &stmt->ifs;
4948 expression_t const *const cond = ifs->condition;
4950 if (!expression_returns(cond))
4953 int const val = determine_truth(cond);
4956 check_reachable(ifs->true_statement);
4961 if (ifs->false_statement != NULL) {
4962 check_reachable(ifs->false_statement);
4966 next = stmt->base.next;
4970 case STATEMENT_SWITCH: {
4971 switch_statement_t const *const switchs = &stmt->switchs;
4972 expression_t const *const expr = switchs->expression;
4974 if (!expression_returns(expr))
4977 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4978 long const val = fold_constant_to_int(expr);
4979 case_label_statement_t * defaults = NULL;
4980 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4981 if (i->expression == NULL) {
4986 if (i->first_case <= val && val <= i->last_case) {
4987 check_reachable((statement_t*)i);
4992 if (defaults != NULL) {
4993 check_reachable((statement_t*)defaults);
4997 bool has_default = false;
4998 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4999 if (i->expression == NULL)
5002 check_reachable((statement_t*)i);
5009 next = stmt->base.next;
5013 case STATEMENT_EXPRESSION: {
5014 /* Check for noreturn function call */
5015 expression_t const *const expr = stmt->expression.expression;
5016 if (!expression_returns(expr))
5019 next = stmt->base.next;
5023 case STATEMENT_CONTINUE:
5024 for (statement_t *parent = stmt;;) {
5025 parent = parent->base.parent;
5026 if (parent == NULL) /* continue not within loop */
5030 switch (parent->kind) {
5031 case STATEMENT_WHILE: goto continue_while;
5032 case STATEMENT_DO_WHILE: goto continue_do_while;
5033 case STATEMENT_FOR: goto continue_for;
5039 case STATEMENT_BREAK:
5040 for (statement_t *parent = stmt;;) {
5041 parent = parent->base.parent;
5042 if (parent == NULL) /* break not within loop/switch */
5045 switch (parent->kind) {
5046 case STATEMENT_SWITCH:
5047 case STATEMENT_WHILE:
5048 case STATEMENT_DO_WHILE:
5051 next = parent->base.next;
5052 goto found_break_parent;
5060 case STATEMENT_GOTO:
5061 if (stmt->gotos.expression) {
5062 if (!expression_returns(stmt->gotos.expression))
5065 statement_t *parent = stmt->base.parent;
5066 if (parent == NULL) /* top level goto */
5070 next = stmt->gotos.label->statement;
5071 if (next == NULL) /* missing label */
5076 case STATEMENT_LABEL:
5077 next = stmt->label.statement;
5080 case STATEMENT_CASE_LABEL:
5081 next = stmt->case_label.statement;
5084 case STATEMENT_WHILE: {
5085 while_statement_t const *const whiles = &stmt->whiles;
5086 expression_t const *const cond = whiles->condition;
5088 if (!expression_returns(cond))
5091 int const val = determine_truth(cond);
5094 check_reachable(whiles->body);
5099 next = stmt->base.next;
5103 case STATEMENT_DO_WHILE:
5104 next = stmt->do_while.body;
5107 case STATEMENT_FOR: {
5108 for_statement_t *const fors = &stmt->fors;
5110 if (fors->condition_reachable)
5112 fors->condition_reachable = true;
5114 expression_t const *const cond = fors->condition;
5119 } else if (expression_returns(cond)) {
5120 val = determine_truth(cond);
5126 check_reachable(fors->body);
5131 next = stmt->base.next;
5135 case STATEMENT_MS_TRY: {
5136 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5137 check_reachable(ms_try->try_statement);
5138 next = ms_try->final_statement;
5142 case STATEMENT_LEAVE: {
5143 statement_t *parent = stmt;
5145 parent = parent->base.parent;
5146 if (parent == NULL) /* __leave not within __try */
5149 if (parent->kind == STATEMENT_MS_TRY) {
5151 next = parent->ms_try.final_statement;
5159 panic("invalid statement kind");
5162 while (next == NULL) {
5163 next = last->base.parent;
5165 noreturn_candidate = false;
5167 type_t *const type = skip_typeref(current_function->base.type);
5168 assert(is_type_function(type));
5169 type_t *const ret = skip_typeref(type->function.return_type);
5170 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5171 is_type_valid(ret) &&
5172 !is_sym_main(current_function->base.base.symbol)) {
5173 source_position_t const *const pos = &stmt->base.source_position;
5174 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5179 switch (next->kind) {
5180 case STATEMENT_INVALID:
5181 case STATEMENT_EMPTY:
5182 case STATEMENT_DECLARATION:
5183 case STATEMENT_EXPRESSION:
5185 case STATEMENT_RETURN:
5186 case STATEMENT_CONTINUE:
5187 case STATEMENT_BREAK:
5188 case STATEMENT_GOTO:
5189 case STATEMENT_LEAVE:
5190 panic("invalid control flow in function");
5192 case STATEMENT_COMPOUND:
5193 if (next->compound.stmt_expr) {
5199 case STATEMENT_SWITCH:
5200 case STATEMENT_LABEL:
5201 case STATEMENT_CASE_LABEL:
5203 next = next->base.next;
5206 case STATEMENT_WHILE: {
5208 if (next->base.reachable)
5210 next->base.reachable = true;
5212 while_statement_t const *const whiles = &next->whiles;
5213 expression_t const *const cond = whiles->condition;
5215 if (!expression_returns(cond))
5218 int const val = determine_truth(cond);
5221 check_reachable(whiles->body);
5227 next = next->base.next;
5231 case STATEMENT_DO_WHILE: {
5233 if (next->base.reachable)
5235 next->base.reachable = true;
5237 do_while_statement_t const *const dw = &next->do_while;
5238 expression_t const *const cond = dw->condition;
5240 if (!expression_returns(cond))
5243 int const val = determine_truth(cond);
5246 check_reachable(dw->body);
5252 next = next->base.next;
5256 case STATEMENT_FOR: {
5258 for_statement_t *const fors = &next->fors;
5260 fors->step_reachable = true;
5262 if (fors->condition_reachable)
5264 fors->condition_reachable = true;
5266 expression_t const *const cond = fors->condition;
5271 } else if (expression_returns(cond)) {
5272 val = determine_truth(cond);
5278 check_reachable(fors->body);
5284 next = next->base.next;
5288 case STATEMENT_MS_TRY:
5290 next = next->ms_try.final_statement;
5295 check_reachable(next);
5298 static void check_unreachable(statement_t* const stmt, void *const env)
5302 switch (stmt->kind) {
5303 case STATEMENT_DO_WHILE:
5304 if (!stmt->base.reachable) {
5305 expression_t const *const cond = stmt->do_while.condition;
5306 if (determine_truth(cond) >= 0) {
5307 source_position_t const *const pos = &cond->base.source_position;
5308 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5313 case STATEMENT_FOR: {
5314 for_statement_t const* const fors = &stmt->fors;
5316 // if init and step are unreachable, cond is unreachable, too
5317 if (!stmt->base.reachable && !fors->step_reachable) {
5318 goto warn_unreachable;
5320 if (!stmt->base.reachable && fors->initialisation != NULL) {
5321 source_position_t const *const pos = &fors->initialisation->base.source_position;
5322 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5325 if (!fors->condition_reachable && fors->condition != NULL) {
5326 source_position_t const *const pos = &fors->condition->base.source_position;
5327 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5330 if (!fors->step_reachable && fors->step != NULL) {
5331 source_position_t const *const pos = &fors->step->base.source_position;
5332 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5338 case STATEMENT_COMPOUND:
5339 if (stmt->compound.statements != NULL)
5341 goto warn_unreachable;
5343 case STATEMENT_DECLARATION: {
5344 /* Only warn if there is at least one declarator with an initializer.
5345 * This typically occurs in switch statements. */
5346 declaration_statement_t const *const decl = &stmt->declaration;
5347 entity_t const * ent = decl->declarations_begin;
5348 entity_t const *const last = decl->declarations_end;
5350 for (;; ent = ent->base.next) {
5351 if (ent->kind == ENTITY_VARIABLE &&
5352 ent->variable.initializer != NULL) {
5353 goto warn_unreachable;
5363 if (!stmt->base.reachable) {
5364 source_position_t const *const pos = &stmt->base.source_position;
5365 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5371 static void parse_external_declaration(void)
5373 /* function-definitions and declarations both start with declaration
5375 add_anchor_token(';');
5376 declaration_specifiers_t specifiers;
5377 parse_declaration_specifiers(&specifiers);
5378 rem_anchor_token(';');
5380 /* must be a declaration */
5381 if (token.type == ';') {
5382 parse_anonymous_declaration_rest(&specifiers);
5386 add_anchor_token(',');
5387 add_anchor_token('=');
5388 add_anchor_token(';');
5389 add_anchor_token('{');
5391 /* declarator is common to both function-definitions and declarations */
5392 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5394 rem_anchor_token('{');
5395 rem_anchor_token(';');
5396 rem_anchor_token('=');
5397 rem_anchor_token(',');
5399 /* must be a declaration */
5400 switch (token.type) {
5404 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5409 /* must be a function definition */
5410 parse_kr_declaration_list(ndeclaration);
5412 if (token.type != '{') {
5413 parse_error_expected("while parsing function definition", '{', NULL);
5414 eat_until_matching_token(';');
5418 assert(is_declaration(ndeclaration));
5419 type_t *const orig_type = ndeclaration->declaration.type;
5420 type_t * type = skip_typeref(orig_type);
5422 if (!is_type_function(type)) {
5423 if (is_type_valid(type)) {
5424 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5430 source_position_t const *const pos = &ndeclaration->base.source_position;
5431 if (is_typeref(orig_type)) {
5433 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5436 if (is_type_compound(skip_typeref(type->function.return_type))) {
5437 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5439 if (type->function.unspecified_parameters) {
5440 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5442 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5445 /* §6.7.5.3:14 a function definition with () means no
5446 * parameters (and not unspecified parameters) */
5447 if (type->function.unspecified_parameters &&
5448 type->function.parameters == NULL) {
5449 type_t *copy = duplicate_type(type);
5450 copy->function.unspecified_parameters = false;
5451 type = identify_new_type(copy);
5453 ndeclaration->declaration.type = type;
5456 entity_t *const entity = record_entity(ndeclaration, true);
5457 assert(entity->kind == ENTITY_FUNCTION);
5458 assert(ndeclaration->kind == ENTITY_FUNCTION);
5460 function_t *const function = &entity->function;
5461 if (ndeclaration != entity) {
5462 function->parameters = ndeclaration->function.parameters;
5464 assert(is_declaration(entity));
5465 type = skip_typeref(entity->declaration.type);
5467 /* push function parameters and switch scope */
5468 size_t const top = environment_top();
5469 scope_t *old_scope = scope_push(&function->parameters);
5471 entity_t *parameter = function->parameters.entities;
5472 for (; parameter != NULL; parameter = parameter->base.next) {
5473 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5474 parameter->base.parent_scope = current_scope;
5476 assert(parameter->base.parent_scope == NULL
5477 || parameter->base.parent_scope == current_scope);
5478 parameter->base.parent_scope = current_scope;
5479 if (parameter->base.symbol == NULL) {
5480 errorf(¶meter->base.source_position, "parameter name omitted");
5483 environment_push(parameter);
5486 if (function->statement != NULL) {
5487 parser_error_multiple_definition(entity, HERE);
5490 /* parse function body */
5491 int label_stack_top = label_top();
5492 function_t *old_current_function = current_function;
5493 entity_t *old_current_entity = current_entity;
5494 current_function = function;
5495 current_entity = entity;
5496 current_parent = NULL;
5499 goto_anchor = &goto_first;
5501 label_anchor = &label_first;
5503 statement_t *const body = parse_compound_statement(false);
5504 function->statement = body;
5507 check_declarations();
5508 if (is_warn_on(WARN_RETURN_TYPE) ||
5509 is_warn_on(WARN_UNREACHABLE_CODE) ||
5510 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5511 noreturn_candidate = true;
5512 check_reachable(body);
5513 if (is_warn_on(WARN_UNREACHABLE_CODE))
5514 walk_statements(body, check_unreachable, NULL);
5515 if (noreturn_candidate &&
5516 !(function->base.modifiers & DM_NORETURN)) {
5517 source_position_t const *const pos = &body->base.source_position;
5518 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5522 assert(current_parent == NULL);
5523 assert(current_function == function);
5524 assert(current_entity == entity);
5525 current_entity = old_current_entity;
5526 current_function = old_current_function;
5527 label_pop_to(label_stack_top);
5530 assert(current_scope == &function->parameters);
5531 scope_pop(old_scope);
5532 environment_pop_to(top);
5535 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5536 source_position_t *source_position,
5537 const symbol_t *symbol)
5539 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5541 type->bitfield.base_type = base_type;
5542 type->bitfield.size_expression = size;
5545 type_t *skipped_type = skip_typeref(base_type);
5546 if (!is_type_integer(skipped_type)) {
5547 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5550 bit_size = get_type_size(base_type) * 8;
5553 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5554 long v = fold_constant_to_int(size);
5555 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5558 errorf(source_position, "negative width in bit-field '%Y'",
5560 } else if (v == 0 && symbol != NULL) {
5561 errorf(source_position, "zero width for bit-field '%Y'",
5563 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5564 errorf(source_position, "width of '%Y' exceeds its type",
5567 type->bitfield.bit_size = v;
5574 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5576 entity_t *iter = compound->members.entities;
5577 for (; iter != NULL; iter = iter->base.next) {
5578 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5581 if (iter->base.symbol == symbol) {
5583 } else if (iter->base.symbol == NULL) {
5584 /* search in anonymous structs and unions */
5585 type_t *type = skip_typeref(iter->declaration.type);
5586 if (is_type_compound(type)) {
5587 if (find_compound_entry(type->compound.compound, symbol)
5598 static void check_deprecated(const source_position_t *source_position,
5599 const entity_t *entity)
5601 if (!is_declaration(entity))
5603 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5606 source_position_t const *const epos = &entity->base.source_position;
5607 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5609 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5611 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5616 static expression_t *create_select(const source_position_t *pos,
5618 type_qualifiers_t qualifiers,
5621 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5623 check_deprecated(pos, entry);
5625 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5626 select->select.compound = addr;
5627 select->select.compound_entry = entry;
5629 type_t *entry_type = entry->declaration.type;
5630 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5632 /* we always do the auto-type conversions; the & and sizeof parser contains
5633 * code to revert this! */
5634 select->base.type = automatic_type_conversion(res_type);
5635 if (res_type->kind == TYPE_BITFIELD) {
5636 select->base.type = res_type->bitfield.base_type;
5643 * Find entry with symbol in compound. Search anonymous structs and unions and
5644 * creates implicit select expressions for them.
5645 * Returns the adress for the innermost compound.
5647 static expression_t *find_create_select(const source_position_t *pos,
5649 type_qualifiers_t qualifiers,
5650 compound_t *compound, symbol_t *symbol)
5652 entity_t *iter = compound->members.entities;
5653 for (; iter != NULL; iter = iter->base.next) {
5654 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5657 symbol_t *iter_symbol = iter->base.symbol;
5658 if (iter_symbol == NULL) {
5659 type_t *type = iter->declaration.type;
5660 if (type->kind != TYPE_COMPOUND_STRUCT
5661 && type->kind != TYPE_COMPOUND_UNION)
5664 compound_t *sub_compound = type->compound.compound;
5666 if (find_compound_entry(sub_compound, symbol) == NULL)
5669 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5670 sub_addr->base.source_position = *pos;
5671 sub_addr->select.implicit = true;
5672 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5676 if (iter_symbol == symbol) {
5677 return create_select(pos, addr, qualifiers, iter);
5684 static void parse_compound_declarators(compound_t *compound,
5685 const declaration_specifiers_t *specifiers)
5690 if (token.type == ':') {
5691 source_position_t source_position = *HERE;
5694 type_t *base_type = specifiers->type;
5695 expression_t *size = parse_constant_expression();
5697 type_t *type = make_bitfield_type(base_type, size,
5698 &source_position, NULL);
5700 attribute_t *attributes = parse_attributes(NULL);
5701 attribute_t **anchor = &attributes;
5702 while (*anchor != NULL)
5703 anchor = &(*anchor)->next;
5704 *anchor = specifiers->attributes;
5706 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5707 entity->base.source_position = source_position;
5708 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5709 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5710 entity->declaration.type = type;
5711 entity->declaration.attributes = attributes;
5713 if (attributes != NULL) {
5714 handle_entity_attributes(attributes, entity);
5716 append_entity(&compound->members, entity);
5718 entity = parse_declarator(specifiers,
5719 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5720 source_position_t const *const pos = &entity->base.source_position;
5721 if (entity->kind == ENTITY_TYPEDEF) {
5722 errorf(pos, "typedef not allowed as compound member");
5724 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5726 /* make sure we don't define a symbol multiple times */
5727 symbol_t *symbol = entity->base.symbol;
5728 if (symbol != NULL) {
5729 entity_t *prev = find_compound_entry(compound, symbol);
5731 source_position_t const *const ppos = &prev->base.source_position;
5732 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5736 if (token.type == ':') {
5737 source_position_t source_position = *HERE;
5739 expression_t *size = parse_constant_expression();
5741 type_t *type = entity->declaration.type;
5742 type_t *bitfield_type = make_bitfield_type(type, size,
5743 &source_position, entity->base.symbol);
5745 attribute_t *attributes = parse_attributes(NULL);
5746 entity->declaration.type = bitfield_type;
5747 handle_entity_attributes(attributes, entity);
5749 type_t *orig_type = entity->declaration.type;
5750 type_t *type = skip_typeref(orig_type);
5751 if (is_type_function(type)) {
5752 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5753 } else if (is_type_incomplete(type)) {
5754 /* §6.7.2.1:16 flexible array member */
5755 if (!is_type_array(type) ||
5756 token.type != ';' ||
5757 look_ahead(1)->type != '}') {
5758 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5763 append_entity(&compound->members, entity);
5766 } while (next_if(','));
5767 expect(';', end_error);
5770 anonymous_entity = NULL;
5773 static void parse_compound_type_entries(compound_t *compound)
5776 add_anchor_token('}');
5778 while (token.type != '}') {
5779 if (token.type == T_EOF) {
5780 errorf(HERE, "EOF while parsing struct");
5783 declaration_specifiers_t specifiers;
5784 parse_declaration_specifiers(&specifiers);
5785 parse_compound_declarators(compound, &specifiers);
5787 rem_anchor_token('}');
5791 compound->complete = true;
5794 static type_t *parse_typename(void)
5796 declaration_specifiers_t specifiers;
5797 parse_declaration_specifiers(&specifiers);
5798 if (specifiers.storage_class != STORAGE_CLASS_NONE
5799 || specifiers.thread_local) {
5800 /* TODO: improve error message, user does probably not know what a
5801 * storage class is...
5803 errorf(&specifiers.source_position, "typename must not have a storage class");
5806 type_t *result = parse_abstract_declarator(specifiers.type);
5814 typedef expression_t* (*parse_expression_function)(void);
5815 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5817 typedef struct expression_parser_function_t expression_parser_function_t;
5818 struct expression_parser_function_t {
5819 parse_expression_function parser;
5820 precedence_t infix_precedence;
5821 parse_expression_infix_function infix_parser;
5824 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5827 * Prints an error message if an expression was expected but not read
5829 static expression_t *expected_expression_error(void)
5831 /* skip the error message if the error token was read */
5832 if (token.type != T_ERROR) {
5833 errorf(HERE, "expected expression, got token %K", &token);
5837 return create_invalid_expression();
5840 static type_t *get_string_type(void)
5842 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5845 static type_t *get_wide_string_type(void)
5847 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5851 * Parse a string constant.
5853 static expression_t *parse_string_literal(void)
5855 source_position_t begin = token.source_position;
5856 string_t res = token.literal;
5857 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5860 while (token.type == T_STRING_LITERAL
5861 || token.type == T_WIDE_STRING_LITERAL) {
5862 warn_string_concat(&token.source_position);
5863 res = concat_strings(&res, &token.literal);
5865 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5868 expression_t *literal;
5870 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5871 literal->base.type = get_wide_string_type();
5873 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5874 literal->base.type = get_string_type();
5876 literal->base.source_position = begin;
5877 literal->literal.value = res;
5883 * Parse a boolean constant.
5885 static expression_t *parse_boolean_literal(bool value)
5887 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5888 literal->base.source_position = token.source_position;
5889 literal->base.type = type_bool;
5890 literal->literal.value.begin = value ? "true" : "false";
5891 literal->literal.value.size = value ? 4 : 5;
5897 static void warn_traditional_suffix(void)
5899 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5902 static void check_integer_suffix(void)
5904 symbol_t *suffix = token.symbol;
5908 bool not_traditional = false;
5909 const char *c = suffix->string;
5910 if (*c == 'l' || *c == 'L') {
5913 not_traditional = true;
5915 if (*c == 'u' || *c == 'U') {
5918 } else if (*c == 'u' || *c == 'U') {
5919 not_traditional = true;
5922 } else if (*c == 'u' || *c == 'U') {
5923 not_traditional = true;
5925 if (*c == 'l' || *c == 'L') {
5933 errorf(&token.source_position,
5934 "invalid suffix '%s' on integer constant", suffix->string);
5935 } else if (not_traditional) {
5936 warn_traditional_suffix();
5940 static type_t *check_floatingpoint_suffix(void)
5942 symbol_t *suffix = token.symbol;
5943 type_t *type = type_double;
5947 bool not_traditional = false;
5948 const char *c = suffix->string;
5949 if (*c == 'f' || *c == 'F') {
5952 } else if (*c == 'l' || *c == 'L') {
5954 type = type_long_double;
5957 errorf(&token.source_position,
5958 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5959 } else if (not_traditional) {
5960 warn_traditional_suffix();
5967 * Parse an integer constant.
5969 static expression_t *parse_number_literal(void)
5971 expression_kind_t kind;
5974 switch (token.type) {
5976 kind = EXPR_LITERAL_INTEGER;
5977 check_integer_suffix();
5980 case T_INTEGER_OCTAL:
5981 kind = EXPR_LITERAL_INTEGER_OCTAL;
5982 check_integer_suffix();
5985 case T_INTEGER_HEXADECIMAL:
5986 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5987 check_integer_suffix();
5990 case T_FLOATINGPOINT:
5991 kind = EXPR_LITERAL_FLOATINGPOINT;
5992 type = check_floatingpoint_suffix();
5994 case T_FLOATINGPOINT_HEXADECIMAL:
5995 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5996 type = check_floatingpoint_suffix();
5999 panic("unexpected token type in parse_number_literal");
6002 expression_t *literal = allocate_expression_zero(kind);
6003 literal->base.source_position = token.source_position;
6004 literal->base.type = type;
6005 literal->literal.value = token.literal;
6006 literal->literal.suffix = token.symbol;
6009 /* integer type depends on the size of the number and the size
6010 * representable by the types. The backend/codegeneration has to determine
6013 determine_literal_type(&literal->literal);
6018 * Parse a character constant.
6020 static expression_t *parse_character_constant(void)
6022 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6023 literal->base.source_position = token.source_position;
6024 literal->base.type = c_mode & _CXX ? type_char : type_int;
6025 literal->literal.value = token.literal;
6027 size_t len = literal->literal.value.size;
6029 if (!GNU_MODE && !(c_mode & _C99)) {
6030 errorf(HERE, "more than 1 character in character constant");
6032 literal->base.type = type_int;
6033 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6042 * Parse a wide character constant.
6044 static expression_t *parse_wide_character_constant(void)
6046 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6047 literal->base.source_position = token.source_position;
6048 literal->base.type = type_int;
6049 literal->literal.value = token.literal;
6051 size_t len = wstrlen(&literal->literal.value);
6053 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6060 static entity_t *create_implicit_function(symbol_t *symbol,
6061 const source_position_t *source_position)
6063 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6064 ntype->function.return_type = type_int;
6065 ntype->function.unspecified_parameters = true;
6066 ntype->function.linkage = LINKAGE_C;
6067 type_t *type = identify_new_type(ntype);
6069 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6070 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6071 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6072 entity->declaration.type = type;
6073 entity->declaration.implicit = true;
6074 entity->base.source_position = *source_position;
6076 if (current_scope != NULL)
6077 record_entity(entity, false);
6083 * Performs automatic type cast as described in §6.3.2.1.
6085 * @param orig_type the original type
6087 static type_t *automatic_type_conversion(type_t *orig_type)
6089 type_t *type = skip_typeref(orig_type);
6090 if (is_type_array(type)) {
6091 array_type_t *array_type = &type->array;
6092 type_t *element_type = array_type->element_type;
6093 unsigned qualifiers = array_type->base.qualifiers;
6095 return make_pointer_type(element_type, qualifiers);
6098 if (is_type_function(type)) {
6099 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6106 * reverts the automatic casts of array to pointer types and function
6107 * to function-pointer types as defined §6.3.2.1
6109 type_t *revert_automatic_type_conversion(const expression_t *expression)
6111 switch (expression->kind) {
6112 case EXPR_REFERENCE: {
6113 entity_t *entity = expression->reference.entity;
6114 if (is_declaration(entity)) {
6115 return entity->declaration.type;
6116 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6117 return entity->enum_value.enum_type;
6119 panic("no declaration or enum in reference");
6124 entity_t *entity = expression->select.compound_entry;
6125 assert(is_declaration(entity));
6126 type_t *type = entity->declaration.type;
6127 return get_qualified_type(type,
6128 expression->base.type->base.qualifiers);
6131 case EXPR_UNARY_DEREFERENCE: {
6132 const expression_t *const value = expression->unary.value;
6133 type_t *const type = skip_typeref(value->base.type);
6134 if (!is_type_pointer(type))
6135 return type_error_type;
6136 return type->pointer.points_to;
6139 case EXPR_ARRAY_ACCESS: {
6140 const expression_t *array_ref = expression->array_access.array_ref;
6141 type_t *type_left = skip_typeref(array_ref->base.type);
6142 if (!is_type_pointer(type_left))
6143 return type_error_type;
6144 return type_left->pointer.points_to;
6147 case EXPR_STRING_LITERAL: {
6148 size_t size = expression->string_literal.value.size;
6149 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6152 case EXPR_WIDE_STRING_LITERAL: {
6153 size_t size = wstrlen(&expression->string_literal.value);
6154 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6157 case EXPR_COMPOUND_LITERAL:
6158 return expression->compound_literal.type;
6163 return expression->base.type;
6167 * Find an entity matching a symbol in a scope.
6168 * Uses current scope if scope is NULL
6170 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6171 namespace_tag_t namespc)
6173 if (scope == NULL) {
6174 return get_entity(symbol, namespc);
6177 /* we should optimize here, if scope grows above a certain size we should
6178 construct a hashmap here... */
6179 entity_t *entity = scope->entities;
6180 for ( ; entity != NULL; entity = entity->base.next) {
6181 if (entity->base.symbol == symbol
6182 && (namespace_tag_t)entity->base.namespc == namespc)
6189 static entity_t *parse_qualified_identifier(void)
6191 /* namespace containing the symbol */
6193 source_position_t pos;
6194 const scope_t *lookup_scope = NULL;
6196 if (next_if(T_COLONCOLON))
6197 lookup_scope = &unit->scope;
6201 if (token.type != T_IDENTIFIER) {
6202 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6203 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6205 symbol = token.symbol;
6210 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6212 if (!next_if(T_COLONCOLON))
6215 switch (entity->kind) {
6216 case ENTITY_NAMESPACE:
6217 lookup_scope = &entity->namespacee.members;
6222 lookup_scope = &entity->compound.members;
6225 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6226 symbol, get_entity_kind_name(entity->kind));
6228 /* skip further qualifications */
6229 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6231 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6235 if (entity == NULL) {
6236 if (!strict_mode && token.type == '(') {
6237 /* an implicitly declared function */
6238 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6239 entity = create_implicit_function(symbol, &pos);
6241 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6242 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6249 static expression_t *parse_reference(void)
6251 source_position_t const pos = token.source_position;
6252 entity_t *const entity = parse_qualified_identifier();
6255 if (is_declaration(entity)) {
6256 orig_type = entity->declaration.type;
6257 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6258 orig_type = entity->enum_value.enum_type;
6260 panic("expected declaration or enum value in reference");
6263 /* we always do the auto-type conversions; the & and sizeof parser contains
6264 * code to revert this! */
6265 type_t *type = automatic_type_conversion(orig_type);
6267 expression_kind_t kind = EXPR_REFERENCE;
6268 if (entity->kind == ENTITY_ENUM_VALUE)
6269 kind = EXPR_REFERENCE_ENUM_VALUE;
6271 expression_t *expression = allocate_expression_zero(kind);
6272 expression->base.source_position = pos;
6273 expression->base.type = type;
6274 expression->reference.entity = entity;
6276 /* this declaration is used */
6277 if (is_declaration(entity)) {
6278 entity->declaration.used = true;
6281 if (entity->base.parent_scope != file_scope
6282 && (current_function != NULL
6283 && entity->base.parent_scope->depth < current_function->parameters.depth)
6284 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6285 if (entity->kind == ENTITY_VARIABLE) {
6286 /* access of a variable from an outer function */
6287 entity->variable.address_taken = true;
6288 } else if (entity->kind == ENTITY_PARAMETER) {
6289 entity->parameter.address_taken = true;
6291 current_function->need_closure = true;
6294 check_deprecated(&pos, entity);
6296 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6297 current_init_decl = NULL;
6298 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6304 static bool semantic_cast(expression_t *cast)
6306 expression_t *expression = cast->unary.value;
6307 type_t *orig_dest_type = cast->base.type;
6308 type_t *orig_type_right = expression->base.type;
6309 type_t const *dst_type = skip_typeref(orig_dest_type);
6310 type_t const *src_type = skip_typeref(orig_type_right);
6311 source_position_t const *pos = &cast->base.source_position;
6313 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6314 if (dst_type == type_void)
6317 /* only integer and pointer can be casted to pointer */
6318 if (is_type_pointer(dst_type) &&
6319 !is_type_pointer(src_type) &&
6320 !is_type_integer(src_type) &&
6321 is_type_valid(src_type)) {
6322 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6326 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6327 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6331 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6332 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6336 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6337 type_t *src = skip_typeref(src_type->pointer.points_to);
6338 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6339 unsigned missing_qualifiers =
6340 src->base.qualifiers & ~dst->base.qualifiers;
6341 if (missing_qualifiers != 0) {
6342 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6348 static expression_t *parse_compound_literal(type_t *type)
6350 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6352 parse_initializer_env_t env;
6355 env.must_be_constant = false;
6356 initializer_t *initializer = parse_initializer(&env);
6359 expression->compound_literal.initializer = initializer;
6360 expression->compound_literal.type = type;
6361 expression->base.type = automatic_type_conversion(type);
6367 * Parse a cast expression.
6369 static expression_t *parse_cast(void)
6371 source_position_t source_position = token.source_position;
6374 add_anchor_token(')');
6376 type_t *type = parse_typename();
6378 rem_anchor_token(')');
6379 expect(')', end_error);
6381 if (token.type == '{') {
6382 return parse_compound_literal(type);
6385 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6386 cast->base.source_position = source_position;
6388 expression_t *value = parse_subexpression(PREC_CAST);
6389 cast->base.type = type;
6390 cast->unary.value = value;
6392 if (! semantic_cast(cast)) {
6393 /* TODO: record the error in the AST. else it is impossible to detect it */
6398 return create_invalid_expression();
6402 * Parse a statement expression.
6404 static expression_t *parse_statement_expression(void)
6406 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6409 add_anchor_token(')');
6411 statement_t *statement = parse_compound_statement(true);
6412 statement->compound.stmt_expr = true;
6413 expression->statement.statement = statement;
6415 /* find last statement and use its type */
6416 type_t *type = type_void;
6417 const statement_t *stmt = statement->compound.statements;
6419 while (stmt->base.next != NULL)
6420 stmt = stmt->base.next;
6422 if (stmt->kind == STATEMENT_EXPRESSION) {
6423 type = stmt->expression.expression->base.type;
6426 source_position_t const *const pos = &expression->base.source_position;
6427 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6429 expression->base.type = type;
6431 rem_anchor_token(')');
6432 expect(')', end_error);
6439 * Parse a parenthesized expression.
6441 static expression_t *parse_parenthesized_expression(void)
6443 token_t const* const la1 = look_ahead(1);
6444 switch (la1->type) {
6446 /* gcc extension: a statement expression */
6447 return parse_statement_expression();
6450 if (is_typedef_symbol(la1->symbol)) {
6452 return parse_cast();
6457 add_anchor_token(')');
6458 expression_t *result = parse_expression();
6459 result->base.parenthesized = true;
6460 rem_anchor_token(')');
6461 expect(')', end_error);
6467 static expression_t *parse_function_keyword(void)
6471 if (current_function == NULL) {
6472 errorf(HERE, "'__func__' used outside of a function");
6475 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6476 expression->base.type = type_char_ptr;
6477 expression->funcname.kind = FUNCNAME_FUNCTION;
6484 static expression_t *parse_pretty_function_keyword(void)
6486 if (current_function == NULL) {
6487 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6490 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6491 expression->base.type = type_char_ptr;
6492 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6494 eat(T___PRETTY_FUNCTION__);
6499 static expression_t *parse_funcsig_keyword(void)
6501 if (current_function == NULL) {
6502 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6505 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6506 expression->base.type = type_char_ptr;
6507 expression->funcname.kind = FUNCNAME_FUNCSIG;
6514 static expression_t *parse_funcdname_keyword(void)
6516 if (current_function == NULL) {
6517 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6520 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6521 expression->base.type = type_char_ptr;
6522 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6524 eat(T___FUNCDNAME__);
6529 static designator_t *parse_designator(void)
6531 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6532 result->source_position = *HERE;
6534 if (token.type != T_IDENTIFIER) {
6535 parse_error_expected("while parsing member designator",
6536 T_IDENTIFIER, NULL);
6539 result->symbol = token.symbol;
6542 designator_t *last_designator = result;
6545 if (token.type != T_IDENTIFIER) {
6546 parse_error_expected("while parsing member designator",
6547 T_IDENTIFIER, NULL);
6550 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6551 designator->source_position = *HERE;
6552 designator->symbol = token.symbol;
6555 last_designator->next = designator;
6556 last_designator = designator;
6560 add_anchor_token(']');
6561 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6562 designator->source_position = *HERE;
6563 designator->array_index = parse_expression();
6564 rem_anchor_token(']');
6565 expect(']', end_error);
6566 if (designator->array_index == NULL) {
6570 last_designator->next = designator;
6571 last_designator = designator;
6583 * Parse the __builtin_offsetof() expression.
6585 static expression_t *parse_offsetof(void)
6587 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6588 expression->base.type = type_size_t;
6590 eat(T___builtin_offsetof);
6592 expect('(', end_error);
6593 add_anchor_token(',');
6594 type_t *type = parse_typename();
6595 rem_anchor_token(',');
6596 expect(',', end_error);
6597 add_anchor_token(')');
6598 designator_t *designator = parse_designator();
6599 rem_anchor_token(')');
6600 expect(')', end_error);
6602 expression->offsetofe.type = type;
6603 expression->offsetofe.designator = designator;
6606 memset(&path, 0, sizeof(path));
6607 path.top_type = type;
6608 path.path = NEW_ARR_F(type_path_entry_t, 0);
6610 descend_into_subtype(&path);
6612 if (!walk_designator(&path, designator, true)) {
6613 return create_invalid_expression();
6616 DEL_ARR_F(path.path);
6620 return create_invalid_expression();
6624 * Parses a _builtin_va_start() expression.
6626 static expression_t *parse_va_start(void)
6628 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6630 eat(T___builtin_va_start);
6632 expect('(', end_error);
6633 add_anchor_token(',');
6634 expression->va_starte.ap = parse_assignment_expression();
6635 rem_anchor_token(',');
6636 expect(',', end_error);
6637 expression_t *const expr = parse_assignment_expression();
6638 if (expr->kind == EXPR_REFERENCE) {
6639 entity_t *const entity = expr->reference.entity;
6640 if (!current_function->base.type->function.variadic) {
6641 errorf(&expr->base.source_position,
6642 "'va_start' used in non-variadic function");
6643 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6644 entity->base.next != NULL ||
6645 entity->kind != ENTITY_PARAMETER) {
6646 errorf(&expr->base.source_position,
6647 "second argument of 'va_start' must be last parameter of the current function");
6649 expression->va_starte.parameter = &entity->variable;
6651 expect(')', end_error);
6654 expect(')', end_error);
6656 return create_invalid_expression();
6660 * Parses a __builtin_va_arg() expression.
6662 static expression_t *parse_va_arg(void)
6664 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6666 eat(T___builtin_va_arg);
6668 expect('(', end_error);
6670 ap.expression = parse_assignment_expression();
6671 expression->va_arge.ap = ap.expression;
6672 check_call_argument(type_valist, &ap, 1);
6674 expect(',', end_error);
6675 expression->base.type = parse_typename();
6676 expect(')', end_error);
6680 return create_invalid_expression();
6684 * Parses a __builtin_va_copy() expression.
6686 static expression_t *parse_va_copy(void)
6688 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6690 eat(T___builtin_va_copy);
6692 expect('(', end_error);
6693 expression_t *dst = parse_assignment_expression();
6694 assign_error_t error = semantic_assign(type_valist, dst);
6695 report_assign_error(error, type_valist, dst, "call argument 1",
6696 &dst->base.source_position);
6697 expression->va_copye.dst = dst;
6699 expect(',', end_error);
6701 call_argument_t src;
6702 src.expression = parse_assignment_expression();
6703 check_call_argument(type_valist, &src, 2);
6704 expression->va_copye.src = src.expression;
6705 expect(')', end_error);
6709 return create_invalid_expression();
6713 * Parses a __builtin_constant_p() expression.
6715 static expression_t *parse_builtin_constant(void)
6717 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6719 eat(T___builtin_constant_p);
6721 expect('(', end_error);
6722 add_anchor_token(')');
6723 expression->builtin_constant.value = parse_assignment_expression();
6724 rem_anchor_token(')');
6725 expect(')', end_error);
6726 expression->base.type = type_int;
6730 return create_invalid_expression();
6734 * Parses a __builtin_types_compatible_p() expression.
6736 static expression_t *parse_builtin_types_compatible(void)
6738 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6740 eat(T___builtin_types_compatible_p);
6742 expect('(', end_error);
6743 add_anchor_token(')');
6744 add_anchor_token(',');
6745 expression->builtin_types_compatible.left = parse_typename();
6746 rem_anchor_token(',');
6747 expect(',', end_error);
6748 expression->builtin_types_compatible.right = parse_typename();
6749 rem_anchor_token(')');
6750 expect(')', end_error);
6751 expression->base.type = type_int;
6755 return create_invalid_expression();
6759 * Parses a __builtin_is_*() compare expression.
6761 static expression_t *parse_compare_builtin(void)
6763 expression_t *expression;
6765 switch (token.type) {
6766 case T___builtin_isgreater:
6767 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6769 case T___builtin_isgreaterequal:
6770 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6772 case T___builtin_isless:
6773 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6775 case T___builtin_islessequal:
6776 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6778 case T___builtin_islessgreater:
6779 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6781 case T___builtin_isunordered:
6782 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6785 internal_errorf(HERE, "invalid compare builtin found");
6787 expression->base.source_position = *HERE;
6790 expect('(', end_error);
6791 expression->binary.left = parse_assignment_expression();
6792 expect(',', end_error);
6793 expression->binary.right = parse_assignment_expression();
6794 expect(')', end_error);
6796 type_t *const orig_type_left = expression->binary.left->base.type;
6797 type_t *const orig_type_right = expression->binary.right->base.type;
6799 type_t *const type_left = skip_typeref(orig_type_left);
6800 type_t *const type_right = skip_typeref(orig_type_right);
6801 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6802 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6803 type_error_incompatible("invalid operands in comparison",
6804 &expression->base.source_position, orig_type_left, orig_type_right);
6807 semantic_comparison(&expression->binary);
6812 return create_invalid_expression();
6816 * Parses a MS assume() expression.
6818 static expression_t *parse_assume(void)
6820 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6824 expect('(', end_error);
6825 add_anchor_token(')');
6826 expression->unary.value = parse_assignment_expression();
6827 rem_anchor_token(')');
6828 expect(')', end_error);
6830 expression->base.type = type_void;
6833 return create_invalid_expression();
6837 * Return the label for the current symbol or create a new one.
6839 static label_t *get_label(void)
6841 assert(token.type == T_IDENTIFIER);
6842 assert(current_function != NULL);
6844 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6845 /* If we find a local label, we already created the declaration. */
6846 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6847 if (label->base.parent_scope != current_scope) {
6848 assert(label->base.parent_scope->depth < current_scope->depth);
6849 current_function->goto_to_outer = true;
6851 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6852 /* There is no matching label in the same function, so create a new one. */
6853 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6858 return &label->label;
6862 * Parses a GNU && label address expression.
6864 static expression_t *parse_label_address(void)
6866 source_position_t source_position = token.source_position;
6868 if (token.type != T_IDENTIFIER) {
6869 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6870 return create_invalid_expression();
6873 label_t *const label = get_label();
6875 label->address_taken = true;
6877 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6878 expression->base.source_position = source_position;
6880 /* label address is treated as a void pointer */
6881 expression->base.type = type_void_ptr;
6882 expression->label_address.label = label;
6887 * Parse a microsoft __noop expression.
6889 static expression_t *parse_noop_expression(void)
6891 /* the result is a (int)0 */
6892 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6893 literal->base.type = type_int;
6894 literal->base.source_position = token.source_position;
6895 literal->literal.value.begin = "__noop";
6896 literal->literal.value.size = 6;
6900 if (token.type == '(') {
6901 /* parse arguments */
6903 add_anchor_token(')');
6904 add_anchor_token(',');
6906 if (token.type != ')') do {
6907 (void)parse_assignment_expression();
6908 } while (next_if(','));
6910 rem_anchor_token(',');
6911 rem_anchor_token(')');
6912 expect(')', end_error);
6919 * Parses a primary expression.
6921 static expression_t *parse_primary_expression(void)
6923 switch (token.type) {
6924 case T_false: return parse_boolean_literal(false);
6925 case T_true: return parse_boolean_literal(true);
6927 case T_INTEGER_OCTAL:
6928 case T_INTEGER_HEXADECIMAL:
6929 case T_FLOATINGPOINT:
6930 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6931 case T_CHARACTER_CONSTANT: return parse_character_constant();
6932 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6933 case T_STRING_LITERAL:
6934 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6935 case T___FUNCTION__:
6936 case T___func__: return parse_function_keyword();
6937 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6938 case T___FUNCSIG__: return parse_funcsig_keyword();
6939 case T___FUNCDNAME__: return parse_funcdname_keyword();
6940 case T___builtin_offsetof: return parse_offsetof();
6941 case T___builtin_va_start: return parse_va_start();
6942 case T___builtin_va_arg: return parse_va_arg();
6943 case T___builtin_va_copy: return parse_va_copy();
6944 case T___builtin_isgreater:
6945 case T___builtin_isgreaterequal:
6946 case T___builtin_isless:
6947 case T___builtin_islessequal:
6948 case T___builtin_islessgreater:
6949 case T___builtin_isunordered: return parse_compare_builtin();
6950 case T___builtin_constant_p: return parse_builtin_constant();
6951 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6952 case T__assume: return parse_assume();
6955 return parse_label_address();
6958 case '(': return parse_parenthesized_expression();
6959 case T___noop: return parse_noop_expression();
6961 /* Gracefully handle type names while parsing expressions. */
6963 return parse_reference();
6965 if (!is_typedef_symbol(token.symbol)) {
6966 return parse_reference();
6970 source_position_t const pos = *HERE;
6971 declaration_specifiers_t specifiers;
6972 parse_declaration_specifiers(&specifiers);
6973 type_t const *const type = parse_abstract_declarator(specifiers.type);
6974 errorf(&pos, "encountered type '%T' while parsing expression", type);
6975 return create_invalid_expression();
6979 errorf(HERE, "unexpected token %K, expected an expression", &token);
6981 return create_invalid_expression();
6984 static expression_t *parse_array_expression(expression_t *left)
6986 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6987 array_access_expression_t *const arr = &expr->array_access;
6990 add_anchor_token(']');
6992 expression_t *const inside = parse_expression();
6994 type_t *const orig_type_left = left->base.type;
6995 type_t *const orig_type_inside = inside->base.type;
6997 type_t *const type_left = skip_typeref(orig_type_left);
6998 type_t *const type_inside = skip_typeref(orig_type_inside);
7004 if (is_type_pointer(type_left)) {
7007 idx_type = type_inside;
7008 res_type = type_left->pointer.points_to;
7010 } else if (is_type_pointer(type_inside)) {
7011 arr->flipped = true;
7014 idx_type = type_left;
7015 res_type = type_inside->pointer.points_to;
7017 res_type = automatic_type_conversion(res_type);
7018 if (!is_type_integer(idx_type)) {
7019 errorf(&idx->base.source_position, "array subscript must have integer type");
7020 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7021 source_position_t const *const pos = &idx->base.source_position;
7022 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7025 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7026 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7028 res_type = type_error_type;
7033 arr->array_ref = ref;
7035 arr->base.type = res_type;
7037 rem_anchor_token(']');
7038 expect(']', end_error);
7043 static expression_t *parse_typeprop(expression_kind_t const kind)
7045 expression_t *tp_expression = allocate_expression_zero(kind);
7046 tp_expression->base.type = type_size_t;
7048 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7050 /* we only refer to a type property, mark this case */
7051 bool old = in_type_prop;
7052 in_type_prop = true;
7055 expression_t *expression;
7056 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7058 add_anchor_token(')');
7059 orig_type = parse_typename();
7060 rem_anchor_token(')');
7061 expect(')', end_error);
7063 if (token.type == '{') {
7064 /* It was not sizeof(type) after all. It is sizeof of an expression
7065 * starting with a compound literal */
7066 expression = parse_compound_literal(orig_type);
7067 goto typeprop_expression;
7070 expression = parse_subexpression(PREC_UNARY);
7072 typeprop_expression:
7073 tp_expression->typeprop.tp_expression = expression;
7075 orig_type = revert_automatic_type_conversion(expression);
7076 expression->base.type = orig_type;
7079 tp_expression->typeprop.type = orig_type;
7080 type_t const* const type = skip_typeref(orig_type);
7081 char const* wrong_type = NULL;
7082 if (is_type_incomplete(type)) {
7083 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7084 wrong_type = "incomplete";
7085 } else if (type->kind == TYPE_FUNCTION) {
7087 /* function types are allowed (and return 1) */
7088 source_position_t const *const pos = &tp_expression->base.source_position;
7089 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7090 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7092 wrong_type = "function";
7095 if (is_type_incomplete(type))
7096 wrong_type = "incomplete";
7098 if (type->kind == TYPE_BITFIELD)
7099 wrong_type = "bitfield";
7101 if (wrong_type != NULL) {
7102 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7103 errorf(&tp_expression->base.source_position,
7104 "operand of %s expression must not be of %s type '%T'",
7105 what, wrong_type, orig_type);
7110 return tp_expression;
7113 static expression_t *parse_sizeof(void)
7115 return parse_typeprop(EXPR_SIZEOF);
7118 static expression_t *parse_alignof(void)
7120 return parse_typeprop(EXPR_ALIGNOF);
7123 static expression_t *parse_select_expression(expression_t *addr)
7125 assert(token.type == '.' || token.type == T_MINUSGREATER);
7126 bool select_left_arrow = (token.type == T_MINUSGREATER);
7127 source_position_t const pos = *HERE;
7130 if (token.type != T_IDENTIFIER) {
7131 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7132 return create_invalid_expression();
7134 symbol_t *symbol = token.symbol;
7137 type_t *const orig_type = addr->base.type;
7138 type_t *const type = skip_typeref(orig_type);
7141 bool saw_error = false;
7142 if (is_type_pointer(type)) {
7143 if (!select_left_arrow) {
7145 "request for member '%Y' in something not a struct or union, but '%T'",
7149 type_left = skip_typeref(type->pointer.points_to);
7151 if (select_left_arrow && is_type_valid(type)) {
7152 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7158 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7159 type_left->kind != TYPE_COMPOUND_UNION) {
7161 if (is_type_valid(type_left) && !saw_error) {
7163 "request for member '%Y' in something not a struct or union, but '%T'",
7166 return create_invalid_expression();
7169 compound_t *compound = type_left->compound.compound;
7170 if (!compound->complete) {
7171 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7173 return create_invalid_expression();
7176 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7177 expression_t *result =
7178 find_create_select(&pos, addr, qualifiers, compound, symbol);
7180 if (result == NULL) {
7181 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7182 return create_invalid_expression();
7188 static void check_call_argument(type_t *expected_type,
7189 call_argument_t *argument, unsigned pos)
7191 type_t *expected_type_skip = skip_typeref(expected_type);
7192 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7193 expression_t *arg_expr = argument->expression;
7194 type_t *arg_type = skip_typeref(arg_expr->base.type);
7196 /* handle transparent union gnu extension */
7197 if (is_type_union(expected_type_skip)
7198 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7199 compound_t *union_decl = expected_type_skip->compound.compound;
7200 type_t *best_type = NULL;
7201 entity_t *entry = union_decl->members.entities;
7202 for ( ; entry != NULL; entry = entry->base.next) {
7203 assert(is_declaration(entry));
7204 type_t *decl_type = entry->declaration.type;
7205 error = semantic_assign(decl_type, arg_expr);
7206 if (error == ASSIGN_ERROR_INCOMPATIBLE
7207 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7210 if (error == ASSIGN_SUCCESS) {
7211 best_type = decl_type;
7212 } else if (best_type == NULL) {
7213 best_type = decl_type;
7217 if (best_type != NULL) {
7218 expected_type = best_type;
7222 error = semantic_assign(expected_type, arg_expr);
7223 argument->expression = create_implicit_cast(arg_expr, expected_type);
7225 if (error != ASSIGN_SUCCESS) {
7226 /* report exact scope in error messages (like "in argument 3") */
7228 snprintf(buf, sizeof(buf), "call argument %u", pos);
7229 report_assign_error(error, expected_type, arg_expr, buf,
7230 &arg_expr->base.source_position);
7232 type_t *const promoted_type = get_default_promoted_type(arg_type);
7233 if (!types_compatible(expected_type_skip, promoted_type) &&
7234 !types_compatible(expected_type_skip, type_void_ptr) &&
7235 !types_compatible(type_void_ptr, promoted_type)) {
7236 /* Deliberately show the skipped types in this warning */
7237 source_position_t const *const apos = &arg_expr->base.source_position;
7238 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7244 * Handle the semantic restrictions of builtin calls
7246 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7247 switch (call->function->reference.entity->function.btk) {
7248 case bk_gnu_builtin_return_address:
7249 case bk_gnu_builtin_frame_address: {
7250 /* argument must be constant */
7251 call_argument_t *argument = call->arguments;
7253 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7254 errorf(&call->base.source_position,
7255 "argument of '%Y' must be a constant expression",
7256 call->function->reference.entity->base.symbol);
7260 case bk_gnu_builtin_object_size:
7261 if (call->arguments == NULL)
7264 call_argument_t *arg = call->arguments->next;
7265 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7266 errorf(&call->base.source_position,
7267 "second argument of '%Y' must be a constant expression",
7268 call->function->reference.entity->base.symbol);
7271 case bk_gnu_builtin_prefetch:
7272 /* second and third argument must be constant if existent */
7273 if (call->arguments == NULL)
7275 call_argument_t *rw = call->arguments->next;
7276 call_argument_t *locality = NULL;
7279 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7280 errorf(&call->base.source_position,
7281 "second argument of '%Y' must be a constant expression",
7282 call->function->reference.entity->base.symbol);
7284 locality = rw->next;
7286 if (locality != NULL) {
7287 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7288 errorf(&call->base.source_position,
7289 "third argument of '%Y' must be a constant expression",
7290 call->function->reference.entity->base.symbol);
7292 locality = rw->next;
7301 * Parse a call expression, ie. expression '( ... )'.
7303 * @param expression the function address
7305 static expression_t *parse_call_expression(expression_t *expression)
7307 expression_t *result = allocate_expression_zero(EXPR_CALL);
7308 call_expression_t *call = &result->call;
7309 call->function = expression;
7311 type_t *const orig_type = expression->base.type;
7312 type_t *const type = skip_typeref(orig_type);
7314 function_type_t *function_type = NULL;
7315 if (is_type_pointer(type)) {
7316 type_t *const to_type = skip_typeref(type->pointer.points_to);
7318 if (is_type_function(to_type)) {
7319 function_type = &to_type->function;
7320 call->base.type = function_type->return_type;
7324 if (function_type == NULL && is_type_valid(type)) {
7326 "called object '%E' (type '%T') is not a pointer to a function",
7327 expression, orig_type);
7330 /* parse arguments */
7332 add_anchor_token(')');
7333 add_anchor_token(',');
7335 if (token.type != ')') {
7336 call_argument_t **anchor = &call->arguments;
7338 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7339 argument->expression = parse_assignment_expression();
7342 anchor = &argument->next;
7343 } while (next_if(','));
7345 rem_anchor_token(',');
7346 rem_anchor_token(')');
7347 expect(')', end_error);
7349 if (function_type == NULL)
7352 /* check type and count of call arguments */
7353 function_parameter_t *parameter = function_type->parameters;
7354 call_argument_t *argument = call->arguments;
7355 if (!function_type->unspecified_parameters) {
7356 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7357 parameter = parameter->next, argument = argument->next) {
7358 check_call_argument(parameter->type, argument, ++pos);
7361 if (parameter != NULL) {
7362 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7363 } else if (argument != NULL && !function_type->variadic) {
7364 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7368 /* do default promotion for other arguments */
7369 for (; argument != NULL; argument = argument->next) {
7370 type_t *argument_type = argument->expression->base.type;
7371 if (!is_type_object(skip_typeref(argument_type))) {
7372 errorf(&argument->expression->base.source_position,
7373 "call argument '%E' must not be void", argument->expression);
7376 argument_type = get_default_promoted_type(argument_type);
7378 argument->expression
7379 = create_implicit_cast(argument->expression, argument_type);
7384 if (is_type_compound(skip_typeref(function_type->return_type))) {
7385 source_position_t const *const pos = &expression->base.source_position;
7386 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7389 if (expression->kind == EXPR_REFERENCE) {
7390 reference_expression_t *reference = &expression->reference;
7391 if (reference->entity->kind == ENTITY_FUNCTION &&
7392 reference->entity->function.btk != bk_none)
7393 handle_builtin_argument_restrictions(call);
7400 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7402 static bool same_compound_type(const type_t *type1, const type_t *type2)
7405 is_type_compound(type1) &&
7406 type1->kind == type2->kind &&
7407 type1->compound.compound == type2->compound.compound;
7410 static expression_t const *get_reference_address(expression_t const *expr)
7412 bool regular_take_address = true;
7414 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7415 expr = expr->unary.value;
7417 regular_take_address = false;
7420 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7423 expr = expr->unary.value;
7426 if (expr->kind != EXPR_REFERENCE)
7429 /* special case for functions which are automatically converted to a
7430 * pointer to function without an extra TAKE_ADDRESS operation */
7431 if (!regular_take_address &&
7432 expr->reference.entity->kind != ENTITY_FUNCTION) {
7439 static void warn_reference_address_as_bool(expression_t const* expr)
7441 expr = get_reference_address(expr);
7443 source_position_t const *const pos = &expr->base.source_position;
7444 entity_t const *const ent = expr->reference.entity;
7445 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7449 static void warn_assignment_in_condition(const expression_t *const expr)
7451 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7453 if (expr->base.parenthesized)
7455 source_position_t const *const pos = &expr->base.source_position;
7456 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7459 static void semantic_condition(expression_t const *const expr,
7460 char const *const context)
7462 type_t *const type = skip_typeref(expr->base.type);
7463 if (is_type_scalar(type)) {
7464 warn_reference_address_as_bool(expr);
7465 warn_assignment_in_condition(expr);
7466 } else if (is_type_valid(type)) {
7467 errorf(&expr->base.source_position,
7468 "%s must have scalar type", context);
7473 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7475 * @param expression the conditional expression
7477 static expression_t *parse_conditional_expression(expression_t *expression)
7479 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7481 conditional_expression_t *conditional = &result->conditional;
7482 conditional->condition = expression;
7485 add_anchor_token(':');
7487 /* §6.5.15:2 The first operand shall have scalar type. */
7488 semantic_condition(expression, "condition of conditional operator");
7490 expression_t *true_expression = expression;
7491 bool gnu_cond = false;
7492 if (GNU_MODE && token.type == ':') {
7495 true_expression = parse_expression();
7497 rem_anchor_token(':');
7498 expect(':', end_error);
7500 expression_t *false_expression =
7501 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7503 type_t *const orig_true_type = true_expression->base.type;
7504 type_t *const orig_false_type = false_expression->base.type;
7505 type_t *const true_type = skip_typeref(orig_true_type);
7506 type_t *const false_type = skip_typeref(orig_false_type);
7509 source_position_t const *const pos = &conditional->base.source_position;
7510 type_t *result_type;
7511 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7512 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7513 /* ISO/IEC 14882:1998(E) §5.16:2 */
7514 if (true_expression->kind == EXPR_UNARY_THROW) {
7515 result_type = false_type;
7516 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7517 result_type = true_type;
7519 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7520 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7521 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7523 result_type = type_void;
7525 } else if (is_type_arithmetic(true_type)
7526 && is_type_arithmetic(false_type)) {
7527 result_type = semantic_arithmetic(true_type, false_type);
7528 } else if (same_compound_type(true_type, false_type)) {
7529 /* just take 1 of the 2 types */
7530 result_type = true_type;
7531 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7532 type_t *pointer_type;
7534 expression_t *other_expression;
7535 if (is_type_pointer(true_type) &&
7536 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7537 pointer_type = true_type;
7538 other_type = false_type;
7539 other_expression = false_expression;
7541 pointer_type = false_type;
7542 other_type = true_type;
7543 other_expression = true_expression;
7546 if (is_null_pointer_constant(other_expression)) {
7547 result_type = pointer_type;
7548 } else if (is_type_pointer(other_type)) {
7549 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7550 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7553 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7554 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7556 } else if (types_compatible(get_unqualified_type(to1),
7557 get_unqualified_type(to2))) {
7560 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7564 type_t *const type =
7565 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7566 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7567 } else if (is_type_integer(other_type)) {
7568 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7569 result_type = pointer_type;
7571 goto types_incompatible;
7575 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7576 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7578 result_type = type_error_type;
7581 conditional->true_expression
7582 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7583 conditional->false_expression
7584 = create_implicit_cast(false_expression, result_type);
7585 conditional->base.type = result_type;
7590 * Parse an extension expression.
7592 static expression_t *parse_extension(void)
7594 eat(T___extension__);
7596 bool old_gcc_extension = in_gcc_extension;
7597 in_gcc_extension = true;
7598 expression_t *expression = parse_subexpression(PREC_UNARY);
7599 in_gcc_extension = old_gcc_extension;
7604 * Parse a __builtin_classify_type() expression.
7606 static expression_t *parse_builtin_classify_type(void)
7608 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7609 result->base.type = type_int;
7611 eat(T___builtin_classify_type);
7613 expect('(', end_error);
7614 add_anchor_token(')');
7615 expression_t *expression = parse_expression();
7616 rem_anchor_token(')');
7617 expect(')', end_error);
7618 result->classify_type.type_expression = expression;
7622 return create_invalid_expression();
7626 * Parse a delete expression
7627 * ISO/IEC 14882:1998(E) §5.3.5
7629 static expression_t *parse_delete(void)
7631 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7632 result->base.type = type_void;
7637 result->kind = EXPR_UNARY_DELETE_ARRAY;
7638 expect(']', end_error);
7642 expression_t *const value = parse_subexpression(PREC_CAST);
7643 result->unary.value = value;
7645 type_t *const type = skip_typeref(value->base.type);
7646 if (!is_type_pointer(type)) {
7647 if (is_type_valid(type)) {
7648 errorf(&value->base.source_position,
7649 "operand of delete must have pointer type");
7651 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7652 source_position_t const *const pos = &value->base.source_position;
7653 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7660 * Parse a throw expression
7661 * ISO/IEC 14882:1998(E) §15:1
7663 static expression_t *parse_throw(void)
7665 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7666 result->base.type = type_void;
7670 expression_t *value = NULL;
7671 switch (token.type) {
7673 value = parse_assignment_expression();
7674 /* ISO/IEC 14882:1998(E) §15.1:3 */
7675 type_t *const orig_type = value->base.type;
7676 type_t *const type = skip_typeref(orig_type);
7677 if (is_type_incomplete(type)) {
7678 errorf(&value->base.source_position,
7679 "cannot throw object of incomplete type '%T'", orig_type);
7680 } else if (is_type_pointer(type)) {
7681 type_t *const points_to = skip_typeref(type->pointer.points_to);
7682 if (is_type_incomplete(points_to) &&
7683 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7684 errorf(&value->base.source_position,
7685 "cannot throw pointer to incomplete type '%T'", orig_type);
7693 result->unary.value = value;
7698 static bool check_pointer_arithmetic(const source_position_t *source_position,
7699 type_t *pointer_type,
7700 type_t *orig_pointer_type)
7702 type_t *points_to = pointer_type->pointer.points_to;
7703 points_to = skip_typeref(points_to);
7705 if (is_type_incomplete(points_to)) {
7706 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7707 errorf(source_position,
7708 "arithmetic with pointer to incomplete type '%T' not allowed",
7712 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7714 } else if (is_type_function(points_to)) {
7716 errorf(source_position,
7717 "arithmetic with pointer to function type '%T' not allowed",
7721 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7727 static bool is_lvalue(const expression_t *expression)
7729 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7730 switch (expression->kind) {
7731 case EXPR_ARRAY_ACCESS:
7732 case EXPR_COMPOUND_LITERAL:
7733 case EXPR_REFERENCE:
7735 case EXPR_UNARY_DEREFERENCE:
7739 type_t *type = skip_typeref(expression->base.type);
7741 /* ISO/IEC 14882:1998(E) §3.10:3 */
7742 is_type_reference(type) ||
7743 /* Claim it is an lvalue, if the type is invalid. There was a parse
7744 * error before, which maybe prevented properly recognizing it as
7746 !is_type_valid(type);
7751 static void semantic_incdec(unary_expression_t *expression)
7753 type_t *const orig_type = expression->value->base.type;
7754 type_t *const type = skip_typeref(orig_type);
7755 if (is_type_pointer(type)) {
7756 if (!check_pointer_arithmetic(&expression->base.source_position,
7760 } else if (!is_type_real(type) && is_type_valid(type)) {
7761 /* TODO: improve error message */
7762 errorf(&expression->base.source_position,
7763 "operation needs an arithmetic or pointer type");
7766 if (!is_lvalue(expression->value)) {
7767 /* TODO: improve error message */
7768 errorf(&expression->base.source_position, "lvalue required as operand");
7770 expression->base.type = orig_type;
7773 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7775 type_t *const orig_type = expression->value->base.type;
7776 type_t *const type = skip_typeref(orig_type);
7777 if (!is_type_arithmetic(type)) {
7778 if (is_type_valid(type)) {
7779 /* TODO: improve error message */
7780 errorf(&expression->base.source_position,
7781 "operation needs an arithmetic type");
7786 expression->base.type = orig_type;
7789 static void semantic_unexpr_plus(unary_expression_t *expression)
7791 semantic_unexpr_arithmetic(expression);
7792 source_position_t const *const pos = &expression->base.source_position;
7793 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7796 static void semantic_not(unary_expression_t *expression)
7798 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7799 semantic_condition(expression->value, "operand of !");
7800 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7803 static void semantic_unexpr_integer(unary_expression_t *expression)
7805 type_t *const orig_type = expression->value->base.type;
7806 type_t *const type = skip_typeref(orig_type);
7807 if (!is_type_integer(type)) {
7808 if (is_type_valid(type)) {
7809 errorf(&expression->base.source_position,
7810 "operand of ~ must be of integer type");
7815 expression->base.type = orig_type;
7818 static void semantic_dereference(unary_expression_t *expression)
7820 type_t *const orig_type = expression->value->base.type;
7821 type_t *const type = skip_typeref(orig_type);
7822 if (!is_type_pointer(type)) {
7823 if (is_type_valid(type)) {
7824 errorf(&expression->base.source_position,
7825 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7830 type_t *result_type = type->pointer.points_to;
7831 result_type = automatic_type_conversion(result_type);
7832 expression->base.type = result_type;
7836 * Record that an address is taken (expression represents an lvalue).
7838 * @param expression the expression
7839 * @param may_be_register if true, the expression might be an register
7841 static void set_address_taken(expression_t *expression, bool may_be_register)
7843 if (expression->kind != EXPR_REFERENCE)
7846 entity_t *const entity = expression->reference.entity;
7848 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7851 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7852 && !may_be_register) {
7853 source_position_t const *const pos = &expression->base.source_position;
7854 errorf(pos, "address of register '%N' requested", entity);
7857 if (entity->kind == ENTITY_VARIABLE) {
7858 entity->variable.address_taken = true;
7860 assert(entity->kind == ENTITY_PARAMETER);
7861 entity->parameter.address_taken = true;
7866 * Check the semantic of the address taken expression.
7868 static void semantic_take_addr(unary_expression_t *expression)
7870 expression_t *value = expression->value;
7871 value->base.type = revert_automatic_type_conversion(value);
7873 type_t *orig_type = value->base.type;
7874 type_t *type = skip_typeref(orig_type);
7875 if (!is_type_valid(type))
7879 if (!is_lvalue(value)) {
7880 errorf(&expression->base.source_position, "'&' requires an lvalue");
7882 if (type->kind == TYPE_BITFIELD) {
7883 errorf(&expression->base.source_position,
7884 "'&' not allowed on object with bitfield type '%T'",
7888 set_address_taken(value, false);
7890 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7893 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7894 static expression_t *parse_##unexpression_type(void) \
7896 expression_t *unary_expression \
7897 = allocate_expression_zero(unexpression_type); \
7899 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7901 sfunc(&unary_expression->unary); \
7903 return unary_expression; \
7906 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7907 semantic_unexpr_arithmetic)
7908 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7909 semantic_unexpr_plus)
7910 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7912 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7913 semantic_dereference)
7914 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7916 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7917 semantic_unexpr_integer)
7918 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7920 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7923 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7925 static expression_t *parse_##unexpression_type(expression_t *left) \
7927 expression_t *unary_expression \
7928 = allocate_expression_zero(unexpression_type); \
7930 unary_expression->unary.value = left; \
7932 sfunc(&unary_expression->unary); \
7934 return unary_expression; \
7937 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7938 EXPR_UNARY_POSTFIX_INCREMENT,
7940 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7941 EXPR_UNARY_POSTFIX_DECREMENT,
7944 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7946 /* TODO: handle complex + imaginary types */
7948 type_left = get_unqualified_type(type_left);
7949 type_right = get_unqualified_type(type_right);
7951 /* §6.3.1.8 Usual arithmetic conversions */
7952 if (type_left == type_long_double || type_right == type_long_double) {
7953 return type_long_double;
7954 } else if (type_left == type_double || type_right == type_double) {
7956 } else if (type_left == type_float || type_right == type_float) {
7960 type_left = promote_integer(type_left);
7961 type_right = promote_integer(type_right);
7963 if (type_left == type_right)
7966 bool const signed_left = is_type_signed(type_left);
7967 bool const signed_right = is_type_signed(type_right);
7968 int const rank_left = get_rank(type_left);
7969 int const rank_right = get_rank(type_right);
7971 if (signed_left == signed_right)
7972 return rank_left >= rank_right ? type_left : type_right;
7981 u_rank = rank_right;
7982 u_type = type_right;
7984 s_rank = rank_right;
7985 s_type = type_right;
7990 if (u_rank >= s_rank)
7993 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7995 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7996 > get_atomic_type_size((atomic_type_kind_t) u_rank))
8000 case ATOMIC_TYPE_INT: return type_unsigned_int;
8001 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8002 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8004 default: panic("invalid atomic type");
8009 * Check the semantic restrictions for a binary expression.
8011 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8013 expression_t *const left = expression->left;
8014 expression_t *const right = expression->right;
8015 type_t *const orig_type_left = left->base.type;
8016 type_t *const orig_type_right = right->base.type;
8017 type_t *const type_left = skip_typeref(orig_type_left);
8018 type_t *const type_right = skip_typeref(orig_type_right);
8020 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8021 /* TODO: improve error message */
8022 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8023 errorf(&expression->base.source_position,
8024 "operation needs arithmetic types");
8029 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8030 expression->left = create_implicit_cast(left, arithmetic_type);
8031 expression->right = create_implicit_cast(right, arithmetic_type);
8032 expression->base.type = arithmetic_type;
8035 static void semantic_binexpr_integer(binary_expression_t *const expression)
8037 expression_t *const left = expression->left;
8038 expression_t *const right = expression->right;
8039 type_t *const orig_type_left = left->base.type;
8040 type_t *const orig_type_right = right->base.type;
8041 type_t *const type_left = skip_typeref(orig_type_left);
8042 type_t *const type_right = skip_typeref(orig_type_right);
8044 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8045 /* TODO: improve error message */
8046 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8047 errorf(&expression->base.source_position,
8048 "operation needs integer types");
8053 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8054 expression->left = create_implicit_cast(left, result_type);
8055 expression->right = create_implicit_cast(right, result_type);
8056 expression->base.type = result_type;
8059 static void warn_div_by_zero(binary_expression_t const *const expression)
8061 if (!is_type_integer(expression->base.type))
8064 expression_t const *const right = expression->right;
8065 /* The type of the right operand can be different for /= */
8066 if (is_type_integer(right->base.type) &&
8067 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8068 !fold_constant_to_bool(right)) {
8069 source_position_t const *const pos = &expression->base.source_position;
8070 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8075 * Check the semantic restrictions for a div/mod expression.
8077 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8079 semantic_binexpr_arithmetic(expression);
8080 warn_div_by_zero(expression);
8083 static void warn_addsub_in_shift(const expression_t *const expr)
8085 if (expr->base.parenthesized)
8089 switch (expr->kind) {
8090 case EXPR_BINARY_ADD: op = '+'; break;
8091 case EXPR_BINARY_SUB: op = '-'; break;
8095 source_position_t const *const pos = &expr->base.source_position;
8096 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8099 static bool semantic_shift(binary_expression_t *expression)
8101 expression_t *const left = expression->left;
8102 expression_t *const right = expression->right;
8103 type_t *const orig_type_left = left->base.type;
8104 type_t *const orig_type_right = right->base.type;
8105 type_t * type_left = skip_typeref(orig_type_left);
8106 type_t * type_right = skip_typeref(orig_type_right);
8108 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8109 /* TODO: improve error message */
8110 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8111 errorf(&expression->base.source_position,
8112 "operands of shift operation must have integer types");
8117 type_left = promote_integer(type_left);
8119 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8120 source_position_t const *const pos = &right->base.source_position;
8121 long const count = fold_constant_to_int(right);
8123 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8124 } else if ((unsigned long)count >=
8125 get_atomic_type_size(type_left->atomic.akind) * 8) {
8126 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8130 type_right = promote_integer(type_right);
8131 expression->right = create_implicit_cast(right, type_right);
8136 static void semantic_shift_op(binary_expression_t *expression)
8138 expression_t *const left = expression->left;
8139 expression_t *const right = expression->right;
8141 if (!semantic_shift(expression))
8144 warn_addsub_in_shift(left);
8145 warn_addsub_in_shift(right);
8147 type_t *const orig_type_left = left->base.type;
8148 type_t * type_left = skip_typeref(orig_type_left);
8150 type_left = promote_integer(type_left);
8151 expression->left = create_implicit_cast(left, type_left);
8152 expression->base.type = type_left;
8155 static void semantic_add(binary_expression_t *expression)
8157 expression_t *const left = expression->left;
8158 expression_t *const right = expression->right;
8159 type_t *const orig_type_left = left->base.type;
8160 type_t *const orig_type_right = right->base.type;
8161 type_t *const type_left = skip_typeref(orig_type_left);
8162 type_t *const type_right = skip_typeref(orig_type_right);
8165 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8166 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8167 expression->left = create_implicit_cast(left, arithmetic_type);
8168 expression->right = create_implicit_cast(right, arithmetic_type);
8169 expression->base.type = arithmetic_type;
8170 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8171 check_pointer_arithmetic(&expression->base.source_position,
8172 type_left, orig_type_left);
8173 expression->base.type = type_left;
8174 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8175 check_pointer_arithmetic(&expression->base.source_position,
8176 type_right, orig_type_right);
8177 expression->base.type = type_right;
8178 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8179 errorf(&expression->base.source_position,
8180 "invalid operands to binary + ('%T', '%T')",
8181 orig_type_left, orig_type_right);
8185 static void semantic_sub(binary_expression_t *expression)
8187 expression_t *const left = expression->left;
8188 expression_t *const right = expression->right;
8189 type_t *const orig_type_left = left->base.type;
8190 type_t *const orig_type_right = right->base.type;
8191 type_t *const type_left = skip_typeref(orig_type_left);
8192 type_t *const type_right = skip_typeref(orig_type_right);
8193 source_position_t const *const pos = &expression->base.source_position;
8196 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8197 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8198 expression->left = create_implicit_cast(left, arithmetic_type);
8199 expression->right = create_implicit_cast(right, arithmetic_type);
8200 expression->base.type = arithmetic_type;
8201 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8202 check_pointer_arithmetic(&expression->base.source_position,
8203 type_left, orig_type_left);
8204 expression->base.type = type_left;
8205 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8206 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8207 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8208 if (!types_compatible(unqual_left, unqual_right)) {
8210 "subtracting pointers to incompatible types '%T' and '%T'",
8211 orig_type_left, orig_type_right);
8212 } else if (!is_type_object(unqual_left)) {
8213 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8214 errorf(pos, "subtracting pointers to non-object types '%T'",
8217 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8220 expression->base.type = type_ptrdiff_t;
8221 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8222 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8223 orig_type_left, orig_type_right);
8227 static void warn_string_literal_address(expression_t const* expr)
8229 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8230 expr = expr->unary.value;
8231 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8233 expr = expr->unary.value;
8236 if (expr->kind == EXPR_STRING_LITERAL
8237 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8238 source_position_t const *const pos = &expr->base.source_position;
8239 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8243 static bool maybe_negative(expression_t const *const expr)
8245 switch (is_constant_expression(expr)) {
8246 case EXPR_CLASS_ERROR: return false;
8247 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8248 default: return true;
8252 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8254 warn_string_literal_address(expr);
8256 expression_t const* const ref = get_reference_address(expr);
8257 if (ref != NULL && is_null_pointer_constant(other)) {
8258 entity_t const *const ent = ref->reference.entity;
8259 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8262 if (!expr->base.parenthesized) {
8263 switch (expr->base.kind) {
8264 case EXPR_BINARY_LESS:
8265 case EXPR_BINARY_GREATER:
8266 case EXPR_BINARY_LESSEQUAL:
8267 case EXPR_BINARY_GREATEREQUAL:
8268 case EXPR_BINARY_NOTEQUAL:
8269 case EXPR_BINARY_EQUAL:
8270 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8279 * Check the semantics of comparison expressions.
8281 * @param expression The expression to check.
8283 static void semantic_comparison(binary_expression_t *expression)
8285 source_position_t const *const pos = &expression->base.source_position;
8286 expression_t *const left = expression->left;
8287 expression_t *const right = expression->right;
8289 warn_comparison(pos, left, right);
8290 warn_comparison(pos, right, left);
8292 type_t *orig_type_left = left->base.type;
8293 type_t *orig_type_right = right->base.type;
8294 type_t *type_left = skip_typeref(orig_type_left);
8295 type_t *type_right = skip_typeref(orig_type_right);
8297 /* TODO non-arithmetic types */
8298 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8299 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8301 /* test for signed vs unsigned compares */
8302 if (is_type_integer(arithmetic_type)) {
8303 bool const signed_left = is_type_signed(type_left);
8304 bool const signed_right = is_type_signed(type_right);
8305 if (signed_left != signed_right) {
8306 /* FIXME long long needs better const folding magic */
8307 /* TODO check whether constant value can be represented by other type */
8308 if ((signed_left && maybe_negative(left)) ||
8309 (signed_right && maybe_negative(right))) {
8310 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8315 expression->left = create_implicit_cast(left, arithmetic_type);
8316 expression->right = create_implicit_cast(right, arithmetic_type);
8317 expression->base.type = arithmetic_type;
8318 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8319 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8320 is_type_float(arithmetic_type)) {
8321 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8323 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8324 /* TODO check compatibility */
8325 } else if (is_type_pointer(type_left)) {
8326 expression->right = create_implicit_cast(right, type_left);
8327 } else if (is_type_pointer(type_right)) {
8328 expression->left = create_implicit_cast(left, type_right);
8329 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8330 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8332 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8336 * Checks if a compound type has constant fields.
8338 static bool has_const_fields(const compound_type_t *type)
8340 compound_t *compound = type->compound;
8341 entity_t *entry = compound->members.entities;
8343 for (; entry != NULL; entry = entry->base.next) {
8344 if (!is_declaration(entry))
8347 const type_t *decl_type = skip_typeref(entry->declaration.type);
8348 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8355 static bool is_valid_assignment_lhs(expression_t const* const left)
8357 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8358 type_t *const type_left = skip_typeref(orig_type_left);
8360 if (!is_lvalue(left)) {
8361 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8366 if (left->kind == EXPR_REFERENCE
8367 && left->reference.entity->kind == ENTITY_FUNCTION) {
8368 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8372 if (is_type_array(type_left)) {
8373 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8376 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8377 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8381 if (is_type_incomplete(type_left)) {
8382 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8383 left, orig_type_left);
8386 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8387 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8388 left, orig_type_left);
8395 static void semantic_arithmetic_assign(binary_expression_t *expression)
8397 expression_t *left = expression->left;
8398 expression_t *right = expression->right;
8399 type_t *orig_type_left = left->base.type;
8400 type_t *orig_type_right = right->base.type;
8402 if (!is_valid_assignment_lhs(left))
8405 type_t *type_left = skip_typeref(orig_type_left);
8406 type_t *type_right = skip_typeref(orig_type_right);
8408 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8409 /* TODO: improve error message */
8410 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8411 errorf(&expression->base.source_position,
8412 "operation needs arithmetic types");
8417 /* combined instructions are tricky. We can't create an implicit cast on
8418 * the left side, because we need the uncasted form for the store.
8419 * The ast2firm pass has to know that left_type must be right_type
8420 * for the arithmetic operation and create a cast by itself */
8421 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8422 expression->right = create_implicit_cast(right, arithmetic_type);
8423 expression->base.type = type_left;
8426 static void semantic_divmod_assign(binary_expression_t *expression)
8428 semantic_arithmetic_assign(expression);
8429 warn_div_by_zero(expression);
8432 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8434 expression_t *const left = expression->left;
8435 expression_t *const right = expression->right;
8436 type_t *const orig_type_left = left->base.type;
8437 type_t *const orig_type_right = right->base.type;
8438 type_t *const type_left = skip_typeref(orig_type_left);
8439 type_t *const type_right = skip_typeref(orig_type_right);
8441 if (!is_valid_assignment_lhs(left))
8444 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8445 /* combined instructions are tricky. We can't create an implicit cast on
8446 * the left side, because we need the uncasted form for the store.
8447 * The ast2firm pass has to know that left_type must be right_type
8448 * for the arithmetic operation and create a cast by itself */
8449 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8450 expression->right = create_implicit_cast(right, arithmetic_type);
8451 expression->base.type = type_left;
8452 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8453 check_pointer_arithmetic(&expression->base.source_position,
8454 type_left, orig_type_left);
8455 expression->base.type = type_left;
8456 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8457 errorf(&expression->base.source_position,
8458 "incompatible types '%T' and '%T' in assignment",
8459 orig_type_left, orig_type_right);
8463 static void semantic_integer_assign(binary_expression_t *expression)
8465 expression_t *left = expression->left;
8466 expression_t *right = expression->right;
8467 type_t *orig_type_left = left->base.type;
8468 type_t *orig_type_right = right->base.type;
8470 if (!is_valid_assignment_lhs(left))
8473 type_t *type_left = skip_typeref(orig_type_left);
8474 type_t *type_right = skip_typeref(orig_type_right);
8476 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8477 /* TODO: improve error message */
8478 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8479 errorf(&expression->base.source_position,
8480 "operation needs integer types");
8485 /* combined instructions are tricky. We can't create an implicit cast on
8486 * the left side, because we need the uncasted form for the store.
8487 * The ast2firm pass has to know that left_type must be right_type
8488 * for the arithmetic operation and create a cast by itself */
8489 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8490 expression->right = create_implicit_cast(right, arithmetic_type);
8491 expression->base.type = type_left;
8494 static void semantic_shift_assign(binary_expression_t *expression)
8496 expression_t *left = expression->left;
8498 if (!is_valid_assignment_lhs(left))
8501 if (!semantic_shift(expression))
8504 expression->base.type = skip_typeref(left->base.type);
8507 static void warn_logical_and_within_or(const expression_t *const expr)
8509 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8511 if (expr->base.parenthesized)
8513 source_position_t const *const pos = &expr->base.source_position;
8514 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8518 * Check the semantic restrictions of a logical expression.
8520 static void semantic_logical_op(binary_expression_t *expression)
8522 /* §6.5.13:2 Each of the operands shall have scalar type.
8523 * §6.5.14:2 Each of the operands shall have scalar type. */
8524 semantic_condition(expression->left, "left operand of logical operator");
8525 semantic_condition(expression->right, "right operand of logical operator");
8526 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8527 warn_logical_and_within_or(expression->left);
8528 warn_logical_and_within_or(expression->right);
8530 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8534 * Check the semantic restrictions of a binary assign expression.
8536 static void semantic_binexpr_assign(binary_expression_t *expression)
8538 expression_t *left = expression->left;
8539 type_t *orig_type_left = left->base.type;
8541 if (!is_valid_assignment_lhs(left))
8544 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8545 report_assign_error(error, orig_type_left, expression->right,
8546 "assignment", &left->base.source_position);
8547 expression->right = create_implicit_cast(expression->right, orig_type_left);
8548 expression->base.type = orig_type_left;
8552 * Determine if the outermost operation (or parts thereof) of the given
8553 * expression has no effect in order to generate a warning about this fact.
8554 * Therefore in some cases this only examines some of the operands of the
8555 * expression (see comments in the function and examples below).
8557 * f() + 23; // warning, because + has no effect
8558 * x || f(); // no warning, because x controls execution of f()
8559 * x ? y : f(); // warning, because y has no effect
8560 * (void)x; // no warning to be able to suppress the warning
8561 * This function can NOT be used for an "expression has definitely no effect"-
8563 static bool expression_has_effect(const expression_t *const expr)
8565 switch (expr->kind) {
8566 case EXPR_UNKNOWN: break;
8567 case EXPR_INVALID: return true; /* do NOT warn */
8568 case EXPR_REFERENCE: return false;
8569 case EXPR_REFERENCE_ENUM_VALUE: return false;
8570 case EXPR_LABEL_ADDRESS: return false;
8572 /* suppress the warning for microsoft __noop operations */
8573 case EXPR_LITERAL_MS_NOOP: return true;
8574 case EXPR_LITERAL_BOOLEAN:
8575 case EXPR_LITERAL_CHARACTER:
8576 case EXPR_LITERAL_WIDE_CHARACTER:
8577 case EXPR_LITERAL_INTEGER:
8578 case EXPR_LITERAL_INTEGER_OCTAL:
8579 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8580 case EXPR_LITERAL_FLOATINGPOINT:
8581 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8582 case EXPR_STRING_LITERAL: return false;
8583 case EXPR_WIDE_STRING_LITERAL: return false;
8586 const call_expression_t *const call = &expr->call;
8587 if (call->function->kind != EXPR_REFERENCE)
8590 switch (call->function->reference.entity->function.btk) {
8591 /* FIXME: which builtins have no effect? */
8592 default: return true;
8596 /* Generate the warning if either the left or right hand side of a
8597 * conditional expression has no effect */
8598 case EXPR_CONDITIONAL: {
8599 conditional_expression_t const *const cond = &expr->conditional;
8600 expression_t const *const t = cond->true_expression;
8602 (t == NULL || expression_has_effect(t)) &&
8603 expression_has_effect(cond->false_expression);
8606 case EXPR_SELECT: return false;
8607 case EXPR_ARRAY_ACCESS: return false;
8608 case EXPR_SIZEOF: return false;
8609 case EXPR_CLASSIFY_TYPE: return false;
8610 case EXPR_ALIGNOF: return false;
8612 case EXPR_FUNCNAME: return false;
8613 case EXPR_BUILTIN_CONSTANT_P: return false;
8614 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8615 case EXPR_OFFSETOF: return false;
8616 case EXPR_VA_START: return true;
8617 case EXPR_VA_ARG: return true;
8618 case EXPR_VA_COPY: return true;
8619 case EXPR_STATEMENT: return true; // TODO
8620 case EXPR_COMPOUND_LITERAL: return false;
8622 case EXPR_UNARY_NEGATE: return false;
8623 case EXPR_UNARY_PLUS: return false;
8624 case EXPR_UNARY_BITWISE_NEGATE: return false;
8625 case EXPR_UNARY_NOT: return false;
8626 case EXPR_UNARY_DEREFERENCE: return false;
8627 case EXPR_UNARY_TAKE_ADDRESS: return false;
8628 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8629 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8630 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8631 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8633 /* Treat void casts as if they have an effect in order to being able to
8634 * suppress the warning */
8635 case EXPR_UNARY_CAST: {
8636 type_t *const type = skip_typeref(expr->base.type);
8637 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8640 case EXPR_UNARY_CAST_IMPLICIT: return true;
8641 case EXPR_UNARY_ASSUME: return true;
8642 case EXPR_UNARY_DELETE: return true;
8643 case EXPR_UNARY_DELETE_ARRAY: return true;
8644 case EXPR_UNARY_THROW: return true;
8646 case EXPR_BINARY_ADD: return false;
8647 case EXPR_BINARY_SUB: return false;
8648 case EXPR_BINARY_MUL: return false;
8649 case EXPR_BINARY_DIV: return false;
8650 case EXPR_BINARY_MOD: return false;
8651 case EXPR_BINARY_EQUAL: return false;
8652 case EXPR_BINARY_NOTEQUAL: return false;
8653 case EXPR_BINARY_LESS: return false;
8654 case EXPR_BINARY_LESSEQUAL: return false;
8655 case EXPR_BINARY_GREATER: return false;
8656 case EXPR_BINARY_GREATEREQUAL: return false;
8657 case EXPR_BINARY_BITWISE_AND: return false;
8658 case EXPR_BINARY_BITWISE_OR: return false;
8659 case EXPR_BINARY_BITWISE_XOR: return false;
8660 case EXPR_BINARY_SHIFTLEFT: return false;
8661 case EXPR_BINARY_SHIFTRIGHT: return false;
8662 case EXPR_BINARY_ASSIGN: return true;
8663 case EXPR_BINARY_MUL_ASSIGN: return true;
8664 case EXPR_BINARY_DIV_ASSIGN: return true;
8665 case EXPR_BINARY_MOD_ASSIGN: return true;
8666 case EXPR_BINARY_ADD_ASSIGN: return true;
8667 case EXPR_BINARY_SUB_ASSIGN: return true;
8668 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8669 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8670 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8671 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8672 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8674 /* Only examine the right hand side of && and ||, because the left hand
8675 * side already has the effect of controlling the execution of the right
8677 case EXPR_BINARY_LOGICAL_AND:
8678 case EXPR_BINARY_LOGICAL_OR:
8679 /* Only examine the right hand side of a comma expression, because the left
8680 * hand side has a separate warning */
8681 case EXPR_BINARY_COMMA:
8682 return expression_has_effect(expr->binary.right);
8684 case EXPR_BINARY_ISGREATER: return false;
8685 case EXPR_BINARY_ISGREATEREQUAL: return false;
8686 case EXPR_BINARY_ISLESS: return false;
8687 case EXPR_BINARY_ISLESSEQUAL: return false;
8688 case EXPR_BINARY_ISLESSGREATER: return false;
8689 case EXPR_BINARY_ISUNORDERED: return false;
8692 internal_errorf(HERE, "unexpected expression");
8695 static void semantic_comma(binary_expression_t *expression)
8697 const expression_t *const left = expression->left;
8698 if (!expression_has_effect(left)) {
8699 source_position_t const *const pos = &left->base.source_position;
8700 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8702 expression->base.type = expression->right->base.type;
8706 * @param prec_r precedence of the right operand
8708 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8709 static expression_t *parse_##binexpression_type(expression_t *left) \
8711 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8712 binexpr->binary.left = left; \
8715 expression_t *right = parse_subexpression(prec_r); \
8717 binexpr->binary.right = right; \
8718 sfunc(&binexpr->binary); \
8723 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8724 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8725 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8726 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8727 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8728 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8729 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8730 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8731 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8732 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8733 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8734 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8735 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8736 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8737 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8738 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8739 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8740 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8741 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8742 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8743 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8744 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8745 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8746 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8747 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8748 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8749 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8750 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8751 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8752 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8755 static expression_t *parse_subexpression(precedence_t precedence)
8757 if (token.type < 0) {
8758 return expected_expression_error();
8761 expression_parser_function_t *parser
8762 = &expression_parsers[token.type];
8765 if (parser->parser != NULL) {
8766 left = parser->parser();
8768 left = parse_primary_expression();
8770 assert(left != NULL);
8773 if (token.type < 0) {
8774 return expected_expression_error();
8777 parser = &expression_parsers[token.type];
8778 if (parser->infix_parser == NULL)
8780 if (parser->infix_precedence < precedence)
8783 left = parser->infix_parser(left);
8785 assert(left != NULL);
8786 assert(left->kind != EXPR_UNKNOWN);
8793 * Parse an expression.
8795 static expression_t *parse_expression(void)
8797 return parse_subexpression(PREC_EXPRESSION);
8801 * Register a parser for a prefix-like operator.
8803 * @param parser the parser function
8804 * @param token_type the token type of the prefix token
8806 static void register_expression_parser(parse_expression_function parser,
8809 expression_parser_function_t *entry = &expression_parsers[token_type];
8811 if (entry->parser != NULL) {
8812 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8813 panic("trying to register multiple expression parsers for a token");
8815 entry->parser = parser;
8819 * Register a parser for an infix operator with given precedence.
8821 * @param parser the parser function
8822 * @param token_type the token type of the infix operator
8823 * @param precedence the precedence of the operator
8825 static void register_infix_parser(parse_expression_infix_function parser,
8826 int token_type, precedence_t precedence)
8828 expression_parser_function_t *entry = &expression_parsers[token_type];
8830 if (entry->infix_parser != NULL) {
8831 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8832 panic("trying to register multiple infix expression parsers for a "
8835 entry->infix_parser = parser;
8836 entry->infix_precedence = precedence;
8840 * Initialize the expression parsers.
8842 static void init_expression_parsers(void)
8844 memset(&expression_parsers, 0, sizeof(expression_parsers));
8846 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8847 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8848 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8849 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8850 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8851 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8852 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8853 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8854 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8855 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8856 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8857 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8858 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8859 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8860 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8861 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8862 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8863 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8864 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8865 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8866 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8867 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8868 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8869 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8870 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8871 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8872 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8873 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8874 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8875 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8876 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8877 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8878 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8879 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8880 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8881 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8882 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8884 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8885 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8886 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8887 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8888 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8889 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8890 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8891 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8892 register_expression_parser(parse_sizeof, T_sizeof);
8893 register_expression_parser(parse_alignof, T___alignof__);
8894 register_expression_parser(parse_extension, T___extension__);
8895 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8896 register_expression_parser(parse_delete, T_delete);
8897 register_expression_parser(parse_throw, T_throw);
8901 * Parse a asm statement arguments specification.
8903 static asm_argument_t *parse_asm_arguments(bool is_out)
8905 asm_argument_t *result = NULL;
8906 asm_argument_t **anchor = &result;
8908 while (token.type == T_STRING_LITERAL || token.type == '[') {
8909 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8910 memset(argument, 0, sizeof(argument[0]));
8913 if (token.type != T_IDENTIFIER) {
8914 parse_error_expected("while parsing asm argument",
8915 T_IDENTIFIER, NULL);
8918 argument->symbol = token.symbol;
8920 expect(']', end_error);
8923 argument->constraints = parse_string_literals();
8924 expect('(', end_error);
8925 add_anchor_token(')');
8926 expression_t *expression = parse_expression();
8927 rem_anchor_token(')');
8929 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8930 * change size or type representation (e.g. int -> long is ok, but
8931 * int -> float is not) */
8932 if (expression->kind == EXPR_UNARY_CAST) {
8933 type_t *const type = expression->base.type;
8934 type_kind_t const kind = type->kind;
8935 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8938 if (kind == TYPE_ATOMIC) {
8939 atomic_type_kind_t const akind = type->atomic.akind;
8940 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8941 size = get_atomic_type_size(akind);
8943 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8944 size = get_atomic_type_size(get_intptr_kind());
8948 expression_t *const value = expression->unary.value;
8949 type_t *const value_type = value->base.type;
8950 type_kind_t const value_kind = value_type->kind;
8952 unsigned value_flags;
8953 unsigned value_size;
8954 if (value_kind == TYPE_ATOMIC) {
8955 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8956 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8957 value_size = get_atomic_type_size(value_akind);
8958 } else if (value_kind == TYPE_POINTER) {
8959 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8960 value_size = get_atomic_type_size(get_intptr_kind());
8965 if (value_flags != flags || value_size != size)
8969 } while (expression->kind == EXPR_UNARY_CAST);
8973 if (!is_lvalue(expression)) {
8974 errorf(&expression->base.source_position,
8975 "asm output argument is not an lvalue");
8978 if (argument->constraints.begin[0] == '=')
8979 determine_lhs_ent(expression, NULL);
8981 mark_vars_read(expression, NULL);
8983 mark_vars_read(expression, NULL);
8985 argument->expression = expression;
8986 expect(')', end_error);
8988 set_address_taken(expression, true);
8991 anchor = &argument->next;
9003 * Parse a asm statement clobber specification.
9005 static asm_clobber_t *parse_asm_clobbers(void)
9007 asm_clobber_t *result = NULL;
9008 asm_clobber_t **anchor = &result;
9010 while (token.type == T_STRING_LITERAL) {
9011 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9012 clobber->clobber = parse_string_literals();
9015 anchor = &clobber->next;
9025 * Parse an asm statement.
9027 static statement_t *parse_asm_statement(void)
9029 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9030 asm_statement_t *asm_statement = &statement->asms;
9034 if (next_if(T_volatile))
9035 asm_statement->is_volatile = true;
9037 expect('(', end_error);
9038 add_anchor_token(')');
9039 if (token.type != T_STRING_LITERAL) {
9040 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9043 asm_statement->asm_text = parse_string_literals();
9045 add_anchor_token(':');
9046 if (!next_if(':')) {
9047 rem_anchor_token(':');
9051 asm_statement->outputs = parse_asm_arguments(true);
9052 if (!next_if(':')) {
9053 rem_anchor_token(':');
9057 asm_statement->inputs = parse_asm_arguments(false);
9058 if (!next_if(':')) {
9059 rem_anchor_token(':');
9062 rem_anchor_token(':');
9064 asm_statement->clobbers = parse_asm_clobbers();
9067 rem_anchor_token(')');
9068 expect(')', end_error);
9069 expect(';', end_error);
9071 if (asm_statement->outputs == NULL) {
9072 /* GCC: An 'asm' instruction without any output operands will be treated
9073 * identically to a volatile 'asm' instruction. */
9074 asm_statement->is_volatile = true;
9079 return create_invalid_statement();
9082 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9084 statement_t *inner_stmt;
9085 switch (token.type) {
9087 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9088 inner_stmt = create_invalid_statement();
9092 if (label->kind == STATEMENT_LABEL) {
9093 /* Eat an empty statement here, to avoid the warning about an empty
9094 * statement after a label. label:; is commonly used to have a label
9095 * before a closing brace. */
9096 inner_stmt = create_empty_statement();
9103 inner_stmt = parse_statement();
9104 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9105 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9106 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9114 * Parse a case statement.
9116 static statement_t *parse_case_statement(void)
9118 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9119 source_position_t *const pos = &statement->base.source_position;
9123 expression_t *const expression = parse_expression();
9124 statement->case_label.expression = expression;
9125 expression_classification_t const expr_class = is_constant_expression(expression);
9126 if (expr_class != EXPR_CLASS_CONSTANT) {
9127 if (expr_class != EXPR_CLASS_ERROR) {
9128 errorf(pos, "case label does not reduce to an integer constant");
9130 statement->case_label.is_bad = true;
9132 long const val = fold_constant_to_int(expression);
9133 statement->case_label.first_case = val;
9134 statement->case_label.last_case = val;
9138 if (next_if(T_DOTDOTDOT)) {
9139 expression_t *const end_range = parse_expression();
9140 statement->case_label.end_range = end_range;
9141 expression_classification_t const end_class = is_constant_expression(end_range);
9142 if (end_class != EXPR_CLASS_CONSTANT) {
9143 if (end_class != EXPR_CLASS_ERROR) {
9144 errorf(pos, "case range does not reduce to an integer constant");
9146 statement->case_label.is_bad = true;
9148 long const val = fold_constant_to_int(end_range);
9149 statement->case_label.last_case = val;
9151 if (val < statement->case_label.first_case) {
9152 statement->case_label.is_empty_range = true;
9153 warningf(WARN_OTHER, pos, "empty range specified");
9159 PUSH_PARENT(statement);
9161 expect(':', end_error);
9164 if (current_switch != NULL) {
9165 if (! statement->case_label.is_bad) {
9166 /* Check for duplicate case values */
9167 case_label_statement_t *c = &statement->case_label;
9168 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9169 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9172 if (c->last_case < l->first_case || c->first_case > l->last_case)
9175 errorf(pos, "duplicate case value (previously used %P)",
9176 &l->base.source_position);
9180 /* link all cases into the switch statement */
9181 if (current_switch->last_case == NULL) {
9182 current_switch->first_case = &statement->case_label;
9184 current_switch->last_case->next = &statement->case_label;
9186 current_switch->last_case = &statement->case_label;
9188 errorf(pos, "case label not within a switch statement");
9191 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9198 * Parse a default statement.
9200 static statement_t *parse_default_statement(void)
9202 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9206 PUSH_PARENT(statement);
9208 expect(':', end_error);
9211 if (current_switch != NULL) {
9212 const case_label_statement_t *def_label = current_switch->default_label;
9213 if (def_label != NULL) {
9214 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9216 current_switch->default_label = &statement->case_label;
9218 /* link all cases into the switch statement */
9219 if (current_switch->last_case == NULL) {
9220 current_switch->first_case = &statement->case_label;
9222 current_switch->last_case->next = &statement->case_label;
9224 current_switch->last_case = &statement->case_label;
9227 errorf(&statement->base.source_position,
9228 "'default' label not within a switch statement");
9231 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9238 * Parse a label statement.
9240 static statement_t *parse_label_statement(void)
9242 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9243 label_t *const label = get_label();
9244 statement->label.label = label;
9246 PUSH_PARENT(statement);
9248 /* if statement is already set then the label is defined twice,
9249 * otherwise it was just mentioned in a goto/local label declaration so far
9251 source_position_t const* const pos = &statement->base.source_position;
9252 if (label->statement != NULL) {
9253 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9255 label->base.source_position = *pos;
9256 label->statement = statement;
9261 statement->label.statement = parse_label_inner_statement(statement, "label");
9263 /* remember the labels in a list for later checking */
9264 *label_anchor = &statement->label;
9265 label_anchor = &statement->label.next;
9272 * Parse an if statement.
9274 static statement_t *parse_if(void)
9276 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9280 PUSH_PARENT(statement);
9282 add_anchor_token('{');
9284 expect('(', end_error);
9285 add_anchor_token(')');
9286 expression_t *const expr = parse_expression();
9287 statement->ifs.condition = expr;
9288 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9290 semantic_condition(expr, "condition of 'if'-statment");
9291 mark_vars_read(expr, NULL);
9292 rem_anchor_token(')');
9293 expect(')', end_error);
9296 rem_anchor_token('{');
9298 add_anchor_token(T_else);
9299 statement_t *const true_stmt = parse_statement();
9300 statement->ifs.true_statement = true_stmt;
9301 rem_anchor_token(T_else);
9303 if (next_if(T_else)) {
9304 statement->ifs.false_statement = parse_statement();
9305 } else if (true_stmt->kind == STATEMENT_IF &&
9306 true_stmt->ifs.false_statement != NULL) {
9307 source_position_t const *const pos = &true_stmt->base.source_position;
9308 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9316 * Check that all enums are handled in a switch.
9318 * @param statement the switch statement to check
9320 static void check_enum_cases(const switch_statement_t *statement)
9322 if (!is_warn_on(WARN_SWITCH_ENUM))
9324 const type_t *type = skip_typeref(statement->expression->base.type);
9325 if (! is_type_enum(type))
9327 const enum_type_t *enumt = &type->enumt;
9329 /* if we have a default, no warnings */
9330 if (statement->default_label != NULL)
9333 /* FIXME: calculation of value should be done while parsing */
9334 /* TODO: quadratic algorithm here. Change to an n log n one */
9335 long last_value = -1;
9336 const entity_t *entry = enumt->enume->base.next;
9337 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9338 entry = entry->base.next) {
9339 const expression_t *expression = entry->enum_value.value;
9340 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9342 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9343 if (l->expression == NULL)
9345 if (l->first_case <= value && value <= l->last_case) {
9351 source_position_t const *const pos = &statement->base.source_position;
9352 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9359 * Parse a switch statement.
9361 static statement_t *parse_switch(void)
9363 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9367 PUSH_PARENT(statement);
9369 expect('(', end_error);
9370 add_anchor_token(')');
9371 expression_t *const expr = parse_expression();
9372 mark_vars_read(expr, NULL);
9373 type_t * type = skip_typeref(expr->base.type);
9374 if (is_type_integer(type)) {
9375 type = promote_integer(type);
9376 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9377 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9379 } else if (is_type_valid(type)) {
9380 errorf(&expr->base.source_position,
9381 "switch quantity is not an integer, but '%T'", type);
9382 type = type_error_type;
9384 statement->switchs.expression = create_implicit_cast(expr, type);
9385 expect(')', end_error);
9386 rem_anchor_token(')');
9388 switch_statement_t *rem = current_switch;
9389 current_switch = &statement->switchs;
9390 statement->switchs.body = parse_statement();
9391 current_switch = rem;
9393 if (statement->switchs.default_label == NULL) {
9394 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9396 check_enum_cases(&statement->switchs);
9402 return create_invalid_statement();
9405 static statement_t *parse_loop_body(statement_t *const loop)
9407 statement_t *const rem = current_loop;
9408 current_loop = loop;
9410 statement_t *const body = parse_statement();
9417 * Parse a while statement.
9419 static statement_t *parse_while(void)
9421 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9425 PUSH_PARENT(statement);
9427 expect('(', end_error);
9428 add_anchor_token(')');
9429 expression_t *const cond = parse_expression();
9430 statement->whiles.condition = cond;
9431 /* §6.8.5:2 The controlling expression of an iteration statement shall
9432 * have scalar type. */
9433 semantic_condition(cond, "condition of 'while'-statement");
9434 mark_vars_read(cond, NULL);
9435 rem_anchor_token(')');
9436 expect(')', end_error);
9438 statement->whiles.body = parse_loop_body(statement);
9444 return create_invalid_statement();
9448 * Parse a do statement.
9450 static statement_t *parse_do(void)
9452 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9456 PUSH_PARENT(statement);
9458 add_anchor_token(T_while);
9459 statement->do_while.body = parse_loop_body(statement);
9460 rem_anchor_token(T_while);
9462 expect(T_while, end_error);
9463 expect('(', end_error);
9464 add_anchor_token(')');
9465 expression_t *const cond = parse_expression();
9466 statement->do_while.condition = cond;
9467 /* §6.8.5:2 The controlling expression of an iteration statement shall
9468 * have scalar type. */
9469 semantic_condition(cond, "condition of 'do-while'-statement");
9470 mark_vars_read(cond, NULL);
9471 rem_anchor_token(')');
9472 expect(')', end_error);
9473 expect(';', end_error);
9479 return create_invalid_statement();
9483 * Parse a for statement.
9485 static statement_t *parse_for(void)
9487 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9491 expect('(', end_error1);
9492 add_anchor_token(')');
9494 PUSH_PARENT(statement);
9496 size_t const top = environment_top();
9497 scope_t *old_scope = scope_push(&statement->fors.scope);
9499 bool old_gcc_extension = in_gcc_extension;
9500 while (next_if(T___extension__)) {
9501 in_gcc_extension = true;
9505 } else if (is_declaration_specifier(&token)) {
9506 parse_declaration(record_entity, DECL_FLAGS_NONE);
9508 add_anchor_token(';');
9509 expression_t *const init = parse_expression();
9510 statement->fors.initialisation = init;
9511 mark_vars_read(init, ENT_ANY);
9512 if (!expression_has_effect(init)) {
9513 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9515 rem_anchor_token(';');
9516 expect(';', end_error2);
9518 in_gcc_extension = old_gcc_extension;
9520 if (token.type != ';') {
9521 add_anchor_token(';');
9522 expression_t *const cond = parse_expression();
9523 statement->fors.condition = cond;
9524 /* §6.8.5:2 The controlling expression of an iteration statement
9525 * shall have scalar type. */
9526 semantic_condition(cond, "condition of 'for'-statement");
9527 mark_vars_read(cond, NULL);
9528 rem_anchor_token(';');
9530 expect(';', end_error2);
9531 if (token.type != ')') {
9532 expression_t *const step = parse_expression();
9533 statement->fors.step = step;
9534 mark_vars_read(step, ENT_ANY);
9535 if (!expression_has_effect(step)) {
9536 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9539 expect(')', end_error2);
9540 rem_anchor_token(')');
9541 statement->fors.body = parse_loop_body(statement);
9543 assert(current_scope == &statement->fors.scope);
9544 scope_pop(old_scope);
9545 environment_pop_to(top);
9552 rem_anchor_token(')');
9553 assert(current_scope == &statement->fors.scope);
9554 scope_pop(old_scope);
9555 environment_pop_to(top);
9559 return create_invalid_statement();
9563 * Parse a goto statement.
9565 static statement_t *parse_goto(void)
9567 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9570 if (GNU_MODE && next_if('*')) {
9571 expression_t *expression = parse_expression();
9572 mark_vars_read(expression, NULL);
9574 /* Argh: although documentation says the expression must be of type void*,
9575 * gcc accepts anything that can be casted into void* without error */
9576 type_t *type = expression->base.type;
9578 if (type != type_error_type) {
9579 if (!is_type_pointer(type) && !is_type_integer(type)) {
9580 errorf(&expression->base.source_position,
9581 "cannot convert to a pointer type");
9582 } else if (type != type_void_ptr) {
9583 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9585 expression = create_implicit_cast(expression, type_void_ptr);
9588 statement->gotos.expression = expression;
9589 } else if (token.type == T_IDENTIFIER) {
9590 label_t *const label = get_label();
9592 statement->gotos.label = label;
9595 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9597 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9599 return create_invalid_statement();
9602 /* remember the goto's in a list for later checking */
9603 *goto_anchor = &statement->gotos;
9604 goto_anchor = &statement->gotos.next;
9606 expect(';', end_error);
9613 * Parse a continue statement.
9615 static statement_t *parse_continue(void)
9617 if (current_loop == NULL) {
9618 errorf(HERE, "continue statement not within loop");
9621 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9624 expect(';', end_error);
9631 * Parse a break statement.
9633 static statement_t *parse_break(void)
9635 if (current_switch == NULL && current_loop == NULL) {
9636 errorf(HERE, "break statement not within loop or switch");
9639 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9642 expect(';', end_error);
9649 * Parse a __leave statement.
9651 static statement_t *parse_leave_statement(void)
9653 if (current_try == NULL) {
9654 errorf(HERE, "__leave statement not within __try");
9657 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9660 expect(';', end_error);
9667 * Check if a given entity represents a local variable.
9669 static bool is_local_variable(const entity_t *entity)
9671 if (entity->kind != ENTITY_VARIABLE)
9674 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9675 case STORAGE_CLASS_AUTO:
9676 case STORAGE_CLASS_REGISTER: {
9677 const type_t *type = skip_typeref(entity->declaration.type);
9678 if (is_type_function(type)) {
9690 * Check if a given expression represents a local variable.
9692 static bool expression_is_local_variable(const expression_t *expression)
9694 if (expression->base.kind != EXPR_REFERENCE) {
9697 const entity_t *entity = expression->reference.entity;
9698 return is_local_variable(entity);
9702 * Check if a given expression represents a local variable and
9703 * return its declaration then, else return NULL.
9705 entity_t *expression_is_variable(const expression_t *expression)
9707 if (expression->base.kind != EXPR_REFERENCE) {
9710 entity_t *entity = expression->reference.entity;
9711 if (entity->kind != ENTITY_VARIABLE)
9718 * Parse a return statement.
9720 static statement_t *parse_return(void)
9722 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9725 expression_t *return_value = NULL;
9726 if (token.type != ';') {
9727 return_value = parse_expression();
9728 mark_vars_read(return_value, NULL);
9731 const type_t *const func_type = skip_typeref(current_function->base.type);
9732 assert(is_type_function(func_type));
9733 type_t *const return_type = skip_typeref(func_type->function.return_type);
9735 source_position_t const *const pos = &statement->base.source_position;
9736 if (return_value != NULL) {
9737 type_t *return_value_type = skip_typeref(return_value->base.type);
9739 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9740 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9741 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9742 /* Only warn in C mode, because GCC does the same */
9743 if (c_mode & _CXX || strict_mode) {
9745 "'return' with a value, in function returning 'void'");
9747 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9749 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9750 /* Only warn in C mode, because GCC does the same */
9753 "'return' with expression in function returning 'void'");
9755 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9759 assign_error_t error = semantic_assign(return_type, return_value);
9760 report_assign_error(error, return_type, return_value, "'return'",
9763 return_value = create_implicit_cast(return_value, return_type);
9764 /* check for returning address of a local var */
9765 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9766 const expression_t *expression = return_value->unary.value;
9767 if (expression_is_local_variable(expression)) {
9768 warningf(WARN_OTHER, pos, "function returns address of local variable");
9771 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9772 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9773 if (c_mode & _CXX || strict_mode) {
9775 "'return' without value, in function returning non-void");
9777 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9780 statement->returns.value = return_value;
9782 expect(';', end_error);
9789 * Parse a declaration statement.
9791 static statement_t *parse_declaration_statement(void)
9793 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9795 entity_t *before = current_scope->last_entity;
9797 parse_external_declaration();
9799 parse_declaration(record_entity, DECL_FLAGS_NONE);
9802 declaration_statement_t *const decl = &statement->declaration;
9803 entity_t *const begin =
9804 before != NULL ? before->base.next : current_scope->entities;
9805 decl->declarations_begin = begin;
9806 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9812 * Parse an expression statement, ie. expr ';'.
9814 static statement_t *parse_expression_statement(void)
9816 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9818 expression_t *const expr = parse_expression();
9819 statement->expression.expression = expr;
9820 mark_vars_read(expr, ENT_ANY);
9822 expect(';', end_error);
9829 * Parse a microsoft __try { } __finally { } or
9830 * __try{ } __except() { }
9832 static statement_t *parse_ms_try_statment(void)
9834 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9837 PUSH_PARENT(statement);
9839 ms_try_statement_t *rem = current_try;
9840 current_try = &statement->ms_try;
9841 statement->ms_try.try_statement = parse_compound_statement(false);
9846 if (next_if(T___except)) {
9847 expect('(', end_error);
9848 add_anchor_token(')');
9849 expression_t *const expr = parse_expression();
9850 mark_vars_read(expr, NULL);
9851 type_t * type = skip_typeref(expr->base.type);
9852 if (is_type_integer(type)) {
9853 type = promote_integer(type);
9854 } else if (is_type_valid(type)) {
9855 errorf(&expr->base.source_position,
9856 "__expect expression is not an integer, but '%T'", type);
9857 type = type_error_type;
9859 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9860 rem_anchor_token(')');
9861 expect(')', end_error);
9862 statement->ms_try.final_statement = parse_compound_statement(false);
9863 } else if (next_if(T__finally)) {
9864 statement->ms_try.final_statement = parse_compound_statement(false);
9866 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9867 return create_invalid_statement();
9871 return create_invalid_statement();
9874 static statement_t *parse_empty_statement(void)
9876 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9877 statement_t *const statement = create_empty_statement();
9882 static statement_t *parse_local_label_declaration(void)
9884 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9888 entity_t *begin = NULL;
9889 entity_t *end = NULL;
9890 entity_t **anchor = &begin;
9892 if (token.type != T_IDENTIFIER) {
9893 parse_error_expected("while parsing local label declaration",
9894 T_IDENTIFIER, NULL);
9897 symbol_t *symbol = token.symbol;
9898 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9899 if (entity != NULL && entity->base.parent_scope == current_scope) {
9900 source_position_t const *const ppos = &entity->base.source_position;
9901 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9903 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9904 entity->base.parent_scope = current_scope;
9905 entity->base.source_position = token.source_position;
9908 anchor = &entity->base.next;
9911 environment_push(entity);
9914 } while (next_if(','));
9915 expect(';', end_error);
9917 statement->declaration.declarations_begin = begin;
9918 statement->declaration.declarations_end = end;
9922 static void parse_namespace_definition(void)
9926 entity_t *entity = NULL;
9927 symbol_t *symbol = NULL;
9929 if (token.type == T_IDENTIFIER) {
9930 symbol = token.symbol;
9933 entity = get_entity(symbol, NAMESPACE_NORMAL);
9935 && entity->kind != ENTITY_NAMESPACE
9936 && entity->base.parent_scope == current_scope) {
9937 if (is_entity_valid(entity)) {
9938 error_redefined_as_different_kind(&token.source_position,
9939 entity, ENTITY_NAMESPACE);
9945 if (entity == NULL) {
9946 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9947 entity->base.source_position = token.source_position;
9948 entity->base.parent_scope = current_scope;
9951 if (token.type == '=') {
9952 /* TODO: parse namespace alias */
9953 panic("namespace alias definition not supported yet");
9956 environment_push(entity);
9957 append_entity(current_scope, entity);
9959 size_t const top = environment_top();
9960 scope_t *old_scope = scope_push(&entity->namespacee.members);
9962 entity_t *old_current_entity = current_entity;
9963 current_entity = entity;
9965 expect('{', end_error);
9967 expect('}', end_error);
9970 assert(current_scope == &entity->namespacee.members);
9971 assert(current_entity == entity);
9972 current_entity = old_current_entity;
9973 scope_pop(old_scope);
9974 environment_pop_to(top);
9978 * Parse a statement.
9979 * There's also parse_statement() which additionally checks for
9980 * "statement has no effect" warnings
9982 static statement_t *intern_parse_statement(void)
9984 statement_t *statement = NULL;
9986 /* declaration or statement */
9987 add_anchor_token(';');
9988 switch (token.type) {
9989 case T_IDENTIFIER: {
9990 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9991 if (la1_type == ':') {
9992 statement = parse_label_statement();
9993 } else if (is_typedef_symbol(token.symbol)) {
9994 statement = parse_declaration_statement();
9996 /* it's an identifier, the grammar says this must be an
9997 * expression statement. However it is common that users mistype
9998 * declaration types, so we guess a bit here to improve robustness
9999 * for incorrect programs */
10000 switch (la1_type) {
10003 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10005 statement = parse_expression_statement();
10009 statement = parse_declaration_statement();
10017 case T___extension__:
10018 /* This can be a prefix to a declaration or an expression statement.
10019 * We simply eat it now and parse the rest with tail recursion. */
10020 while (next_if(T___extension__)) {}
10021 bool old_gcc_extension = in_gcc_extension;
10022 in_gcc_extension = true;
10023 statement = intern_parse_statement();
10024 in_gcc_extension = old_gcc_extension;
10028 statement = parse_declaration_statement();
10032 statement = parse_local_label_declaration();
10035 case ';': statement = parse_empty_statement(); break;
10036 case '{': statement = parse_compound_statement(false); break;
10037 case T___leave: statement = parse_leave_statement(); break;
10038 case T___try: statement = parse_ms_try_statment(); break;
10039 case T_asm: statement = parse_asm_statement(); break;
10040 case T_break: statement = parse_break(); break;
10041 case T_case: statement = parse_case_statement(); break;
10042 case T_continue: statement = parse_continue(); break;
10043 case T_default: statement = parse_default_statement(); break;
10044 case T_do: statement = parse_do(); break;
10045 case T_for: statement = parse_for(); break;
10046 case T_goto: statement = parse_goto(); break;
10047 case T_if: statement = parse_if(); break;
10048 case T_return: statement = parse_return(); break;
10049 case T_switch: statement = parse_switch(); break;
10050 case T_while: statement = parse_while(); break;
10053 statement = parse_expression_statement();
10057 errorf(HERE, "unexpected token %K while parsing statement", &token);
10058 statement = create_invalid_statement();
10063 rem_anchor_token(';');
10065 assert(statement != NULL
10066 && statement->base.source_position.input_name != NULL);
10072 * parse a statement and emits "statement has no effect" warning if needed
10073 * (This is really a wrapper around intern_parse_statement with check for 1
10074 * single warning. It is needed, because for statement expressions we have
10075 * to avoid the warning on the last statement)
10077 static statement_t *parse_statement(void)
10079 statement_t *statement = intern_parse_statement();
10081 if (statement->kind == STATEMENT_EXPRESSION) {
10082 expression_t *expression = statement->expression.expression;
10083 if (!expression_has_effect(expression)) {
10084 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10092 * Parse a compound statement.
10094 static statement_t *parse_compound_statement(bool inside_expression_statement)
10096 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10098 PUSH_PARENT(statement);
10101 add_anchor_token('}');
10102 /* tokens, which can start a statement */
10103 /* TODO MS, __builtin_FOO */
10104 add_anchor_token('!');
10105 add_anchor_token('&');
10106 add_anchor_token('(');
10107 add_anchor_token('*');
10108 add_anchor_token('+');
10109 add_anchor_token('-');
10110 add_anchor_token('{');
10111 add_anchor_token('~');
10112 add_anchor_token(T_CHARACTER_CONSTANT);
10113 add_anchor_token(T_COLONCOLON);
10114 add_anchor_token(T_FLOATINGPOINT);
10115 add_anchor_token(T_IDENTIFIER);
10116 add_anchor_token(T_INTEGER);
10117 add_anchor_token(T_MINUSMINUS);
10118 add_anchor_token(T_PLUSPLUS);
10119 add_anchor_token(T_STRING_LITERAL);
10120 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10121 add_anchor_token(T_WIDE_STRING_LITERAL);
10122 add_anchor_token(T__Bool);
10123 add_anchor_token(T__Complex);
10124 add_anchor_token(T__Imaginary);
10125 add_anchor_token(T___FUNCTION__);
10126 add_anchor_token(T___PRETTY_FUNCTION__);
10127 add_anchor_token(T___alignof__);
10128 add_anchor_token(T___attribute__);
10129 add_anchor_token(T___builtin_va_start);
10130 add_anchor_token(T___extension__);
10131 add_anchor_token(T___func__);
10132 add_anchor_token(T___imag__);
10133 add_anchor_token(T___label__);
10134 add_anchor_token(T___real__);
10135 add_anchor_token(T___thread);
10136 add_anchor_token(T_asm);
10137 add_anchor_token(T_auto);
10138 add_anchor_token(T_bool);
10139 add_anchor_token(T_break);
10140 add_anchor_token(T_case);
10141 add_anchor_token(T_char);
10142 add_anchor_token(T_class);
10143 add_anchor_token(T_const);
10144 add_anchor_token(T_const_cast);
10145 add_anchor_token(T_continue);
10146 add_anchor_token(T_default);
10147 add_anchor_token(T_delete);
10148 add_anchor_token(T_double);
10149 add_anchor_token(T_do);
10150 add_anchor_token(T_dynamic_cast);
10151 add_anchor_token(T_enum);
10152 add_anchor_token(T_extern);
10153 add_anchor_token(T_false);
10154 add_anchor_token(T_float);
10155 add_anchor_token(T_for);
10156 add_anchor_token(T_goto);
10157 add_anchor_token(T_if);
10158 add_anchor_token(T_inline);
10159 add_anchor_token(T_int);
10160 add_anchor_token(T_long);
10161 add_anchor_token(T_new);
10162 add_anchor_token(T_operator);
10163 add_anchor_token(T_register);
10164 add_anchor_token(T_reinterpret_cast);
10165 add_anchor_token(T_restrict);
10166 add_anchor_token(T_return);
10167 add_anchor_token(T_short);
10168 add_anchor_token(T_signed);
10169 add_anchor_token(T_sizeof);
10170 add_anchor_token(T_static);
10171 add_anchor_token(T_static_cast);
10172 add_anchor_token(T_struct);
10173 add_anchor_token(T_switch);
10174 add_anchor_token(T_template);
10175 add_anchor_token(T_this);
10176 add_anchor_token(T_throw);
10177 add_anchor_token(T_true);
10178 add_anchor_token(T_try);
10179 add_anchor_token(T_typedef);
10180 add_anchor_token(T_typeid);
10181 add_anchor_token(T_typename);
10182 add_anchor_token(T_typeof);
10183 add_anchor_token(T_union);
10184 add_anchor_token(T_unsigned);
10185 add_anchor_token(T_using);
10186 add_anchor_token(T_void);
10187 add_anchor_token(T_volatile);
10188 add_anchor_token(T_wchar_t);
10189 add_anchor_token(T_while);
10191 size_t const top = environment_top();
10192 scope_t *old_scope = scope_push(&statement->compound.scope);
10194 statement_t **anchor = &statement->compound.statements;
10195 bool only_decls_so_far = true;
10196 while (token.type != '}') {
10197 if (token.type == T_EOF) {
10198 errorf(&statement->base.source_position,
10199 "EOF while parsing compound statement");
10202 statement_t *sub_statement = intern_parse_statement();
10203 if (is_invalid_statement(sub_statement)) {
10204 /* an error occurred. if we are at an anchor, return */
10210 if (sub_statement->kind != STATEMENT_DECLARATION) {
10211 only_decls_so_far = false;
10212 } else if (!only_decls_so_far) {
10213 source_position_t const *const pos = &sub_statement->base.source_position;
10214 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10217 *anchor = sub_statement;
10219 while (sub_statement->base.next != NULL)
10220 sub_statement = sub_statement->base.next;
10222 anchor = &sub_statement->base.next;
10226 /* look over all statements again to produce no effect warnings */
10227 if (is_warn_on(WARN_UNUSED_VALUE)) {
10228 statement_t *sub_statement = statement->compound.statements;
10229 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10230 if (sub_statement->kind != STATEMENT_EXPRESSION)
10232 /* don't emit a warning for the last expression in an expression
10233 * statement as it has always an effect */
10234 if (inside_expression_statement && sub_statement->base.next == NULL)
10237 expression_t *expression = sub_statement->expression.expression;
10238 if (!expression_has_effect(expression)) {
10239 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10245 rem_anchor_token(T_while);
10246 rem_anchor_token(T_wchar_t);
10247 rem_anchor_token(T_volatile);
10248 rem_anchor_token(T_void);
10249 rem_anchor_token(T_using);
10250 rem_anchor_token(T_unsigned);
10251 rem_anchor_token(T_union);
10252 rem_anchor_token(T_typeof);
10253 rem_anchor_token(T_typename);
10254 rem_anchor_token(T_typeid);
10255 rem_anchor_token(T_typedef);
10256 rem_anchor_token(T_try);
10257 rem_anchor_token(T_true);
10258 rem_anchor_token(T_throw);
10259 rem_anchor_token(T_this);
10260 rem_anchor_token(T_template);
10261 rem_anchor_token(T_switch);
10262 rem_anchor_token(T_struct);
10263 rem_anchor_token(T_static_cast);
10264 rem_anchor_token(T_static);
10265 rem_anchor_token(T_sizeof);
10266 rem_anchor_token(T_signed);
10267 rem_anchor_token(T_short);
10268 rem_anchor_token(T_return);
10269 rem_anchor_token(T_restrict);
10270 rem_anchor_token(T_reinterpret_cast);
10271 rem_anchor_token(T_register);
10272 rem_anchor_token(T_operator);
10273 rem_anchor_token(T_new);
10274 rem_anchor_token(T_long);
10275 rem_anchor_token(T_int);
10276 rem_anchor_token(T_inline);
10277 rem_anchor_token(T_if);
10278 rem_anchor_token(T_goto);
10279 rem_anchor_token(T_for);
10280 rem_anchor_token(T_float);
10281 rem_anchor_token(T_false);
10282 rem_anchor_token(T_extern);
10283 rem_anchor_token(T_enum);
10284 rem_anchor_token(T_dynamic_cast);
10285 rem_anchor_token(T_do);
10286 rem_anchor_token(T_double);
10287 rem_anchor_token(T_delete);
10288 rem_anchor_token(T_default);
10289 rem_anchor_token(T_continue);
10290 rem_anchor_token(T_const_cast);
10291 rem_anchor_token(T_const);
10292 rem_anchor_token(T_class);
10293 rem_anchor_token(T_char);
10294 rem_anchor_token(T_case);
10295 rem_anchor_token(T_break);
10296 rem_anchor_token(T_bool);
10297 rem_anchor_token(T_auto);
10298 rem_anchor_token(T_asm);
10299 rem_anchor_token(T___thread);
10300 rem_anchor_token(T___real__);
10301 rem_anchor_token(T___label__);
10302 rem_anchor_token(T___imag__);
10303 rem_anchor_token(T___func__);
10304 rem_anchor_token(T___extension__);
10305 rem_anchor_token(T___builtin_va_start);
10306 rem_anchor_token(T___attribute__);
10307 rem_anchor_token(T___alignof__);
10308 rem_anchor_token(T___PRETTY_FUNCTION__);
10309 rem_anchor_token(T___FUNCTION__);
10310 rem_anchor_token(T__Imaginary);
10311 rem_anchor_token(T__Complex);
10312 rem_anchor_token(T__Bool);
10313 rem_anchor_token(T_WIDE_STRING_LITERAL);
10314 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10315 rem_anchor_token(T_STRING_LITERAL);
10316 rem_anchor_token(T_PLUSPLUS);
10317 rem_anchor_token(T_MINUSMINUS);
10318 rem_anchor_token(T_INTEGER);
10319 rem_anchor_token(T_IDENTIFIER);
10320 rem_anchor_token(T_FLOATINGPOINT);
10321 rem_anchor_token(T_COLONCOLON);
10322 rem_anchor_token(T_CHARACTER_CONSTANT);
10323 rem_anchor_token('~');
10324 rem_anchor_token('{');
10325 rem_anchor_token('-');
10326 rem_anchor_token('+');
10327 rem_anchor_token('*');
10328 rem_anchor_token('(');
10329 rem_anchor_token('&');
10330 rem_anchor_token('!');
10331 rem_anchor_token('}');
10332 assert(current_scope == &statement->compound.scope);
10333 scope_pop(old_scope);
10334 environment_pop_to(top);
10341 * Check for unused global static functions and variables
10343 static void check_unused_globals(void)
10345 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10348 for (const entity_t *entity = file_scope->entities; entity != NULL;
10349 entity = entity->base.next) {
10350 if (!is_declaration(entity))
10353 const declaration_t *declaration = &entity->declaration;
10354 if (declaration->used ||
10355 declaration->modifiers & DM_UNUSED ||
10356 declaration->modifiers & DM_USED ||
10357 declaration->storage_class != STORAGE_CLASS_STATIC)
10362 if (entity->kind == ENTITY_FUNCTION) {
10363 /* inhibit warning for static inline functions */
10364 if (entity->function.is_inline)
10367 why = WARN_UNUSED_FUNCTION;
10368 s = entity->function.statement != NULL ? "defined" : "declared";
10370 why = WARN_UNUSED_VARIABLE;
10374 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10378 static void parse_global_asm(void)
10380 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10383 expect('(', end_error);
10385 statement->asms.asm_text = parse_string_literals();
10386 statement->base.next = unit->global_asm;
10387 unit->global_asm = statement;
10389 expect(')', end_error);
10390 expect(';', end_error);
10395 static void parse_linkage_specification(void)
10399 source_position_t const pos = *HERE;
10400 char const *const linkage = parse_string_literals().begin;
10402 linkage_kind_t old_linkage = current_linkage;
10403 linkage_kind_t new_linkage;
10404 if (strcmp(linkage, "C") == 0) {
10405 new_linkage = LINKAGE_C;
10406 } else if (strcmp(linkage, "C++") == 0) {
10407 new_linkage = LINKAGE_CXX;
10409 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10410 new_linkage = LINKAGE_INVALID;
10412 current_linkage = new_linkage;
10414 if (next_if('{')) {
10416 expect('}', end_error);
10422 assert(current_linkage == new_linkage);
10423 current_linkage = old_linkage;
10426 static void parse_external(void)
10428 switch (token.type) {
10429 DECLARATION_START_NO_EXTERN
10431 case T___extension__:
10432 /* tokens below are for implicit int */
10433 case '&': /* & x; -> int& x; (and error later, because C++ has no
10435 case '*': /* * x; -> int* x; */
10436 case '(': /* (x); -> int (x); */
10437 parse_external_declaration();
10441 if (look_ahead(1)->type == T_STRING_LITERAL) {
10442 parse_linkage_specification();
10444 parse_external_declaration();
10449 parse_global_asm();
10453 parse_namespace_definition();
10457 if (!strict_mode) {
10458 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10465 errorf(HERE, "stray %K outside of function", &token);
10466 if (token.type == '(' || token.type == '{' || token.type == '[')
10467 eat_until_matching_token(token.type);
10473 static void parse_externals(void)
10475 add_anchor_token('}');
10476 add_anchor_token(T_EOF);
10479 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10480 unsigned char token_anchor_copy[T_LAST_TOKEN];
10481 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10484 while (token.type != T_EOF && token.type != '}') {
10486 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10487 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10489 /* the anchor set and its copy differs */
10490 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10493 if (in_gcc_extension) {
10494 /* an gcc extension scope was not closed */
10495 internal_errorf(HERE, "Leaked __extension__");
10502 rem_anchor_token(T_EOF);
10503 rem_anchor_token('}');
10507 * Parse a translation unit.
10509 static void parse_translation_unit(void)
10511 add_anchor_token(T_EOF);
10516 if (token.type == T_EOF)
10519 errorf(HERE, "stray %K outside of function", &token);
10520 if (token.type == '(' || token.type == '{' || token.type == '[')
10521 eat_until_matching_token(token.type);
10526 void set_default_visibility(elf_visibility_tag_t visibility)
10528 default_visibility = visibility;
10534 * @return the translation unit or NULL if errors occurred.
10536 void start_parsing(void)
10538 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10539 label_stack = NEW_ARR_F(stack_entry_t, 0);
10540 diagnostic_count = 0;
10544 print_to_file(stderr);
10546 assert(unit == NULL);
10547 unit = allocate_ast_zero(sizeof(unit[0]));
10549 assert(file_scope == NULL);
10550 file_scope = &unit->scope;
10552 assert(current_scope == NULL);
10553 scope_push(&unit->scope);
10555 create_gnu_builtins();
10557 create_microsoft_intrinsics();
10560 translation_unit_t *finish_parsing(void)
10562 assert(current_scope == &unit->scope);
10565 assert(file_scope == &unit->scope);
10566 check_unused_globals();
10569 DEL_ARR_F(environment_stack);
10570 DEL_ARR_F(label_stack);
10572 translation_unit_t *result = unit;
10577 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10578 * are given length one. */
10579 static void complete_incomplete_arrays(void)
10581 size_t n = ARR_LEN(incomplete_arrays);
10582 for (size_t i = 0; i != n; ++i) {
10583 declaration_t *const decl = incomplete_arrays[i];
10584 type_t *const type = skip_typeref(decl->type);
10586 if (!is_type_incomplete(type))
10589 source_position_t const *const pos = &decl->base.source_position;
10590 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10592 type_t *const new_type = duplicate_type(type);
10593 new_type->array.size_constant = true;
10594 new_type->array.has_implicit_size = true;
10595 new_type->array.size = 1;
10597 type_t *const result = identify_new_type(new_type);
10599 decl->type = result;
10603 void prepare_main_collect2(entity_t *entity)
10605 // create call to __main
10606 symbol_t *symbol = symbol_table_insert("__main");
10607 entity_t *subsubmain_ent
10608 = create_implicit_function(symbol, &builtin_source_position);
10610 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10611 type_t *ftype = subsubmain_ent->declaration.type;
10612 ref->base.source_position = builtin_source_position;
10613 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10614 ref->reference.entity = subsubmain_ent;
10616 expression_t *call = allocate_expression_zero(EXPR_CALL);
10617 call->base.source_position = builtin_source_position;
10618 call->base.type = type_void;
10619 call->call.function = ref;
10621 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10622 expr_statement->base.source_position = builtin_source_position;
10623 expr_statement->expression.expression = call;
10625 statement_t *statement = entity->function.statement;
10626 assert(statement->kind == STATEMENT_COMPOUND);
10627 compound_statement_t *compounds = &statement->compound;
10629 expr_statement->base.next = compounds->statements;
10630 compounds->statements = expr_statement;
10635 lookahead_bufpos = 0;
10636 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10639 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10640 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10641 parse_translation_unit();
10642 complete_incomplete_arrays();
10643 DEL_ARR_F(incomplete_arrays);
10644 incomplete_arrays = NULL;
10648 * Initialize the parser.
10650 void init_parser(void)
10652 sym_anonymous = symbol_table_insert("<anonymous>");
10654 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10656 init_expression_parsers();
10657 obstack_init(&temp_obst);
10661 * Terminate the parser.
10663 void exit_parser(void)
10665 obstack_free(&temp_obst, NULL);