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
26 #include "adt/strutil.h"
28 #include "diagnostic.h"
29 #include "format_check.h"
35 #include "type_hash.h"
38 #include "attribute_t.h"
39 #include "lang_features.h"
43 #include "adt/bitfiddle.h"
44 #include "adt/error.h"
45 #include "adt/array.h"
47 //#define PRINT_TOKENS
48 #define MAX_LOOKAHEAD 1
53 entity_namespace_t namespc;
56 typedef struct declaration_specifiers_t declaration_specifiers_t;
57 struct declaration_specifiers_t {
58 source_position_t source_position;
59 storage_class_t storage_class;
60 unsigned char alignment; /**< Alignment, 0 if not set. */
62 bool thread_local : 1; /**< GCC __thread */
63 attribute_t *attributes; /**< list of attributes */
68 * An environment for parsing initializers (and compound literals).
70 typedef struct parse_initializer_env_t {
71 type_t *type; /**< the type of the initializer. In case of an
72 array type with unspecified size this gets
73 adjusted to the actual size. */
74 entity_t *entity; /**< the variable that is initialized if any */
75 bool must_be_constant;
76 } parse_initializer_env_t;
78 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
80 /** The current token. */
82 /** The lookahead ring-buffer. */
83 static token_t lookahead_buffer[MAX_LOOKAHEAD];
84 /** Position of the next token in the lookahead buffer. */
85 static size_t lookahead_bufpos;
86 static stack_entry_t *environment_stack = NULL;
87 static stack_entry_t *label_stack = NULL;
88 static scope_t *file_scope = NULL;
89 static scope_t *current_scope = NULL;
90 /** Point to the current function declaration if inside a function. */
91 static function_t *current_function = NULL;
92 static entity_t *current_entity = 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;
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 an __extension__ context. */
105 static bool in_gcc_extension = false;
106 static struct obstack temp_obst;
107 static entity_t *anonymous_entity;
108 static declaration_t **incomplete_arrays;
109 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
112 #define PUSH_PARENT(stmt) \
113 statement_t *const new_parent = (stmt); \
114 statement_t *const old_parent = current_parent; \
115 ((void)(current_parent = new_parent))
116 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
118 #define PUSH_SCOPE(scope) \
119 size_t const top = environment_top(); \
120 scope_t *const new_scope = (scope); \
121 scope_t *const old_scope = scope_push(new_scope)
122 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
124 #define PUSH_EXTENSION() \
126 bool const old_gcc_extension = in_gcc_extension; \
127 while (next_if(T___extension__)) { \
128 in_gcc_extension = true; \
131 #define POP_EXTENSION() \
132 ((void)(in_gcc_extension = old_gcc_extension))
134 /** special symbol used for anonymous entities. */
135 static symbol_t *sym_anonymous = NULL;
137 /** The token anchor set */
138 static unsigned short token_anchor_set[T_LAST_TOKEN];
140 /** The current source position. */
141 #define HERE (&token.base.source_position)
143 /** true if we are in GCC mode. */
144 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
146 static statement_t *parse_compound_statement(bool inside_expression_statement);
147 static statement_t *parse_statement(void);
149 static expression_t *parse_subexpression(precedence_t);
150 static expression_t *parse_expression(void);
151 static type_t *parse_typename(void);
152 static void parse_externals(void);
153 static void parse_external(void);
155 static void parse_compound_type_entries(compound_t *compound_declaration);
157 static void check_call_argument(type_t *expected_type,
158 call_argument_t *argument, unsigned pos);
160 typedef enum declarator_flags_t {
162 DECL_MAY_BE_ABSTRACT = 1U << 0,
163 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
164 DECL_IS_PARAMETER = 1U << 2
165 } declarator_flags_t;
167 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
168 declarator_flags_t flags);
170 static void semantic_comparison(binary_expression_t *expression);
172 #define STORAGE_CLASSES \
173 STORAGE_CLASSES_NO_EXTERN \
176 #define STORAGE_CLASSES_NO_EXTERN \
183 #define TYPE_QUALIFIERS \
188 case T__forceinline: \
189 case T___attribute__:
191 #define COMPLEX_SPECIFIERS \
193 #define IMAGINARY_SPECIFIERS \
196 #define TYPE_SPECIFIERS \
198 case T___builtin_va_list: \
223 #define DECLARATION_START \
228 #define DECLARATION_START_NO_EXTERN \
229 STORAGE_CLASSES_NO_EXTERN \
233 #define EXPRESSION_START \
242 case T_CHARACTER_CONSTANT: \
243 case T_FLOATINGPOINT: \
244 case T_FLOATINGPOINT_HEXADECIMAL: \
246 case T_INTEGER_HEXADECIMAL: \
247 case T_INTEGER_OCTAL: \
250 case T_STRING_LITERAL: \
251 case T_WIDE_CHARACTER_CONSTANT: \
252 case T_WIDE_STRING_LITERAL: \
253 case T___FUNCDNAME__: \
254 case T___FUNCSIG__: \
255 case T___FUNCTION__: \
256 case T___PRETTY_FUNCTION__: \
257 case T___alignof__: \
258 case T___builtin_classify_type: \
259 case T___builtin_constant_p: \
260 case T___builtin_isgreater: \
261 case T___builtin_isgreaterequal: \
262 case T___builtin_isless: \
263 case T___builtin_islessequal: \
264 case T___builtin_islessgreater: \
265 case T___builtin_isunordered: \
266 case T___builtin_offsetof: \
267 case T___builtin_va_arg: \
268 case T___builtin_va_copy: \
269 case T___builtin_va_start: \
280 * Returns the size of a statement node.
282 * @param kind the statement kind
284 static size_t get_statement_struct_size(statement_kind_t kind)
286 static const size_t sizes[] = {
287 [STATEMENT_ERROR] = sizeof(statement_base_t),
288 [STATEMENT_EMPTY] = sizeof(statement_base_t),
289 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
290 [STATEMENT_RETURN] = sizeof(return_statement_t),
291 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
292 [STATEMENT_IF] = sizeof(if_statement_t),
293 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
294 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
295 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
296 [STATEMENT_BREAK] = sizeof(statement_base_t),
297 [STATEMENT_COMPUTED_GOTO] = sizeof(computed_goto_statement_t),
298 [STATEMENT_GOTO] = sizeof(goto_statement_t),
299 [STATEMENT_LABEL] = sizeof(label_statement_t),
300 [STATEMENT_CASE_LABEL] = sizeof(case_label_statement_t),
301 [STATEMENT_WHILE] = sizeof(while_statement_t),
302 [STATEMENT_DO_WHILE] = sizeof(do_while_statement_t),
303 [STATEMENT_FOR] = sizeof(for_statement_t),
304 [STATEMENT_ASM] = sizeof(asm_statement_t),
305 [STATEMENT_MS_TRY] = sizeof(ms_try_statement_t),
306 [STATEMENT_LEAVE] = sizeof(leave_statement_t)
308 assert((size_t)kind < lengthof(sizes));
309 assert(sizes[kind] != 0);
314 * Returns the size of an expression node.
316 * @param kind the expression kind
318 static size_t get_expression_struct_size(expression_kind_t kind)
320 static const size_t sizes[] = {
321 [EXPR_ERROR] = sizeof(expression_base_t),
322 [EXPR_REFERENCE] = sizeof(reference_expression_t),
323 [EXPR_ENUM_CONSTANT] = sizeof(reference_expression_t),
324 [EXPR_LITERAL_BOOLEAN] = sizeof(literal_expression_t),
325 [EXPR_LITERAL_INTEGER] = sizeof(literal_expression_t),
326 [EXPR_LITERAL_INTEGER_OCTAL] = sizeof(literal_expression_t),
327 [EXPR_LITERAL_INTEGER_HEXADECIMAL]= sizeof(literal_expression_t),
328 [EXPR_LITERAL_FLOATINGPOINT] = sizeof(literal_expression_t),
329 [EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL] = sizeof(literal_expression_t),
330 [EXPR_LITERAL_CHARACTER] = sizeof(literal_expression_t),
331 [EXPR_LITERAL_WIDE_CHARACTER] = sizeof(literal_expression_t),
332 [EXPR_STRING_LITERAL] = sizeof(string_literal_expression_t),
333 [EXPR_WIDE_STRING_LITERAL] = sizeof(string_literal_expression_t),
334 [EXPR_COMPOUND_LITERAL] = sizeof(compound_literal_expression_t),
335 [EXPR_CALL] = sizeof(call_expression_t),
336 [EXPR_UNARY_FIRST] = sizeof(unary_expression_t),
337 [EXPR_BINARY_FIRST] = sizeof(binary_expression_t),
338 [EXPR_CONDITIONAL] = sizeof(conditional_expression_t),
339 [EXPR_SELECT] = sizeof(select_expression_t),
340 [EXPR_ARRAY_ACCESS] = sizeof(array_access_expression_t),
341 [EXPR_SIZEOF] = sizeof(typeprop_expression_t),
342 [EXPR_ALIGNOF] = sizeof(typeprop_expression_t),
343 [EXPR_CLASSIFY_TYPE] = sizeof(classify_type_expression_t),
344 [EXPR_FUNCNAME] = sizeof(funcname_expression_t),
345 [EXPR_BUILTIN_CONSTANT_P] = sizeof(builtin_constant_expression_t),
346 [EXPR_BUILTIN_TYPES_COMPATIBLE_P] = sizeof(builtin_types_compatible_expression_t),
347 [EXPR_OFFSETOF] = sizeof(offsetof_expression_t),
348 [EXPR_VA_START] = sizeof(va_start_expression_t),
349 [EXPR_VA_ARG] = sizeof(va_arg_expression_t),
350 [EXPR_VA_COPY] = sizeof(va_copy_expression_t),
351 [EXPR_STATEMENT] = sizeof(statement_expression_t),
352 [EXPR_LABEL_ADDRESS] = sizeof(label_address_expression_t),
354 if (kind >= EXPR_UNARY_FIRST && kind <= EXPR_UNARY_LAST) {
355 return sizes[EXPR_UNARY_FIRST];
357 if (kind >= EXPR_BINARY_FIRST && kind <= EXPR_BINARY_LAST) {
358 return sizes[EXPR_BINARY_FIRST];
360 assert((size_t)kind < lengthof(sizes));
361 assert(sizes[kind] != 0);
366 * Allocate a statement node of given kind and initialize all
367 * fields with zero. Sets its source position to the position
368 * of the current token.
370 static statement_t *allocate_statement_zero(statement_kind_t kind)
372 size_t size = get_statement_struct_size(kind);
373 statement_t *res = allocate_ast_zero(size);
375 res->base.kind = kind;
376 res->base.parent = current_parent;
377 res->base.source_position = token.base.source_position;
382 * Allocate an expression node of given kind and initialize all
385 * @param kind the kind of the expression to allocate
387 static expression_t *allocate_expression_zero(expression_kind_t kind)
389 size_t size = get_expression_struct_size(kind);
390 expression_t *res = allocate_ast_zero(size);
392 res->base.kind = kind;
393 res->base.type = type_error_type;
394 res->base.source_position = token.base.source_position;
399 * Creates a new invalid expression at the source position
400 * of the current token.
402 static expression_t *create_error_expression(void)
404 expression_t *expression = allocate_expression_zero(EXPR_ERROR);
405 expression->base.type = type_error_type;
410 * Creates a new invalid statement.
412 static statement_t *create_error_statement(void)
414 return allocate_statement_zero(STATEMENT_ERROR);
418 * Allocate a new empty statement.
420 static statement_t *create_empty_statement(void)
422 return allocate_statement_zero(STATEMENT_EMPTY);
426 * Returns the size of an initializer node.
428 * @param kind the initializer kind
430 static size_t get_initializer_size(initializer_kind_t kind)
432 static const size_t sizes[] = {
433 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
434 [INITIALIZER_STRING] = sizeof(initializer_string_t),
435 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
436 [INITIALIZER_LIST] = sizeof(initializer_list_t),
437 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
439 assert((size_t)kind < lengthof(sizes));
440 assert(sizes[kind] != 0);
445 * Allocate an initializer node of given kind and initialize all
448 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
450 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
457 * Returns the index of the top element of the environment stack.
459 static size_t environment_top(void)
461 return ARR_LEN(environment_stack);
465 * Returns the index of the top element of the global label stack.
467 static size_t label_top(void)
469 return ARR_LEN(label_stack);
473 * Return the next token.
475 static inline void next_token(void)
477 token = lookahead_buffer[lookahead_bufpos];
478 lookahead_buffer[lookahead_bufpos] = lexer_token;
481 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
484 print_token(stderr, &token);
485 fprintf(stderr, "\n");
489 static inline bool next_if(int const type)
491 if (token.kind == type) {
500 * Return the next token with a given lookahead.
502 static inline const token_t *look_ahead(size_t num)
504 assert(0 < num && num <= MAX_LOOKAHEAD);
505 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
506 return &lookahead_buffer[pos];
510 * Adds a token type to the token type anchor set (a multi-set).
512 static void add_anchor_token(int token_kind)
514 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
515 ++token_anchor_set[token_kind];
519 * Set the number of tokens types of the given type
520 * to zero and return the old count.
522 static int save_and_reset_anchor_state(int token_kind)
524 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
525 int count = token_anchor_set[token_kind];
526 token_anchor_set[token_kind] = 0;
531 * Restore the number of token types to the given count.
533 static void restore_anchor_state(int token_kind, int count)
535 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
536 token_anchor_set[token_kind] = count;
540 * Remove a token type from the token type anchor set (a multi-set).
542 static void rem_anchor_token(int token_kind)
544 assert(0 <= token_kind && token_kind < T_LAST_TOKEN);
545 assert(token_anchor_set[token_kind] != 0);
546 --token_anchor_set[token_kind];
550 * Eat tokens until a matching token type is found.
552 static void eat_until_matching_token(int type)
556 case '(': end_token = ')'; break;
557 case '{': end_token = '}'; break;
558 case '[': end_token = ']'; break;
559 default: end_token = type; break;
562 unsigned parenthesis_count = 0;
563 unsigned brace_count = 0;
564 unsigned bracket_count = 0;
565 while (token.kind != end_token ||
566 parenthesis_count != 0 ||
568 bracket_count != 0) {
569 switch (token.kind) {
571 case '(': ++parenthesis_count; break;
572 case '{': ++brace_count; break;
573 case '[': ++bracket_count; break;
576 if (parenthesis_count > 0)
586 if (bracket_count > 0)
589 if (token.kind == end_token &&
590 parenthesis_count == 0 &&
604 * Eat input tokens until an anchor is found.
606 static void eat_until_anchor(void)
608 while (token_anchor_set[token.kind] == 0) {
609 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
610 eat_until_matching_token(token.kind);
616 * Eat a whole block from input tokens.
618 static void eat_block(void)
620 eat_until_matching_token('{');
624 #define eat(token_kind) (assert(token.kind == (token_kind)), next_token())
627 * Report a parse error because an expected token was not found.
630 #if defined __GNUC__ && __GNUC__ >= 4
631 __attribute__((sentinel))
633 void parse_error_expected(const char *message, ...)
635 if (message != NULL) {
636 errorf(HERE, "%s", message);
639 va_start(ap, message);
640 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
645 * Report an incompatible type.
647 static void type_error_incompatible(const char *msg,
648 const source_position_t *source_position, type_t *type1, type_t *type2)
650 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
655 * Expect the current token is the expected token.
656 * If not, generate an error, eat the current statement,
657 * and goto the error_label label.
659 #define expect(expected, error_label) \
661 if (UNLIKELY(token.kind != (expected))) { \
662 parse_error_expected(NULL, (expected), NULL); \
663 add_anchor_token(expected); \
664 eat_until_anchor(); \
665 rem_anchor_token(expected); \
666 if (token.kind != (expected)) \
673 * Push a given scope on the scope stack and make it the
676 static scope_t *scope_push(scope_t *new_scope)
678 if (current_scope != NULL) {
679 new_scope->depth = current_scope->depth + 1;
682 scope_t *old_scope = current_scope;
683 current_scope = new_scope;
688 * Pop the current scope from the scope stack.
690 static void scope_pop(scope_t *old_scope)
692 current_scope = old_scope;
696 * Search an entity by its symbol in a given namespace.
698 static entity_t *get_entity(const symbol_t *const symbol,
699 namespace_tag_t namespc)
701 entity_t *entity = symbol->entity;
702 for (; entity != NULL; entity = entity->base.symbol_next) {
703 if ((namespace_tag_t)entity->base.namespc == namespc)
710 /* §6.2.3:1 24) There is only one name space for tags even though three are
712 static entity_t *get_tag(symbol_t const *const symbol,
713 entity_kind_tag_t const kind)
715 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
716 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
718 "'%Y' defined as wrong kind of tag (previous definition %P)",
719 symbol, &entity->base.source_position);
726 * pushs an entity on the environment stack and links the corresponding symbol
729 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
731 symbol_t *symbol = entity->base.symbol;
732 entity_namespace_t namespc = entity->base.namespc;
733 assert(namespc != 0);
735 /* replace/add entity into entity list of the symbol */
738 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
743 /* replace an entry? */
744 if (iter->base.namespc == namespc) {
745 entity->base.symbol_next = iter->base.symbol_next;
751 /* remember old declaration */
753 entry.symbol = symbol;
754 entry.old_entity = iter;
755 entry.namespc = namespc;
756 ARR_APP1(stack_entry_t, *stack_ptr, entry);
760 * Push an entity on the environment stack.
762 static void environment_push(entity_t *entity)
764 assert(entity->base.source_position.input_name != NULL);
765 assert(entity->base.parent_scope != NULL);
766 stack_push(&environment_stack, entity);
770 * Push a declaration on the global label stack.
772 * @param declaration the declaration
774 static void label_push(entity_t *label)
776 /* we abuse the parameters scope as parent for the labels */
777 label->base.parent_scope = ¤t_function->parameters;
778 stack_push(&label_stack, label);
782 * pops symbols from the environment stack until @p new_top is the top element
784 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
786 stack_entry_t *stack = *stack_ptr;
787 size_t top = ARR_LEN(stack);
790 assert(new_top <= top);
794 for (i = top; i > new_top; --i) {
795 stack_entry_t *entry = &stack[i - 1];
797 entity_t *old_entity = entry->old_entity;
798 symbol_t *symbol = entry->symbol;
799 entity_namespace_t namespc = entry->namespc;
801 /* replace with old_entity/remove */
804 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
806 assert(iter != NULL);
807 /* replace an entry? */
808 if (iter->base.namespc == namespc)
812 /* restore definition from outer scopes (if there was one) */
813 if (old_entity != NULL) {
814 old_entity->base.symbol_next = iter->base.symbol_next;
815 *anchor = old_entity;
817 /* remove entry from list */
818 *anchor = iter->base.symbol_next;
822 ARR_SHRINKLEN(*stack_ptr, new_top);
826 * Pop all entries from the environment stack until the new_top
829 * @param new_top the new stack top
831 static void environment_pop_to(size_t new_top)
833 stack_pop_to(&environment_stack, new_top);
837 * Pop all entries from the global label stack until the new_top
840 * @param new_top the new stack top
842 static void label_pop_to(size_t new_top)
844 stack_pop_to(&label_stack, new_top);
847 static atomic_type_kind_t get_akind(const type_t *type)
849 assert(type->kind == TYPE_ATOMIC || type->kind == TYPE_COMPLEX
850 || type->kind == TYPE_IMAGINARY || type->kind == TYPE_ENUM);
851 return type->atomic.akind;
855 * §6.3.1.1:2 Do integer promotion for a given type.
857 * @param type the type to promote
858 * @return the promoted type
860 static type_t *promote_integer(type_t *type)
862 if (get_akind_rank(get_akind(type)) < get_akind_rank(ATOMIC_TYPE_INT))
869 * Check if a given expression represents a null pointer constant.
871 * @param expression the expression to check
873 static bool is_null_pointer_constant(const expression_t *expression)
875 /* skip void* cast */
876 if (expression->kind == EXPR_UNARY_CAST) {
877 type_t *const type = skip_typeref(expression->base.type);
878 if (types_compatible(type, type_void_ptr))
879 expression = expression->unary.value;
882 type_t *const type = skip_typeref(expression->base.type);
883 if (!is_type_integer(type))
885 switch (is_constant_expression(expression)) {
886 case EXPR_CLASS_ERROR: return true;
887 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
888 default: return false;
893 * Create an implicit cast expression.
895 * @param expression the expression to cast
896 * @param dest_type the destination type
898 static expression_t *create_implicit_cast(expression_t *expression,
901 type_t *const source_type = expression->base.type;
903 if (source_type == dest_type)
906 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
907 cast->unary.value = expression;
908 cast->base.type = dest_type;
909 cast->base.implicit = true;
914 typedef enum assign_error_t {
916 ASSIGN_ERROR_INCOMPATIBLE,
917 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
918 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
919 ASSIGN_WARNING_POINTER_FROM_INT,
920 ASSIGN_WARNING_INT_FROM_POINTER
923 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)
925 type_t *const orig_type_right = right->base.type;
926 type_t *const type_left = skip_typeref(orig_type_left);
927 type_t *const type_right = skip_typeref(orig_type_right);
932 case ASSIGN_ERROR_INCOMPATIBLE:
933 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
936 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
937 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
938 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
940 /* the left type has all qualifiers from the right type */
941 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
942 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);
946 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
947 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
950 case ASSIGN_WARNING_POINTER_FROM_INT:
951 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
954 case ASSIGN_WARNING_INT_FROM_POINTER:
955 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
959 panic("invalid error value");
963 /** Implements the rules from §6.5.16.1 */
964 static assign_error_t semantic_assign(type_t *orig_type_left,
965 const expression_t *const right)
967 type_t *const orig_type_right = right->base.type;
968 type_t *const type_left = skip_typeref(orig_type_left);
969 type_t *const type_right = skip_typeref(orig_type_right);
971 if (is_type_pointer(type_left)) {
972 if (is_null_pointer_constant(right)) {
973 return ASSIGN_SUCCESS;
974 } else if (is_type_pointer(type_right)) {
975 type_t *points_to_left
976 = skip_typeref(type_left->pointer.points_to);
977 type_t *points_to_right
978 = skip_typeref(type_right->pointer.points_to);
979 assign_error_t res = ASSIGN_SUCCESS;
981 /* the left type has all qualifiers from the right type */
982 unsigned missing_qualifiers
983 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
984 if (missing_qualifiers != 0) {
985 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
988 points_to_left = get_unqualified_type(points_to_left);
989 points_to_right = get_unqualified_type(points_to_right);
991 if (is_type_void(points_to_left))
994 if (is_type_void(points_to_right)) {
995 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
996 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
999 if (!types_compatible(points_to_left, points_to_right)) {
1000 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1004 } else if (is_type_integer(type_right)) {
1005 return ASSIGN_WARNING_POINTER_FROM_INT;
1007 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1008 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1009 && is_type_pointer(type_right))) {
1010 return ASSIGN_SUCCESS;
1011 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1012 type_t *const unqual_type_left = get_unqualified_type(type_left);
1013 type_t *const unqual_type_right = get_unqualified_type(type_right);
1014 if (types_compatible(unqual_type_left, unqual_type_right)) {
1015 return ASSIGN_SUCCESS;
1017 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1018 return ASSIGN_WARNING_INT_FROM_POINTER;
1021 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1022 return ASSIGN_SUCCESS;
1024 return ASSIGN_ERROR_INCOMPATIBLE;
1027 static expression_t *parse_constant_expression(void)
1029 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1031 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1032 errorf(&result->base.source_position,
1033 "expression '%E' is not constant", result);
1039 static expression_t *parse_assignment_expression(void)
1041 return parse_subexpression(PREC_ASSIGNMENT);
1044 static void warn_string_concat(const source_position_t *pos)
1046 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1049 static string_t parse_string_literals(void)
1051 assert(token.kind == T_STRING_LITERAL);
1052 string_t result = token.string.string;
1056 while (token.kind == T_STRING_LITERAL) {
1057 warn_string_concat(&token.base.source_position);
1058 result = concat_strings(&result, &token.string.string);
1065 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1067 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1068 attribute->kind = kind;
1069 attribute->source_position = *HERE;
1074 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1077 * __attribute__ ( ( attribute-list ) )
1081 * attribute_list , attrib
1086 * any-word ( identifier )
1087 * any-word ( identifier , nonempty-expr-list )
1088 * any-word ( expr-list )
1090 * where the "identifier" must not be declared as a type, and
1091 * "any-word" may be any identifier (including one declared as a
1092 * type), a reserved word storage class specifier, type specifier or
1093 * type qualifier. ??? This still leaves out most reserved keywords
1094 * (following the old parser), shouldn't we include them, and why not
1095 * allow identifiers declared as types to start the arguments?
1097 * Matze: this all looks confusing and little systematic, so we're even less
1098 * strict and parse any list of things which are identifiers or
1099 * (assignment-)expressions.
1101 static attribute_argument_t *parse_attribute_arguments(void)
1103 attribute_argument_t *first = NULL;
1104 attribute_argument_t **anchor = &first;
1105 if (token.kind != ')') do {
1106 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1108 /* is it an identifier */
1109 if (token.kind == T_IDENTIFIER
1110 && (look_ahead(1)->kind == ',' || look_ahead(1)->kind == ')')) {
1111 symbol_t *symbol = token.identifier.symbol;
1112 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1113 argument->v.symbol = symbol;
1116 /* must be an expression */
1117 expression_t *expression = parse_assignment_expression();
1119 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1120 argument->v.expression = expression;
1123 /* append argument */
1125 anchor = &argument->next;
1126 } while (next_if(','));
1127 expect(')', end_error);
1132 static attribute_t *parse_attribute_asm(void)
1134 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1137 expect('(', end_error);
1138 attribute->a.arguments = parse_attribute_arguments();
1145 static symbol_t *get_symbol_from_token(void)
1147 switch(token.kind) {
1149 return token.identifier.symbol;
1178 /* maybe we need more tokens ... add them on demand */
1179 return get_token_kind_symbol(token.kind);
1185 static attribute_t *parse_attribute_gnu_single(void)
1187 /* parse "any-word" */
1188 symbol_t *symbol = get_symbol_from_token();
1189 if (symbol == NULL) {
1190 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1194 attribute_kind_t kind;
1195 char const *const name = symbol->string;
1196 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1197 if (kind > ATTRIBUTE_GNU_LAST) {
1198 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1199 /* TODO: we should still save the attribute in the list... */
1200 kind = ATTRIBUTE_UNKNOWN;
1204 const char *attribute_name = get_attribute_name(kind);
1205 if (attribute_name != NULL && streq_underscore(attribute_name, name))
1209 attribute_t *attribute = allocate_attribute_zero(kind);
1212 /* parse arguments */
1214 attribute->a.arguments = parse_attribute_arguments();
1219 static attribute_t *parse_attribute_gnu(void)
1221 attribute_t *first = NULL;
1222 attribute_t **anchor = &first;
1224 eat(T___attribute__);
1225 expect('(', end_error);
1226 expect('(', end_error);
1228 if (token.kind != ')') do {
1229 attribute_t *attribute = parse_attribute_gnu_single();
1230 if (attribute == NULL)
1233 *anchor = attribute;
1234 anchor = &attribute->next;
1235 } while (next_if(','));
1236 expect(')', end_error);
1237 expect(')', end_error);
1243 /** Parse attributes. */
1244 static attribute_t *parse_attributes(attribute_t *first)
1246 attribute_t **anchor = &first;
1248 while (*anchor != NULL)
1249 anchor = &(*anchor)->next;
1251 attribute_t *attribute;
1252 switch (token.kind) {
1253 case T___attribute__:
1254 attribute = parse_attribute_gnu();
1255 if (attribute == NULL)
1260 attribute = parse_attribute_asm();
1264 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1269 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1273 case T__forceinline:
1274 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1275 eat(T__forceinline);
1279 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1284 /* TODO record modifier */
1285 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1286 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1294 *anchor = attribute;
1295 anchor = &attribute->next;
1299 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1301 static entity_t *determine_lhs_ent(expression_t *const expr,
1304 switch (expr->kind) {
1305 case EXPR_REFERENCE: {
1306 entity_t *const entity = expr->reference.entity;
1307 /* we should only find variables as lvalues... */
1308 if (entity->base.kind != ENTITY_VARIABLE
1309 && entity->base.kind != ENTITY_PARAMETER)
1315 case EXPR_ARRAY_ACCESS: {
1316 expression_t *const ref = expr->array_access.array_ref;
1317 entity_t * ent = NULL;
1318 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1319 ent = determine_lhs_ent(ref, lhs_ent);
1322 mark_vars_read(ref, lhs_ent);
1324 mark_vars_read(expr->array_access.index, lhs_ent);
1329 mark_vars_read(expr->select.compound, lhs_ent);
1330 if (is_type_compound(skip_typeref(expr->base.type)))
1331 return determine_lhs_ent(expr->select.compound, lhs_ent);
1335 case EXPR_UNARY_DEREFERENCE: {
1336 expression_t *const val = expr->unary.value;
1337 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1339 return determine_lhs_ent(val->unary.value, lhs_ent);
1341 mark_vars_read(val, NULL);
1347 mark_vars_read(expr, NULL);
1352 #define ENT_ANY ((entity_t*)-1)
1355 * Mark declarations, which are read. This is used to detect variables, which
1359 * x is not marked as "read", because it is only read to calculate its own new
1363 * x and y are not detected as "not read", because multiple variables are
1366 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1368 switch (expr->kind) {
1369 case EXPR_REFERENCE: {
1370 entity_t *const entity = expr->reference.entity;
1371 if (entity->kind != ENTITY_VARIABLE
1372 && entity->kind != ENTITY_PARAMETER)
1375 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1376 if (entity->kind == ENTITY_VARIABLE) {
1377 entity->variable.read = true;
1379 entity->parameter.read = true;
1386 // TODO respect pure/const
1387 mark_vars_read(expr->call.function, NULL);
1388 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1389 mark_vars_read(arg->expression, NULL);
1393 case EXPR_CONDITIONAL:
1394 // TODO lhs_decl should depend on whether true/false have an effect
1395 mark_vars_read(expr->conditional.condition, NULL);
1396 if (expr->conditional.true_expression != NULL)
1397 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1398 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1402 if (lhs_ent == ENT_ANY
1403 && !is_type_compound(skip_typeref(expr->base.type)))
1405 mark_vars_read(expr->select.compound, lhs_ent);
1408 case EXPR_ARRAY_ACCESS: {
1409 mark_vars_read(expr->array_access.index, lhs_ent);
1410 expression_t *const ref = expr->array_access.array_ref;
1411 if (!is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1412 if (lhs_ent == ENT_ANY)
1415 mark_vars_read(ref, lhs_ent);
1420 mark_vars_read(expr->va_arge.ap, lhs_ent);
1424 mark_vars_read(expr->va_copye.src, lhs_ent);
1427 case EXPR_UNARY_CAST:
1428 /* Special case: Use void cast to mark a variable as "read" */
1429 if (is_type_void(skip_typeref(expr->base.type)))
1434 case EXPR_UNARY_THROW:
1435 if (expr->unary.value == NULL)
1438 case EXPR_UNARY_DEREFERENCE:
1439 case EXPR_UNARY_DELETE:
1440 case EXPR_UNARY_DELETE_ARRAY:
1441 if (lhs_ent == ENT_ANY)
1445 case EXPR_UNARY_NEGATE:
1446 case EXPR_UNARY_PLUS:
1447 case EXPR_UNARY_BITWISE_NEGATE:
1448 case EXPR_UNARY_NOT:
1449 case EXPR_UNARY_TAKE_ADDRESS:
1450 case EXPR_UNARY_POSTFIX_INCREMENT:
1451 case EXPR_UNARY_POSTFIX_DECREMENT:
1452 case EXPR_UNARY_PREFIX_INCREMENT:
1453 case EXPR_UNARY_PREFIX_DECREMENT:
1454 case EXPR_UNARY_ASSUME:
1456 mark_vars_read(expr->unary.value, lhs_ent);
1459 case EXPR_BINARY_ADD:
1460 case EXPR_BINARY_SUB:
1461 case EXPR_BINARY_MUL:
1462 case EXPR_BINARY_DIV:
1463 case EXPR_BINARY_MOD:
1464 case EXPR_BINARY_EQUAL:
1465 case EXPR_BINARY_NOTEQUAL:
1466 case EXPR_BINARY_LESS:
1467 case EXPR_BINARY_LESSEQUAL:
1468 case EXPR_BINARY_GREATER:
1469 case EXPR_BINARY_GREATEREQUAL:
1470 case EXPR_BINARY_BITWISE_AND:
1471 case EXPR_BINARY_BITWISE_OR:
1472 case EXPR_BINARY_BITWISE_XOR:
1473 case EXPR_BINARY_LOGICAL_AND:
1474 case EXPR_BINARY_LOGICAL_OR:
1475 case EXPR_BINARY_SHIFTLEFT:
1476 case EXPR_BINARY_SHIFTRIGHT:
1477 case EXPR_BINARY_COMMA:
1478 case EXPR_BINARY_ISGREATER:
1479 case EXPR_BINARY_ISGREATEREQUAL:
1480 case EXPR_BINARY_ISLESS:
1481 case EXPR_BINARY_ISLESSEQUAL:
1482 case EXPR_BINARY_ISLESSGREATER:
1483 case EXPR_BINARY_ISUNORDERED:
1484 mark_vars_read(expr->binary.left, lhs_ent);
1485 mark_vars_read(expr->binary.right, lhs_ent);
1488 case EXPR_BINARY_ASSIGN:
1489 case EXPR_BINARY_MUL_ASSIGN:
1490 case EXPR_BINARY_DIV_ASSIGN:
1491 case EXPR_BINARY_MOD_ASSIGN:
1492 case EXPR_BINARY_ADD_ASSIGN:
1493 case EXPR_BINARY_SUB_ASSIGN:
1494 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1495 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1496 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1497 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1498 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1499 if (lhs_ent == ENT_ANY)
1501 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1502 mark_vars_read(expr->binary.right, lhs_ent);
1507 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1510 case EXPR_LITERAL_CASES:
1512 case EXPR_STRING_LITERAL:
1513 case EXPR_WIDE_STRING_LITERAL:
1514 case EXPR_COMPOUND_LITERAL: // TODO init?
1516 case EXPR_CLASSIFY_TYPE:
1519 case EXPR_BUILTIN_CONSTANT_P:
1520 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1522 case EXPR_STATEMENT: // TODO
1523 case EXPR_LABEL_ADDRESS:
1524 case EXPR_ENUM_CONSTANT:
1528 panic("unhandled expression");
1531 static designator_t *parse_designation(void)
1533 designator_t *result = NULL;
1534 designator_t **anchor = &result;
1537 designator_t *designator;
1538 switch (token.kind) {
1540 designator = allocate_ast_zero(sizeof(designator[0]));
1541 designator->source_position = token.base.source_position;
1543 add_anchor_token(']');
1544 designator->array_index = parse_constant_expression();
1545 rem_anchor_token(']');
1546 expect(']', end_error);
1549 designator = allocate_ast_zero(sizeof(designator[0]));
1550 designator->source_position = token.base.source_position;
1552 if (token.kind != T_IDENTIFIER) {
1553 parse_error_expected("while parsing designator",
1554 T_IDENTIFIER, NULL);
1557 designator->symbol = token.identifier.symbol;
1561 expect('=', end_error);
1565 assert(designator != NULL);
1566 *anchor = designator;
1567 anchor = &designator->next;
1573 static initializer_t *initializer_from_string(array_type_t *const type,
1574 const string_t *const string)
1576 /* TODO: check len vs. size of array type */
1579 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1580 initializer->string.string = *string;
1585 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1586 const string_t *const string)
1588 /* TODO: check len vs. size of array type */
1591 initializer_t *const initializer =
1592 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1593 initializer->wide_string.string = *string;
1599 * Build an initializer from a given expression.
1601 static initializer_t *initializer_from_expression(type_t *orig_type,
1602 expression_t *expression)
1604 /* TODO check that expression is a constant expression */
1606 /* §6.7.8.14/15 char array may be initialized by string literals */
1607 type_t *type = skip_typeref(orig_type);
1608 type_t *expr_type_orig = expression->base.type;
1609 type_t *expr_type = skip_typeref(expr_type_orig);
1611 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1612 array_type_t *const array_type = &type->array;
1613 type_t *const element_type = skip_typeref(array_type->element_type);
1615 if (element_type->kind == TYPE_ATOMIC) {
1616 atomic_type_kind_t akind = element_type->atomic.akind;
1617 switch (expression->kind) {
1618 case EXPR_STRING_LITERAL:
1619 if (akind == ATOMIC_TYPE_CHAR
1620 || akind == ATOMIC_TYPE_SCHAR
1621 || akind == ATOMIC_TYPE_UCHAR) {
1622 return initializer_from_string(array_type,
1623 &expression->string_literal.value);
1627 case EXPR_WIDE_STRING_LITERAL: {
1628 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1629 if (get_unqualified_type(element_type) == bare_wchar_type) {
1630 return initializer_from_wide_string(array_type,
1631 &expression->string_literal.value);
1642 assign_error_t error = semantic_assign(type, expression);
1643 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1645 report_assign_error(error, type, expression, "initializer",
1646 &expression->base.source_position);
1648 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1649 result->value.value = create_implicit_cast(expression, type);
1655 * Parses an scalar initializer.
1657 * §6.7.8.11; eat {} without warning
1659 static initializer_t *parse_scalar_initializer(type_t *type,
1660 bool must_be_constant)
1662 /* there might be extra {} hierarchies */
1664 if (token.kind == '{') {
1665 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1669 } while (token.kind == '{');
1672 expression_t *expression = parse_assignment_expression();
1673 mark_vars_read(expression, NULL);
1674 if (must_be_constant && !is_linker_constant(expression)) {
1675 errorf(&expression->base.source_position,
1676 "initialisation expression '%E' is not constant",
1680 initializer_t *initializer = initializer_from_expression(type, expression);
1682 if (initializer == NULL) {
1683 errorf(&expression->base.source_position,
1684 "expression '%E' (type '%T') doesn't match expected type '%T'",
1685 expression, expression->base.type, type);
1690 bool additional_warning_displayed = false;
1691 while (braces > 0) {
1693 if (token.kind != '}') {
1694 if (!additional_warning_displayed) {
1695 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1696 additional_warning_displayed = true;
1707 * An entry in the type path.
1709 typedef struct type_path_entry_t type_path_entry_t;
1710 struct type_path_entry_t {
1711 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1713 size_t index; /**< For array types: the current index. */
1714 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1719 * A type path expression a position inside compound or array types.
1721 typedef struct type_path_t type_path_t;
1722 struct type_path_t {
1723 type_path_entry_t *path; /**< An flexible array containing the current path. */
1724 type_t *top_type; /**< type of the element the path points */
1725 size_t max_index; /**< largest index in outermost array */
1729 * Prints a type path for debugging.
1731 static __attribute__((unused)) void debug_print_type_path(
1732 const type_path_t *path)
1734 size_t len = ARR_LEN(path->path);
1736 for (size_t i = 0; i < len; ++i) {
1737 const type_path_entry_t *entry = & path->path[i];
1739 type_t *type = skip_typeref(entry->type);
1740 if (is_type_compound(type)) {
1741 /* in gcc mode structs can have no members */
1742 if (entry->v.compound_entry == NULL) {
1746 fprintf(stderr, ".%s",
1747 entry->v.compound_entry->base.symbol->string);
1748 } else if (is_type_array(type)) {
1749 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1751 fprintf(stderr, "-INVALID-");
1754 if (path->top_type != NULL) {
1755 fprintf(stderr, " (");
1756 print_type(path->top_type);
1757 fprintf(stderr, ")");
1762 * Return the top type path entry, ie. in a path
1763 * (type).a.b returns the b.
1765 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1767 size_t len = ARR_LEN(path->path);
1769 return &path->path[len-1];
1773 * Enlarge the type path by an (empty) element.
1775 static type_path_entry_t *append_to_type_path(type_path_t *path)
1777 size_t len = ARR_LEN(path->path);
1778 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1780 type_path_entry_t *result = & path->path[len];
1781 memset(result, 0, sizeof(result[0]));
1786 * Descending into a sub-type. Enter the scope of the current top_type.
1788 static void descend_into_subtype(type_path_t *path)
1790 type_t *orig_top_type = path->top_type;
1791 type_t *top_type = skip_typeref(orig_top_type);
1793 type_path_entry_t *top = append_to_type_path(path);
1794 top->type = top_type;
1796 if (is_type_compound(top_type)) {
1797 compound_t *const compound = top_type->compound.compound;
1798 entity_t *const entry = skip_unnamed_bitfields(compound->members.entities);
1800 if (entry != NULL) {
1801 top->v.compound_entry = &entry->declaration;
1802 path->top_type = entry->declaration.type;
1804 path->top_type = NULL;
1806 } else if (is_type_array(top_type)) {
1808 path->top_type = top_type->array.element_type;
1810 assert(!is_type_valid(top_type));
1815 * Pop an entry from the given type path, ie. returning from
1816 * (type).a.b to (type).a
1818 static void ascend_from_subtype(type_path_t *path)
1820 type_path_entry_t *top = get_type_path_top(path);
1822 path->top_type = top->type;
1824 size_t len = ARR_LEN(path->path);
1825 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1829 * Pop entries from the given type path until the given
1830 * path level is reached.
1832 static void ascend_to(type_path_t *path, size_t top_path_level)
1834 size_t len = ARR_LEN(path->path);
1836 while (len > top_path_level) {
1837 ascend_from_subtype(path);
1838 len = ARR_LEN(path->path);
1842 static bool walk_designator(type_path_t *path, const designator_t *designator,
1843 bool used_in_offsetof)
1845 for (; designator != NULL; designator = designator->next) {
1846 type_path_entry_t *top = get_type_path_top(path);
1847 type_t *orig_type = top->type;
1849 type_t *type = skip_typeref(orig_type);
1851 if (designator->symbol != NULL) {
1852 symbol_t *symbol = designator->symbol;
1853 if (!is_type_compound(type)) {
1854 if (is_type_valid(type)) {
1855 errorf(&designator->source_position,
1856 "'.%Y' designator used for non-compound type '%T'",
1860 top->type = type_error_type;
1861 top->v.compound_entry = NULL;
1862 orig_type = type_error_type;
1864 compound_t *compound = type->compound.compound;
1865 entity_t *iter = compound->members.entities;
1866 for (; iter != NULL; iter = iter->base.next) {
1867 if (iter->base.symbol == symbol) {
1872 errorf(&designator->source_position,
1873 "'%T' has no member named '%Y'", orig_type, symbol);
1876 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1877 if (used_in_offsetof && iter->compound_member.bitfield) {
1878 errorf(&designator->source_position,
1879 "offsetof designator '%Y' must not specify bitfield",
1884 top->type = orig_type;
1885 top->v.compound_entry = &iter->declaration;
1886 orig_type = iter->declaration.type;
1889 expression_t *array_index = designator->array_index;
1890 assert(designator->array_index != NULL);
1892 if (!is_type_array(type)) {
1893 if (is_type_valid(type)) {
1894 errorf(&designator->source_position,
1895 "[%E] designator used for non-array type '%T'",
1896 array_index, orig_type);
1901 long index = fold_constant_to_int(array_index);
1902 if (!used_in_offsetof) {
1904 errorf(&designator->source_position,
1905 "array index [%E] must be positive", array_index);
1906 } else if (type->array.size_constant) {
1907 long array_size = type->array.size;
1908 if (index >= array_size) {
1909 errorf(&designator->source_position,
1910 "designator [%E] (%d) exceeds array size %d",
1911 array_index, index, array_size);
1916 top->type = orig_type;
1917 top->v.index = (size_t) index;
1918 orig_type = type->array.element_type;
1920 path->top_type = orig_type;
1922 if (designator->next != NULL) {
1923 descend_into_subtype(path);
1929 static void advance_current_object(type_path_t *path, size_t top_path_level)
1931 type_path_entry_t *top = get_type_path_top(path);
1933 type_t *type = skip_typeref(top->type);
1934 if (is_type_union(type)) {
1935 /* in unions only the first element is initialized */
1936 top->v.compound_entry = NULL;
1937 } else if (is_type_struct(type)) {
1938 declaration_t *entry = top->v.compound_entry;
1940 entity_t *const next_entity = skip_unnamed_bitfields(entry->base.next);
1941 if (next_entity != NULL) {
1942 assert(is_declaration(next_entity));
1943 entry = &next_entity->declaration;
1948 top->v.compound_entry = entry;
1949 if (entry != NULL) {
1950 path->top_type = entry->type;
1953 } else if (is_type_array(type)) {
1954 assert(is_type_array(type));
1958 if (!type->array.size_constant || top->v.index < type->array.size) {
1962 assert(!is_type_valid(type));
1966 /* we're past the last member of the current sub-aggregate, try if we
1967 * can ascend in the type hierarchy and continue with another subobject */
1968 size_t len = ARR_LEN(path->path);
1970 if (len > top_path_level) {
1971 ascend_from_subtype(path);
1972 advance_current_object(path, top_path_level);
1974 path->top_type = NULL;
1979 * skip any {...} blocks until a closing bracket is reached.
1981 static void skip_initializers(void)
1985 while (token.kind != '}') {
1986 if (token.kind == T_EOF)
1988 if (token.kind == '{') {
1996 static initializer_t *create_empty_initializer(void)
1998 static initializer_t empty_initializer
1999 = { .list = { { INITIALIZER_LIST }, 0 } };
2000 return &empty_initializer;
2004 * Parse a part of an initialiser for a struct or union,
2006 static initializer_t *parse_sub_initializer(type_path_t *path,
2007 type_t *outer_type, size_t top_path_level,
2008 parse_initializer_env_t *env)
2010 if (token.kind == '}') {
2011 /* empty initializer */
2012 return create_empty_initializer();
2015 type_t *orig_type = path->top_type;
2016 type_t *type = NULL;
2018 if (orig_type == NULL) {
2019 /* We are initializing an empty compound. */
2021 type = skip_typeref(orig_type);
2024 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2027 designator_t *designator = NULL;
2028 if (token.kind == '.' || token.kind == '[') {
2029 designator = parse_designation();
2030 goto finish_designator;
2031 } else if (token.kind == T_IDENTIFIER && look_ahead(1)->kind == ':') {
2032 /* GNU-style designator ("identifier: value") */
2033 designator = allocate_ast_zero(sizeof(designator[0]));
2034 designator->source_position = token.base.source_position;
2035 designator->symbol = token.identifier.symbol;
2040 /* reset path to toplevel, evaluate designator from there */
2041 ascend_to(path, top_path_level);
2042 if (!walk_designator(path, designator, false)) {
2043 /* can't continue after designation error */
2047 initializer_t *designator_initializer
2048 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2049 designator_initializer->designator.designator = designator;
2050 ARR_APP1(initializer_t*, initializers, designator_initializer);
2052 orig_type = path->top_type;
2053 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2058 if (token.kind == '{') {
2059 if (type != NULL && is_type_scalar(type)) {
2060 sub = parse_scalar_initializer(type, env->must_be_constant);
2063 if (env->entity != NULL) {
2065 "extra brace group at end of initializer for '%Y'",
2066 env->entity->base.symbol);
2068 errorf(HERE, "extra brace group at end of initializer");
2073 descend_into_subtype(path);
2076 add_anchor_token('}');
2077 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2079 rem_anchor_token('}');
2082 ascend_from_subtype(path);
2083 expect('}', end_error);
2085 expect('}', end_error);
2086 goto error_parse_next;
2090 /* must be an expression */
2091 expression_t *expression = parse_assignment_expression();
2092 mark_vars_read(expression, NULL);
2094 if (env->must_be_constant && !is_linker_constant(expression)) {
2095 errorf(&expression->base.source_position,
2096 "Initialisation expression '%E' is not constant",
2101 /* we are already outside, ... */
2102 if (outer_type == NULL)
2103 goto error_parse_next;
2104 type_t *const outer_type_skip = skip_typeref(outer_type);
2105 if (is_type_compound(outer_type_skip) &&
2106 !outer_type_skip->compound.compound->complete) {
2107 goto error_parse_next;
2110 source_position_t const* const pos = &expression->base.source_position;
2111 if (env->entity != NULL) {
2112 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2114 warningf(WARN_OTHER, pos, "excess elements in initializer");
2116 goto error_parse_next;
2119 /* handle { "string" } special case */
2120 if ((expression->kind == EXPR_STRING_LITERAL
2121 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2122 && outer_type != NULL) {
2123 sub = initializer_from_expression(outer_type, expression);
2126 if (token.kind != '}') {
2127 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2129 /* TODO: eat , ... */
2134 /* descend into subtypes until expression matches type */
2136 orig_type = path->top_type;
2137 type = skip_typeref(orig_type);
2139 sub = initializer_from_expression(orig_type, expression);
2143 if (!is_type_valid(type)) {
2146 if (is_type_scalar(type)) {
2147 errorf(&expression->base.source_position,
2148 "expression '%E' doesn't match expected type '%T'",
2149 expression, orig_type);
2153 descend_into_subtype(path);
2157 /* update largest index of top array */
2158 const type_path_entry_t *first = &path->path[0];
2159 type_t *first_type = first->type;
2160 first_type = skip_typeref(first_type);
2161 if (is_type_array(first_type)) {
2162 size_t index = first->v.index;
2163 if (index > path->max_index)
2164 path->max_index = index;
2167 /* append to initializers list */
2168 ARR_APP1(initializer_t*, initializers, sub);
2171 if (token.kind == '}') {
2174 expect(',', end_error);
2175 if (token.kind == '}') {
2180 /* advance to the next declaration if we are not at the end */
2181 advance_current_object(path, top_path_level);
2182 orig_type = path->top_type;
2183 if (orig_type != NULL)
2184 type = skip_typeref(orig_type);
2190 size_t len = ARR_LEN(initializers);
2191 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2192 initializer_t *result = allocate_ast_zero(size);
2193 result->kind = INITIALIZER_LIST;
2194 result->list.len = len;
2195 memcpy(&result->list.initializers, initializers,
2196 len * sizeof(initializers[0]));
2198 DEL_ARR_F(initializers);
2199 ascend_to(path, top_path_level+1);
2204 skip_initializers();
2205 DEL_ARR_F(initializers);
2206 ascend_to(path, top_path_level+1);
2210 static expression_t *make_size_literal(size_t value)
2212 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2213 literal->base.type = type_size_t;
2216 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2217 literal->literal.value = make_string(buf);
2223 * Parses an initializer. Parsers either a compound literal
2224 * (env->declaration == NULL) or an initializer of a declaration.
2226 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2228 type_t *type = skip_typeref(env->type);
2229 size_t max_index = 0;
2230 initializer_t *result;
2232 if (is_type_scalar(type)) {
2233 result = parse_scalar_initializer(type, env->must_be_constant);
2234 } else if (token.kind == '{') {
2238 memset(&path, 0, sizeof(path));
2239 path.top_type = env->type;
2240 path.path = NEW_ARR_F(type_path_entry_t, 0);
2242 descend_into_subtype(&path);
2244 add_anchor_token('}');
2245 result = parse_sub_initializer(&path, env->type, 1, env);
2246 rem_anchor_token('}');
2248 max_index = path.max_index;
2249 DEL_ARR_F(path.path);
2251 expect('}', end_error);
2254 /* parse_scalar_initializer() also works in this case: we simply
2255 * have an expression without {} around it */
2256 result = parse_scalar_initializer(type, env->must_be_constant);
2259 /* §6.7.8:22 array initializers for arrays with unknown size determine
2260 * the array type size */
2261 if (is_type_array(type) && type->array.size_expression == NULL
2262 && result != NULL) {
2264 switch (result->kind) {
2265 case INITIALIZER_LIST:
2266 assert(max_index != 0xdeadbeaf);
2267 size = max_index + 1;
2270 case INITIALIZER_STRING:
2271 size = result->string.string.size;
2274 case INITIALIZER_WIDE_STRING:
2275 size = result->wide_string.string.size;
2278 case INITIALIZER_DESIGNATOR:
2279 case INITIALIZER_VALUE:
2280 /* can happen for parse errors */
2285 internal_errorf(HERE, "invalid initializer type");
2288 type_t *new_type = duplicate_type(type);
2290 new_type->array.size_expression = make_size_literal(size);
2291 new_type->array.size_constant = true;
2292 new_type->array.has_implicit_size = true;
2293 new_type->array.size = size;
2294 env->type = new_type;
2300 static void append_entity(scope_t *scope, entity_t *entity)
2302 if (scope->last_entity != NULL) {
2303 scope->last_entity->base.next = entity;
2305 scope->entities = entity;
2307 entity->base.parent_entity = current_entity;
2308 scope->last_entity = entity;
2312 static compound_t *parse_compound_type_specifier(bool is_struct)
2314 source_position_t const pos = *HERE;
2315 eat(is_struct ? T_struct : T_union);
2317 symbol_t *symbol = NULL;
2318 entity_t *entity = NULL;
2319 attribute_t *attributes = NULL;
2321 if (token.kind == T___attribute__) {
2322 attributes = parse_attributes(NULL);
2325 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2326 if (token.kind == T_IDENTIFIER) {
2327 /* the compound has a name, check if we have seen it already */
2328 symbol = token.identifier.symbol;
2329 entity = get_tag(symbol, kind);
2332 if (entity != NULL) {
2333 if (entity->base.parent_scope != current_scope &&
2334 (token.kind == '{' || token.kind == ';')) {
2335 /* we're in an inner scope and have a definition. Shadow
2336 * existing definition in outer scope */
2338 } else if (entity->compound.complete && token.kind == '{') {
2339 source_position_t const *const ppos = &entity->base.source_position;
2340 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2341 /* clear members in the hope to avoid further errors */
2342 entity->compound.members.entities = NULL;
2345 } else if (token.kind != '{') {
2346 char const *const msg =
2347 is_struct ? "while parsing struct type specifier" :
2348 "while parsing union type specifier";
2349 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2354 if (entity == NULL) {
2355 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2356 entity->compound.alignment = 1;
2357 entity->base.source_position = pos;
2358 entity->base.parent_scope = current_scope;
2359 if (symbol != NULL) {
2360 environment_push(entity);
2362 append_entity(current_scope, entity);
2365 if (token.kind == '{') {
2366 parse_compound_type_entries(&entity->compound);
2368 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2369 if (symbol == NULL) {
2370 assert(anonymous_entity == NULL);
2371 anonymous_entity = entity;
2375 if (attributes != NULL) {
2376 handle_entity_attributes(attributes, entity);
2379 return &entity->compound;
2382 static void parse_enum_entries(type_t *const enum_type)
2386 if (token.kind == '}') {
2387 errorf(HERE, "empty enum not allowed");
2392 add_anchor_token('}');
2394 if (token.kind != T_IDENTIFIER) {
2395 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2397 rem_anchor_token('}');
2401 symbol_t *symbol = token.identifier.symbol;
2402 entity_t *const entity
2403 = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol);
2404 entity->enum_value.enum_type = enum_type;
2405 entity->base.source_position = token.base.source_position;
2409 expression_t *value = parse_constant_expression();
2411 value = create_implicit_cast(value, enum_type);
2412 entity->enum_value.value = value;
2417 record_entity(entity, false);
2418 } while (next_if(',') && token.kind != '}');
2419 rem_anchor_token('}');
2421 expect('}', end_error);
2427 static type_t *parse_enum_specifier(void)
2429 source_position_t const pos = *HERE;
2434 switch (token.kind) {
2436 symbol = token.identifier.symbol;
2437 entity = get_tag(symbol, ENTITY_ENUM);
2440 if (entity != NULL) {
2441 if (entity->base.parent_scope != current_scope &&
2442 (token.kind == '{' || token.kind == ';')) {
2443 /* we're in an inner scope and have a definition. Shadow
2444 * existing definition in outer scope */
2446 } else if (entity->enume.complete && token.kind == '{') {
2447 source_position_t const *const ppos = &entity->base.source_position;
2448 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2459 parse_error_expected("while parsing enum type specifier",
2460 T_IDENTIFIER, '{', NULL);
2464 if (entity == NULL) {
2465 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2466 entity->base.source_position = pos;
2467 entity->base.parent_scope = current_scope;
2470 type_t *const type = allocate_type_zero(TYPE_ENUM);
2471 type->enumt.enume = &entity->enume;
2472 type->enumt.base.akind = ATOMIC_TYPE_INT;
2474 if (token.kind == '{') {
2475 if (symbol != NULL) {
2476 environment_push(entity);
2478 append_entity(current_scope, entity);
2479 entity->enume.complete = true;
2481 parse_enum_entries(type);
2482 parse_attributes(NULL);
2484 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2485 if (symbol == NULL) {
2486 assert(anonymous_entity == NULL);
2487 anonymous_entity = entity;
2489 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2490 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2497 * if a symbol is a typedef to another type, return true
2499 static bool is_typedef_symbol(symbol_t *symbol)
2501 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2502 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2505 static type_t *parse_typeof(void)
2511 expect('(', end_error);
2512 add_anchor_token(')');
2514 expression_t *expression = NULL;
2516 switch (token.kind) {
2518 if (is_typedef_symbol(token.identifier.symbol)) {
2520 type = parse_typename();
2523 expression = parse_expression();
2524 type = revert_automatic_type_conversion(expression);
2529 rem_anchor_token(')');
2530 expect(')', end_error);
2532 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2533 typeof_type->typeoft.expression = expression;
2534 typeof_type->typeoft.typeof_type = type;
2541 typedef enum specifiers_t {
2542 SPECIFIER_SIGNED = 1 << 0,
2543 SPECIFIER_UNSIGNED = 1 << 1,
2544 SPECIFIER_LONG = 1 << 2,
2545 SPECIFIER_INT = 1 << 3,
2546 SPECIFIER_DOUBLE = 1 << 4,
2547 SPECIFIER_CHAR = 1 << 5,
2548 SPECIFIER_WCHAR_T = 1 << 6,
2549 SPECIFIER_SHORT = 1 << 7,
2550 SPECIFIER_LONG_LONG = 1 << 8,
2551 SPECIFIER_FLOAT = 1 << 9,
2552 SPECIFIER_BOOL = 1 << 10,
2553 SPECIFIER_VOID = 1 << 11,
2554 SPECIFIER_INT8 = 1 << 12,
2555 SPECIFIER_INT16 = 1 << 13,
2556 SPECIFIER_INT32 = 1 << 14,
2557 SPECIFIER_INT64 = 1 << 15,
2558 SPECIFIER_INT128 = 1 << 16,
2559 SPECIFIER_COMPLEX = 1 << 17,
2560 SPECIFIER_IMAGINARY = 1 << 18,
2563 static type_t *get_typedef_type(symbol_t *symbol)
2565 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2566 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2569 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2570 type->typedeft.typedefe = &entity->typedefe;
2575 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2577 expect('(', end_error);
2579 attribute_property_argument_t *property
2580 = allocate_ast_zero(sizeof(*property));
2583 if (token.kind != T_IDENTIFIER) {
2584 parse_error_expected("while parsing property declspec",
2585 T_IDENTIFIER, NULL);
2590 symbol_t *symbol = token.identifier.symbol;
2591 if (streq(symbol->string, "put")) {
2592 prop = &property->put_symbol;
2593 } else if (streq(symbol->string, "get")) {
2594 prop = &property->get_symbol;
2596 errorf(HERE, "expected put or get in property declspec");
2600 expect('=', end_error);
2601 if (token.kind != T_IDENTIFIER) {
2602 parse_error_expected("while parsing property declspec",
2603 T_IDENTIFIER, NULL);
2607 *prop = token.identifier.symbol;
2609 } while (next_if(','));
2611 attribute->a.property = property;
2613 expect(')', end_error);
2619 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2621 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2622 if (next_if(T_restrict)) {
2623 kind = ATTRIBUTE_MS_RESTRICT;
2624 } else if (token.kind == T_IDENTIFIER) {
2625 const char *name = token.identifier.symbol->string;
2626 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2628 const char *attribute_name = get_attribute_name(k);
2629 if (attribute_name != NULL && streq(attribute_name, name)) {
2635 if (kind == ATTRIBUTE_UNKNOWN) {
2636 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2639 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2643 attribute_t *attribute = allocate_attribute_zero(kind);
2646 if (kind == ATTRIBUTE_MS_PROPERTY) {
2647 return parse_attribute_ms_property(attribute);
2650 /* parse arguments */
2652 attribute->a.arguments = parse_attribute_arguments();
2657 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2661 expect('(', end_error);
2662 if (token.kind != ')') {
2663 add_anchor_token(')');
2665 attribute_t **anchor = &first;
2667 while (*anchor != NULL)
2668 anchor = &(*anchor)->next;
2670 attribute_t *attribute
2671 = parse_microsoft_extended_decl_modifier_single();
2672 if (attribute == NULL)
2675 *anchor = attribute;
2676 anchor = &attribute->next;
2677 } while (next_if(','));
2679 rem_anchor_token(')');
2681 expect(')', end_error);
2686 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2688 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2689 entity->base.source_position = *HERE;
2690 if (is_declaration(entity)) {
2691 entity->declaration.type = type_error_type;
2692 entity->declaration.implicit = true;
2693 } else if (kind == ENTITY_TYPEDEF) {
2694 entity->typedefe.type = type_error_type;
2695 entity->typedefe.builtin = true;
2697 if (kind != ENTITY_COMPOUND_MEMBER)
2698 record_entity(entity, false);
2702 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2704 type_t *type = NULL;
2705 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2706 unsigned type_specifiers = 0;
2707 bool newtype = false;
2708 bool saw_error = false;
2710 memset(specifiers, 0, sizeof(*specifiers));
2711 specifiers->source_position = token.base.source_position;
2714 specifiers->attributes = parse_attributes(specifiers->attributes);
2716 switch (token.kind) {
2718 #define MATCH_STORAGE_CLASS(token, class) \
2720 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2721 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2723 specifiers->storage_class = class; \
2724 if (specifiers->thread_local) \
2725 goto check_thread_storage_class; \
2729 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2730 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2731 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2732 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2733 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2736 specifiers->attributes
2737 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2741 if (specifiers->thread_local) {
2742 errorf(HERE, "duplicate '__thread'");
2744 specifiers->thread_local = true;
2745 check_thread_storage_class:
2746 switch (specifiers->storage_class) {
2747 case STORAGE_CLASS_EXTERN:
2748 case STORAGE_CLASS_NONE:
2749 case STORAGE_CLASS_STATIC:
2753 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2754 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2755 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2756 wrong_thread_storage_class:
2757 errorf(HERE, "'__thread' used with '%s'", wrong);
2764 /* type qualifiers */
2765 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2767 qualifiers |= qualifier; \
2771 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2772 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2773 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2774 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2775 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2776 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2777 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2778 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2780 /* type specifiers */
2781 #define MATCH_SPECIFIER(token, specifier, name) \
2783 if (type_specifiers & specifier) { \
2784 errorf(HERE, "multiple " name " type specifiers given"); \
2786 type_specifiers |= specifier; \
2791 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2792 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2793 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2794 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2795 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2796 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2797 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2798 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2799 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2800 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2801 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2802 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2803 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2804 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2805 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2806 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2807 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2808 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2812 specifiers->is_inline = true;
2816 case T__forceinline:
2818 specifiers->modifiers |= DM_FORCEINLINE;
2823 if (type_specifiers & SPECIFIER_LONG_LONG) {
2824 errorf(HERE, "too many long type specifiers given");
2825 } else if (type_specifiers & SPECIFIER_LONG) {
2826 type_specifiers |= SPECIFIER_LONG_LONG;
2828 type_specifiers |= SPECIFIER_LONG;
2833 #define CHECK_DOUBLE_TYPE() \
2834 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2837 CHECK_DOUBLE_TYPE();
2838 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2840 type->compound.compound = parse_compound_type_specifier(true);
2843 CHECK_DOUBLE_TYPE();
2844 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2845 type->compound.compound = parse_compound_type_specifier(false);
2848 CHECK_DOUBLE_TYPE();
2849 type = parse_enum_specifier();
2852 CHECK_DOUBLE_TYPE();
2853 type = parse_typeof();
2855 case T___builtin_va_list:
2856 CHECK_DOUBLE_TYPE();
2857 type = duplicate_type(type_valist);
2861 case T_IDENTIFIER: {
2862 /* only parse identifier if we haven't found a type yet */
2863 if (type != NULL || type_specifiers != 0) {
2864 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2865 * declaration, so it doesn't generate errors about expecting '(' or
2867 switch (look_ahead(1)->kind) {
2874 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2878 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2883 goto finish_specifiers;
2887 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2888 if (typedef_type == NULL) {
2889 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2890 * declaration, so it doesn't generate 'implicit int' followed by more
2891 * errors later on. */
2892 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2898 errorf(HERE, "%K does not name a type", &token);
2900 symbol_t *symbol = token.identifier.symbol;
2902 = create_error_entity(symbol, ENTITY_TYPEDEF);
2904 type = allocate_type_zero(TYPE_TYPEDEF);
2905 type->typedeft.typedefe = &entity->typedefe;
2913 goto finish_specifiers;
2918 type = typedef_type;
2922 /* function specifier */
2924 goto finish_specifiers;
2929 specifiers->attributes = parse_attributes(specifiers->attributes);
2931 if (type == NULL || (saw_error && type_specifiers != 0)) {
2932 atomic_type_kind_t atomic_type;
2934 /* match valid basic types */
2935 switch (type_specifiers) {
2936 case SPECIFIER_VOID:
2937 atomic_type = ATOMIC_TYPE_VOID;
2939 case SPECIFIER_WCHAR_T:
2940 atomic_type = ATOMIC_TYPE_WCHAR_T;
2942 case SPECIFIER_CHAR:
2943 atomic_type = ATOMIC_TYPE_CHAR;
2945 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2946 atomic_type = ATOMIC_TYPE_SCHAR;
2948 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2949 atomic_type = ATOMIC_TYPE_UCHAR;
2951 case SPECIFIER_SHORT:
2952 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2953 case SPECIFIER_SHORT | SPECIFIER_INT:
2954 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2955 atomic_type = ATOMIC_TYPE_SHORT;
2957 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2958 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2959 atomic_type = ATOMIC_TYPE_USHORT;
2962 case SPECIFIER_SIGNED:
2963 case SPECIFIER_SIGNED | SPECIFIER_INT:
2964 atomic_type = ATOMIC_TYPE_INT;
2966 case SPECIFIER_UNSIGNED:
2967 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2968 atomic_type = ATOMIC_TYPE_UINT;
2970 case SPECIFIER_LONG:
2971 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2972 case SPECIFIER_LONG | SPECIFIER_INT:
2973 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2974 atomic_type = ATOMIC_TYPE_LONG;
2976 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2977 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2978 atomic_type = ATOMIC_TYPE_ULONG;
2981 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2982 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2983 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2984 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2986 atomic_type = ATOMIC_TYPE_LONGLONG;
2987 goto warn_about_long_long;
2989 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2990 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2992 atomic_type = ATOMIC_TYPE_ULONGLONG;
2993 warn_about_long_long:
2994 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2997 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2998 atomic_type = unsigned_int8_type_kind;
3001 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3002 atomic_type = unsigned_int16_type_kind;
3005 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3006 atomic_type = unsigned_int32_type_kind;
3009 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3010 atomic_type = unsigned_int64_type_kind;
3013 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3014 atomic_type = unsigned_int128_type_kind;
3017 case SPECIFIER_INT8:
3018 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3019 atomic_type = int8_type_kind;
3022 case SPECIFIER_INT16:
3023 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3024 atomic_type = int16_type_kind;
3027 case SPECIFIER_INT32:
3028 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3029 atomic_type = int32_type_kind;
3032 case SPECIFIER_INT64:
3033 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3034 atomic_type = int64_type_kind;
3037 case SPECIFIER_INT128:
3038 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3039 atomic_type = int128_type_kind;
3042 case SPECIFIER_FLOAT:
3043 atomic_type = ATOMIC_TYPE_FLOAT;
3045 case SPECIFIER_DOUBLE:
3046 atomic_type = ATOMIC_TYPE_DOUBLE;
3048 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3049 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3051 case SPECIFIER_BOOL:
3052 atomic_type = ATOMIC_TYPE_BOOL;
3054 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3055 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3056 atomic_type = ATOMIC_TYPE_FLOAT;
3058 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3059 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3060 atomic_type = ATOMIC_TYPE_DOUBLE;
3062 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3063 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3064 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3067 /* invalid specifier combination, give an error message */
3068 source_position_t const* const pos = &specifiers->source_position;
3069 if (type_specifiers == 0) {
3071 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3072 if (!(c_mode & _CXX) && !strict_mode) {
3073 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3074 atomic_type = ATOMIC_TYPE_INT;
3077 errorf(pos, "no type specifiers given in declaration");
3080 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3081 (type_specifiers & SPECIFIER_UNSIGNED)) {
3082 errorf(pos, "signed and unsigned specifiers given");
3083 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3084 errorf(pos, "only integer types can be signed or unsigned");
3086 errorf(pos, "multiple datatypes in declaration");
3092 if (type_specifiers & SPECIFIER_COMPLEX) {
3093 type = allocate_type_zero(TYPE_COMPLEX);
3094 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3095 type = allocate_type_zero(TYPE_IMAGINARY);
3097 type = allocate_type_zero(TYPE_ATOMIC);
3099 type->atomic.akind = atomic_type;
3101 } else if (type_specifiers != 0) {
3102 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3105 /* FIXME: check type qualifiers here */
3106 type->base.qualifiers = qualifiers;
3109 type = identify_new_type(type);
3111 type = typehash_insert(type);
3114 if (specifiers->attributes != NULL)
3115 type = handle_type_attributes(specifiers->attributes, type);
3116 specifiers->type = type;
3120 specifiers->type = type_error_type;
3123 static type_qualifiers_t parse_type_qualifiers(void)
3125 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3128 switch (token.kind) {
3129 /* type qualifiers */
3130 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3131 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3132 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3133 /* microsoft extended type modifiers */
3134 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3135 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3136 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3137 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3138 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3147 * Parses an K&R identifier list
3149 static void parse_identifier_list(scope_t *scope)
3151 assert(token.kind == T_IDENTIFIER);
3153 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol);
3154 entity->base.source_position = token.base.source_position;
3155 /* a K&R parameter has no type, yet */
3159 append_entity(scope, entity);
3160 } while (next_if(',') && token.kind == T_IDENTIFIER);
3163 static entity_t *parse_parameter(void)
3165 declaration_specifiers_t specifiers;
3166 parse_declaration_specifiers(&specifiers);
3168 entity_t *entity = parse_declarator(&specifiers,
3169 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3170 anonymous_entity = NULL;
3174 static void semantic_parameter_incomplete(const entity_t *entity)
3176 assert(entity->kind == ENTITY_PARAMETER);
3178 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3179 * list in a function declarator that is part of a
3180 * definition of that function shall not have
3181 * incomplete type. */
3182 type_t *type = skip_typeref(entity->declaration.type);
3183 if (is_type_incomplete(type)) {
3184 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3188 static bool has_parameters(void)
3190 /* func(void) is not a parameter */
3191 if (look_ahead(1)->kind != ')')
3193 if (token.kind == T_IDENTIFIER) {
3194 entity_t const *const entity
3195 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3198 if (entity->kind != ENTITY_TYPEDEF)
3200 type_t const *const type = skip_typeref(entity->typedefe.type);
3201 if (!is_type_void(type))
3203 if (c_mode & _CXX) {
3204 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3205 * is not allowed. */
3206 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3207 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3208 /* §6.7.5.3:10 Qualification is not allowed here. */
3209 errorf(HERE, "'void' as parameter must not have type qualifiers");
3211 } else if (token.kind != T_void) {
3219 * Parses function type parameters (and optionally creates variable_t entities
3220 * for them in a scope)
3222 static void parse_parameters(function_type_t *type, scope_t *scope)
3225 add_anchor_token(')');
3226 int saved_comma_state = save_and_reset_anchor_state(',');
3228 if (token.kind == T_IDENTIFIER
3229 && !is_typedef_symbol(token.identifier.symbol)) {
3230 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3231 if (la1_type == ',' || la1_type == ')') {
3232 type->kr_style_parameters = true;
3233 parse_identifier_list(scope);
3234 goto parameters_finished;
3238 if (token.kind == ')') {
3239 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3240 if (!(c_mode & _CXX))
3241 type->unspecified_parameters = true;
3242 } else if (has_parameters()) {
3243 function_parameter_t **anchor = &type->parameters;
3245 switch (token.kind) {
3248 type->variadic = true;
3249 goto parameters_finished;
3254 entity_t *entity = parse_parameter();
3255 if (entity->kind == ENTITY_TYPEDEF) {
3256 errorf(&entity->base.source_position,
3257 "typedef not allowed as function parameter");
3260 assert(is_declaration(entity));
3262 semantic_parameter_incomplete(entity);
3264 function_parameter_t *const parameter =
3265 allocate_parameter(entity->declaration.type);
3267 if (scope != NULL) {
3268 append_entity(scope, entity);
3271 *anchor = parameter;
3272 anchor = ¶meter->next;
3277 goto parameters_finished;
3279 } while (next_if(','));
3282 parameters_finished:
3283 rem_anchor_token(')');
3284 expect(')', end_error);
3287 restore_anchor_state(',', saved_comma_state);
3290 typedef enum construct_type_kind_t {
3291 CONSTRUCT_POINTER = 1,
3292 CONSTRUCT_REFERENCE,
3295 } construct_type_kind_t;
3297 typedef union construct_type_t construct_type_t;
3299 typedef struct construct_type_base_t {
3300 construct_type_kind_t kind;
3301 source_position_t pos;
3302 construct_type_t *next;
3303 } construct_type_base_t;
3305 typedef struct parsed_pointer_t {
3306 construct_type_base_t base;
3307 type_qualifiers_t type_qualifiers;
3308 variable_t *base_variable; /**< MS __based extension. */
3311 typedef struct parsed_reference_t {
3312 construct_type_base_t base;
3313 } parsed_reference_t;
3315 typedef struct construct_function_type_t {
3316 construct_type_base_t base;
3317 type_t *function_type;
3318 } construct_function_type_t;
3320 typedef struct parsed_array_t {
3321 construct_type_base_t base;
3322 type_qualifiers_t type_qualifiers;
3328 union construct_type_t {
3329 construct_type_kind_t kind;
3330 construct_type_base_t base;
3331 parsed_pointer_t pointer;
3332 parsed_reference_t reference;
3333 construct_function_type_t function;
3334 parsed_array_t array;
3337 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3339 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3340 memset(cons, 0, size);
3342 cons->base.pos = *HERE;
3347 static construct_type_t *parse_pointer_declarator(void)
3349 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3351 cons->pointer.type_qualifiers = parse_type_qualifiers();
3352 //cons->pointer.base_variable = base_variable;
3357 /* ISO/IEC 14882:1998(E) §8.3.2 */
3358 static construct_type_t *parse_reference_declarator(void)
3360 if (!(c_mode & _CXX))
3361 errorf(HERE, "references are only available for C++");
3363 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3370 static construct_type_t *parse_array_declarator(void)
3372 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3373 parsed_array_t *const array = &cons->array;
3376 add_anchor_token(']');
3378 bool is_static = next_if(T_static);
3380 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3383 is_static = next_if(T_static);
3385 array->type_qualifiers = type_qualifiers;
3386 array->is_static = is_static;
3388 expression_t *size = NULL;
3389 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3390 array->is_variable = true;
3392 } else if (token.kind != ']') {
3393 size = parse_assignment_expression();
3395 /* §6.7.5.2:1 Array size must have integer type */
3396 type_t *const orig_type = size->base.type;
3397 type_t *const type = skip_typeref(orig_type);
3398 if (!is_type_integer(type) && is_type_valid(type)) {
3399 errorf(&size->base.source_position,
3400 "array size '%E' must have integer type but has type '%T'",
3405 mark_vars_read(size, NULL);
3408 if (is_static && size == NULL)
3409 errorf(&array->base.pos, "static array parameters require a size");
3411 rem_anchor_token(']');
3412 expect(']', end_error);
3419 static construct_type_t *parse_function_declarator(scope_t *scope)
3421 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3423 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3424 function_type_t *ftype = &type->function;
3426 ftype->linkage = current_linkage;
3427 ftype->calling_convention = CC_DEFAULT;
3429 parse_parameters(ftype, scope);
3431 cons->function.function_type = type;
3436 typedef struct parse_declarator_env_t {
3437 bool may_be_abstract : 1;
3438 bool must_be_abstract : 1;
3439 decl_modifiers_t modifiers;
3441 source_position_t source_position;
3443 attribute_t *attributes;
3444 } parse_declarator_env_t;
3447 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3449 /* construct a single linked list of construct_type_t's which describe
3450 * how to construct the final declarator type */
3451 construct_type_t *first = NULL;
3452 construct_type_t **anchor = &first;
3454 env->attributes = parse_attributes(env->attributes);
3457 construct_type_t *type;
3458 //variable_t *based = NULL; /* MS __based extension */
3459 switch (token.kind) {
3461 type = parse_reference_declarator();
3465 panic("based not supported anymore");
3470 type = parse_pointer_declarator();
3474 goto ptr_operator_end;
3478 anchor = &type->base.next;
3480 /* TODO: find out if this is correct */
3481 env->attributes = parse_attributes(env->attributes);
3485 construct_type_t *inner_types = NULL;
3487 switch (token.kind) {
3489 if (env->must_be_abstract) {
3490 errorf(HERE, "no identifier expected in typename");
3492 env->symbol = token.identifier.symbol;
3493 env->source_position = token.base.source_position;
3499 /* Parenthesized declarator or function declarator? */
3500 token_t const *const la1 = look_ahead(1);
3501 switch (la1->kind) {
3503 if (is_typedef_symbol(la1->identifier.symbol)) {
3505 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3506 * interpreted as ``function with no parameter specification'', rather
3507 * than redundant parentheses around the omitted identifier. */
3509 /* Function declarator. */
3510 if (!env->may_be_abstract) {
3511 errorf(HERE, "function declarator must have a name");
3518 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3519 /* Paranthesized declarator. */
3521 add_anchor_token(')');
3522 inner_types = parse_inner_declarator(env);
3523 if (inner_types != NULL) {
3524 /* All later declarators only modify the return type */
3525 env->must_be_abstract = true;
3527 rem_anchor_token(')');
3528 expect(')', end_error);
3536 if (env->may_be_abstract)
3538 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3543 construct_type_t **const p = anchor;
3546 construct_type_t *type;
3547 switch (token.kind) {
3549 scope_t *scope = NULL;
3550 if (!env->must_be_abstract) {
3551 scope = &env->parameters;
3554 type = parse_function_declarator(scope);
3558 type = parse_array_declarator();
3561 goto declarator_finished;
3564 /* insert in the middle of the list (at p) */
3565 type->base.next = *p;
3568 anchor = &type->base.next;
3571 declarator_finished:
3572 /* append inner_types at the end of the list, we don't to set anchor anymore
3573 * as it's not needed anymore */
3574 *anchor = inner_types;
3581 static type_t *construct_declarator_type(construct_type_t *construct_list,
3584 construct_type_t *iter = construct_list;
3585 for (; iter != NULL; iter = iter->base.next) {
3586 source_position_t const* const pos = &iter->base.pos;
3587 switch (iter->kind) {
3588 case CONSTRUCT_FUNCTION: {
3589 construct_function_type_t *function = &iter->function;
3590 type_t *function_type = function->function_type;
3592 function_type->function.return_type = type;
3594 type_t *skipped_return_type = skip_typeref(type);
3596 if (is_type_function(skipped_return_type)) {
3597 errorf(pos, "function returning function is not allowed");
3598 } else if (is_type_array(skipped_return_type)) {
3599 errorf(pos, "function returning array is not allowed");
3601 if (skipped_return_type->base.qualifiers != 0) {
3602 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3606 /* The function type was constructed earlier. Freeing it here will
3607 * destroy other types. */
3608 type = typehash_insert(function_type);
3612 case CONSTRUCT_POINTER: {
3613 if (is_type_reference(skip_typeref(type)))
3614 errorf(pos, "cannot declare a pointer to reference");
3616 parsed_pointer_t *pointer = &iter->pointer;
3617 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3621 case CONSTRUCT_REFERENCE:
3622 if (is_type_reference(skip_typeref(type)))
3623 errorf(pos, "cannot declare a reference to reference");
3625 type = make_reference_type(type);
3628 case CONSTRUCT_ARRAY: {
3629 if (is_type_reference(skip_typeref(type)))
3630 errorf(pos, "cannot declare an array of references");
3632 parsed_array_t *array = &iter->array;
3633 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3635 expression_t *size_expression = array->size;
3636 if (size_expression != NULL) {
3638 = create_implicit_cast(size_expression, type_size_t);
3641 array_type->base.qualifiers = array->type_qualifiers;
3642 array_type->array.element_type = type;
3643 array_type->array.is_static = array->is_static;
3644 array_type->array.is_variable = array->is_variable;
3645 array_type->array.size_expression = size_expression;
3647 if (size_expression != NULL) {
3648 switch (is_constant_expression(size_expression)) {
3649 case EXPR_CLASS_CONSTANT: {
3650 long const size = fold_constant_to_int(size_expression);
3651 array_type->array.size = size;
3652 array_type->array.size_constant = true;
3653 /* §6.7.5.2:1 If the expression is a constant expression,
3654 * it shall have a value greater than zero. */
3656 errorf(&size_expression->base.source_position,
3657 "size of array must be greater than zero");
3658 } else if (size == 0 && !GNU_MODE) {
3659 errorf(&size_expression->base.source_position,
3660 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3665 case EXPR_CLASS_VARIABLE:
3666 array_type->array.is_vla = true;
3669 case EXPR_CLASS_ERROR:
3674 type_t *skipped_type = skip_typeref(type);
3676 if (is_type_incomplete(skipped_type)) {
3677 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3678 } else if (is_type_function(skipped_type)) {
3679 errorf(pos, "array of functions is not allowed");
3681 type = identify_new_type(array_type);
3685 internal_errorf(pos, "invalid type construction found");
3691 static type_t *automatic_type_conversion(type_t *orig_type);
3693 static type_t *semantic_parameter(const source_position_t *pos,
3695 const declaration_specifiers_t *specifiers,
3696 entity_t const *const param)
3698 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3699 * shall be adjusted to ``qualified pointer to type'',
3701 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3702 * type'' shall be adjusted to ``pointer to function
3703 * returning type'', as in 6.3.2.1. */
3704 type = automatic_type_conversion(type);
3706 if (specifiers->is_inline && is_type_valid(type)) {
3707 errorf(pos, "'%N' declared 'inline'", param);
3710 /* §6.9.1:6 The declarations in the declaration list shall contain
3711 * no storage-class specifier other than register and no
3712 * initializations. */
3713 if (specifiers->thread_local || (
3714 specifiers->storage_class != STORAGE_CLASS_NONE &&
3715 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3717 errorf(pos, "invalid storage class for '%N'", param);
3720 /* delay test for incomplete type, because we might have (void)
3721 * which is legal but incomplete... */
3726 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3727 declarator_flags_t flags)
3729 parse_declarator_env_t env;
3730 memset(&env, 0, sizeof(env));
3731 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3733 construct_type_t *construct_type = parse_inner_declarator(&env);
3735 construct_declarator_type(construct_type, specifiers->type);
3736 type_t *type = skip_typeref(orig_type);
3738 if (construct_type != NULL) {
3739 obstack_free(&temp_obst, construct_type);
3742 attribute_t *attributes = parse_attributes(env.attributes);
3743 /* append (shared) specifier attribute behind attributes of this
3745 attribute_t **anchor = &attributes;
3746 while (*anchor != NULL)
3747 anchor = &(*anchor)->next;
3748 *anchor = specifiers->attributes;
3751 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3752 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3753 entity->base.source_position = env.source_position;
3754 entity->typedefe.type = orig_type;
3756 if (anonymous_entity != NULL) {
3757 if (is_type_compound(type)) {
3758 assert(anonymous_entity->compound.alias == NULL);
3759 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3760 anonymous_entity->kind == ENTITY_UNION);
3761 anonymous_entity->compound.alias = entity;
3762 anonymous_entity = NULL;
3763 } else if (is_type_enum(type)) {
3764 assert(anonymous_entity->enume.alias == NULL);
3765 assert(anonymous_entity->kind == ENTITY_ENUM);
3766 anonymous_entity->enume.alias = entity;
3767 anonymous_entity = NULL;
3771 /* create a declaration type entity */
3772 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3773 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3775 if (env.symbol != NULL) {
3776 if (specifiers->is_inline && is_type_valid(type)) {
3777 errorf(&env.source_position,
3778 "compound member '%Y' declared 'inline'", env.symbol);
3781 if (specifiers->thread_local ||
3782 specifiers->storage_class != STORAGE_CLASS_NONE) {
3783 errorf(&env.source_position,
3784 "compound member '%Y' must have no storage class",
3788 } else if (flags & DECL_IS_PARAMETER) {
3789 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3790 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3791 } else if (is_type_function(type)) {
3792 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3793 entity->function.is_inline = specifiers->is_inline;
3794 entity->function.elf_visibility = default_visibility;
3795 entity->function.parameters = env.parameters;
3797 if (env.symbol != NULL) {
3798 /* this needs fixes for C++ */
3799 bool in_function_scope = current_function != NULL;
3801 if (specifiers->thread_local || (
3802 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3803 specifiers->storage_class != STORAGE_CLASS_NONE &&
3804 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3806 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3810 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3811 entity->variable.elf_visibility = default_visibility;
3812 entity->variable.thread_local = specifiers->thread_local;
3814 if (env.symbol != NULL) {
3815 if (specifiers->is_inline && is_type_valid(type)) {
3816 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3819 bool invalid_storage_class = false;
3820 if (current_scope == file_scope) {
3821 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3822 specifiers->storage_class != STORAGE_CLASS_NONE &&
3823 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3824 invalid_storage_class = true;
3827 if (specifiers->thread_local &&
3828 specifiers->storage_class == STORAGE_CLASS_NONE) {
3829 invalid_storage_class = true;
3832 if (invalid_storage_class) {
3833 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3838 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3839 entity->declaration.type = orig_type;
3840 entity->declaration.alignment = get_type_alignment(orig_type);
3841 entity->declaration.modifiers = env.modifiers;
3842 entity->declaration.attributes = attributes;
3844 storage_class_t storage_class = specifiers->storage_class;
3845 entity->declaration.declared_storage_class = storage_class;
3847 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3848 storage_class = STORAGE_CLASS_AUTO;
3849 entity->declaration.storage_class = storage_class;
3852 if (attributes != NULL) {
3853 handle_entity_attributes(attributes, entity);
3856 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3857 adapt_special_functions(&entity->function);
3863 static type_t *parse_abstract_declarator(type_t *base_type)
3865 parse_declarator_env_t env;
3866 memset(&env, 0, sizeof(env));
3867 env.may_be_abstract = true;
3868 env.must_be_abstract = true;
3870 construct_type_t *construct_type = parse_inner_declarator(&env);
3872 type_t *result = construct_declarator_type(construct_type, base_type);
3873 if (construct_type != NULL) {
3874 obstack_free(&temp_obst, construct_type);
3876 result = handle_type_attributes(env.attributes, result);
3882 * Check if the declaration of main is suspicious. main should be a
3883 * function with external linkage, returning int, taking either zero
3884 * arguments, two, or three arguments of appropriate types, ie.
3886 * int main([ int argc, char **argv [, char **env ] ]).
3888 * @param decl the declaration to check
3889 * @param type the function type of the declaration
3891 static void check_main(const entity_t *entity)
3893 const source_position_t *pos = &entity->base.source_position;
3894 if (entity->kind != ENTITY_FUNCTION) {
3895 warningf(WARN_MAIN, pos, "'main' is not a function");
3899 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3900 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3903 type_t *type = skip_typeref(entity->declaration.type);
3904 assert(is_type_function(type));
3906 function_type_t const *const func_type = &type->function;
3907 type_t *const ret_type = func_type->return_type;
3908 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3909 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3911 const function_parameter_t *parm = func_type->parameters;
3913 type_t *const first_type = skip_typeref(parm->type);
3914 type_t *const first_type_unqual = get_unqualified_type(first_type);
3915 if (!types_compatible(first_type_unqual, type_int)) {
3916 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3920 type_t *const second_type = skip_typeref(parm->type);
3921 type_t *const second_type_unqual
3922 = get_unqualified_type(second_type);
3923 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3924 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3928 type_t *const third_type = skip_typeref(parm->type);
3929 type_t *const third_type_unqual
3930 = get_unqualified_type(third_type);
3931 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3932 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3936 goto warn_arg_count;
3940 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3946 * Check if a symbol is the equal to "main".
3948 static bool is_sym_main(const symbol_t *const sym)
3950 return streq(sym->string, "main");
3953 static void error_redefined_as_different_kind(const source_position_t *pos,
3954 const entity_t *old, entity_kind_t new_kind)
3956 char const *const what = get_entity_kind_name(new_kind);
3957 source_position_t const *const ppos = &old->base.source_position;
3958 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3961 static bool is_entity_valid(entity_t *const ent)
3963 if (is_declaration(ent)) {
3964 return is_type_valid(skip_typeref(ent->declaration.type));
3965 } else if (ent->kind == ENTITY_TYPEDEF) {
3966 return is_type_valid(skip_typeref(ent->typedefe.type));
3971 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3973 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3974 if (attributes_equal(tattr, attr))
3981 * test wether new_list contains any attributes not included in old_list
3983 static bool has_new_attributes(const attribute_t *old_list,
3984 const attribute_t *new_list)
3986 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3987 if (!contains_attribute(old_list, attr))
3994 * Merge in attributes from an attribute list (probably from a previous
3995 * declaration with the same name). Warning: destroys the old structure
3996 * of the attribute list - don't reuse attributes after this call.
3998 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4001 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4003 if (contains_attribute(decl->attributes, attr))
4006 /* move attribute to new declarations attributes list */
4007 attr->next = decl->attributes;
4008 decl->attributes = attr;
4013 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4014 * for various problems that occur for multiple definitions
4016 entity_t *record_entity(entity_t *entity, const bool is_definition)
4018 const symbol_t *const symbol = entity->base.symbol;
4019 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4020 const source_position_t *pos = &entity->base.source_position;
4022 /* can happen in error cases */
4026 entity_t *const previous_entity = get_entity(symbol, namespc);
4027 /* pushing the same entity twice will break the stack structure */
4028 assert(previous_entity != entity);
4030 if (entity->kind == ENTITY_FUNCTION) {
4031 type_t *const orig_type = entity->declaration.type;
4032 type_t *const type = skip_typeref(orig_type);
4034 assert(is_type_function(type));
4035 if (type->function.unspecified_parameters &&
4036 previous_entity == NULL &&
4037 !entity->declaration.implicit) {
4038 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4041 if (current_scope == file_scope && is_sym_main(symbol)) {
4046 if (is_declaration(entity) &&
4047 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4048 current_scope != file_scope &&
4049 !entity->declaration.implicit) {
4050 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4053 if (previous_entity != NULL) {
4054 source_position_t const *const ppos = &previous_entity->base.source_position;
4056 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4057 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4058 assert(previous_entity->kind == ENTITY_PARAMETER);
4059 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4063 if (previous_entity->base.parent_scope == current_scope) {
4064 if (previous_entity->kind != entity->kind) {
4065 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4066 error_redefined_as_different_kind(pos, previous_entity,
4071 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4072 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4075 if (previous_entity->kind == ENTITY_TYPEDEF) {
4076 type_t *const type = skip_typeref(entity->typedefe.type);
4077 type_t *const prev_type
4078 = skip_typeref(previous_entity->typedefe.type);
4079 if (c_mode & _CXX) {
4080 /* C++ allows double typedef if they are identical
4081 * (after skipping typedefs) */
4082 if (type == prev_type)
4085 /* GCC extension: redef in system headers is allowed */
4086 if ((pos->is_system_header || ppos->is_system_header) &&
4087 types_compatible(type, prev_type))
4090 errorf(pos, "redefinition of '%N' (declared %P)",
4095 /* at this point we should have only VARIABLES or FUNCTIONS */
4096 assert(is_declaration(previous_entity) && is_declaration(entity));
4098 declaration_t *const prev_decl = &previous_entity->declaration;
4099 declaration_t *const decl = &entity->declaration;
4101 /* can happen for K&R style declarations */
4102 if (prev_decl->type == NULL &&
4103 previous_entity->kind == ENTITY_PARAMETER &&
4104 entity->kind == ENTITY_PARAMETER) {
4105 prev_decl->type = decl->type;
4106 prev_decl->storage_class = decl->storage_class;
4107 prev_decl->declared_storage_class = decl->declared_storage_class;
4108 prev_decl->modifiers = decl->modifiers;
4109 return previous_entity;
4112 type_t *const type = skip_typeref(decl->type);
4113 type_t *const prev_type = skip_typeref(prev_decl->type);
4115 if (!types_compatible(type, prev_type)) {
4116 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4118 unsigned old_storage_class = prev_decl->storage_class;
4120 if (is_definition &&
4122 !(prev_decl->modifiers & DM_USED) &&
4123 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4124 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4127 storage_class_t new_storage_class = decl->storage_class;
4129 /* pretend no storage class means extern for function
4130 * declarations (except if the previous declaration is neither
4131 * none nor extern) */
4132 if (entity->kind == ENTITY_FUNCTION) {
4133 /* the previous declaration could have unspecified parameters or
4134 * be a typedef, so use the new type */
4135 if (prev_type->function.unspecified_parameters || is_definition)
4136 prev_decl->type = type;
4138 switch (old_storage_class) {
4139 case STORAGE_CLASS_NONE:
4140 old_storage_class = STORAGE_CLASS_EXTERN;
4143 case STORAGE_CLASS_EXTERN:
4144 if (is_definition) {
4145 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4146 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4148 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4149 new_storage_class = STORAGE_CLASS_EXTERN;
4156 } else if (is_type_incomplete(prev_type)) {
4157 prev_decl->type = type;
4160 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4161 new_storage_class == STORAGE_CLASS_EXTERN) {
4163 warn_redundant_declaration: ;
4165 = has_new_attributes(prev_decl->attributes,
4167 if (has_new_attrs) {
4168 merge_in_attributes(decl, prev_decl->attributes);
4169 } else if (!is_definition &&
4170 is_type_valid(prev_type) &&
4171 !pos->is_system_header) {
4172 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4174 } else if (current_function == NULL) {
4175 if (old_storage_class != STORAGE_CLASS_STATIC &&
4176 new_storage_class == STORAGE_CLASS_STATIC) {
4177 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4178 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4179 prev_decl->storage_class = STORAGE_CLASS_NONE;
4180 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4182 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4184 goto error_redeclaration;
4185 goto warn_redundant_declaration;
4187 } else if (is_type_valid(prev_type)) {
4188 if (old_storage_class == new_storage_class) {
4189 error_redeclaration:
4190 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4192 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4197 prev_decl->modifiers |= decl->modifiers;
4198 if (entity->kind == ENTITY_FUNCTION) {
4199 previous_entity->function.is_inline |= entity->function.is_inline;
4201 return previous_entity;
4205 if (is_warn_on(why = WARN_SHADOW) ||
4206 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4207 char const *const what = get_entity_kind_name(previous_entity->kind);
4208 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4212 if (entity->kind == ENTITY_FUNCTION) {
4213 if (is_definition &&
4214 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4215 !is_sym_main(symbol)) {
4216 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4217 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4219 goto warn_missing_declaration;
4222 } else if (entity->kind == ENTITY_VARIABLE) {
4223 if (current_scope == file_scope &&
4224 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4225 !entity->declaration.implicit) {
4226 warn_missing_declaration:
4227 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4232 assert(entity->base.parent_scope == NULL);
4233 assert(current_scope != NULL);
4235 entity->base.parent_scope = current_scope;
4236 environment_push(entity);
4237 append_entity(current_scope, entity);
4242 static void parser_error_multiple_definition(entity_t *entity,
4243 const source_position_t *source_position)
4245 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4246 entity->base.symbol, &entity->base.source_position);
4249 static bool is_declaration_specifier(const token_t *token)
4251 switch (token->kind) {
4255 return is_typedef_symbol(token->identifier.symbol);
4262 static void parse_init_declarator_rest(entity_t *entity)
4264 type_t *orig_type = type_error_type;
4266 if (entity->base.kind == ENTITY_TYPEDEF) {
4267 source_position_t const *const pos = &entity->base.source_position;
4268 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4270 assert(is_declaration(entity));
4271 orig_type = entity->declaration.type;
4274 type_t *type = skip_typeref(orig_type);
4276 if (entity->kind == ENTITY_VARIABLE
4277 && entity->variable.initializer != NULL) {
4278 parser_error_multiple_definition(entity, HERE);
4282 declaration_t *const declaration = &entity->declaration;
4283 bool must_be_constant = false;
4284 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4285 entity->base.parent_scope == file_scope) {
4286 must_be_constant = true;
4289 if (is_type_function(type)) {
4290 source_position_t const *const pos = &entity->base.source_position;
4291 errorf(pos, "'%N' is initialized like a variable", entity);
4292 orig_type = type_error_type;
4295 parse_initializer_env_t env;
4296 env.type = orig_type;
4297 env.must_be_constant = must_be_constant;
4298 env.entity = entity;
4300 initializer_t *initializer = parse_initializer(&env);
4302 if (entity->kind == ENTITY_VARIABLE) {
4303 /* §6.7.5:22 array initializers for arrays with unknown size
4304 * determine the array type size */
4305 declaration->type = env.type;
4306 entity->variable.initializer = initializer;
4310 /* parse rest of a declaration without any declarator */
4311 static void parse_anonymous_declaration_rest(
4312 const declaration_specifiers_t *specifiers)
4315 anonymous_entity = NULL;
4317 source_position_t const *const pos = &specifiers->source_position;
4318 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4319 specifiers->thread_local) {
4320 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4323 type_t *type = specifiers->type;
4324 switch (type->kind) {
4325 case TYPE_COMPOUND_STRUCT:
4326 case TYPE_COMPOUND_UNION: {
4327 if (type->compound.compound->base.symbol == NULL) {
4328 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4337 warningf(WARN_OTHER, pos, "empty declaration");
4342 static void check_variable_type_complete(entity_t *ent)
4344 if (ent->kind != ENTITY_VARIABLE)
4347 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4348 * type for the object shall be complete [...] */
4349 declaration_t *decl = &ent->declaration;
4350 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4351 decl->storage_class == STORAGE_CLASS_STATIC)
4354 type_t *const type = skip_typeref(decl->type);
4355 if (!is_type_incomplete(type))
4358 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4359 * are given length one. */
4360 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4361 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4365 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4369 static void parse_declaration_rest(entity_t *ndeclaration,
4370 const declaration_specifiers_t *specifiers,
4371 parsed_declaration_func finished_declaration,
4372 declarator_flags_t flags)
4374 add_anchor_token(';');
4375 add_anchor_token(',');
4377 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4379 if (token.kind == '=') {
4380 parse_init_declarator_rest(entity);
4381 } else if (entity->kind == ENTITY_VARIABLE) {
4382 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4383 * [...] where the extern specifier is explicitly used. */
4384 declaration_t *decl = &entity->declaration;
4385 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4386 is_type_reference(skip_typeref(decl->type))) {
4387 source_position_t const *const pos = &entity->base.source_position;
4388 errorf(pos, "reference '%#N' must be initialized", entity);
4392 check_variable_type_complete(entity);
4397 add_anchor_token('=');
4398 ndeclaration = parse_declarator(specifiers, flags);
4399 rem_anchor_token('=');
4401 rem_anchor_token(',');
4402 rem_anchor_token(';');
4403 expect(';', end_error);
4406 anonymous_entity = NULL;
4409 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4411 symbol_t *symbol = entity->base.symbol;
4415 assert(entity->base.namespc == NAMESPACE_NORMAL);
4416 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4417 if (previous_entity == NULL
4418 || previous_entity->base.parent_scope != current_scope) {
4419 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4424 if (is_definition) {
4425 errorf(HERE, "'%N' is initialised", entity);
4428 return record_entity(entity, false);
4431 static void parse_declaration(parsed_declaration_func finished_declaration,
4432 declarator_flags_t flags)
4434 add_anchor_token(';');
4435 declaration_specifiers_t specifiers;
4436 parse_declaration_specifiers(&specifiers);
4437 rem_anchor_token(';');
4439 if (token.kind == ';') {
4440 parse_anonymous_declaration_rest(&specifiers);
4442 entity_t *entity = parse_declarator(&specifiers, flags);
4443 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4448 static type_t *get_default_promoted_type(type_t *orig_type)
4450 type_t *result = orig_type;
4452 type_t *type = skip_typeref(orig_type);
4453 if (is_type_integer(type)) {
4454 result = promote_integer(type);
4455 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4456 result = type_double;
4462 static void parse_kr_declaration_list(entity_t *entity)
4464 if (entity->kind != ENTITY_FUNCTION)
4467 type_t *type = skip_typeref(entity->declaration.type);
4468 assert(is_type_function(type));
4469 if (!type->function.kr_style_parameters)
4472 add_anchor_token('{');
4474 PUSH_SCOPE(&entity->function.parameters);
4476 entity_t *parameter = entity->function.parameters.entities;
4477 for ( ; parameter != NULL; parameter = parameter->base.next) {
4478 assert(parameter->base.parent_scope == NULL);
4479 parameter->base.parent_scope = current_scope;
4480 environment_push(parameter);
4483 /* parse declaration list */
4485 switch (token.kind) {
4487 /* This covers symbols, which are no type, too, and results in
4488 * better error messages. The typical cases are misspelled type
4489 * names and missing includes. */
4491 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4501 /* update function type */
4502 type_t *new_type = duplicate_type(type);
4504 function_parameter_t *parameters = NULL;
4505 function_parameter_t **anchor = ¶meters;
4507 /* did we have an earlier prototype? */
4508 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4509 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4512 function_parameter_t *proto_parameter = NULL;
4513 if (proto_type != NULL) {
4514 type_t *proto_type_type = proto_type->declaration.type;
4515 proto_parameter = proto_type_type->function.parameters;
4516 /* If a K&R function definition has a variadic prototype earlier, then
4517 * make the function definition variadic, too. This should conform to
4518 * §6.7.5.3:15 and §6.9.1:8. */
4519 new_type->function.variadic = proto_type_type->function.variadic;
4521 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4523 new_type->function.unspecified_parameters = true;
4526 bool need_incompatible_warning = false;
4527 parameter = entity->function.parameters.entities;
4528 for (; parameter != NULL; parameter = parameter->base.next,
4530 proto_parameter == NULL ? NULL : proto_parameter->next) {
4531 if (parameter->kind != ENTITY_PARAMETER)
4534 type_t *parameter_type = parameter->declaration.type;
4535 if (parameter_type == NULL) {
4536 source_position_t const* const pos = ¶meter->base.source_position;
4538 errorf(pos, "no type specified for function '%N'", parameter);
4539 parameter_type = type_error_type;
4541 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4542 parameter_type = type_int;
4544 parameter->declaration.type = parameter_type;
4547 semantic_parameter_incomplete(parameter);
4549 /* we need the default promoted types for the function type */
4550 type_t *not_promoted = parameter_type;
4551 parameter_type = get_default_promoted_type(parameter_type);
4553 /* gcc special: if the type of the prototype matches the unpromoted
4554 * type don't promote */
4555 if (!strict_mode && proto_parameter != NULL) {
4556 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4557 type_t *promo_skip = skip_typeref(parameter_type);
4558 type_t *param_skip = skip_typeref(not_promoted);
4559 if (!types_compatible(proto_p_type, promo_skip)
4560 && types_compatible(proto_p_type, param_skip)) {
4562 need_incompatible_warning = true;
4563 parameter_type = not_promoted;
4566 function_parameter_t *const function_parameter
4567 = allocate_parameter(parameter_type);
4569 *anchor = function_parameter;
4570 anchor = &function_parameter->next;
4573 new_type->function.parameters = parameters;
4574 new_type = identify_new_type(new_type);
4576 if (need_incompatible_warning) {
4577 symbol_t const *const sym = entity->base.symbol;
4578 source_position_t const *const pos = &entity->base.source_position;
4579 source_position_t const *const ppos = &proto_type->base.source_position;
4580 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4582 entity->declaration.type = new_type;
4584 rem_anchor_token('{');
4587 static bool first_err = true;
4590 * When called with first_err set, prints the name of the current function,
4593 static void print_in_function(void)
4597 char const *const file = current_function->base.base.source_position.input_name;
4598 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4603 * Check if all labels are defined in the current function.
4604 * Check if all labels are used in the current function.
4606 static void check_labels(void)
4608 for (const goto_statement_t *goto_statement = goto_first;
4609 goto_statement != NULL;
4610 goto_statement = goto_statement->next) {
4611 label_t *label = goto_statement->label;
4612 if (label->base.source_position.input_name == NULL) {
4613 print_in_function();
4614 source_position_t const *const pos = &goto_statement->base.source_position;
4615 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4619 if (is_warn_on(WARN_UNUSED_LABEL)) {
4620 for (const label_statement_t *label_statement = label_first;
4621 label_statement != NULL;
4622 label_statement = label_statement->next) {
4623 label_t *label = label_statement->label;
4625 if (! label->used) {
4626 print_in_function();
4627 source_position_t const *const pos = &label_statement->base.source_position;
4628 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4634 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4636 entity_t const *const end = last != NULL ? last->base.next : NULL;
4637 for (; entity != end; entity = entity->base.next) {
4638 if (!is_declaration(entity))
4641 declaration_t *declaration = &entity->declaration;
4642 if (declaration->implicit)
4645 if (!declaration->used) {
4646 print_in_function();
4647 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4648 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4649 print_in_function();
4650 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4655 static void check_unused_variables(statement_t *const stmt, void *const env)
4659 switch (stmt->kind) {
4660 case STATEMENT_DECLARATION: {
4661 declaration_statement_t const *const decls = &stmt->declaration;
4662 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4667 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4676 * Check declarations of current_function for unused entities.
4678 static void check_declarations(void)
4680 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4681 const scope_t *scope = ¤t_function->parameters;
4683 /* do not issue unused warnings for main */
4684 if (!is_sym_main(current_function->base.base.symbol)) {
4685 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4688 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4689 walk_statements(current_function->statement, check_unused_variables,
4694 static int determine_truth(expression_t const* const cond)
4697 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4698 fold_constant_to_bool(cond) ? 1 :
4702 static void check_reachable(statement_t *);
4703 static bool reaches_end;
4705 static bool expression_returns(expression_t const *const expr)
4707 switch (expr->kind) {
4709 expression_t const *const func = expr->call.function;
4710 type_t const *const type = skip_typeref(func->base.type);
4711 if (type->kind == TYPE_POINTER) {
4712 type_t const *const points_to
4713 = skip_typeref(type->pointer.points_to);
4714 if (points_to->kind == TYPE_FUNCTION
4715 && points_to->function.modifiers & DM_NORETURN)
4719 if (!expression_returns(func))
4722 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4723 if (!expression_returns(arg->expression))
4730 case EXPR_REFERENCE:
4731 case EXPR_ENUM_CONSTANT:
4732 case EXPR_LITERAL_CASES:
4733 case EXPR_STRING_LITERAL:
4734 case EXPR_WIDE_STRING_LITERAL:
4735 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4736 case EXPR_LABEL_ADDRESS:
4737 case EXPR_CLASSIFY_TYPE:
4738 case EXPR_SIZEOF: // TODO handle obscure VLA case
4741 case EXPR_BUILTIN_CONSTANT_P:
4742 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4747 case EXPR_STATEMENT: {
4748 bool old_reaches_end = reaches_end;
4749 reaches_end = false;
4750 check_reachable(expr->statement.statement);
4751 bool returns = reaches_end;
4752 reaches_end = old_reaches_end;
4756 case EXPR_CONDITIONAL:
4757 // TODO handle constant expression
4759 if (!expression_returns(expr->conditional.condition))
4762 if (expr->conditional.true_expression != NULL
4763 && expression_returns(expr->conditional.true_expression))
4766 return expression_returns(expr->conditional.false_expression);
4769 return expression_returns(expr->select.compound);
4771 case EXPR_ARRAY_ACCESS:
4773 expression_returns(expr->array_access.array_ref) &&
4774 expression_returns(expr->array_access.index);
4777 return expression_returns(expr->va_starte.ap);
4780 return expression_returns(expr->va_arge.ap);
4783 return expression_returns(expr->va_copye.src);
4785 case EXPR_UNARY_CASES_MANDATORY:
4786 return expression_returns(expr->unary.value);
4788 case EXPR_UNARY_THROW:
4791 case EXPR_BINARY_CASES:
4792 // TODO handle constant lhs of && and ||
4794 expression_returns(expr->binary.left) &&
4795 expression_returns(expr->binary.right);
4798 panic("unhandled expression");
4801 static bool initializer_returns(initializer_t const *const init)
4803 switch (init->kind) {
4804 case INITIALIZER_VALUE:
4805 return expression_returns(init->value.value);
4807 case INITIALIZER_LIST: {
4808 initializer_t * const* i = init->list.initializers;
4809 initializer_t * const* const end = i + init->list.len;
4810 bool returns = true;
4811 for (; i != end; ++i) {
4812 if (!initializer_returns(*i))
4818 case INITIALIZER_STRING:
4819 case INITIALIZER_WIDE_STRING:
4820 case INITIALIZER_DESIGNATOR: // designators have no payload
4823 panic("unhandled initializer");
4826 static bool noreturn_candidate;
4828 static void check_reachable(statement_t *const stmt)
4830 if (stmt->base.reachable)
4832 if (stmt->kind != STATEMENT_DO_WHILE)
4833 stmt->base.reachable = true;
4835 statement_t *last = stmt;
4837 switch (stmt->kind) {
4838 case STATEMENT_ERROR:
4839 case STATEMENT_EMPTY:
4841 next = stmt->base.next;
4844 case STATEMENT_DECLARATION: {
4845 declaration_statement_t const *const decl = &stmt->declaration;
4846 entity_t const * ent = decl->declarations_begin;
4847 entity_t const *const last_decl = decl->declarations_end;
4849 for (;; ent = ent->base.next) {
4850 if (ent->kind == ENTITY_VARIABLE &&
4851 ent->variable.initializer != NULL &&
4852 !initializer_returns(ent->variable.initializer)) {
4855 if (ent == last_decl)
4859 next = stmt->base.next;
4863 case STATEMENT_COMPOUND:
4864 next = stmt->compound.statements;
4866 next = stmt->base.next;
4869 case STATEMENT_RETURN: {
4870 expression_t const *const val = stmt->returns.value;
4871 if (val == NULL || expression_returns(val))
4872 noreturn_candidate = false;
4876 case STATEMENT_IF: {
4877 if_statement_t const *const ifs = &stmt->ifs;
4878 expression_t const *const cond = ifs->condition;
4880 if (!expression_returns(cond))
4883 int const val = determine_truth(cond);
4886 check_reachable(ifs->true_statement);
4891 if (ifs->false_statement != NULL) {
4892 check_reachable(ifs->false_statement);
4896 next = stmt->base.next;
4900 case STATEMENT_SWITCH: {
4901 switch_statement_t const *const switchs = &stmt->switchs;
4902 expression_t const *const expr = switchs->expression;
4904 if (!expression_returns(expr))
4907 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4908 long const val = fold_constant_to_int(expr);
4909 case_label_statement_t * defaults = NULL;
4910 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4911 if (i->expression == NULL) {
4916 if (i->first_case <= val && val <= i->last_case) {
4917 check_reachable((statement_t*)i);
4922 if (defaults != NULL) {
4923 check_reachable((statement_t*)defaults);
4927 bool has_default = false;
4928 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4929 if (i->expression == NULL)
4932 check_reachable((statement_t*)i);
4939 next = stmt->base.next;
4943 case STATEMENT_EXPRESSION: {
4944 /* Check for noreturn function call */
4945 expression_t const *const expr = stmt->expression.expression;
4946 if (!expression_returns(expr))
4949 next = stmt->base.next;
4953 case STATEMENT_CONTINUE:
4954 for (statement_t *parent = stmt;;) {
4955 parent = parent->base.parent;
4956 if (parent == NULL) /* continue not within loop */
4960 switch (parent->kind) {
4961 case STATEMENT_WHILE: goto continue_while;
4962 case STATEMENT_DO_WHILE: goto continue_do_while;
4963 case STATEMENT_FOR: goto continue_for;
4969 case STATEMENT_BREAK:
4970 for (statement_t *parent = stmt;;) {
4971 parent = parent->base.parent;
4972 if (parent == NULL) /* break not within loop/switch */
4975 switch (parent->kind) {
4976 case STATEMENT_SWITCH:
4977 case STATEMENT_WHILE:
4978 case STATEMENT_DO_WHILE:
4981 next = parent->base.next;
4982 goto found_break_parent;
4990 case STATEMENT_COMPUTED_GOTO: {
4991 if (!expression_returns(stmt->computed_goto.expression))
4994 statement_t *parent = stmt->base.parent;
4995 if (parent == NULL) /* top level goto */
5001 case STATEMENT_GOTO:
5002 next = stmt->gotos.label->statement;
5003 if (next == NULL) /* missing label */
5007 case STATEMENT_LABEL:
5008 next = stmt->label.statement;
5011 case STATEMENT_CASE_LABEL:
5012 next = stmt->case_label.statement;
5015 case STATEMENT_WHILE: {
5016 while_statement_t const *const whiles = &stmt->whiles;
5017 expression_t const *const cond = whiles->condition;
5019 if (!expression_returns(cond))
5022 int const val = determine_truth(cond);
5025 check_reachable(whiles->body);
5030 next = stmt->base.next;
5034 case STATEMENT_DO_WHILE:
5035 next = stmt->do_while.body;
5038 case STATEMENT_FOR: {
5039 for_statement_t *const fors = &stmt->fors;
5041 if (fors->condition_reachable)
5043 fors->condition_reachable = true;
5045 expression_t const *const cond = fors->condition;
5050 } else if (expression_returns(cond)) {
5051 val = determine_truth(cond);
5057 check_reachable(fors->body);
5062 next = stmt->base.next;
5066 case STATEMENT_MS_TRY: {
5067 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5068 check_reachable(ms_try->try_statement);
5069 next = ms_try->final_statement;
5073 case STATEMENT_LEAVE: {
5074 statement_t *parent = stmt;
5076 parent = parent->base.parent;
5077 if (parent == NULL) /* __leave not within __try */
5080 if (parent->kind == STATEMENT_MS_TRY) {
5082 next = parent->ms_try.final_statement;
5090 panic("invalid statement kind");
5093 while (next == NULL) {
5094 next = last->base.parent;
5096 noreturn_candidate = false;
5098 type_t *const type = skip_typeref(current_function->base.type);
5099 assert(is_type_function(type));
5100 type_t *const ret = skip_typeref(type->function.return_type);
5101 if (!is_type_void(ret) &&
5102 is_type_valid(ret) &&
5103 !is_sym_main(current_function->base.base.symbol)) {
5104 source_position_t const *const pos = &stmt->base.source_position;
5105 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5110 switch (next->kind) {
5111 case STATEMENT_ERROR:
5112 case STATEMENT_EMPTY:
5113 case STATEMENT_DECLARATION:
5114 case STATEMENT_EXPRESSION:
5116 case STATEMENT_RETURN:
5117 case STATEMENT_CONTINUE:
5118 case STATEMENT_BREAK:
5119 case STATEMENT_COMPUTED_GOTO:
5120 case STATEMENT_GOTO:
5121 case STATEMENT_LEAVE:
5122 panic("invalid control flow in function");
5124 case STATEMENT_COMPOUND:
5125 if (next->compound.stmt_expr) {
5131 case STATEMENT_SWITCH:
5132 case STATEMENT_LABEL:
5133 case STATEMENT_CASE_LABEL:
5135 next = next->base.next;
5138 case STATEMENT_WHILE: {
5140 if (next->base.reachable)
5142 next->base.reachable = true;
5144 while_statement_t const *const whiles = &next->whiles;
5145 expression_t const *const cond = whiles->condition;
5147 if (!expression_returns(cond))
5150 int const val = determine_truth(cond);
5153 check_reachable(whiles->body);
5159 next = next->base.next;
5163 case STATEMENT_DO_WHILE: {
5165 if (next->base.reachable)
5167 next->base.reachable = true;
5169 do_while_statement_t const *const dw = &next->do_while;
5170 expression_t const *const cond = dw->condition;
5172 if (!expression_returns(cond))
5175 int const val = determine_truth(cond);
5178 check_reachable(dw->body);
5184 next = next->base.next;
5188 case STATEMENT_FOR: {
5190 for_statement_t *const fors = &next->fors;
5192 fors->step_reachable = true;
5194 if (fors->condition_reachable)
5196 fors->condition_reachable = true;
5198 expression_t const *const cond = fors->condition;
5203 } else if (expression_returns(cond)) {
5204 val = determine_truth(cond);
5210 check_reachable(fors->body);
5216 next = next->base.next;
5220 case STATEMENT_MS_TRY:
5222 next = next->ms_try.final_statement;
5227 check_reachable(next);
5230 static void check_unreachable(statement_t* const stmt, void *const env)
5234 switch (stmt->kind) {
5235 case STATEMENT_DO_WHILE:
5236 if (!stmt->base.reachable) {
5237 expression_t const *const cond = stmt->do_while.condition;
5238 if (determine_truth(cond) >= 0) {
5239 source_position_t const *const pos = &cond->base.source_position;
5240 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5245 case STATEMENT_FOR: {
5246 for_statement_t const* const fors = &stmt->fors;
5248 // if init and step are unreachable, cond is unreachable, too
5249 if (!stmt->base.reachable && !fors->step_reachable) {
5250 goto warn_unreachable;
5252 if (!stmt->base.reachable && fors->initialisation != NULL) {
5253 source_position_t const *const pos = &fors->initialisation->base.source_position;
5254 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5257 if (!fors->condition_reachable && fors->condition != NULL) {
5258 source_position_t const *const pos = &fors->condition->base.source_position;
5259 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5262 if (!fors->step_reachable && fors->step != NULL) {
5263 source_position_t const *const pos = &fors->step->base.source_position;
5264 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5270 case STATEMENT_COMPOUND:
5271 if (stmt->compound.statements != NULL)
5273 goto warn_unreachable;
5275 case STATEMENT_DECLARATION: {
5276 /* Only warn if there is at least one declarator with an initializer.
5277 * This typically occurs in switch statements. */
5278 declaration_statement_t const *const decl = &stmt->declaration;
5279 entity_t const * ent = decl->declarations_begin;
5280 entity_t const *const last = decl->declarations_end;
5282 for (;; ent = ent->base.next) {
5283 if (ent->kind == ENTITY_VARIABLE &&
5284 ent->variable.initializer != NULL) {
5285 goto warn_unreachable;
5295 if (!stmt->base.reachable) {
5296 source_position_t const *const pos = &stmt->base.source_position;
5297 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5303 static bool is_main(entity_t *entity)
5305 static symbol_t *sym_main = NULL;
5306 if (sym_main == NULL) {
5307 sym_main = symbol_table_insert("main");
5310 if (entity->base.symbol != sym_main)
5312 /* must be in outermost scope */
5313 if (entity->base.parent_scope != file_scope)
5319 static void parse_external_declaration(void)
5321 /* function-definitions and declarations both start with declaration
5323 add_anchor_token(';');
5324 declaration_specifiers_t specifiers;
5325 parse_declaration_specifiers(&specifiers);
5326 rem_anchor_token(';');
5328 /* must be a declaration */
5329 if (token.kind == ';') {
5330 parse_anonymous_declaration_rest(&specifiers);
5334 add_anchor_token(',');
5335 add_anchor_token('=');
5336 add_anchor_token(';');
5337 add_anchor_token('{');
5339 /* declarator is common to both function-definitions and declarations */
5340 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5342 rem_anchor_token('{');
5343 rem_anchor_token(';');
5344 rem_anchor_token('=');
5345 rem_anchor_token(',');
5347 /* must be a declaration */
5348 switch (token.kind) {
5352 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5357 /* must be a function definition */
5358 parse_kr_declaration_list(ndeclaration);
5360 if (token.kind != '{') {
5361 parse_error_expected("while parsing function definition", '{', NULL);
5362 eat_until_matching_token(';');
5366 assert(is_declaration(ndeclaration));
5367 type_t *const orig_type = ndeclaration->declaration.type;
5368 type_t * type = skip_typeref(orig_type);
5370 if (!is_type_function(type)) {
5371 if (is_type_valid(type)) {
5372 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5378 source_position_t const *const pos = &ndeclaration->base.source_position;
5379 if (is_typeref(orig_type)) {
5381 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5384 if (is_type_compound(skip_typeref(type->function.return_type))) {
5385 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5387 if (type->function.unspecified_parameters) {
5388 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5390 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5393 /* §6.7.5.3:14 a function definition with () means no
5394 * parameters (and not unspecified parameters) */
5395 if (type->function.unspecified_parameters &&
5396 type->function.parameters == NULL) {
5397 type_t *copy = duplicate_type(type);
5398 copy->function.unspecified_parameters = false;
5399 type = identify_new_type(copy);
5401 ndeclaration->declaration.type = type;
5404 entity_t *const entity = record_entity(ndeclaration, true);
5405 assert(entity->kind == ENTITY_FUNCTION);
5406 assert(ndeclaration->kind == ENTITY_FUNCTION);
5408 function_t *const function = &entity->function;
5409 if (ndeclaration != entity) {
5410 function->parameters = ndeclaration->function.parameters;
5412 assert(is_declaration(entity));
5413 type = skip_typeref(entity->declaration.type);
5415 PUSH_SCOPE(&function->parameters);
5417 entity_t *parameter = function->parameters.entities;
5418 for (; parameter != NULL; parameter = parameter->base.next) {
5419 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5420 parameter->base.parent_scope = current_scope;
5422 assert(parameter->base.parent_scope == NULL
5423 || parameter->base.parent_scope == current_scope);
5424 parameter->base.parent_scope = current_scope;
5425 if (parameter->base.symbol == NULL) {
5426 errorf(¶meter->base.source_position, "parameter name omitted");
5429 environment_push(parameter);
5432 if (function->statement != NULL) {
5433 parser_error_multiple_definition(entity, HERE);
5436 /* parse function body */
5437 int label_stack_top = label_top();
5438 function_t *old_current_function = current_function;
5439 entity_t *old_current_entity = current_entity;
5440 current_function = function;
5441 current_entity = entity;
5445 goto_anchor = &goto_first;
5447 label_anchor = &label_first;
5449 statement_t *const body = parse_compound_statement(false);
5450 function->statement = body;
5453 check_declarations();
5454 if (is_warn_on(WARN_RETURN_TYPE) ||
5455 is_warn_on(WARN_UNREACHABLE_CODE) ||
5456 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5457 noreturn_candidate = true;
5458 check_reachable(body);
5459 if (is_warn_on(WARN_UNREACHABLE_CODE))
5460 walk_statements(body, check_unreachable, NULL);
5461 if (noreturn_candidate &&
5462 !(function->base.modifiers & DM_NORETURN)) {
5463 source_position_t const *const pos = &body->base.source_position;
5464 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5468 if (is_main(entity) && enable_main_collect2_hack)
5469 prepare_main_collect2(entity);
5472 assert(current_function == function);
5473 assert(current_entity == entity);
5474 current_entity = old_current_entity;
5475 current_function = old_current_function;
5476 label_pop_to(label_stack_top);
5482 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5484 entity_t *iter = compound->members.entities;
5485 for (; iter != NULL; iter = iter->base.next) {
5486 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5489 if (iter->base.symbol == symbol) {
5491 } else if (iter->base.symbol == NULL) {
5492 /* search in anonymous structs and unions */
5493 type_t *type = skip_typeref(iter->declaration.type);
5494 if (is_type_compound(type)) {
5495 if (find_compound_entry(type->compound.compound, symbol)
5506 static void check_deprecated(const source_position_t *source_position,
5507 const entity_t *entity)
5509 if (!is_declaration(entity))
5511 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5514 source_position_t const *const epos = &entity->base.source_position;
5515 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5517 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5519 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5524 static expression_t *create_select(const source_position_t *pos,
5526 type_qualifiers_t qualifiers,
5529 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5531 check_deprecated(pos, entry);
5533 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5534 select->select.compound = addr;
5535 select->select.compound_entry = entry;
5537 type_t *entry_type = entry->declaration.type;
5538 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5540 /* bitfields need special treatment */
5541 if (entry->compound_member.bitfield) {
5542 unsigned bit_size = entry->compound_member.bit_size;
5543 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5544 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5545 res_type = type_int;
5549 /* we always do the auto-type conversions; the & and sizeof parser contains
5550 * code to revert this! */
5551 select->base.type = automatic_type_conversion(res_type);
5558 * Find entry with symbol in compound. Search anonymous structs and unions and
5559 * creates implicit select expressions for them.
5560 * Returns the adress for the innermost compound.
5562 static expression_t *find_create_select(const source_position_t *pos,
5564 type_qualifiers_t qualifiers,
5565 compound_t *compound, symbol_t *symbol)
5567 entity_t *iter = compound->members.entities;
5568 for (; iter != NULL; iter = iter->base.next) {
5569 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5572 symbol_t *iter_symbol = iter->base.symbol;
5573 if (iter_symbol == NULL) {
5574 type_t *type = iter->declaration.type;
5575 if (type->kind != TYPE_COMPOUND_STRUCT
5576 && type->kind != TYPE_COMPOUND_UNION)
5579 compound_t *sub_compound = type->compound.compound;
5581 if (find_compound_entry(sub_compound, symbol) == NULL)
5584 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5585 sub_addr->base.source_position = *pos;
5586 sub_addr->base.implicit = true;
5587 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5591 if (iter_symbol == symbol) {
5592 return create_select(pos, addr, qualifiers, iter);
5599 static void parse_bitfield_member(entity_t *entity)
5603 expression_t *size = parse_constant_expression();
5606 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5607 type_t *type = entity->declaration.type;
5608 if (!is_type_integer(skip_typeref(type))) {
5609 errorf(HERE, "bitfield base type '%T' is not an integer type",
5613 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5614 /* error already reported by parse_constant_expression */
5615 size_long = get_type_size(type) * 8;
5617 size_long = fold_constant_to_int(size);
5619 const symbol_t *symbol = entity->base.symbol;
5620 const symbol_t *user_symbol
5621 = symbol == NULL ? sym_anonymous : symbol;
5622 unsigned bit_size = get_type_size(type) * 8;
5623 if (size_long < 0) {
5624 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5625 } else if (size_long == 0 && symbol != NULL) {
5626 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5627 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5628 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5631 /* hope that people don't invent crazy types with more bits
5632 * than our struct can hold */
5634 (1 << sizeof(entity->compound_member.bit_size)*8));
5638 entity->compound_member.bitfield = true;
5639 entity->compound_member.bit_size = (unsigned char)size_long;
5642 static void parse_compound_declarators(compound_t *compound,
5643 const declaration_specifiers_t *specifiers)
5648 if (token.kind == ':') {
5649 /* anonymous bitfield */
5650 type_t *type = specifiers->type;
5651 entity_t *entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER,
5652 NAMESPACE_NORMAL, NULL);
5653 entity->base.source_position = *HERE;
5654 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5655 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5656 entity->declaration.type = type;
5658 parse_bitfield_member(entity);
5660 attribute_t *attributes = parse_attributes(NULL);
5661 attribute_t **anchor = &attributes;
5662 while (*anchor != NULL)
5663 anchor = &(*anchor)->next;
5664 *anchor = specifiers->attributes;
5665 if (attributes != NULL) {
5666 handle_entity_attributes(attributes, entity);
5668 entity->declaration.attributes = attributes;
5670 append_entity(&compound->members, entity);
5672 entity = parse_declarator(specifiers,
5673 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5674 source_position_t const *const pos = &entity->base.source_position;
5675 if (entity->kind == ENTITY_TYPEDEF) {
5676 errorf(pos, "typedef not allowed as compound member");
5678 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5680 /* make sure we don't define a symbol multiple times */
5681 symbol_t *symbol = entity->base.symbol;
5682 if (symbol != NULL) {
5683 entity_t *prev = find_compound_entry(compound, symbol);
5685 source_position_t const *const ppos = &prev->base.source_position;
5686 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5690 if (token.kind == ':') {
5691 parse_bitfield_member(entity);
5693 attribute_t *attributes = parse_attributes(NULL);
5694 handle_entity_attributes(attributes, entity);
5696 type_t *orig_type = entity->declaration.type;
5697 type_t *type = skip_typeref(orig_type);
5698 if (is_type_function(type)) {
5699 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5700 } else if (is_type_incomplete(type)) {
5701 /* §6.7.2.1:16 flexible array member */
5702 if (!is_type_array(type) ||
5703 token.kind != ';' ||
5704 look_ahead(1)->kind != '}') {
5705 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5706 } else if (compound->members.entities == NULL) {
5707 errorf(pos, "flexible array member in otherwise empty struct");
5712 append_entity(&compound->members, entity);
5715 } while (next_if(','));
5716 expect(';', end_error);
5719 anonymous_entity = NULL;
5722 static void parse_compound_type_entries(compound_t *compound)
5725 add_anchor_token('}');
5728 switch (token.kind) {
5730 case T___extension__:
5731 case T_IDENTIFIER: {
5733 declaration_specifiers_t specifiers;
5734 parse_declaration_specifiers(&specifiers);
5735 parse_compound_declarators(compound, &specifiers);
5741 rem_anchor_token('}');
5742 expect('}', end_error);
5745 compound->complete = true;
5751 static type_t *parse_typename(void)
5753 declaration_specifiers_t specifiers;
5754 parse_declaration_specifiers(&specifiers);
5755 if (specifiers.storage_class != STORAGE_CLASS_NONE
5756 || specifiers.thread_local) {
5757 /* TODO: improve error message, user does probably not know what a
5758 * storage class is...
5760 errorf(&specifiers.source_position, "typename must not have a storage class");
5763 type_t *result = parse_abstract_declarator(specifiers.type);
5771 typedef expression_t* (*parse_expression_function)(void);
5772 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5774 typedef struct expression_parser_function_t expression_parser_function_t;
5775 struct expression_parser_function_t {
5776 parse_expression_function parser;
5777 precedence_t infix_precedence;
5778 parse_expression_infix_function infix_parser;
5781 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5784 * Prints an error message if an expression was expected but not read
5786 static expression_t *expected_expression_error(void)
5788 /* skip the error message if the error token was read */
5789 if (token.kind != T_ERROR) {
5790 errorf(HERE, "expected expression, got token %K", &token);
5794 return create_error_expression();
5797 static type_t *get_string_type(void)
5799 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5802 static type_t *get_wide_string_type(void)
5804 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5808 * Parse a string constant.
5810 static expression_t *parse_string_literal(void)
5812 source_position_t begin = token.base.source_position;
5813 string_t res = token.string.string;
5814 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5817 while (token.kind == T_STRING_LITERAL
5818 || token.kind == T_WIDE_STRING_LITERAL) {
5819 warn_string_concat(&token.base.source_position);
5820 res = concat_strings(&res, &token.string.string);
5822 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5825 expression_t *literal;
5827 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5828 literal->base.type = get_wide_string_type();
5830 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5831 literal->base.type = get_string_type();
5833 literal->base.source_position = begin;
5834 literal->literal.value = res;
5840 * Parse a boolean constant.
5842 static expression_t *parse_boolean_literal(bool value)
5844 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5845 literal->base.type = type_bool;
5846 literal->literal.value.begin = value ? "true" : "false";
5847 literal->literal.value.size = value ? 4 : 5;
5853 static void warn_traditional_suffix(void)
5855 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5856 &token.number.suffix);
5859 static void check_integer_suffix(void)
5861 const string_t *suffix = &token.number.suffix;
5862 if (suffix->size == 0)
5865 bool not_traditional = false;
5866 const char *c = suffix->begin;
5867 if (*c == 'l' || *c == 'L') {
5870 not_traditional = true;
5872 if (*c == 'u' || *c == 'U') {
5875 } else if (*c == 'u' || *c == 'U') {
5876 not_traditional = true;
5879 } else if (*c == 'u' || *c == 'U') {
5880 not_traditional = true;
5882 if (*c == 'l' || *c == 'L') {
5890 errorf(&token.base.source_position,
5891 "invalid suffix '%S' on integer constant", suffix);
5892 } else if (not_traditional) {
5893 warn_traditional_suffix();
5897 static type_t *check_floatingpoint_suffix(void)
5899 const string_t *suffix = &token.number.suffix;
5900 type_t *type = type_double;
5901 if (suffix->size == 0)
5904 bool not_traditional = false;
5905 const char *c = suffix->begin;
5906 if (*c == 'f' || *c == 'F') {
5909 } else if (*c == 'l' || *c == 'L') {
5911 type = type_long_double;
5914 errorf(&token.base.source_position,
5915 "invalid suffix '%S' on floatingpoint constant", suffix);
5916 } else if (not_traditional) {
5917 warn_traditional_suffix();
5924 * Parse an integer constant.
5926 static expression_t *parse_number_literal(void)
5928 expression_kind_t kind;
5931 switch (token.kind) {
5933 kind = EXPR_LITERAL_INTEGER;
5934 check_integer_suffix();
5937 case T_INTEGER_OCTAL:
5938 kind = EXPR_LITERAL_INTEGER_OCTAL;
5939 check_integer_suffix();
5942 case T_INTEGER_HEXADECIMAL:
5943 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5944 check_integer_suffix();
5947 case T_FLOATINGPOINT:
5948 kind = EXPR_LITERAL_FLOATINGPOINT;
5949 type = check_floatingpoint_suffix();
5951 case T_FLOATINGPOINT_HEXADECIMAL:
5952 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5953 type = check_floatingpoint_suffix();
5956 panic("unexpected token type in parse_number_literal");
5959 expression_t *literal = allocate_expression_zero(kind);
5960 literal->base.type = type;
5961 literal->literal.value = token.number.number;
5962 literal->literal.suffix = token.number.suffix;
5965 /* integer type depends on the size of the number and the size
5966 * representable by the types. The backend/codegeneration has to determine
5969 determine_literal_type(&literal->literal);
5974 * Parse a character constant.
5976 static expression_t *parse_character_constant(void)
5978 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5979 literal->base.type = c_mode & _CXX ? type_char : type_int;
5980 literal->literal.value = token.string.string;
5982 size_t len = literal->literal.value.size;
5984 if (!GNU_MODE && !(c_mode & _C99)) {
5985 errorf(HERE, "more than 1 character in character constant");
5987 literal->base.type = type_int;
5988 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5997 * Parse a wide character constant.
5999 static expression_t *parse_wide_character_constant(void)
6001 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6002 literal->base.type = type_int;
6003 literal->literal.value = token.string.string;
6005 size_t len = wstrlen(&literal->literal.value);
6007 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6014 static entity_t *create_implicit_function(symbol_t *symbol,
6015 const source_position_t *source_position)
6017 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6018 ntype->function.return_type = type_int;
6019 ntype->function.unspecified_parameters = true;
6020 ntype->function.linkage = LINKAGE_C;
6021 type_t *type = identify_new_type(ntype);
6023 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6024 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6025 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6026 entity->declaration.type = type;
6027 entity->declaration.implicit = true;
6028 entity->base.source_position = *source_position;
6030 if (current_scope != NULL)
6031 record_entity(entity, false);
6037 * Performs automatic type cast as described in §6.3.2.1.
6039 * @param orig_type the original type
6041 static type_t *automatic_type_conversion(type_t *orig_type)
6043 type_t *type = skip_typeref(orig_type);
6044 if (is_type_array(type)) {
6045 array_type_t *array_type = &type->array;
6046 type_t *element_type = array_type->element_type;
6047 unsigned qualifiers = array_type->base.qualifiers;
6049 return make_pointer_type(element_type, qualifiers);
6052 if (is_type_function(type)) {
6053 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6060 * reverts the automatic casts of array to pointer types and function
6061 * to function-pointer types as defined §6.3.2.1
6063 type_t *revert_automatic_type_conversion(const expression_t *expression)
6065 switch (expression->kind) {
6066 case EXPR_REFERENCE: {
6067 entity_t *entity = expression->reference.entity;
6068 if (is_declaration(entity)) {
6069 return entity->declaration.type;
6070 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6071 return entity->enum_value.enum_type;
6073 panic("no declaration or enum in reference");
6078 entity_t *entity = expression->select.compound_entry;
6079 assert(is_declaration(entity));
6080 type_t *type = entity->declaration.type;
6081 return get_qualified_type(type, expression->base.type->base.qualifiers);
6084 case EXPR_UNARY_DEREFERENCE: {
6085 const expression_t *const value = expression->unary.value;
6086 type_t *const type = skip_typeref(value->base.type);
6087 if (!is_type_pointer(type))
6088 return type_error_type;
6089 return type->pointer.points_to;
6092 case EXPR_ARRAY_ACCESS: {
6093 const expression_t *array_ref = expression->array_access.array_ref;
6094 type_t *type_left = skip_typeref(array_ref->base.type);
6095 if (!is_type_pointer(type_left))
6096 return type_error_type;
6097 return type_left->pointer.points_to;
6100 case EXPR_STRING_LITERAL: {
6101 size_t size = expression->string_literal.value.size;
6102 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6105 case EXPR_WIDE_STRING_LITERAL: {
6106 size_t size = wstrlen(&expression->string_literal.value);
6107 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6110 case EXPR_COMPOUND_LITERAL:
6111 return expression->compound_literal.type;
6116 return expression->base.type;
6120 * Find an entity matching a symbol in a scope.
6121 * Uses current scope if scope is NULL
6123 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6124 namespace_tag_t namespc)
6126 if (scope == NULL) {
6127 return get_entity(symbol, namespc);
6130 /* we should optimize here, if scope grows above a certain size we should
6131 construct a hashmap here... */
6132 entity_t *entity = scope->entities;
6133 for ( ; entity != NULL; entity = entity->base.next) {
6134 if (entity->base.symbol == symbol
6135 && (namespace_tag_t)entity->base.namespc == namespc)
6142 static entity_t *parse_qualified_identifier(void)
6144 /* namespace containing the symbol */
6146 source_position_t pos;
6147 const scope_t *lookup_scope = NULL;
6149 if (next_if(T_COLONCOLON))
6150 lookup_scope = &unit->scope;
6154 if (token.kind != T_IDENTIFIER) {
6155 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6156 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6158 symbol = token.identifier.symbol;
6163 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6165 if (!next_if(T_COLONCOLON))
6168 switch (entity->kind) {
6169 case ENTITY_NAMESPACE:
6170 lookup_scope = &entity->namespacee.members;
6175 lookup_scope = &entity->compound.members;
6178 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6179 symbol, get_entity_kind_name(entity->kind));
6181 /* skip further qualifications */
6182 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6184 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6188 if (entity == NULL) {
6189 if (!strict_mode && token.kind == '(') {
6190 /* an implicitly declared function */
6191 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6192 "implicit declaration of function '%Y'", symbol);
6193 entity = create_implicit_function(symbol, &pos);
6195 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6196 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6203 static expression_t *parse_reference(void)
6205 source_position_t const pos = token.base.source_position;
6206 entity_t *const entity = parse_qualified_identifier();
6209 if (is_declaration(entity)) {
6210 orig_type = entity->declaration.type;
6211 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6212 orig_type = entity->enum_value.enum_type;
6214 panic("expected declaration or enum value in reference");
6217 /* we always do the auto-type conversions; the & and sizeof parser contains
6218 * code to revert this! */
6219 type_t *type = automatic_type_conversion(orig_type);
6221 expression_kind_t kind = EXPR_REFERENCE;
6222 if (entity->kind == ENTITY_ENUM_VALUE)
6223 kind = EXPR_ENUM_CONSTANT;
6225 expression_t *expression = allocate_expression_zero(kind);
6226 expression->base.source_position = pos;
6227 expression->base.type = type;
6228 expression->reference.entity = entity;
6230 /* this declaration is used */
6231 if (is_declaration(entity)) {
6232 entity->declaration.used = true;
6235 if (entity->base.parent_scope != file_scope
6236 && (current_function != NULL
6237 && entity->base.parent_scope->depth < current_function->parameters.depth)
6238 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6239 if (entity->kind == ENTITY_VARIABLE) {
6240 /* access of a variable from an outer function */
6241 entity->variable.address_taken = true;
6242 } else if (entity->kind == ENTITY_PARAMETER) {
6243 entity->parameter.address_taken = true;
6245 current_function->need_closure = true;
6248 check_deprecated(&pos, entity);
6253 static bool semantic_cast(expression_t *cast)
6255 expression_t *expression = cast->unary.value;
6256 type_t *orig_dest_type = cast->base.type;
6257 type_t *orig_type_right = expression->base.type;
6258 type_t const *dst_type = skip_typeref(orig_dest_type);
6259 type_t const *src_type = skip_typeref(orig_type_right);
6260 source_position_t const *pos = &cast->base.source_position;
6262 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6263 if (is_type_void(dst_type))
6266 /* only integer and pointer can be casted to pointer */
6267 if (is_type_pointer(dst_type) &&
6268 !is_type_pointer(src_type) &&
6269 !is_type_integer(src_type) &&
6270 is_type_valid(src_type)) {
6271 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6275 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6276 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6280 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6281 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6285 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6286 type_t *src = skip_typeref(src_type->pointer.points_to);
6287 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6288 unsigned missing_qualifiers =
6289 src->base.qualifiers & ~dst->base.qualifiers;
6290 if (missing_qualifiers != 0) {
6291 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6297 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6299 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6300 expression->base.source_position = *pos;
6302 parse_initializer_env_t env;
6305 env.must_be_constant = false;
6306 initializer_t *initializer = parse_initializer(&env);
6309 expression->compound_literal.initializer = initializer;
6310 expression->compound_literal.type = type;
6311 expression->base.type = automatic_type_conversion(type);
6317 * Parse a cast expression.
6319 static expression_t *parse_cast(void)
6321 source_position_t const pos = *HERE;
6324 add_anchor_token(')');
6326 type_t *type = parse_typename();
6328 rem_anchor_token(')');
6329 expect(')', end_error);
6331 if (token.kind == '{') {
6332 return parse_compound_literal(&pos, type);
6335 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6336 cast->base.source_position = pos;
6338 expression_t *value = parse_subexpression(PREC_CAST);
6339 cast->base.type = type;
6340 cast->unary.value = value;
6342 if (! semantic_cast(cast)) {
6343 /* TODO: record the error in the AST. else it is impossible to detect it */
6348 return create_error_expression();
6352 * Parse a statement expression.
6354 static expression_t *parse_statement_expression(void)
6356 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6359 add_anchor_token(')');
6361 statement_t *statement = parse_compound_statement(true);
6362 statement->compound.stmt_expr = true;
6363 expression->statement.statement = statement;
6365 /* find last statement and use its type */
6366 type_t *type = type_void;
6367 const statement_t *stmt = statement->compound.statements;
6369 while (stmt->base.next != NULL)
6370 stmt = stmt->base.next;
6372 if (stmt->kind == STATEMENT_EXPRESSION) {
6373 type = stmt->expression.expression->base.type;
6376 source_position_t const *const pos = &expression->base.source_position;
6377 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6379 expression->base.type = type;
6381 rem_anchor_token(')');
6382 expect(')', end_error);
6389 * Parse a parenthesized expression.
6391 static expression_t *parse_parenthesized_expression(void)
6393 token_t const* const la1 = look_ahead(1);
6394 switch (la1->kind) {
6396 /* gcc extension: a statement expression */
6397 return parse_statement_expression();
6400 if (is_typedef_symbol(la1->identifier.symbol)) {
6402 return parse_cast();
6407 add_anchor_token(')');
6408 expression_t *result = parse_expression();
6409 result->base.parenthesized = true;
6410 rem_anchor_token(')');
6411 expect(')', end_error);
6417 static expression_t *parse_function_keyword(void)
6421 if (current_function == NULL) {
6422 errorf(HERE, "'__func__' used outside of a function");
6425 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6426 expression->base.type = type_char_ptr;
6427 expression->funcname.kind = FUNCNAME_FUNCTION;
6434 static expression_t *parse_pretty_function_keyword(void)
6436 if (current_function == NULL) {
6437 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6440 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6441 expression->base.type = type_char_ptr;
6442 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6444 eat(T___PRETTY_FUNCTION__);
6449 static expression_t *parse_funcsig_keyword(void)
6451 if (current_function == NULL) {
6452 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6455 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6456 expression->base.type = type_char_ptr;
6457 expression->funcname.kind = FUNCNAME_FUNCSIG;
6464 static expression_t *parse_funcdname_keyword(void)
6466 if (current_function == NULL) {
6467 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6470 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6471 expression->base.type = type_char_ptr;
6472 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6474 eat(T___FUNCDNAME__);
6479 static designator_t *parse_designator(void)
6481 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6482 result->source_position = *HERE;
6484 if (token.kind != T_IDENTIFIER) {
6485 parse_error_expected("while parsing member designator",
6486 T_IDENTIFIER, NULL);
6489 result->symbol = token.identifier.symbol;
6492 designator_t *last_designator = result;
6495 if (token.kind != T_IDENTIFIER) {
6496 parse_error_expected("while parsing member designator",
6497 T_IDENTIFIER, NULL);
6500 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6501 designator->source_position = *HERE;
6502 designator->symbol = token.identifier.symbol;
6505 last_designator->next = designator;
6506 last_designator = designator;
6510 add_anchor_token(']');
6511 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6512 designator->source_position = *HERE;
6513 designator->array_index = parse_expression();
6514 rem_anchor_token(']');
6515 expect(']', end_error);
6516 if (designator->array_index == NULL) {
6520 last_designator->next = designator;
6521 last_designator = designator;
6533 * Parse the __builtin_offsetof() expression.
6535 static expression_t *parse_offsetof(void)
6537 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6538 expression->base.type = type_size_t;
6540 eat(T___builtin_offsetof);
6542 expect('(', end_error);
6543 add_anchor_token(',');
6544 type_t *type = parse_typename();
6545 rem_anchor_token(',');
6546 expect(',', end_error);
6547 add_anchor_token(')');
6548 designator_t *designator = parse_designator();
6549 rem_anchor_token(')');
6550 expect(')', end_error);
6552 expression->offsetofe.type = type;
6553 expression->offsetofe.designator = designator;
6556 memset(&path, 0, sizeof(path));
6557 path.top_type = type;
6558 path.path = NEW_ARR_F(type_path_entry_t, 0);
6560 descend_into_subtype(&path);
6562 if (!walk_designator(&path, designator, true)) {
6563 return create_error_expression();
6566 DEL_ARR_F(path.path);
6570 return create_error_expression();
6574 * Parses a _builtin_va_start() expression.
6576 static expression_t *parse_va_start(void)
6578 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6580 eat(T___builtin_va_start);
6582 expect('(', end_error);
6583 add_anchor_token(',');
6584 expression->va_starte.ap = parse_assignment_expression();
6585 rem_anchor_token(',');
6586 expect(',', end_error);
6587 expression_t *const expr = parse_assignment_expression();
6588 if (expr->kind == EXPR_REFERENCE) {
6589 entity_t *const entity = expr->reference.entity;
6590 if (!current_function->base.type->function.variadic) {
6591 errorf(&expr->base.source_position,
6592 "'va_start' used in non-variadic function");
6593 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6594 entity->base.next != NULL ||
6595 entity->kind != ENTITY_PARAMETER) {
6596 errorf(&expr->base.source_position,
6597 "second argument of 'va_start' must be last parameter of the current function");
6599 expression->va_starte.parameter = &entity->variable;
6601 expect(')', end_error);
6604 expect(')', end_error);
6606 return create_error_expression();
6610 * Parses a __builtin_va_arg() expression.
6612 static expression_t *parse_va_arg(void)
6614 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6616 eat(T___builtin_va_arg);
6618 expect('(', end_error);
6620 ap.expression = parse_assignment_expression();
6621 expression->va_arge.ap = ap.expression;
6622 check_call_argument(type_valist, &ap, 1);
6624 expect(',', end_error);
6625 expression->base.type = parse_typename();
6626 expect(')', end_error);
6630 return create_error_expression();
6634 * Parses a __builtin_va_copy() expression.
6636 static expression_t *parse_va_copy(void)
6638 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6640 eat(T___builtin_va_copy);
6642 expect('(', end_error);
6643 expression_t *dst = parse_assignment_expression();
6644 assign_error_t error = semantic_assign(type_valist, dst);
6645 report_assign_error(error, type_valist, dst, "call argument 1",
6646 &dst->base.source_position);
6647 expression->va_copye.dst = dst;
6649 expect(',', end_error);
6651 call_argument_t src;
6652 src.expression = parse_assignment_expression();
6653 check_call_argument(type_valist, &src, 2);
6654 expression->va_copye.src = src.expression;
6655 expect(')', end_error);
6659 return create_error_expression();
6663 * Parses a __builtin_constant_p() expression.
6665 static expression_t *parse_builtin_constant(void)
6667 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6669 eat(T___builtin_constant_p);
6671 expect('(', end_error);
6672 add_anchor_token(')');
6673 expression->builtin_constant.value = parse_assignment_expression();
6674 rem_anchor_token(')');
6675 expect(')', end_error);
6676 expression->base.type = type_int;
6680 return create_error_expression();
6684 * Parses a __builtin_types_compatible_p() expression.
6686 static expression_t *parse_builtin_types_compatible(void)
6688 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6690 eat(T___builtin_types_compatible_p);
6692 expect('(', end_error);
6693 add_anchor_token(')');
6694 add_anchor_token(',');
6695 expression->builtin_types_compatible.left = parse_typename();
6696 rem_anchor_token(',');
6697 expect(',', end_error);
6698 expression->builtin_types_compatible.right = parse_typename();
6699 rem_anchor_token(')');
6700 expect(')', end_error);
6701 expression->base.type = type_int;
6705 return create_error_expression();
6709 * Parses a __builtin_is_*() compare expression.
6711 static expression_t *parse_compare_builtin(void)
6713 expression_t *expression;
6715 switch (token.kind) {
6716 case T___builtin_isgreater:
6717 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6719 case T___builtin_isgreaterequal:
6720 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6722 case T___builtin_isless:
6723 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6725 case T___builtin_islessequal:
6726 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6728 case T___builtin_islessgreater:
6729 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6731 case T___builtin_isunordered:
6732 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6735 internal_errorf(HERE, "invalid compare builtin found");
6737 expression->base.source_position = *HERE;
6740 expect('(', end_error);
6741 expression->binary.left = parse_assignment_expression();
6742 expect(',', end_error);
6743 expression->binary.right = parse_assignment_expression();
6744 expect(')', end_error);
6746 type_t *const orig_type_left = expression->binary.left->base.type;
6747 type_t *const orig_type_right = expression->binary.right->base.type;
6749 type_t *const type_left = skip_typeref(orig_type_left);
6750 type_t *const type_right = skip_typeref(orig_type_right);
6751 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6752 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6753 type_error_incompatible("invalid operands in comparison",
6754 &expression->base.source_position, orig_type_left, orig_type_right);
6757 semantic_comparison(&expression->binary);
6762 return create_error_expression();
6766 * Parses a MS assume() expression.
6768 static expression_t *parse_assume(void)
6770 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6774 expect('(', end_error);
6775 add_anchor_token(')');
6776 expression->unary.value = parse_assignment_expression();
6777 rem_anchor_token(')');
6778 expect(')', end_error);
6780 expression->base.type = type_void;
6783 return create_error_expression();
6787 * Return the label for the current symbol or create a new one.
6789 static label_t *get_label(void)
6791 assert(token.kind == T_IDENTIFIER);
6792 assert(current_function != NULL);
6794 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6795 /* If we find a local label, we already created the declaration. */
6796 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6797 if (label->base.parent_scope != current_scope) {
6798 assert(label->base.parent_scope->depth < current_scope->depth);
6799 current_function->goto_to_outer = true;
6801 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6802 /* There is no matching label in the same function, so create a new one. */
6803 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol);
6808 return &label->label;
6812 * Parses a GNU && label address expression.
6814 static expression_t *parse_label_address(void)
6816 source_position_t source_position = token.base.source_position;
6818 if (token.kind != T_IDENTIFIER) {
6819 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6820 return create_error_expression();
6823 label_t *const label = get_label();
6825 label->address_taken = true;
6827 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6828 expression->base.source_position = source_position;
6830 /* label address is treated as a void pointer */
6831 expression->base.type = type_void_ptr;
6832 expression->label_address.label = label;
6837 * Parse a microsoft __noop expression.
6839 static expression_t *parse_noop_expression(void)
6841 /* the result is a (int)0 */
6842 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6843 literal->base.type = type_int;
6844 literal->literal.value.begin = "__noop";
6845 literal->literal.value.size = 6;
6849 if (token.kind == '(') {
6850 /* parse arguments */
6852 add_anchor_token(')');
6853 add_anchor_token(',');
6855 if (token.kind != ')') do {
6856 (void)parse_assignment_expression();
6857 } while (next_if(','));
6859 rem_anchor_token(',');
6860 rem_anchor_token(')');
6862 expect(')', end_error);
6869 * Parses a primary expression.
6871 static expression_t *parse_primary_expression(void)
6873 switch (token.kind) {
6874 case T_false: return parse_boolean_literal(false);
6875 case T_true: return parse_boolean_literal(true);
6877 case T_INTEGER_OCTAL:
6878 case T_INTEGER_HEXADECIMAL:
6879 case T_FLOATINGPOINT:
6880 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6881 case T_CHARACTER_CONSTANT: return parse_character_constant();
6882 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6883 case T_STRING_LITERAL:
6884 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6885 case T___FUNCTION__:
6886 case T___func__: return parse_function_keyword();
6887 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6888 case T___FUNCSIG__: return parse_funcsig_keyword();
6889 case T___FUNCDNAME__: return parse_funcdname_keyword();
6890 case T___builtin_offsetof: return parse_offsetof();
6891 case T___builtin_va_start: return parse_va_start();
6892 case T___builtin_va_arg: return parse_va_arg();
6893 case T___builtin_va_copy: return parse_va_copy();
6894 case T___builtin_isgreater:
6895 case T___builtin_isgreaterequal:
6896 case T___builtin_isless:
6897 case T___builtin_islessequal:
6898 case T___builtin_islessgreater:
6899 case T___builtin_isunordered: return parse_compare_builtin();
6900 case T___builtin_constant_p: return parse_builtin_constant();
6901 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6902 case T__assume: return parse_assume();
6905 return parse_label_address();
6908 case '(': return parse_parenthesized_expression();
6909 case T___noop: return parse_noop_expression();
6911 /* Gracefully handle type names while parsing expressions. */
6913 return parse_reference();
6915 if (!is_typedef_symbol(token.identifier.symbol)) {
6916 return parse_reference();
6920 source_position_t const pos = *HERE;
6921 declaration_specifiers_t specifiers;
6922 parse_declaration_specifiers(&specifiers);
6923 type_t const *const type = parse_abstract_declarator(specifiers.type);
6924 errorf(&pos, "encountered type '%T' while parsing expression", type);
6925 return create_error_expression();
6929 errorf(HERE, "unexpected token %K, expected an expression", &token);
6931 return create_error_expression();
6934 static expression_t *parse_array_expression(expression_t *left)
6936 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6937 array_access_expression_t *const arr = &expr->array_access;
6940 add_anchor_token(']');
6942 expression_t *const inside = parse_expression();
6944 type_t *const orig_type_left = left->base.type;
6945 type_t *const orig_type_inside = inside->base.type;
6947 type_t *const type_left = skip_typeref(orig_type_left);
6948 type_t *const type_inside = skip_typeref(orig_type_inside);
6954 if (is_type_pointer(type_left)) {
6957 idx_type = type_inside;
6958 res_type = type_left->pointer.points_to;
6960 } else if (is_type_pointer(type_inside)) {
6961 arr->flipped = true;
6964 idx_type = type_left;
6965 res_type = type_inside->pointer.points_to;
6967 res_type = automatic_type_conversion(res_type);
6968 if (!is_type_integer(idx_type)) {
6969 errorf(&idx->base.source_position, "array subscript must have integer type");
6970 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6971 source_position_t const *const pos = &idx->base.source_position;
6972 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6975 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6976 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6978 res_type = type_error_type;
6983 arr->array_ref = ref;
6985 arr->base.type = res_type;
6987 rem_anchor_token(']');
6988 expect(']', end_error);
6993 static bool is_bitfield(const expression_t *expression)
6995 return expression->kind == EXPR_SELECT
6996 && expression->select.compound_entry->compound_member.bitfield;
6999 static expression_t *parse_typeprop(expression_kind_t const kind)
7001 expression_t *tp_expression = allocate_expression_zero(kind);
7002 tp_expression->base.type = type_size_t;
7004 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7007 expression_t *expression;
7008 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
7009 source_position_t const pos = *HERE;
7011 add_anchor_token(')');
7012 orig_type = parse_typename();
7013 rem_anchor_token(')');
7014 expect(')', end_error);
7016 if (token.kind == '{') {
7017 /* It was not sizeof(type) after all. It is sizeof of an expression
7018 * starting with a compound literal */
7019 expression = parse_compound_literal(&pos, orig_type);
7020 goto typeprop_expression;
7023 expression = parse_subexpression(PREC_UNARY);
7025 typeprop_expression:
7026 if (is_bitfield(expression)) {
7027 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7028 errorf(&tp_expression->base.source_position,
7029 "operand of %s expression must not be a bitfield", what);
7032 tp_expression->typeprop.tp_expression = expression;
7034 orig_type = revert_automatic_type_conversion(expression);
7035 expression->base.type = orig_type;
7038 tp_expression->typeprop.type = orig_type;
7039 type_t const* const type = skip_typeref(orig_type);
7040 char const* wrong_type = NULL;
7041 if (is_type_incomplete(type)) {
7042 if (!is_type_void(type) || !GNU_MODE)
7043 wrong_type = "incomplete";
7044 } else if (type->kind == TYPE_FUNCTION) {
7046 /* function types are allowed (and return 1) */
7047 source_position_t const *const pos = &tp_expression->base.source_position;
7048 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7049 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7051 wrong_type = "function";
7055 if (wrong_type != NULL) {
7056 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7057 errorf(&tp_expression->base.source_position,
7058 "operand of %s expression must not be of %s type '%T'",
7059 what, wrong_type, orig_type);
7063 return tp_expression;
7066 static expression_t *parse_sizeof(void)
7068 return parse_typeprop(EXPR_SIZEOF);
7071 static expression_t *parse_alignof(void)
7073 return parse_typeprop(EXPR_ALIGNOF);
7076 static expression_t *parse_select_expression(expression_t *addr)
7078 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7079 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7080 source_position_t const pos = *HERE;
7083 if (token.kind != T_IDENTIFIER) {
7084 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7085 return create_error_expression();
7087 symbol_t *symbol = token.identifier.symbol;
7090 type_t *const orig_type = addr->base.type;
7091 type_t *const type = skip_typeref(orig_type);
7094 bool saw_error = false;
7095 if (is_type_pointer(type)) {
7096 if (!select_left_arrow) {
7098 "request for member '%Y' in something not a struct or union, but '%T'",
7102 type_left = skip_typeref(type->pointer.points_to);
7104 if (select_left_arrow && is_type_valid(type)) {
7105 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7111 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7112 type_left->kind != TYPE_COMPOUND_UNION) {
7114 if (is_type_valid(type_left) && !saw_error) {
7116 "request for member '%Y' in something not a struct or union, but '%T'",
7119 return create_error_expression();
7122 compound_t *compound = type_left->compound.compound;
7123 if (!compound->complete) {
7124 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7126 return create_error_expression();
7129 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7130 expression_t *result =
7131 find_create_select(&pos, addr, qualifiers, compound, symbol);
7133 if (result == NULL) {
7134 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7135 return create_error_expression();
7141 static void check_call_argument(type_t *expected_type,
7142 call_argument_t *argument, unsigned pos)
7144 type_t *expected_type_skip = skip_typeref(expected_type);
7145 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7146 expression_t *arg_expr = argument->expression;
7147 type_t *arg_type = skip_typeref(arg_expr->base.type);
7149 /* handle transparent union gnu extension */
7150 if (is_type_union(expected_type_skip)
7151 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7152 compound_t *union_decl = expected_type_skip->compound.compound;
7153 type_t *best_type = NULL;
7154 entity_t *entry = union_decl->members.entities;
7155 for ( ; entry != NULL; entry = entry->base.next) {
7156 assert(is_declaration(entry));
7157 type_t *decl_type = entry->declaration.type;
7158 error = semantic_assign(decl_type, arg_expr);
7159 if (error == ASSIGN_ERROR_INCOMPATIBLE
7160 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7163 if (error == ASSIGN_SUCCESS) {
7164 best_type = decl_type;
7165 } else if (best_type == NULL) {
7166 best_type = decl_type;
7170 if (best_type != NULL) {
7171 expected_type = best_type;
7175 error = semantic_assign(expected_type, arg_expr);
7176 argument->expression = create_implicit_cast(arg_expr, expected_type);
7178 if (error != ASSIGN_SUCCESS) {
7179 /* report exact scope in error messages (like "in argument 3") */
7181 snprintf(buf, sizeof(buf), "call argument %u", pos);
7182 report_assign_error(error, expected_type, arg_expr, buf,
7183 &arg_expr->base.source_position);
7185 type_t *const promoted_type = get_default_promoted_type(arg_type);
7186 if (!types_compatible(expected_type_skip, promoted_type) &&
7187 !types_compatible(expected_type_skip, type_void_ptr) &&
7188 !types_compatible(type_void_ptr, promoted_type)) {
7189 /* Deliberately show the skipped types in this warning */
7190 source_position_t const *const apos = &arg_expr->base.source_position;
7191 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7197 * Handle the semantic restrictions of builtin calls
7199 static void handle_builtin_argument_restrictions(call_expression_t *call)
7201 entity_t *entity = call->function->reference.entity;
7202 switch (entity->function.btk) {
7204 switch (entity->function.b.firm_builtin_kind) {
7205 case ir_bk_return_address:
7206 case ir_bk_frame_address: {
7207 /* argument must be constant */
7208 call_argument_t *argument = call->arguments;
7210 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7211 errorf(&call->base.source_position,
7212 "argument of '%Y' must be a constant expression",
7213 call->function->reference.entity->base.symbol);
7217 case ir_bk_prefetch:
7218 /* second and third argument must be constant if existent */
7219 if (call->arguments == NULL)
7221 call_argument_t *rw = call->arguments->next;
7222 call_argument_t *locality = NULL;
7225 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7226 errorf(&call->base.source_position,
7227 "second argument of '%Y' must be a constant expression",
7228 call->function->reference.entity->base.symbol);
7230 locality = rw->next;
7232 if (locality != NULL) {
7233 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7234 errorf(&call->base.source_position,
7235 "third argument of '%Y' must be a constant expression",
7236 call->function->reference.entity->base.symbol);
7238 locality = rw->next;
7245 case BUILTIN_OBJECT_SIZE:
7246 if (call->arguments == NULL)
7249 call_argument_t *arg = call->arguments->next;
7250 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7251 errorf(&call->base.source_position,
7252 "second argument of '%Y' must be a constant expression",
7253 call->function->reference.entity->base.symbol);
7262 * Parse a call expression, ie. expression '( ... )'.
7264 * @param expression the function address
7266 static expression_t *parse_call_expression(expression_t *expression)
7268 expression_t *result = allocate_expression_zero(EXPR_CALL);
7269 call_expression_t *call = &result->call;
7270 call->function = expression;
7272 type_t *const orig_type = expression->base.type;
7273 type_t *const type = skip_typeref(orig_type);
7275 function_type_t *function_type = NULL;
7276 if (is_type_pointer(type)) {
7277 type_t *const to_type = skip_typeref(type->pointer.points_to);
7279 if (is_type_function(to_type)) {
7280 function_type = &to_type->function;
7281 call->base.type = function_type->return_type;
7285 if (function_type == NULL && is_type_valid(type)) {
7287 "called object '%E' (type '%T') is not a pointer to a function",
7288 expression, orig_type);
7291 /* parse arguments */
7293 add_anchor_token(')');
7294 add_anchor_token(',');
7296 if (token.kind != ')') {
7297 call_argument_t **anchor = &call->arguments;
7299 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7300 argument->expression = parse_assignment_expression();
7303 anchor = &argument->next;
7304 } while (next_if(','));
7306 rem_anchor_token(',');
7307 rem_anchor_token(')');
7308 expect(')', end_error);
7310 if (function_type == NULL)
7313 /* check type and count of call arguments */
7314 function_parameter_t *parameter = function_type->parameters;
7315 call_argument_t *argument = call->arguments;
7316 if (!function_type->unspecified_parameters) {
7317 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7318 parameter = parameter->next, argument = argument->next) {
7319 check_call_argument(parameter->type, argument, ++pos);
7322 if (parameter != NULL) {
7323 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7324 } else if (argument != NULL && !function_type->variadic) {
7325 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7329 /* do default promotion for other arguments */
7330 for (; argument != NULL; argument = argument->next) {
7331 type_t *argument_type = argument->expression->base.type;
7332 if (!is_type_object(skip_typeref(argument_type))) {
7333 errorf(&argument->expression->base.source_position,
7334 "call argument '%E' must not be void", argument->expression);
7337 argument_type = get_default_promoted_type(argument_type);
7339 argument->expression
7340 = create_implicit_cast(argument->expression, argument_type);
7345 if (is_type_compound(skip_typeref(function_type->return_type))) {
7346 source_position_t const *const pos = &expression->base.source_position;
7347 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7350 if (expression->kind == EXPR_REFERENCE) {
7351 reference_expression_t *reference = &expression->reference;
7352 if (reference->entity->kind == ENTITY_FUNCTION &&
7353 reference->entity->function.btk != BUILTIN_NONE)
7354 handle_builtin_argument_restrictions(call);
7361 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7363 static bool same_compound_type(const type_t *type1, const type_t *type2)
7366 is_type_compound(type1) &&
7367 type1->kind == type2->kind &&
7368 type1->compound.compound == type2->compound.compound;
7371 static expression_t const *get_reference_address(expression_t const *expr)
7373 bool regular_take_address = true;
7375 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7376 expr = expr->unary.value;
7378 regular_take_address = false;
7381 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7384 expr = expr->unary.value;
7387 if (expr->kind != EXPR_REFERENCE)
7390 /* special case for functions which are automatically converted to a
7391 * pointer to function without an extra TAKE_ADDRESS operation */
7392 if (!regular_take_address &&
7393 expr->reference.entity->kind != ENTITY_FUNCTION) {
7400 static void warn_reference_address_as_bool(expression_t const* expr)
7402 expr = get_reference_address(expr);
7404 source_position_t const *const pos = &expr->base.source_position;
7405 entity_t const *const ent = expr->reference.entity;
7406 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7410 static void warn_assignment_in_condition(const expression_t *const expr)
7412 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7414 if (expr->base.parenthesized)
7416 source_position_t const *const pos = &expr->base.source_position;
7417 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7420 static void semantic_condition(expression_t const *const expr,
7421 char const *const context)
7423 type_t *const type = skip_typeref(expr->base.type);
7424 if (is_type_scalar(type)) {
7425 warn_reference_address_as_bool(expr);
7426 warn_assignment_in_condition(expr);
7427 } else if (is_type_valid(type)) {
7428 errorf(&expr->base.source_position,
7429 "%s must have scalar type", context);
7434 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7436 * @param expression the conditional expression
7438 static expression_t *parse_conditional_expression(expression_t *expression)
7440 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7442 conditional_expression_t *conditional = &result->conditional;
7443 conditional->condition = expression;
7446 add_anchor_token(':');
7448 /* §6.5.15:2 The first operand shall have scalar type. */
7449 semantic_condition(expression, "condition of conditional operator");
7451 expression_t *true_expression = expression;
7452 bool gnu_cond = false;
7453 if (GNU_MODE && token.kind == ':') {
7456 true_expression = parse_expression();
7458 rem_anchor_token(':');
7459 expect(':', end_error);
7461 expression_t *false_expression =
7462 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7464 type_t *const orig_true_type = true_expression->base.type;
7465 type_t *const orig_false_type = false_expression->base.type;
7466 type_t *const true_type = skip_typeref(orig_true_type);
7467 type_t *const false_type = skip_typeref(orig_false_type);
7470 source_position_t const *const pos = &conditional->base.source_position;
7471 type_t *result_type;
7472 if (is_type_void(true_type) || is_type_void(false_type)) {
7473 /* ISO/IEC 14882:1998(E) §5.16:2 */
7474 if (true_expression->kind == EXPR_UNARY_THROW) {
7475 result_type = false_type;
7476 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7477 result_type = true_type;
7479 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7480 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7482 result_type = type_void;
7484 } else if (is_type_arithmetic(true_type)
7485 && is_type_arithmetic(false_type)) {
7486 result_type = semantic_arithmetic(true_type, false_type);
7487 } else if (same_compound_type(true_type, false_type)) {
7488 /* just take 1 of the 2 types */
7489 result_type = true_type;
7490 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7491 type_t *pointer_type;
7493 expression_t *other_expression;
7494 if (is_type_pointer(true_type) &&
7495 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7496 pointer_type = true_type;
7497 other_type = false_type;
7498 other_expression = false_expression;
7500 pointer_type = false_type;
7501 other_type = true_type;
7502 other_expression = true_expression;
7505 if (is_null_pointer_constant(other_expression)) {
7506 result_type = pointer_type;
7507 } else if (is_type_pointer(other_type)) {
7508 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7509 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7512 if (is_type_void(to1) || is_type_void(to2)) {
7514 } else if (types_compatible(get_unqualified_type(to1),
7515 get_unqualified_type(to2))) {
7518 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7522 type_t *const type =
7523 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7524 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7525 } else if (is_type_integer(other_type)) {
7526 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7527 result_type = pointer_type;
7529 goto types_incompatible;
7533 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7534 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7536 result_type = type_error_type;
7539 conditional->true_expression
7540 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7541 conditional->false_expression
7542 = create_implicit_cast(false_expression, result_type);
7543 conditional->base.type = result_type;
7548 * Parse an extension expression.
7550 static expression_t *parse_extension(void)
7553 expression_t *expression = parse_subexpression(PREC_UNARY);
7559 * Parse a __builtin_classify_type() expression.
7561 static expression_t *parse_builtin_classify_type(void)
7563 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7564 result->base.type = type_int;
7566 eat(T___builtin_classify_type);
7568 expect('(', end_error);
7569 add_anchor_token(')');
7570 expression_t *expression = parse_expression();
7571 rem_anchor_token(')');
7572 expect(')', end_error);
7573 result->classify_type.type_expression = expression;
7577 return create_error_expression();
7581 * Parse a delete expression
7582 * ISO/IEC 14882:1998(E) §5.3.5
7584 static expression_t *parse_delete(void)
7586 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7587 result->base.type = type_void;
7592 result->kind = EXPR_UNARY_DELETE_ARRAY;
7593 expect(']', end_error);
7597 expression_t *const value = parse_subexpression(PREC_CAST);
7598 result->unary.value = value;
7600 type_t *const type = skip_typeref(value->base.type);
7601 if (!is_type_pointer(type)) {
7602 if (is_type_valid(type)) {
7603 errorf(&value->base.source_position,
7604 "operand of delete must have pointer type");
7606 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7607 source_position_t const *const pos = &value->base.source_position;
7608 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7615 * Parse a throw expression
7616 * ISO/IEC 14882:1998(E) §15:1
7618 static expression_t *parse_throw(void)
7620 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7621 result->base.type = type_void;
7625 expression_t *value = NULL;
7626 switch (token.kind) {
7628 value = parse_assignment_expression();
7629 /* ISO/IEC 14882:1998(E) §15.1:3 */
7630 type_t *const orig_type = value->base.type;
7631 type_t *const type = skip_typeref(orig_type);
7632 if (is_type_incomplete(type)) {
7633 errorf(&value->base.source_position,
7634 "cannot throw object of incomplete type '%T'", orig_type);
7635 } else if (is_type_pointer(type)) {
7636 type_t *const points_to = skip_typeref(type->pointer.points_to);
7637 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7638 errorf(&value->base.source_position,
7639 "cannot throw pointer to incomplete type '%T'", orig_type);
7647 result->unary.value = value;
7652 static bool check_pointer_arithmetic(const source_position_t *source_position,
7653 type_t *pointer_type,
7654 type_t *orig_pointer_type)
7656 type_t *points_to = pointer_type->pointer.points_to;
7657 points_to = skip_typeref(points_to);
7659 if (is_type_incomplete(points_to)) {
7660 if (!GNU_MODE || !is_type_void(points_to)) {
7661 errorf(source_position,
7662 "arithmetic with pointer to incomplete type '%T' not allowed",
7666 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7668 } else if (is_type_function(points_to)) {
7670 errorf(source_position,
7671 "arithmetic with pointer to function type '%T' not allowed",
7675 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7681 static bool is_lvalue(const expression_t *expression)
7683 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7684 switch (expression->kind) {
7685 case EXPR_ARRAY_ACCESS:
7686 case EXPR_COMPOUND_LITERAL:
7687 case EXPR_REFERENCE:
7689 case EXPR_UNARY_DEREFERENCE:
7693 type_t *type = skip_typeref(expression->base.type);
7695 /* ISO/IEC 14882:1998(E) §3.10:3 */
7696 is_type_reference(type) ||
7697 /* Claim it is an lvalue, if the type is invalid. There was a parse
7698 * error before, which maybe prevented properly recognizing it as
7700 !is_type_valid(type);
7705 static void semantic_incdec(unary_expression_t *expression)
7707 type_t *const orig_type = expression->value->base.type;
7708 type_t *const type = skip_typeref(orig_type);
7709 if (is_type_pointer(type)) {
7710 if (!check_pointer_arithmetic(&expression->base.source_position,
7714 } else if (!is_type_real(type) && is_type_valid(type)) {
7715 /* TODO: improve error message */
7716 errorf(&expression->base.source_position,
7717 "operation needs an arithmetic or pointer type");
7720 if (!is_lvalue(expression->value)) {
7721 /* TODO: improve error message */
7722 errorf(&expression->base.source_position, "lvalue required as operand");
7724 expression->base.type = orig_type;
7727 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7729 type_t *const res_type = promote_integer(type);
7730 expr->base.type = res_type;
7731 expr->value = create_implicit_cast(expr->value, res_type);
7734 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7736 type_t *const orig_type = expression->value->base.type;
7737 type_t *const type = skip_typeref(orig_type);
7738 if (!is_type_arithmetic(type)) {
7739 if (is_type_valid(type)) {
7740 /* TODO: improve error message */
7741 errorf(&expression->base.source_position,
7742 "operation needs an arithmetic type");
7745 } else if (is_type_integer(type)) {
7746 promote_unary_int_expr(expression, type);
7748 expression->base.type = orig_type;
7752 static void semantic_unexpr_plus(unary_expression_t *expression)
7754 semantic_unexpr_arithmetic(expression);
7755 source_position_t const *const pos = &expression->base.source_position;
7756 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7759 static void semantic_not(unary_expression_t *expression)
7761 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7762 semantic_condition(expression->value, "operand of !");
7763 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7766 static void semantic_unexpr_integer(unary_expression_t *expression)
7768 type_t *const orig_type = expression->value->base.type;
7769 type_t *const type = skip_typeref(orig_type);
7770 if (!is_type_integer(type)) {
7771 if (is_type_valid(type)) {
7772 errorf(&expression->base.source_position,
7773 "operand of ~ must be of integer type");
7778 promote_unary_int_expr(expression, type);
7781 static void semantic_dereference(unary_expression_t *expression)
7783 type_t *const orig_type = expression->value->base.type;
7784 type_t *const type = skip_typeref(orig_type);
7785 if (!is_type_pointer(type)) {
7786 if (is_type_valid(type)) {
7787 errorf(&expression->base.source_position,
7788 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7793 type_t *result_type = type->pointer.points_to;
7794 result_type = automatic_type_conversion(result_type);
7795 expression->base.type = result_type;
7799 * Record that an address is taken (expression represents an lvalue).
7801 * @param expression the expression
7802 * @param may_be_register if true, the expression might be an register
7804 static void set_address_taken(expression_t *expression, bool may_be_register)
7806 if (expression->kind != EXPR_REFERENCE)
7809 entity_t *const entity = expression->reference.entity;
7811 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7814 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7815 && !may_be_register) {
7816 source_position_t const *const pos = &expression->base.source_position;
7817 errorf(pos, "address of register '%N' requested", entity);
7820 if (entity->kind == ENTITY_VARIABLE) {
7821 entity->variable.address_taken = true;
7823 assert(entity->kind == ENTITY_PARAMETER);
7824 entity->parameter.address_taken = true;
7829 * Check the semantic of the address taken expression.
7831 static void semantic_take_addr(unary_expression_t *expression)
7833 expression_t *value = expression->value;
7834 value->base.type = revert_automatic_type_conversion(value);
7836 type_t *orig_type = value->base.type;
7837 type_t *type = skip_typeref(orig_type);
7838 if (!is_type_valid(type))
7842 if (!is_lvalue(value)) {
7843 errorf(&expression->base.source_position, "'&' requires an lvalue");
7845 if (is_bitfield(value)) {
7846 errorf(&expression->base.source_position,
7847 "'&' not allowed on bitfield");
7850 set_address_taken(value, false);
7852 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7855 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7856 static expression_t *parse_##unexpression_type(void) \
7858 expression_t *unary_expression \
7859 = allocate_expression_zero(unexpression_type); \
7861 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7863 sfunc(&unary_expression->unary); \
7865 return unary_expression; \
7868 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7869 semantic_unexpr_arithmetic)
7870 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7871 semantic_unexpr_plus)
7872 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7874 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7875 semantic_dereference)
7876 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7878 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7879 semantic_unexpr_integer)
7880 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7882 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7885 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7887 static expression_t *parse_##unexpression_type(expression_t *left) \
7889 expression_t *unary_expression \
7890 = allocate_expression_zero(unexpression_type); \
7892 unary_expression->unary.value = left; \
7894 sfunc(&unary_expression->unary); \
7896 return unary_expression; \
7899 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7900 EXPR_UNARY_POSTFIX_INCREMENT,
7902 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7903 EXPR_UNARY_POSTFIX_DECREMENT,
7906 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7908 /* TODO: handle complex + imaginary types */
7910 type_left = get_unqualified_type(type_left);
7911 type_right = get_unqualified_type(type_right);
7913 /* §6.3.1.8 Usual arithmetic conversions */
7914 if (type_left == type_long_double || type_right == type_long_double) {
7915 return type_long_double;
7916 } else if (type_left == type_double || type_right == type_double) {
7918 } else if (type_left == type_float || type_right == type_float) {
7922 type_left = promote_integer(type_left);
7923 type_right = promote_integer(type_right);
7925 if (type_left == type_right)
7928 bool const signed_left = is_type_signed(type_left);
7929 bool const signed_right = is_type_signed(type_right);
7930 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7931 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7933 if (signed_left == signed_right)
7934 return rank_left >= rank_right ? type_left : type_right;
7938 atomic_type_kind_t s_akind;
7939 atomic_type_kind_t u_akind;
7944 u_type = type_right;
7946 s_type = type_right;
7949 s_akind = get_akind(s_type);
7950 u_akind = get_akind(u_type);
7951 s_rank = get_akind_rank(s_akind);
7952 u_rank = get_akind_rank(u_akind);
7954 if (u_rank >= s_rank)
7957 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7961 case ATOMIC_TYPE_INT: return type_unsigned_int;
7962 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7963 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7965 default: panic("invalid atomic type");
7970 * Check the semantic restrictions for a binary expression.
7972 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7974 expression_t *const left = expression->left;
7975 expression_t *const right = expression->right;
7976 type_t *const orig_type_left = left->base.type;
7977 type_t *const orig_type_right = right->base.type;
7978 type_t *const type_left = skip_typeref(orig_type_left);
7979 type_t *const type_right = skip_typeref(orig_type_right);
7981 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7982 /* TODO: improve error message */
7983 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7984 errorf(&expression->base.source_position,
7985 "operation needs arithmetic types");
7990 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7991 expression->left = create_implicit_cast(left, arithmetic_type);
7992 expression->right = create_implicit_cast(right, arithmetic_type);
7993 expression->base.type = arithmetic_type;
7996 static void semantic_binexpr_integer(binary_expression_t *const expression)
7998 expression_t *const left = expression->left;
7999 expression_t *const right = expression->right;
8000 type_t *const orig_type_left = left->base.type;
8001 type_t *const orig_type_right = right->base.type;
8002 type_t *const type_left = skip_typeref(orig_type_left);
8003 type_t *const type_right = skip_typeref(orig_type_right);
8005 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8006 /* TODO: improve error message */
8007 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8008 errorf(&expression->base.source_position,
8009 "operation needs integer types");
8014 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8015 expression->left = create_implicit_cast(left, result_type);
8016 expression->right = create_implicit_cast(right, result_type);
8017 expression->base.type = result_type;
8020 static void warn_div_by_zero(binary_expression_t const *const expression)
8022 if (!is_type_integer(expression->base.type))
8025 expression_t const *const right = expression->right;
8026 /* The type of the right operand can be different for /= */
8027 if (is_type_integer(right->base.type) &&
8028 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8029 !fold_constant_to_bool(right)) {
8030 source_position_t const *const pos = &expression->base.source_position;
8031 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8036 * Check the semantic restrictions for a div/mod expression.
8038 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8040 semantic_binexpr_arithmetic(expression);
8041 warn_div_by_zero(expression);
8044 static void warn_addsub_in_shift(const expression_t *const expr)
8046 if (expr->base.parenthesized)
8050 switch (expr->kind) {
8051 case EXPR_BINARY_ADD: op = '+'; break;
8052 case EXPR_BINARY_SUB: op = '-'; break;
8056 source_position_t const *const pos = &expr->base.source_position;
8057 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8060 static bool semantic_shift(binary_expression_t *expression)
8062 expression_t *const left = expression->left;
8063 expression_t *const right = expression->right;
8064 type_t *const orig_type_left = left->base.type;
8065 type_t *const orig_type_right = right->base.type;
8066 type_t * type_left = skip_typeref(orig_type_left);
8067 type_t * type_right = skip_typeref(orig_type_right);
8069 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8070 /* TODO: improve error message */
8071 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8072 errorf(&expression->base.source_position,
8073 "operands of shift operation must have integer types");
8078 type_left = promote_integer(type_left);
8080 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8081 source_position_t const *const pos = &right->base.source_position;
8082 long const count = fold_constant_to_int(right);
8084 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8085 } else if ((unsigned long)count >=
8086 get_atomic_type_size(type_left->atomic.akind) * 8) {
8087 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8091 type_right = promote_integer(type_right);
8092 expression->right = create_implicit_cast(right, type_right);
8097 static void semantic_shift_op(binary_expression_t *expression)
8099 expression_t *const left = expression->left;
8100 expression_t *const right = expression->right;
8102 if (!semantic_shift(expression))
8105 warn_addsub_in_shift(left);
8106 warn_addsub_in_shift(right);
8108 type_t *const orig_type_left = left->base.type;
8109 type_t * type_left = skip_typeref(orig_type_left);
8111 type_left = promote_integer(type_left);
8112 expression->left = create_implicit_cast(left, type_left);
8113 expression->base.type = type_left;
8116 static void semantic_add(binary_expression_t *expression)
8118 expression_t *const left = expression->left;
8119 expression_t *const right = expression->right;
8120 type_t *const orig_type_left = left->base.type;
8121 type_t *const orig_type_right = right->base.type;
8122 type_t *const type_left = skip_typeref(orig_type_left);
8123 type_t *const type_right = skip_typeref(orig_type_right);
8126 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8127 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8128 expression->left = create_implicit_cast(left, arithmetic_type);
8129 expression->right = create_implicit_cast(right, arithmetic_type);
8130 expression->base.type = arithmetic_type;
8131 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8132 check_pointer_arithmetic(&expression->base.source_position,
8133 type_left, orig_type_left);
8134 expression->base.type = type_left;
8135 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8136 check_pointer_arithmetic(&expression->base.source_position,
8137 type_right, orig_type_right);
8138 expression->base.type = type_right;
8139 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8140 errorf(&expression->base.source_position,
8141 "invalid operands to binary + ('%T', '%T')",
8142 orig_type_left, orig_type_right);
8146 static void semantic_sub(binary_expression_t *expression)
8148 expression_t *const left = expression->left;
8149 expression_t *const right = expression->right;
8150 type_t *const orig_type_left = left->base.type;
8151 type_t *const orig_type_right = right->base.type;
8152 type_t *const type_left = skip_typeref(orig_type_left);
8153 type_t *const type_right = skip_typeref(orig_type_right);
8154 source_position_t const *const pos = &expression->base.source_position;
8157 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8158 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8159 expression->left = create_implicit_cast(left, arithmetic_type);
8160 expression->right = create_implicit_cast(right, arithmetic_type);
8161 expression->base.type = arithmetic_type;
8162 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8163 check_pointer_arithmetic(&expression->base.source_position,
8164 type_left, orig_type_left);
8165 expression->base.type = type_left;
8166 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8167 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8168 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8169 if (!types_compatible(unqual_left, unqual_right)) {
8171 "subtracting pointers to incompatible types '%T' and '%T'",
8172 orig_type_left, orig_type_right);
8173 } else if (!is_type_object(unqual_left)) {
8174 if (!is_type_void(unqual_left)) {
8175 errorf(pos, "subtracting pointers to non-object types '%T'",
8178 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8181 expression->base.type = type_ptrdiff_t;
8182 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8183 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8184 orig_type_left, orig_type_right);
8188 static void warn_string_literal_address(expression_t const* expr)
8190 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8191 expr = expr->unary.value;
8192 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8194 expr = expr->unary.value;
8197 if (expr->kind == EXPR_STRING_LITERAL
8198 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8199 source_position_t const *const pos = &expr->base.source_position;
8200 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8204 static bool maybe_negative(expression_t const *const expr)
8206 switch (is_constant_expression(expr)) {
8207 case EXPR_CLASS_ERROR: return false;
8208 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8209 default: return true;
8213 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8215 warn_string_literal_address(expr);
8217 expression_t const* const ref = get_reference_address(expr);
8218 if (ref != NULL && is_null_pointer_constant(other)) {
8219 entity_t const *const ent = ref->reference.entity;
8220 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8223 if (!expr->base.parenthesized) {
8224 switch (expr->base.kind) {
8225 case EXPR_BINARY_LESS:
8226 case EXPR_BINARY_GREATER:
8227 case EXPR_BINARY_LESSEQUAL:
8228 case EXPR_BINARY_GREATEREQUAL:
8229 case EXPR_BINARY_NOTEQUAL:
8230 case EXPR_BINARY_EQUAL:
8231 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8240 * Check the semantics of comparison expressions.
8242 * @param expression The expression to check.
8244 static void semantic_comparison(binary_expression_t *expression)
8246 source_position_t const *const pos = &expression->base.source_position;
8247 expression_t *const left = expression->left;
8248 expression_t *const right = expression->right;
8250 warn_comparison(pos, left, right);
8251 warn_comparison(pos, right, left);
8253 type_t *orig_type_left = left->base.type;
8254 type_t *orig_type_right = right->base.type;
8255 type_t *type_left = skip_typeref(orig_type_left);
8256 type_t *type_right = skip_typeref(orig_type_right);
8258 /* TODO non-arithmetic types */
8259 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8260 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8262 /* test for signed vs unsigned compares */
8263 if (is_type_integer(arithmetic_type)) {
8264 bool const signed_left = is_type_signed(type_left);
8265 bool const signed_right = is_type_signed(type_right);
8266 if (signed_left != signed_right) {
8267 /* FIXME long long needs better const folding magic */
8268 /* TODO check whether constant value can be represented by other type */
8269 if ((signed_left && maybe_negative(left)) ||
8270 (signed_right && maybe_negative(right))) {
8271 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8276 expression->left = create_implicit_cast(left, arithmetic_type);
8277 expression->right = create_implicit_cast(right, arithmetic_type);
8278 expression->base.type = arithmetic_type;
8279 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8280 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8281 is_type_float(arithmetic_type)) {
8282 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8284 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8285 /* TODO check compatibility */
8286 } else if (is_type_pointer(type_left)) {
8287 expression->right = create_implicit_cast(right, type_left);
8288 } else if (is_type_pointer(type_right)) {
8289 expression->left = create_implicit_cast(left, type_right);
8290 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8291 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8293 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8297 * Checks if a compound type has constant fields.
8299 static bool has_const_fields(const compound_type_t *type)
8301 compound_t *compound = type->compound;
8302 entity_t *entry = compound->members.entities;
8304 for (; entry != NULL; entry = entry->base.next) {
8305 if (!is_declaration(entry))
8308 const type_t *decl_type = skip_typeref(entry->declaration.type);
8309 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8316 static bool is_valid_assignment_lhs(expression_t const* const left)
8318 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8319 type_t *const type_left = skip_typeref(orig_type_left);
8321 if (!is_lvalue(left)) {
8322 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8327 if (left->kind == EXPR_REFERENCE
8328 && left->reference.entity->kind == ENTITY_FUNCTION) {
8329 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8333 if (is_type_array(type_left)) {
8334 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8337 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8338 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8342 if (is_type_incomplete(type_left)) {
8343 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8344 left, orig_type_left);
8347 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8348 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8349 left, orig_type_left);
8356 static void semantic_arithmetic_assign(binary_expression_t *expression)
8358 expression_t *left = expression->left;
8359 expression_t *right = expression->right;
8360 type_t *orig_type_left = left->base.type;
8361 type_t *orig_type_right = right->base.type;
8363 if (!is_valid_assignment_lhs(left))
8366 type_t *type_left = skip_typeref(orig_type_left);
8367 type_t *type_right = skip_typeref(orig_type_right);
8369 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8370 /* TODO: improve error message */
8371 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8372 errorf(&expression->base.source_position,
8373 "operation needs arithmetic types");
8378 /* combined instructions are tricky. We can't create an implicit cast on
8379 * the left side, because we need the uncasted form for the store.
8380 * The ast2firm pass has to know that left_type must be right_type
8381 * for the arithmetic operation and create a cast by itself */
8382 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8383 expression->right = create_implicit_cast(right, arithmetic_type);
8384 expression->base.type = type_left;
8387 static void semantic_divmod_assign(binary_expression_t *expression)
8389 semantic_arithmetic_assign(expression);
8390 warn_div_by_zero(expression);
8393 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8395 expression_t *const left = expression->left;
8396 expression_t *const right = expression->right;
8397 type_t *const orig_type_left = left->base.type;
8398 type_t *const orig_type_right = right->base.type;
8399 type_t *const type_left = skip_typeref(orig_type_left);
8400 type_t *const type_right = skip_typeref(orig_type_right);
8402 if (!is_valid_assignment_lhs(left))
8405 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8406 /* combined instructions are tricky. We can't create an implicit cast on
8407 * the left side, because we need the uncasted form for the store.
8408 * The ast2firm pass has to know that left_type must be right_type
8409 * for the arithmetic operation and create a cast by itself */
8410 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8411 expression->right = create_implicit_cast(right, arithmetic_type);
8412 expression->base.type = type_left;
8413 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8414 check_pointer_arithmetic(&expression->base.source_position,
8415 type_left, orig_type_left);
8416 expression->base.type = type_left;
8417 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8418 errorf(&expression->base.source_position,
8419 "incompatible types '%T' and '%T' in assignment",
8420 orig_type_left, orig_type_right);
8424 static void semantic_integer_assign(binary_expression_t *expression)
8426 expression_t *left = expression->left;
8427 expression_t *right = expression->right;
8428 type_t *orig_type_left = left->base.type;
8429 type_t *orig_type_right = right->base.type;
8431 if (!is_valid_assignment_lhs(left))
8434 type_t *type_left = skip_typeref(orig_type_left);
8435 type_t *type_right = skip_typeref(orig_type_right);
8437 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8438 /* TODO: improve error message */
8439 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8440 errorf(&expression->base.source_position,
8441 "operation needs integer types");
8446 /* combined instructions are tricky. We can't create an implicit cast on
8447 * the left side, because we need the uncasted form for the store.
8448 * The ast2firm pass has to know that left_type must be right_type
8449 * for the arithmetic operation and create a cast by itself */
8450 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8451 expression->right = create_implicit_cast(right, arithmetic_type);
8452 expression->base.type = type_left;
8455 static void semantic_shift_assign(binary_expression_t *expression)
8457 expression_t *left = expression->left;
8459 if (!is_valid_assignment_lhs(left))
8462 if (!semantic_shift(expression))
8465 expression->base.type = skip_typeref(left->base.type);
8468 static void warn_logical_and_within_or(const expression_t *const expr)
8470 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8472 if (expr->base.parenthesized)
8474 source_position_t const *const pos = &expr->base.source_position;
8475 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8479 * Check the semantic restrictions of a logical expression.
8481 static void semantic_logical_op(binary_expression_t *expression)
8483 /* §6.5.13:2 Each of the operands shall have scalar type.
8484 * §6.5.14:2 Each of the operands shall have scalar type. */
8485 semantic_condition(expression->left, "left operand of logical operator");
8486 semantic_condition(expression->right, "right operand of logical operator");
8487 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8488 warn_logical_and_within_or(expression->left);
8489 warn_logical_and_within_or(expression->right);
8491 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8495 * Check the semantic restrictions of a binary assign expression.
8497 static void semantic_binexpr_assign(binary_expression_t *expression)
8499 expression_t *left = expression->left;
8500 type_t *orig_type_left = left->base.type;
8502 if (!is_valid_assignment_lhs(left))
8505 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8506 report_assign_error(error, orig_type_left, expression->right,
8507 "assignment", &left->base.source_position);
8508 expression->right = create_implicit_cast(expression->right, orig_type_left);
8509 expression->base.type = orig_type_left;
8513 * Determine if the outermost operation (or parts thereof) of the given
8514 * expression has no effect in order to generate a warning about this fact.
8515 * Therefore in some cases this only examines some of the operands of the
8516 * expression (see comments in the function and examples below).
8518 * f() + 23; // warning, because + has no effect
8519 * x || f(); // no warning, because x controls execution of f()
8520 * x ? y : f(); // warning, because y has no effect
8521 * (void)x; // no warning to be able to suppress the warning
8522 * This function can NOT be used for an "expression has definitely no effect"-
8524 static bool expression_has_effect(const expression_t *const expr)
8526 switch (expr->kind) {
8527 case EXPR_ERROR: return true; /* do NOT warn */
8528 case EXPR_REFERENCE: return false;
8529 case EXPR_ENUM_CONSTANT: return false;
8530 case EXPR_LABEL_ADDRESS: return false;
8532 /* suppress the warning for microsoft __noop operations */
8533 case EXPR_LITERAL_MS_NOOP: return true;
8534 case EXPR_LITERAL_BOOLEAN:
8535 case EXPR_LITERAL_CHARACTER:
8536 case EXPR_LITERAL_WIDE_CHARACTER:
8537 case EXPR_LITERAL_INTEGER:
8538 case EXPR_LITERAL_INTEGER_OCTAL:
8539 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8540 case EXPR_LITERAL_FLOATINGPOINT:
8541 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8542 case EXPR_STRING_LITERAL: return false;
8543 case EXPR_WIDE_STRING_LITERAL: return false;
8546 const call_expression_t *const call = &expr->call;
8547 if (call->function->kind != EXPR_REFERENCE)
8550 switch (call->function->reference.entity->function.btk) {
8551 /* FIXME: which builtins have no effect? */
8552 default: return true;
8556 /* Generate the warning if either the left or right hand side of a
8557 * conditional expression has no effect */
8558 case EXPR_CONDITIONAL: {
8559 conditional_expression_t const *const cond = &expr->conditional;
8560 expression_t const *const t = cond->true_expression;
8562 (t == NULL || expression_has_effect(t)) &&
8563 expression_has_effect(cond->false_expression);
8566 case EXPR_SELECT: return false;
8567 case EXPR_ARRAY_ACCESS: return false;
8568 case EXPR_SIZEOF: return false;
8569 case EXPR_CLASSIFY_TYPE: return false;
8570 case EXPR_ALIGNOF: return false;
8572 case EXPR_FUNCNAME: return false;
8573 case EXPR_BUILTIN_CONSTANT_P: return false;
8574 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8575 case EXPR_OFFSETOF: return false;
8576 case EXPR_VA_START: return true;
8577 case EXPR_VA_ARG: return true;
8578 case EXPR_VA_COPY: return true;
8579 case EXPR_STATEMENT: return true; // TODO
8580 case EXPR_COMPOUND_LITERAL: return false;
8582 case EXPR_UNARY_NEGATE: return false;
8583 case EXPR_UNARY_PLUS: return false;
8584 case EXPR_UNARY_BITWISE_NEGATE: return false;
8585 case EXPR_UNARY_NOT: return false;
8586 case EXPR_UNARY_DEREFERENCE: return false;
8587 case EXPR_UNARY_TAKE_ADDRESS: return false;
8588 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8589 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8590 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8591 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8593 /* Treat void casts as if they have an effect in order to being able to
8594 * suppress the warning */
8595 case EXPR_UNARY_CAST: {
8596 type_t *const type = skip_typeref(expr->base.type);
8597 return is_type_void(type);
8600 case EXPR_UNARY_ASSUME: return true;
8601 case EXPR_UNARY_DELETE: return true;
8602 case EXPR_UNARY_DELETE_ARRAY: return true;
8603 case EXPR_UNARY_THROW: return true;
8605 case EXPR_BINARY_ADD: return false;
8606 case EXPR_BINARY_SUB: return false;
8607 case EXPR_BINARY_MUL: return false;
8608 case EXPR_BINARY_DIV: return false;
8609 case EXPR_BINARY_MOD: return false;
8610 case EXPR_BINARY_EQUAL: return false;
8611 case EXPR_BINARY_NOTEQUAL: return false;
8612 case EXPR_BINARY_LESS: return false;
8613 case EXPR_BINARY_LESSEQUAL: return false;
8614 case EXPR_BINARY_GREATER: return false;
8615 case EXPR_BINARY_GREATEREQUAL: return false;
8616 case EXPR_BINARY_BITWISE_AND: return false;
8617 case EXPR_BINARY_BITWISE_OR: return false;
8618 case EXPR_BINARY_BITWISE_XOR: return false;
8619 case EXPR_BINARY_SHIFTLEFT: return false;
8620 case EXPR_BINARY_SHIFTRIGHT: return false;
8621 case EXPR_BINARY_ASSIGN: return true;
8622 case EXPR_BINARY_MUL_ASSIGN: return true;
8623 case EXPR_BINARY_DIV_ASSIGN: return true;
8624 case EXPR_BINARY_MOD_ASSIGN: return true;
8625 case EXPR_BINARY_ADD_ASSIGN: return true;
8626 case EXPR_BINARY_SUB_ASSIGN: return true;
8627 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8628 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8629 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8630 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8631 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8633 /* Only examine the right hand side of && and ||, because the left hand
8634 * side already has the effect of controlling the execution of the right
8636 case EXPR_BINARY_LOGICAL_AND:
8637 case EXPR_BINARY_LOGICAL_OR:
8638 /* Only examine the right hand side of a comma expression, because the left
8639 * hand side has a separate warning */
8640 case EXPR_BINARY_COMMA:
8641 return expression_has_effect(expr->binary.right);
8643 case EXPR_BINARY_ISGREATER: return false;
8644 case EXPR_BINARY_ISGREATEREQUAL: return false;
8645 case EXPR_BINARY_ISLESS: return false;
8646 case EXPR_BINARY_ISLESSEQUAL: return false;
8647 case EXPR_BINARY_ISLESSGREATER: return false;
8648 case EXPR_BINARY_ISUNORDERED: return false;
8651 internal_errorf(HERE, "unexpected expression");
8654 static void semantic_comma(binary_expression_t *expression)
8656 const expression_t *const left = expression->left;
8657 if (!expression_has_effect(left)) {
8658 source_position_t const *const pos = &left->base.source_position;
8659 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8661 expression->base.type = expression->right->base.type;
8665 * @param prec_r precedence of the right operand
8667 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8668 static expression_t *parse_##binexpression_type(expression_t *left) \
8670 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8671 binexpr->binary.left = left; \
8674 expression_t *right = parse_subexpression(prec_r); \
8676 binexpr->binary.right = right; \
8677 sfunc(&binexpr->binary); \
8682 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8683 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8684 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8685 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8686 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8687 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8688 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8689 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8690 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8691 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8692 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8693 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8694 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8695 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8696 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8697 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8698 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8699 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8700 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8701 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8702 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8703 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8704 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8705 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8706 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8707 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8708 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8709 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8710 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8711 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8714 static expression_t *parse_subexpression(precedence_t precedence)
8716 if (token.kind < 0) {
8717 return expected_expression_error();
8720 expression_parser_function_t *parser
8721 = &expression_parsers[token.kind];
8724 if (parser->parser != NULL) {
8725 left = parser->parser();
8727 left = parse_primary_expression();
8729 assert(left != NULL);
8732 if (token.kind < 0) {
8733 return expected_expression_error();
8736 parser = &expression_parsers[token.kind];
8737 if (parser->infix_parser == NULL)
8739 if (parser->infix_precedence < precedence)
8742 left = parser->infix_parser(left);
8744 assert(left != NULL);
8751 * Parse an expression.
8753 static expression_t *parse_expression(void)
8755 return parse_subexpression(PREC_EXPRESSION);
8759 * Register a parser for a prefix-like operator.
8761 * @param parser the parser function
8762 * @param token_kind the token type of the prefix token
8764 static void register_expression_parser(parse_expression_function parser,
8767 expression_parser_function_t *entry = &expression_parsers[token_kind];
8769 if (entry->parser != NULL) {
8770 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8771 panic("trying to register multiple expression parsers for a token");
8773 entry->parser = parser;
8777 * Register a parser for an infix operator with given precedence.
8779 * @param parser the parser function
8780 * @param token_kind the token type of the infix operator
8781 * @param precedence the precedence of the operator
8783 static void register_infix_parser(parse_expression_infix_function parser,
8784 int token_kind, precedence_t precedence)
8786 expression_parser_function_t *entry = &expression_parsers[token_kind];
8788 if (entry->infix_parser != NULL) {
8789 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8790 panic("trying to register multiple infix expression parsers for a "
8793 entry->infix_parser = parser;
8794 entry->infix_precedence = precedence;
8798 * Initialize the expression parsers.
8800 static void init_expression_parsers(void)
8802 memset(&expression_parsers, 0, sizeof(expression_parsers));
8804 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8805 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8806 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8807 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8808 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8809 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8810 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8811 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8812 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8813 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8814 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8815 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8816 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8817 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8818 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8819 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8820 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8821 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8822 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8823 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8824 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8825 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8826 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8827 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8828 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8829 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8830 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8831 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8832 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8833 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8834 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8835 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8836 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8837 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8838 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8839 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8840 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8842 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8843 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8844 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8845 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8846 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8847 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8848 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8849 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8850 register_expression_parser(parse_sizeof, T_sizeof);
8851 register_expression_parser(parse_alignof, T___alignof__);
8852 register_expression_parser(parse_extension, T___extension__);
8853 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8854 register_expression_parser(parse_delete, T_delete);
8855 register_expression_parser(parse_throw, T_throw);
8859 * Parse a asm statement arguments specification.
8861 static asm_argument_t *parse_asm_arguments(bool is_out)
8863 asm_argument_t *result = NULL;
8864 asm_argument_t **anchor = &result;
8866 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8867 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8868 memset(argument, 0, sizeof(argument[0]));
8871 if (token.kind != T_IDENTIFIER) {
8872 parse_error_expected("while parsing asm argument",
8873 T_IDENTIFIER, NULL);
8876 argument->symbol = token.identifier.symbol;
8878 expect(']', end_error);
8881 argument->constraints = parse_string_literals();
8882 expect('(', end_error);
8883 add_anchor_token(')');
8884 expression_t *expression = parse_expression();
8885 rem_anchor_token(')');
8887 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8888 * change size or type representation (e.g. int -> long is ok, but
8889 * int -> float is not) */
8890 if (expression->kind == EXPR_UNARY_CAST) {
8891 type_t *const type = expression->base.type;
8892 type_kind_t const kind = type->kind;
8893 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8896 if (kind == TYPE_ATOMIC) {
8897 atomic_type_kind_t const akind = type->atomic.akind;
8898 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8899 size = get_atomic_type_size(akind);
8901 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8902 size = get_type_size(type_void_ptr);
8906 expression_t *const value = expression->unary.value;
8907 type_t *const value_type = value->base.type;
8908 type_kind_t const value_kind = value_type->kind;
8910 unsigned value_flags;
8911 unsigned value_size;
8912 if (value_kind == TYPE_ATOMIC) {
8913 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8914 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8915 value_size = get_atomic_type_size(value_akind);
8916 } else if (value_kind == TYPE_POINTER) {
8917 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8918 value_size = get_type_size(type_void_ptr);
8923 if (value_flags != flags || value_size != size)
8927 } while (expression->kind == EXPR_UNARY_CAST);
8931 if (!is_lvalue(expression)) {
8932 errorf(&expression->base.source_position,
8933 "asm output argument is not an lvalue");
8936 if (argument->constraints.begin[0] == '=')
8937 determine_lhs_ent(expression, NULL);
8939 mark_vars_read(expression, NULL);
8941 mark_vars_read(expression, NULL);
8943 argument->expression = expression;
8944 expect(')', end_error);
8946 set_address_taken(expression, true);
8949 anchor = &argument->next;
8961 * Parse a asm statement clobber specification.
8963 static asm_clobber_t *parse_asm_clobbers(void)
8965 asm_clobber_t *result = NULL;
8966 asm_clobber_t **anchor = &result;
8968 while (token.kind == T_STRING_LITERAL) {
8969 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8970 clobber->clobber = parse_string_literals();
8973 anchor = &clobber->next;
8983 * Parse an asm statement.
8985 static statement_t *parse_asm_statement(void)
8987 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8988 asm_statement_t *asm_statement = &statement->asms;
8992 if (next_if(T_volatile))
8993 asm_statement->is_volatile = true;
8995 expect('(', end_error);
8996 add_anchor_token(')');
8997 if (token.kind != T_STRING_LITERAL) {
8998 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9001 asm_statement->asm_text = parse_string_literals();
9003 add_anchor_token(':');
9004 if (!next_if(':')) {
9005 rem_anchor_token(':');
9009 asm_statement->outputs = parse_asm_arguments(true);
9010 if (!next_if(':')) {
9011 rem_anchor_token(':');
9015 asm_statement->inputs = parse_asm_arguments(false);
9016 if (!next_if(':')) {
9017 rem_anchor_token(':');
9020 rem_anchor_token(':');
9022 asm_statement->clobbers = parse_asm_clobbers();
9025 rem_anchor_token(')');
9026 expect(')', end_error);
9027 expect(';', end_error);
9030 if (asm_statement->outputs == NULL) {
9031 /* GCC: An 'asm' instruction without any output operands will be treated
9032 * identically to a volatile 'asm' instruction. */
9033 asm_statement->is_volatile = true;
9039 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9041 statement_t *inner_stmt;
9042 switch (token.kind) {
9044 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9045 inner_stmt = create_error_statement();
9049 if (label->kind == STATEMENT_LABEL) {
9050 /* Eat an empty statement here, to avoid the warning about an empty
9051 * statement after a label. label:; is commonly used to have a label
9052 * before a closing brace. */
9053 inner_stmt = create_empty_statement();
9060 inner_stmt = parse_statement();
9061 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9062 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9063 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9064 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9072 * Parse a case statement.
9074 static statement_t *parse_case_statement(void)
9076 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9077 source_position_t *const pos = &statement->base.source_position;
9081 expression_t *expression = parse_expression();
9082 type_t *expression_type = expression->base.type;
9083 type_t *skipped = skip_typeref(expression_type);
9084 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9085 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9086 expression, expression_type);
9089 type_t *type = expression_type;
9090 if (current_switch != NULL) {
9091 type_t *switch_type = current_switch->expression->base.type;
9092 if (is_type_valid(switch_type)) {
9093 expression = create_implicit_cast(expression, switch_type);
9097 statement->case_label.expression = expression;
9098 expression_classification_t const expr_class = is_constant_expression(expression);
9099 if (expr_class != EXPR_CLASS_CONSTANT) {
9100 if (expr_class != EXPR_CLASS_ERROR) {
9101 errorf(pos, "case label does not reduce to an integer constant");
9103 statement->case_label.is_bad = true;
9105 long const val = fold_constant_to_int(expression);
9106 statement->case_label.first_case = val;
9107 statement->case_label.last_case = val;
9111 if (next_if(T_DOTDOTDOT)) {
9112 expression_t *end_range = parse_expression();
9113 expression_type = expression->base.type;
9114 skipped = skip_typeref(expression_type);
9115 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9116 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9117 expression, expression_type);
9120 end_range = create_implicit_cast(end_range, type);
9121 statement->case_label.end_range = end_range;
9122 expression_classification_t const end_class = is_constant_expression(end_range);
9123 if (end_class != EXPR_CLASS_CONSTANT) {
9124 if (end_class != EXPR_CLASS_ERROR) {
9125 errorf(pos, "case range does not reduce to an integer constant");
9127 statement->case_label.is_bad = true;
9129 long const val = fold_constant_to_int(end_range);
9130 statement->case_label.last_case = val;
9132 if (val < statement->case_label.first_case) {
9133 statement->case_label.is_empty_range = true;
9134 warningf(WARN_OTHER, pos, "empty range specified");
9140 PUSH_PARENT(statement);
9142 expect(':', end_error);
9145 if (current_switch != NULL) {
9146 if (! statement->case_label.is_bad) {
9147 /* Check for duplicate case values */
9148 case_label_statement_t *c = &statement->case_label;
9149 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9150 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9153 if (c->last_case < l->first_case || c->first_case > l->last_case)
9156 errorf(pos, "duplicate case value (previously used %P)",
9157 &l->base.source_position);
9161 /* link all cases into the switch statement */
9162 if (current_switch->last_case == NULL) {
9163 current_switch->first_case = &statement->case_label;
9165 current_switch->last_case->next = &statement->case_label;
9167 current_switch->last_case = &statement->case_label;
9169 errorf(pos, "case label not within a switch statement");
9172 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9179 * Parse a default statement.
9181 static statement_t *parse_default_statement(void)
9183 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9187 PUSH_PARENT(statement);
9189 expect(':', end_error);
9192 if (current_switch != NULL) {
9193 const case_label_statement_t *def_label = current_switch->default_label;
9194 if (def_label != NULL) {
9195 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9197 current_switch->default_label = &statement->case_label;
9199 /* link all cases into the switch statement */
9200 if (current_switch->last_case == NULL) {
9201 current_switch->first_case = &statement->case_label;
9203 current_switch->last_case->next = &statement->case_label;
9205 current_switch->last_case = &statement->case_label;
9208 errorf(&statement->base.source_position,
9209 "'default' label not within a switch statement");
9212 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9219 * Parse a label statement.
9221 static statement_t *parse_label_statement(void)
9223 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9224 label_t *const label = get_label();
9225 statement->label.label = label;
9227 PUSH_PARENT(statement);
9229 /* if statement is already set then the label is defined twice,
9230 * otherwise it was just mentioned in a goto/local label declaration so far
9232 source_position_t const* const pos = &statement->base.source_position;
9233 if (label->statement != NULL) {
9234 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9236 label->base.source_position = *pos;
9237 label->statement = statement;
9242 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9243 parse_attributes(NULL); // TODO process attributes
9246 statement->label.statement = parse_label_inner_statement(statement, "label");
9248 /* remember the labels in a list for later checking */
9249 *label_anchor = &statement->label;
9250 label_anchor = &statement->label.next;
9256 static statement_t *parse_inner_statement(void)
9258 statement_t *const stmt = parse_statement();
9259 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9260 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9261 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9262 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9268 * Parse an expression in parentheses and mark its variables as read.
9270 static expression_t *parse_condition(void)
9272 expect('(', end_error0);
9273 add_anchor_token(')');
9274 expression_t *const expr = parse_expression();
9275 mark_vars_read(expr, NULL);
9276 rem_anchor_token(')');
9277 expect(')', end_error1);
9281 return create_error_expression();
9285 * Parse an if statement.
9287 static statement_t *parse_if(void)
9289 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9293 PUSH_PARENT(statement);
9295 add_anchor_token('{');
9297 expression_t *const expr = parse_condition();
9298 statement->ifs.condition = expr;
9299 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9301 semantic_condition(expr, "condition of 'if'-statment");
9303 rem_anchor_token('{');
9305 add_anchor_token(T_else);
9306 statement_t *const true_stmt = parse_inner_statement();
9307 statement->ifs.true_statement = true_stmt;
9308 rem_anchor_token(T_else);
9310 if (true_stmt->kind == STATEMENT_EMPTY) {
9311 warningf(WARN_EMPTY_BODY, HERE,
9312 "suggest braces around empty body in an ‘if’ statement");
9315 if (next_if(T_else)) {
9316 statement->ifs.false_statement = parse_inner_statement();
9318 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9319 warningf(WARN_EMPTY_BODY, HERE,
9320 "suggest braces around empty body in an ‘if’ statement");
9322 } else if (true_stmt->kind == STATEMENT_IF &&
9323 true_stmt->ifs.false_statement != NULL) {
9324 source_position_t const *const pos = &true_stmt->base.source_position;
9325 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9333 * Check that all enums are handled in a switch.
9335 * @param statement the switch statement to check
9337 static void check_enum_cases(const switch_statement_t *statement)
9339 if (!is_warn_on(WARN_SWITCH_ENUM))
9341 const type_t *type = skip_typeref(statement->expression->base.type);
9342 if (! is_type_enum(type))
9344 const enum_type_t *enumt = &type->enumt;
9346 /* if we have a default, no warnings */
9347 if (statement->default_label != NULL)
9350 /* FIXME: calculation of value should be done while parsing */
9351 /* TODO: quadratic algorithm here. Change to an n log n one */
9352 long last_value = -1;
9353 const entity_t *entry = enumt->enume->base.next;
9354 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9355 entry = entry->base.next) {
9356 const expression_t *expression = entry->enum_value.value;
9357 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9359 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9360 if (l->expression == NULL)
9362 if (l->first_case <= value && value <= l->last_case) {
9368 source_position_t const *const pos = &statement->base.source_position;
9369 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9376 * Parse a switch statement.
9378 static statement_t *parse_switch(void)
9380 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9384 PUSH_PARENT(statement);
9386 expression_t *const expr = parse_condition();
9387 type_t * type = skip_typeref(expr->base.type);
9388 if (is_type_integer(type)) {
9389 type = promote_integer(type);
9390 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9391 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9393 } else if (is_type_valid(type)) {
9394 errorf(&expr->base.source_position,
9395 "switch quantity is not an integer, but '%T'", type);
9396 type = type_error_type;
9398 statement->switchs.expression = create_implicit_cast(expr, type);
9400 switch_statement_t *rem = current_switch;
9401 current_switch = &statement->switchs;
9402 statement->switchs.body = parse_inner_statement();
9403 current_switch = rem;
9405 if (statement->switchs.default_label == NULL) {
9406 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9408 check_enum_cases(&statement->switchs);
9414 static statement_t *parse_loop_body(statement_t *const loop)
9416 statement_t *const rem = current_loop;
9417 current_loop = loop;
9419 statement_t *const body = parse_inner_statement();
9426 * Parse a while statement.
9428 static statement_t *parse_while(void)
9430 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9434 PUSH_PARENT(statement);
9436 expression_t *const cond = parse_condition();
9437 statement->whiles.condition = cond;
9438 /* §6.8.5:2 The controlling expression of an iteration statement shall
9439 * have scalar type. */
9440 semantic_condition(cond, "condition of 'while'-statement");
9442 statement->whiles.body = parse_loop_body(statement);
9449 * Parse a do statement.
9451 static statement_t *parse_do(void)
9453 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9457 PUSH_PARENT(statement);
9459 add_anchor_token(T_while);
9460 statement->do_while.body = parse_loop_body(statement);
9461 rem_anchor_token(T_while);
9463 expect(T_while, end_error0);
9465 expression_t *const cond = parse_condition();
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 expect(';', end_error1);
9478 * Parse a for statement.
9480 static statement_t *parse_for(void)
9482 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9486 PUSH_PARENT(statement);
9487 PUSH_SCOPE(&statement->fors.scope);
9489 expect('(', end_error1);
9490 add_anchor_token(')');
9495 } else if (is_declaration_specifier(&token)) {
9496 parse_declaration(record_entity, DECL_FLAGS_NONE);
9498 add_anchor_token(';');
9499 expression_t *const init = parse_expression();
9500 statement->fors.initialisation = init;
9501 mark_vars_read(init, ENT_ANY);
9502 if (!expression_has_effect(init)) {
9503 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9505 rem_anchor_token(';');
9506 expect(';', end_error3);
9512 if (token.kind != ';') {
9513 add_anchor_token(';');
9514 expression_t *const cond = parse_expression();
9515 statement->fors.condition = cond;
9516 /* §6.8.5:2 The controlling expression of an iteration statement
9517 * shall have scalar type. */
9518 semantic_condition(cond, "condition of 'for'-statement");
9519 mark_vars_read(cond, NULL);
9520 rem_anchor_token(';');
9522 expect(';', end_error2);
9524 if (token.kind != ')') {
9525 expression_t *const step = parse_expression();
9526 statement->fors.step = step;
9527 mark_vars_read(step, ENT_ANY);
9528 if (!expression_has_effect(step)) {
9529 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9532 rem_anchor_token(')');
9533 expect(')', end_error1);
9535 statement->fors.body = parse_loop_body(statement);
9543 * Parse a goto statement.
9545 static statement_t *parse_goto(void)
9547 statement_t *statement;
9548 if (GNU_MODE && look_ahead(1)->kind == '*') {
9549 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9553 expression_t *expression = parse_expression();
9554 mark_vars_read(expression, NULL);
9556 /* Argh: although documentation says the expression must be of type void*,
9557 * gcc accepts anything that can be casted into void* without error */
9558 type_t *type = expression->base.type;
9560 if (type != type_error_type) {
9561 if (!is_type_pointer(type) && !is_type_integer(type)) {
9562 errorf(&expression->base.source_position,
9563 "cannot convert to a pointer type");
9564 } else if (type != type_void_ptr) {
9565 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9567 expression = create_implicit_cast(expression, type_void_ptr);
9570 statement->computed_goto.expression = expression;
9572 statement = allocate_statement_zero(STATEMENT_GOTO);
9574 if (token.kind == T_IDENTIFIER) {
9575 label_t *const label = get_label();
9577 statement->gotos.label = label;
9579 /* remember the goto's in a list for later checking */
9580 *goto_anchor = &statement->gotos;
9581 goto_anchor = &statement->gotos.next;
9584 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9586 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9588 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous)->label;
9592 expect(';', end_error);
9599 * Parse a continue statement.
9601 static statement_t *parse_continue(void)
9603 if (current_loop == NULL) {
9604 errorf(HERE, "continue statement not within loop");
9607 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9610 expect(';', end_error);
9617 * Parse a break statement.
9619 static statement_t *parse_break(void)
9621 if (current_switch == NULL && current_loop == NULL) {
9622 errorf(HERE, "break statement not within loop or switch");
9625 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9628 expect(';', end_error);
9635 * Parse a __leave statement.
9637 static statement_t *parse_leave_statement(void)
9639 if (current_try == NULL) {
9640 errorf(HERE, "__leave statement not within __try");
9643 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9646 expect(';', end_error);
9653 * Check if a given entity represents a local variable.
9655 static bool is_local_variable(const entity_t *entity)
9657 if (entity->kind != ENTITY_VARIABLE)
9660 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9661 case STORAGE_CLASS_AUTO:
9662 case STORAGE_CLASS_REGISTER: {
9663 const type_t *type = skip_typeref(entity->declaration.type);
9664 if (is_type_function(type)) {
9676 * Check if a given expression represents a local variable.
9678 static bool expression_is_local_variable(const expression_t *expression)
9680 if (expression->base.kind != EXPR_REFERENCE) {
9683 const entity_t *entity = expression->reference.entity;
9684 return is_local_variable(entity);
9688 * Check if a given expression represents a local variable and
9689 * return its declaration then, else return NULL.
9691 entity_t *expression_is_variable(const expression_t *expression)
9693 if (expression->base.kind != EXPR_REFERENCE) {
9696 entity_t *entity = expression->reference.entity;
9697 if (entity->kind != ENTITY_VARIABLE)
9703 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9705 if (c_mode & _CXX || strict_mode) {
9708 warningf(WARN_OTHER, pos, msg);
9713 * Parse a return statement.
9715 static statement_t *parse_return(void)
9717 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9720 expression_t *return_value = NULL;
9721 if (token.kind != ';') {
9722 return_value = parse_expression();
9723 mark_vars_read(return_value, NULL);
9726 const type_t *const func_type = skip_typeref(current_function->base.type);
9727 assert(is_type_function(func_type));
9728 type_t *const return_type = skip_typeref(func_type->function.return_type);
9730 source_position_t const *const pos = &statement->base.source_position;
9731 if (return_value != NULL) {
9732 type_t *return_value_type = skip_typeref(return_value->base.type);
9734 if (is_type_void(return_type)) {
9735 if (!is_type_void(return_value_type)) {
9736 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9737 /* Only warn in C mode, because GCC does the same */
9738 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9739 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9740 /* Only warn in C mode, because GCC does the same */
9741 err_or_warn(pos, "'return' with expression in function returning 'void'");
9744 assign_error_t error = semantic_assign(return_type, return_value);
9745 report_assign_error(error, return_type, return_value, "'return'",
9748 return_value = create_implicit_cast(return_value, return_type);
9749 /* check for returning address of a local var */
9750 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9751 const expression_t *expression = return_value->unary.value;
9752 if (expression_is_local_variable(expression)) {
9753 warningf(WARN_OTHER, pos, "function returns address of local variable");
9756 } else if (!is_type_void(return_type)) {
9757 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9758 err_or_warn(pos, "'return' without value, in function returning non-void");
9760 statement->returns.value = return_value;
9762 expect(';', end_error);
9769 * Parse a declaration statement.
9771 static statement_t *parse_declaration_statement(void)
9773 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9775 entity_t *before = current_scope->last_entity;
9777 parse_external_declaration();
9779 parse_declaration(record_entity, DECL_FLAGS_NONE);
9782 declaration_statement_t *const decl = &statement->declaration;
9783 entity_t *const begin =
9784 before != NULL ? before->base.next : current_scope->entities;
9785 decl->declarations_begin = begin;
9786 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9792 * Parse an expression statement, ie. expr ';'.
9794 static statement_t *parse_expression_statement(void)
9796 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9798 expression_t *const expr = parse_expression();
9799 statement->expression.expression = expr;
9800 mark_vars_read(expr, ENT_ANY);
9802 expect(';', end_error);
9809 * Parse a microsoft __try { } __finally { } or
9810 * __try{ } __except() { }
9812 static statement_t *parse_ms_try_statment(void)
9814 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9817 PUSH_PARENT(statement);
9819 ms_try_statement_t *rem = current_try;
9820 current_try = &statement->ms_try;
9821 statement->ms_try.try_statement = parse_compound_statement(false);
9826 if (next_if(T___except)) {
9827 expression_t *const expr = parse_condition();
9828 type_t * type = skip_typeref(expr->base.type);
9829 if (is_type_integer(type)) {
9830 type = promote_integer(type);
9831 } else if (is_type_valid(type)) {
9832 errorf(&expr->base.source_position,
9833 "__expect expression is not an integer, but '%T'", type);
9834 type = type_error_type;
9836 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9837 } else if (!next_if(T__finally)) {
9838 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9840 statement->ms_try.final_statement = parse_compound_statement(false);
9844 static statement_t *parse_empty_statement(void)
9846 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9847 statement_t *const statement = create_empty_statement();
9852 static statement_t *parse_local_label_declaration(void)
9854 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9858 entity_t *begin = NULL;
9859 entity_t *end = NULL;
9860 entity_t **anchor = &begin;
9862 if (token.kind != T_IDENTIFIER) {
9863 parse_error_expected("while parsing local label declaration",
9864 T_IDENTIFIER, NULL);
9867 symbol_t *symbol = token.identifier.symbol;
9868 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9869 if (entity != NULL && entity->base.parent_scope == current_scope) {
9870 source_position_t const *const ppos = &entity->base.source_position;
9871 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9873 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9874 entity->base.parent_scope = current_scope;
9875 entity->base.source_position = token.base.source_position;
9878 anchor = &entity->base.next;
9881 environment_push(entity);
9884 } while (next_if(','));
9885 expect(';', end_error);
9887 statement->declaration.declarations_begin = begin;
9888 statement->declaration.declarations_end = end;
9892 static void parse_namespace_definition(void)
9896 entity_t *entity = NULL;
9897 symbol_t *symbol = NULL;
9899 if (token.kind == T_IDENTIFIER) {
9900 symbol = token.identifier.symbol;
9903 entity = get_entity(symbol, NAMESPACE_NORMAL);
9905 && entity->kind != ENTITY_NAMESPACE
9906 && entity->base.parent_scope == current_scope) {
9907 if (is_entity_valid(entity)) {
9908 error_redefined_as_different_kind(&token.base.source_position,
9909 entity, ENTITY_NAMESPACE);
9915 if (entity == NULL) {
9916 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9917 entity->base.source_position = token.base.source_position;
9918 entity->base.parent_scope = current_scope;
9921 if (token.kind == '=') {
9922 /* TODO: parse namespace alias */
9923 panic("namespace alias definition not supported yet");
9926 environment_push(entity);
9927 append_entity(current_scope, entity);
9929 PUSH_SCOPE(&entity->namespacee.members);
9931 entity_t *old_current_entity = current_entity;
9932 current_entity = entity;
9934 expect('{', end_error);
9936 expect('}', end_error);
9939 assert(current_entity == entity);
9940 current_entity = old_current_entity;
9945 * Parse a statement.
9946 * There's also parse_statement() which additionally checks for
9947 * "statement has no effect" warnings
9949 static statement_t *intern_parse_statement(void)
9951 /* declaration or statement */
9952 statement_t *statement;
9953 switch (token.kind) {
9954 case T_IDENTIFIER: {
9955 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9956 if (la1_type == ':') {
9957 statement = parse_label_statement();
9958 } else if (is_typedef_symbol(token.identifier.symbol)) {
9959 statement = parse_declaration_statement();
9961 /* it's an identifier, the grammar says this must be an
9962 * expression statement. However it is common that users mistype
9963 * declaration types, so we guess a bit here to improve robustness
9964 * for incorrect programs */
9968 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9970 statement = parse_expression_statement();
9974 statement = parse_declaration_statement();
9982 case T___extension__: {
9983 /* This can be a prefix to a declaration or an expression statement.
9984 * We simply eat it now and parse the rest with tail recursion. */
9986 statement = intern_parse_statement();
9992 statement = parse_declaration_statement();
9996 statement = parse_local_label_declaration();
9999 case ';': statement = parse_empty_statement(); break;
10000 case '{': statement = parse_compound_statement(false); break;
10001 case T___leave: statement = parse_leave_statement(); break;
10002 case T___try: statement = parse_ms_try_statment(); break;
10003 case T_asm: statement = parse_asm_statement(); break;
10004 case T_break: statement = parse_break(); break;
10005 case T_case: statement = parse_case_statement(); break;
10006 case T_continue: statement = parse_continue(); break;
10007 case T_default: statement = parse_default_statement(); break;
10008 case T_do: statement = parse_do(); break;
10009 case T_for: statement = parse_for(); break;
10010 case T_goto: statement = parse_goto(); break;
10011 case T_if: statement = parse_if(); break;
10012 case T_return: statement = parse_return(); break;
10013 case T_switch: statement = parse_switch(); break;
10014 case T_while: statement = parse_while(); break;
10017 statement = parse_expression_statement();
10021 errorf(HERE, "unexpected token %K while parsing statement", &token);
10022 statement = create_error_statement();
10023 eat_until_anchor();
10031 * parse a statement and emits "statement has no effect" warning if needed
10032 * (This is really a wrapper around intern_parse_statement with check for 1
10033 * single warning. It is needed, because for statement expressions we have
10034 * to avoid the warning on the last statement)
10036 static statement_t *parse_statement(void)
10038 statement_t *statement = intern_parse_statement();
10040 if (statement->kind == STATEMENT_EXPRESSION) {
10041 expression_t *expression = statement->expression.expression;
10042 if (!expression_has_effect(expression)) {
10043 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10051 * Parse a compound statement.
10053 static statement_t *parse_compound_statement(bool inside_expression_statement)
10055 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10057 PUSH_PARENT(statement);
10058 PUSH_SCOPE(&statement->compound.scope);
10061 add_anchor_token('}');
10062 /* tokens, which can start a statement */
10063 /* TODO MS, __builtin_FOO */
10064 add_anchor_token('!');
10065 add_anchor_token('&');
10066 add_anchor_token('(');
10067 add_anchor_token('*');
10068 add_anchor_token('+');
10069 add_anchor_token('-');
10070 add_anchor_token(';');
10071 add_anchor_token('{');
10072 add_anchor_token('~');
10073 add_anchor_token(T_CHARACTER_CONSTANT);
10074 add_anchor_token(T_COLONCOLON);
10075 add_anchor_token(T_FLOATINGPOINT);
10076 add_anchor_token(T_IDENTIFIER);
10077 add_anchor_token(T_INTEGER);
10078 add_anchor_token(T_MINUSMINUS);
10079 add_anchor_token(T_PLUSPLUS);
10080 add_anchor_token(T_STRING_LITERAL);
10081 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10082 add_anchor_token(T_WIDE_STRING_LITERAL);
10083 add_anchor_token(T__Bool);
10084 add_anchor_token(T__Complex);
10085 add_anchor_token(T__Imaginary);
10086 add_anchor_token(T___FUNCTION__);
10087 add_anchor_token(T___PRETTY_FUNCTION__);
10088 add_anchor_token(T___alignof__);
10089 add_anchor_token(T___attribute__);
10090 add_anchor_token(T___builtin_va_start);
10091 add_anchor_token(T___extension__);
10092 add_anchor_token(T___func__);
10093 add_anchor_token(T___imag__);
10094 add_anchor_token(T___label__);
10095 add_anchor_token(T___real__);
10096 add_anchor_token(T___thread);
10097 add_anchor_token(T_asm);
10098 add_anchor_token(T_auto);
10099 add_anchor_token(T_bool);
10100 add_anchor_token(T_break);
10101 add_anchor_token(T_case);
10102 add_anchor_token(T_char);
10103 add_anchor_token(T_class);
10104 add_anchor_token(T_const);
10105 add_anchor_token(T_const_cast);
10106 add_anchor_token(T_continue);
10107 add_anchor_token(T_default);
10108 add_anchor_token(T_delete);
10109 add_anchor_token(T_double);
10110 add_anchor_token(T_do);
10111 add_anchor_token(T_dynamic_cast);
10112 add_anchor_token(T_enum);
10113 add_anchor_token(T_extern);
10114 add_anchor_token(T_false);
10115 add_anchor_token(T_float);
10116 add_anchor_token(T_for);
10117 add_anchor_token(T_goto);
10118 add_anchor_token(T_if);
10119 add_anchor_token(T_inline);
10120 add_anchor_token(T_int);
10121 add_anchor_token(T_long);
10122 add_anchor_token(T_new);
10123 add_anchor_token(T_operator);
10124 add_anchor_token(T_register);
10125 add_anchor_token(T_reinterpret_cast);
10126 add_anchor_token(T_restrict);
10127 add_anchor_token(T_return);
10128 add_anchor_token(T_short);
10129 add_anchor_token(T_signed);
10130 add_anchor_token(T_sizeof);
10131 add_anchor_token(T_static);
10132 add_anchor_token(T_static_cast);
10133 add_anchor_token(T_struct);
10134 add_anchor_token(T_switch);
10135 add_anchor_token(T_template);
10136 add_anchor_token(T_this);
10137 add_anchor_token(T_throw);
10138 add_anchor_token(T_true);
10139 add_anchor_token(T_try);
10140 add_anchor_token(T_typedef);
10141 add_anchor_token(T_typeid);
10142 add_anchor_token(T_typename);
10143 add_anchor_token(T_typeof);
10144 add_anchor_token(T_union);
10145 add_anchor_token(T_unsigned);
10146 add_anchor_token(T_using);
10147 add_anchor_token(T_void);
10148 add_anchor_token(T_volatile);
10149 add_anchor_token(T_wchar_t);
10150 add_anchor_token(T_while);
10152 statement_t **anchor = &statement->compound.statements;
10153 bool only_decls_so_far = true;
10154 while (token.kind != '}' && token.kind != T_EOF) {
10155 statement_t *sub_statement = intern_parse_statement();
10156 if (sub_statement->kind == STATEMENT_ERROR) {
10160 if (sub_statement->kind != STATEMENT_DECLARATION) {
10161 only_decls_so_far = false;
10162 } else if (!only_decls_so_far) {
10163 source_position_t const *const pos = &sub_statement->base.source_position;
10164 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10167 *anchor = sub_statement;
10168 anchor = &sub_statement->base.next;
10170 expect('}', end_error);
10173 /* look over all statements again to produce no effect warnings */
10174 if (is_warn_on(WARN_UNUSED_VALUE)) {
10175 statement_t *sub_statement = statement->compound.statements;
10176 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10177 if (sub_statement->kind != STATEMENT_EXPRESSION)
10179 /* don't emit a warning for the last expression in an expression
10180 * statement as it has always an effect */
10181 if (inside_expression_statement && sub_statement->base.next == NULL)
10184 expression_t *expression = sub_statement->expression.expression;
10185 if (!expression_has_effect(expression)) {
10186 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10191 rem_anchor_token(T_while);
10192 rem_anchor_token(T_wchar_t);
10193 rem_anchor_token(T_volatile);
10194 rem_anchor_token(T_void);
10195 rem_anchor_token(T_using);
10196 rem_anchor_token(T_unsigned);
10197 rem_anchor_token(T_union);
10198 rem_anchor_token(T_typeof);
10199 rem_anchor_token(T_typename);
10200 rem_anchor_token(T_typeid);
10201 rem_anchor_token(T_typedef);
10202 rem_anchor_token(T_try);
10203 rem_anchor_token(T_true);
10204 rem_anchor_token(T_throw);
10205 rem_anchor_token(T_this);
10206 rem_anchor_token(T_template);
10207 rem_anchor_token(T_switch);
10208 rem_anchor_token(T_struct);
10209 rem_anchor_token(T_static_cast);
10210 rem_anchor_token(T_static);
10211 rem_anchor_token(T_sizeof);
10212 rem_anchor_token(T_signed);
10213 rem_anchor_token(T_short);
10214 rem_anchor_token(T_return);
10215 rem_anchor_token(T_restrict);
10216 rem_anchor_token(T_reinterpret_cast);
10217 rem_anchor_token(T_register);
10218 rem_anchor_token(T_operator);
10219 rem_anchor_token(T_new);
10220 rem_anchor_token(T_long);
10221 rem_anchor_token(T_int);
10222 rem_anchor_token(T_inline);
10223 rem_anchor_token(T_if);
10224 rem_anchor_token(T_goto);
10225 rem_anchor_token(T_for);
10226 rem_anchor_token(T_float);
10227 rem_anchor_token(T_false);
10228 rem_anchor_token(T_extern);
10229 rem_anchor_token(T_enum);
10230 rem_anchor_token(T_dynamic_cast);
10231 rem_anchor_token(T_do);
10232 rem_anchor_token(T_double);
10233 rem_anchor_token(T_delete);
10234 rem_anchor_token(T_default);
10235 rem_anchor_token(T_continue);
10236 rem_anchor_token(T_const_cast);
10237 rem_anchor_token(T_const);
10238 rem_anchor_token(T_class);
10239 rem_anchor_token(T_char);
10240 rem_anchor_token(T_case);
10241 rem_anchor_token(T_break);
10242 rem_anchor_token(T_bool);
10243 rem_anchor_token(T_auto);
10244 rem_anchor_token(T_asm);
10245 rem_anchor_token(T___thread);
10246 rem_anchor_token(T___real__);
10247 rem_anchor_token(T___label__);
10248 rem_anchor_token(T___imag__);
10249 rem_anchor_token(T___func__);
10250 rem_anchor_token(T___extension__);
10251 rem_anchor_token(T___builtin_va_start);
10252 rem_anchor_token(T___attribute__);
10253 rem_anchor_token(T___alignof__);
10254 rem_anchor_token(T___PRETTY_FUNCTION__);
10255 rem_anchor_token(T___FUNCTION__);
10256 rem_anchor_token(T__Imaginary);
10257 rem_anchor_token(T__Complex);
10258 rem_anchor_token(T__Bool);
10259 rem_anchor_token(T_WIDE_STRING_LITERAL);
10260 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10261 rem_anchor_token(T_STRING_LITERAL);
10262 rem_anchor_token(T_PLUSPLUS);
10263 rem_anchor_token(T_MINUSMINUS);
10264 rem_anchor_token(T_INTEGER);
10265 rem_anchor_token(T_IDENTIFIER);
10266 rem_anchor_token(T_FLOATINGPOINT);
10267 rem_anchor_token(T_COLONCOLON);
10268 rem_anchor_token(T_CHARACTER_CONSTANT);
10269 rem_anchor_token('~');
10270 rem_anchor_token('{');
10271 rem_anchor_token(';');
10272 rem_anchor_token('-');
10273 rem_anchor_token('+');
10274 rem_anchor_token('*');
10275 rem_anchor_token('(');
10276 rem_anchor_token('&');
10277 rem_anchor_token('!');
10278 rem_anchor_token('}');
10286 * Check for unused global static functions and variables
10288 static void check_unused_globals(void)
10290 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10293 for (const entity_t *entity = file_scope->entities; entity != NULL;
10294 entity = entity->base.next) {
10295 if (!is_declaration(entity))
10298 const declaration_t *declaration = &entity->declaration;
10299 if (declaration->used ||
10300 declaration->modifiers & DM_UNUSED ||
10301 declaration->modifiers & DM_USED ||
10302 declaration->storage_class != STORAGE_CLASS_STATIC)
10307 if (entity->kind == ENTITY_FUNCTION) {
10308 /* inhibit warning for static inline functions */
10309 if (entity->function.is_inline)
10312 why = WARN_UNUSED_FUNCTION;
10313 s = entity->function.statement != NULL ? "defined" : "declared";
10315 why = WARN_UNUSED_VARIABLE;
10319 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10323 static void parse_global_asm(void)
10325 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10328 expect('(', end_error);
10330 statement->asms.asm_text = parse_string_literals();
10331 statement->base.next = unit->global_asm;
10332 unit->global_asm = statement;
10334 expect(')', end_error);
10335 expect(';', end_error);
10340 static void parse_linkage_specification(void)
10344 source_position_t const pos = *HERE;
10345 char const *const linkage = parse_string_literals().begin;
10347 linkage_kind_t old_linkage = current_linkage;
10348 linkage_kind_t new_linkage;
10349 if (streq(linkage, "C")) {
10350 new_linkage = LINKAGE_C;
10351 } else if (streq(linkage, "C++")) {
10352 new_linkage = LINKAGE_CXX;
10354 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10355 new_linkage = LINKAGE_C;
10357 current_linkage = new_linkage;
10359 if (next_if('{')) {
10361 expect('}', end_error);
10367 assert(current_linkage == new_linkage);
10368 current_linkage = old_linkage;
10371 static void parse_external(void)
10373 switch (token.kind) {
10375 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10376 parse_linkage_specification();
10378 DECLARATION_START_NO_EXTERN
10380 case T___extension__:
10381 /* tokens below are for implicit int */
10382 case '&': /* & x; -> int& x; (and error later, because C++ has no
10384 case '*': /* * x; -> int* x; */
10385 case '(': /* (x); -> int (x); */
10387 parse_external_declaration();
10393 parse_global_asm();
10397 parse_namespace_definition();
10401 if (!strict_mode) {
10402 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10409 errorf(HERE, "stray %K outside of function", &token);
10410 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10411 eat_until_matching_token(token.kind);
10417 static void parse_externals(void)
10419 add_anchor_token('}');
10420 add_anchor_token(T_EOF);
10423 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10424 unsigned short token_anchor_copy[T_LAST_TOKEN];
10425 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10428 while (token.kind != T_EOF && token.kind != '}') {
10430 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10431 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10433 /* the anchor set and its copy differs */
10434 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10437 if (in_gcc_extension) {
10438 /* an gcc extension scope was not closed */
10439 internal_errorf(HERE, "Leaked __extension__");
10446 rem_anchor_token(T_EOF);
10447 rem_anchor_token('}');
10451 * Parse a translation unit.
10453 static void parse_translation_unit(void)
10455 add_anchor_token(T_EOF);
10460 if (token.kind == T_EOF)
10463 errorf(HERE, "stray %K outside of function", &token);
10464 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10465 eat_until_matching_token(token.kind);
10470 void set_default_visibility(elf_visibility_tag_t visibility)
10472 default_visibility = visibility;
10478 * @return the translation unit or NULL if errors occurred.
10480 void start_parsing(void)
10482 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10483 label_stack = NEW_ARR_F(stack_entry_t, 0);
10484 diagnostic_count = 0;
10488 print_to_file(stderr);
10490 assert(unit == NULL);
10491 unit = allocate_ast_zero(sizeof(unit[0]));
10493 assert(file_scope == NULL);
10494 file_scope = &unit->scope;
10496 assert(current_scope == NULL);
10497 scope_push(&unit->scope);
10499 create_gnu_builtins();
10501 create_microsoft_intrinsics();
10504 translation_unit_t *finish_parsing(void)
10506 assert(current_scope == &unit->scope);
10509 assert(file_scope == &unit->scope);
10510 check_unused_globals();
10513 DEL_ARR_F(environment_stack);
10514 DEL_ARR_F(label_stack);
10516 translation_unit_t *result = unit;
10521 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10522 * are given length one. */
10523 static void complete_incomplete_arrays(void)
10525 size_t n = ARR_LEN(incomplete_arrays);
10526 for (size_t i = 0; i != n; ++i) {
10527 declaration_t *const decl = incomplete_arrays[i];
10528 type_t *const type = skip_typeref(decl->type);
10530 if (!is_type_incomplete(type))
10533 source_position_t const *const pos = &decl->base.source_position;
10534 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10536 type_t *const new_type = duplicate_type(type);
10537 new_type->array.size_constant = true;
10538 new_type->array.has_implicit_size = true;
10539 new_type->array.size = 1;
10541 type_t *const result = identify_new_type(new_type);
10543 decl->type = result;
10547 void prepare_main_collect2(entity_t *entity)
10549 PUSH_SCOPE(&entity->function.statement->compound.scope);
10551 // create call to __main
10552 symbol_t *symbol = symbol_table_insert("__main");
10553 entity_t *subsubmain_ent
10554 = create_implicit_function(symbol, &builtin_source_position);
10556 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10557 type_t *ftype = subsubmain_ent->declaration.type;
10558 ref->base.source_position = builtin_source_position;
10559 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10560 ref->reference.entity = subsubmain_ent;
10562 expression_t *call = allocate_expression_zero(EXPR_CALL);
10563 call->base.source_position = builtin_source_position;
10564 call->base.type = type_void;
10565 call->call.function = ref;
10567 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10568 expr_statement->base.source_position = builtin_source_position;
10569 expr_statement->expression.expression = call;
10571 statement_t *statement = entity->function.statement;
10572 assert(statement->kind == STATEMENT_COMPOUND);
10573 compound_statement_t *compounds = &statement->compound;
10575 expr_statement->base.next = compounds->statements;
10576 compounds->statements = expr_statement;
10583 lookahead_bufpos = 0;
10584 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10587 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10588 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10589 parse_translation_unit();
10590 complete_incomplete_arrays();
10591 DEL_ARR_F(incomplete_arrays);
10592 incomplete_arrays = NULL;
10596 * Initialize the parser.
10598 void init_parser(void)
10600 sym_anonymous = symbol_table_insert("<anonymous>");
10602 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10604 init_expression_parsers();
10605 obstack_init(&temp_obst);
10609 * Terminate the parser.
10611 void exit_parser(void)
10613 obstack_free(&temp_obst, NULL);