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, &pos);
2356 entity->compound.alignment = 1;
2357 entity->base.parent_scope = current_scope;
2358 if (symbol != NULL) {
2359 environment_push(entity);
2361 append_entity(current_scope, entity);
2364 if (token.kind == '{') {
2365 parse_compound_type_entries(&entity->compound);
2367 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2368 if (symbol == NULL) {
2369 assert(anonymous_entity == NULL);
2370 anonymous_entity = entity;
2374 if (attributes != NULL) {
2375 handle_entity_attributes(attributes, entity);
2378 return &entity->compound;
2381 static void parse_enum_entries(type_t *const enum_type)
2385 if (token.kind == '}') {
2386 errorf(HERE, "empty enum not allowed");
2391 add_anchor_token('}');
2393 if (token.kind != T_IDENTIFIER) {
2394 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2396 rem_anchor_token('}');
2400 symbol_t *symbol = token.identifier.symbol;
2401 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, symbol, HERE);
2402 entity->enum_value.enum_type = enum_type;
2406 expression_t *value = parse_constant_expression();
2408 value = create_implicit_cast(value, enum_type);
2409 entity->enum_value.value = value;
2414 record_entity(entity, false);
2415 } while (next_if(',') && token.kind != '}');
2416 rem_anchor_token('}');
2418 expect('}', end_error);
2424 static type_t *parse_enum_specifier(void)
2426 source_position_t const pos = *HERE;
2431 switch (token.kind) {
2433 symbol = token.identifier.symbol;
2434 entity = get_tag(symbol, ENTITY_ENUM);
2437 if (entity != NULL) {
2438 if (entity->base.parent_scope != current_scope &&
2439 (token.kind == '{' || token.kind == ';')) {
2440 /* we're in an inner scope and have a definition. Shadow
2441 * existing definition in outer scope */
2443 } else if (entity->enume.complete && token.kind == '{') {
2444 source_position_t const *const ppos = &entity->base.source_position;
2445 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2456 parse_error_expected("while parsing enum type specifier",
2457 T_IDENTIFIER, '{', NULL);
2461 if (entity == NULL) {
2462 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol, &pos);
2463 entity->base.parent_scope = current_scope;
2466 type_t *const type = allocate_type_zero(TYPE_ENUM);
2467 type->enumt.enume = &entity->enume;
2468 type->enumt.base.akind = ATOMIC_TYPE_INT;
2470 if (token.kind == '{') {
2471 if (symbol != NULL) {
2472 environment_push(entity);
2474 append_entity(current_scope, entity);
2475 entity->enume.complete = true;
2477 parse_enum_entries(type);
2478 parse_attributes(NULL);
2480 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2481 if (symbol == NULL) {
2482 assert(anonymous_entity == NULL);
2483 anonymous_entity = entity;
2485 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2486 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2493 * if a symbol is a typedef to another type, return true
2495 static bool is_typedef_symbol(symbol_t *symbol)
2497 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2498 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2501 static type_t *parse_typeof(void)
2507 expect('(', end_error);
2508 add_anchor_token(')');
2510 expression_t *expression = NULL;
2512 switch (token.kind) {
2514 if (is_typedef_symbol(token.identifier.symbol)) {
2516 type = parse_typename();
2519 expression = parse_expression();
2520 type = revert_automatic_type_conversion(expression);
2525 rem_anchor_token(')');
2526 expect(')', end_error);
2528 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2529 typeof_type->typeoft.expression = expression;
2530 typeof_type->typeoft.typeof_type = type;
2537 typedef enum specifiers_t {
2538 SPECIFIER_SIGNED = 1 << 0,
2539 SPECIFIER_UNSIGNED = 1 << 1,
2540 SPECIFIER_LONG = 1 << 2,
2541 SPECIFIER_INT = 1 << 3,
2542 SPECIFIER_DOUBLE = 1 << 4,
2543 SPECIFIER_CHAR = 1 << 5,
2544 SPECIFIER_WCHAR_T = 1 << 6,
2545 SPECIFIER_SHORT = 1 << 7,
2546 SPECIFIER_LONG_LONG = 1 << 8,
2547 SPECIFIER_FLOAT = 1 << 9,
2548 SPECIFIER_BOOL = 1 << 10,
2549 SPECIFIER_VOID = 1 << 11,
2550 SPECIFIER_INT8 = 1 << 12,
2551 SPECIFIER_INT16 = 1 << 13,
2552 SPECIFIER_INT32 = 1 << 14,
2553 SPECIFIER_INT64 = 1 << 15,
2554 SPECIFIER_INT128 = 1 << 16,
2555 SPECIFIER_COMPLEX = 1 << 17,
2556 SPECIFIER_IMAGINARY = 1 << 18,
2559 static type_t *get_typedef_type(symbol_t *symbol)
2561 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2562 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2565 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2566 type->typedeft.typedefe = &entity->typedefe;
2571 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2573 expect('(', end_error);
2575 attribute_property_argument_t *property
2576 = allocate_ast_zero(sizeof(*property));
2579 if (token.kind != T_IDENTIFIER) {
2580 parse_error_expected("while parsing property declspec",
2581 T_IDENTIFIER, NULL);
2586 symbol_t *symbol = token.identifier.symbol;
2587 if (streq(symbol->string, "put")) {
2588 prop = &property->put_symbol;
2589 } else if (streq(symbol->string, "get")) {
2590 prop = &property->get_symbol;
2592 errorf(HERE, "expected put or get in property declspec");
2596 expect('=', end_error);
2597 if (token.kind != T_IDENTIFIER) {
2598 parse_error_expected("while parsing property declspec",
2599 T_IDENTIFIER, NULL);
2603 *prop = token.identifier.symbol;
2605 } while (next_if(','));
2607 attribute->a.property = property;
2609 expect(')', end_error);
2615 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2617 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2618 if (next_if(T_restrict)) {
2619 kind = ATTRIBUTE_MS_RESTRICT;
2620 } else if (token.kind == T_IDENTIFIER) {
2621 const char *name = token.identifier.symbol->string;
2622 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2624 const char *attribute_name = get_attribute_name(k);
2625 if (attribute_name != NULL && streq(attribute_name, name)) {
2631 if (kind == ATTRIBUTE_UNKNOWN) {
2632 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2635 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2639 attribute_t *attribute = allocate_attribute_zero(kind);
2642 if (kind == ATTRIBUTE_MS_PROPERTY) {
2643 return parse_attribute_ms_property(attribute);
2646 /* parse arguments */
2648 attribute->a.arguments = parse_attribute_arguments();
2653 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2657 expect('(', end_error);
2658 if (token.kind != ')') {
2659 add_anchor_token(')');
2661 attribute_t **anchor = &first;
2663 while (*anchor != NULL)
2664 anchor = &(*anchor)->next;
2666 attribute_t *attribute
2667 = parse_microsoft_extended_decl_modifier_single();
2668 if (attribute == NULL)
2671 *anchor = attribute;
2672 anchor = &attribute->next;
2673 } while (next_if(','));
2675 rem_anchor_token(')');
2677 expect(')', end_error);
2682 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2684 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol, HERE);
2685 if (is_declaration(entity)) {
2686 entity->declaration.type = type_error_type;
2687 entity->declaration.implicit = true;
2688 } else if (kind == ENTITY_TYPEDEF) {
2689 entity->typedefe.type = type_error_type;
2690 entity->typedefe.builtin = true;
2692 if (kind != ENTITY_COMPOUND_MEMBER)
2693 record_entity(entity, false);
2697 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2699 type_t *type = NULL;
2700 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2701 unsigned type_specifiers = 0;
2702 bool newtype = false;
2703 bool saw_error = false;
2705 memset(specifiers, 0, sizeof(*specifiers));
2706 specifiers->source_position = token.base.source_position;
2709 specifiers->attributes = parse_attributes(specifiers->attributes);
2711 switch (token.kind) {
2713 #define MATCH_STORAGE_CLASS(token, class) \
2715 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2716 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2718 specifiers->storage_class = class; \
2719 if (specifiers->thread_local) \
2720 goto check_thread_storage_class; \
2724 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2725 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2726 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2727 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2728 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2731 specifiers->attributes
2732 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2736 if (specifiers->thread_local) {
2737 errorf(HERE, "duplicate '__thread'");
2739 specifiers->thread_local = true;
2740 check_thread_storage_class:
2741 switch (specifiers->storage_class) {
2742 case STORAGE_CLASS_EXTERN:
2743 case STORAGE_CLASS_NONE:
2744 case STORAGE_CLASS_STATIC:
2748 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2749 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2750 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2751 wrong_thread_storage_class:
2752 errorf(HERE, "'__thread' used with '%s'", wrong);
2759 /* type qualifiers */
2760 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2762 qualifiers |= qualifier; \
2766 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2767 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2768 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2769 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2770 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2771 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2772 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2773 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2775 /* type specifiers */
2776 #define MATCH_SPECIFIER(token, specifier, name) \
2778 if (type_specifiers & specifier) { \
2779 errorf(HERE, "multiple " name " type specifiers given"); \
2781 type_specifiers |= specifier; \
2786 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2787 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2788 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2789 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2790 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2791 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2792 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2793 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2794 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2795 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2796 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2797 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2798 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2799 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2800 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2801 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2802 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2803 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2807 specifiers->is_inline = true;
2811 case T__forceinline:
2813 specifiers->modifiers |= DM_FORCEINLINE;
2818 if (type_specifiers & SPECIFIER_LONG_LONG) {
2819 errorf(HERE, "too many long type specifiers given");
2820 } else if (type_specifiers & SPECIFIER_LONG) {
2821 type_specifiers |= SPECIFIER_LONG_LONG;
2823 type_specifiers |= SPECIFIER_LONG;
2828 #define CHECK_DOUBLE_TYPE() \
2829 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2832 CHECK_DOUBLE_TYPE();
2833 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2835 type->compound.compound = parse_compound_type_specifier(true);
2838 CHECK_DOUBLE_TYPE();
2839 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2840 type->compound.compound = parse_compound_type_specifier(false);
2843 CHECK_DOUBLE_TYPE();
2844 type = parse_enum_specifier();
2847 CHECK_DOUBLE_TYPE();
2848 type = parse_typeof();
2850 case T___builtin_va_list:
2851 CHECK_DOUBLE_TYPE();
2852 type = duplicate_type(type_valist);
2856 case T_IDENTIFIER: {
2857 /* only parse identifier if we haven't found a type yet */
2858 if (type != NULL || type_specifiers != 0) {
2859 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2860 * declaration, so it doesn't generate errors about expecting '(' or
2862 switch (look_ahead(1)->kind) {
2869 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2873 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2878 goto finish_specifiers;
2882 type_t *const typedef_type = get_typedef_type(token.identifier.symbol);
2883 if (typedef_type == NULL) {
2884 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2885 * declaration, so it doesn't generate 'implicit int' followed by more
2886 * errors later on. */
2887 token_kind_t const la1_type = (token_kind_t)look_ahead(1)->kind;
2893 errorf(HERE, "%K does not name a type", &token);
2895 symbol_t *symbol = token.identifier.symbol;
2897 = create_error_entity(symbol, ENTITY_TYPEDEF);
2899 type = allocate_type_zero(TYPE_TYPEDEF);
2900 type->typedeft.typedefe = &entity->typedefe;
2908 goto finish_specifiers;
2913 type = typedef_type;
2917 /* function specifier */
2919 goto finish_specifiers;
2924 specifiers->attributes = parse_attributes(specifiers->attributes);
2926 if (type == NULL || (saw_error && type_specifiers != 0)) {
2927 atomic_type_kind_t atomic_type;
2929 /* match valid basic types */
2930 switch (type_specifiers) {
2931 case SPECIFIER_VOID:
2932 atomic_type = ATOMIC_TYPE_VOID;
2934 case SPECIFIER_WCHAR_T:
2935 atomic_type = ATOMIC_TYPE_WCHAR_T;
2937 case SPECIFIER_CHAR:
2938 atomic_type = ATOMIC_TYPE_CHAR;
2940 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
2941 atomic_type = ATOMIC_TYPE_SCHAR;
2943 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
2944 atomic_type = ATOMIC_TYPE_UCHAR;
2946 case SPECIFIER_SHORT:
2947 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
2948 case SPECIFIER_SHORT | SPECIFIER_INT:
2949 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2950 atomic_type = ATOMIC_TYPE_SHORT;
2952 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
2953 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
2954 atomic_type = ATOMIC_TYPE_USHORT;
2957 case SPECIFIER_SIGNED:
2958 case SPECIFIER_SIGNED | SPECIFIER_INT:
2959 atomic_type = ATOMIC_TYPE_INT;
2961 case SPECIFIER_UNSIGNED:
2962 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
2963 atomic_type = ATOMIC_TYPE_UINT;
2965 case SPECIFIER_LONG:
2966 case SPECIFIER_SIGNED | SPECIFIER_LONG:
2967 case SPECIFIER_LONG | SPECIFIER_INT:
2968 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2969 atomic_type = ATOMIC_TYPE_LONG;
2971 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
2972 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
2973 atomic_type = ATOMIC_TYPE_ULONG;
2976 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2977 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2978 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
2979 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2981 atomic_type = ATOMIC_TYPE_LONGLONG;
2982 goto warn_about_long_long;
2984 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
2985 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
2987 atomic_type = ATOMIC_TYPE_ULONGLONG;
2988 warn_about_long_long:
2989 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
2992 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
2993 atomic_type = unsigned_int8_type_kind;
2996 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
2997 atomic_type = unsigned_int16_type_kind;
3000 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3001 atomic_type = unsigned_int32_type_kind;
3004 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3005 atomic_type = unsigned_int64_type_kind;
3008 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3009 atomic_type = unsigned_int128_type_kind;
3012 case SPECIFIER_INT8:
3013 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3014 atomic_type = int8_type_kind;
3017 case SPECIFIER_INT16:
3018 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3019 atomic_type = int16_type_kind;
3022 case SPECIFIER_INT32:
3023 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3024 atomic_type = int32_type_kind;
3027 case SPECIFIER_INT64:
3028 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3029 atomic_type = int64_type_kind;
3032 case SPECIFIER_INT128:
3033 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3034 atomic_type = int128_type_kind;
3037 case SPECIFIER_FLOAT:
3038 atomic_type = ATOMIC_TYPE_FLOAT;
3040 case SPECIFIER_DOUBLE:
3041 atomic_type = ATOMIC_TYPE_DOUBLE;
3043 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3044 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3046 case SPECIFIER_BOOL:
3047 atomic_type = ATOMIC_TYPE_BOOL;
3049 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3050 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3051 atomic_type = ATOMIC_TYPE_FLOAT;
3053 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3054 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3055 atomic_type = ATOMIC_TYPE_DOUBLE;
3057 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3058 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3059 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3062 /* invalid specifier combination, give an error message */
3063 source_position_t const* const pos = &specifiers->source_position;
3064 if (type_specifiers == 0) {
3066 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3067 if (!(c_mode & _CXX) && !strict_mode) {
3068 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3069 atomic_type = ATOMIC_TYPE_INT;
3072 errorf(pos, "no type specifiers given in declaration");
3075 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3076 (type_specifiers & SPECIFIER_UNSIGNED)) {
3077 errorf(pos, "signed and unsigned specifiers given");
3078 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3079 errorf(pos, "only integer types can be signed or unsigned");
3081 errorf(pos, "multiple datatypes in declaration");
3087 if (type_specifiers & SPECIFIER_COMPLEX) {
3088 type = allocate_type_zero(TYPE_COMPLEX);
3089 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3090 type = allocate_type_zero(TYPE_IMAGINARY);
3092 type = allocate_type_zero(TYPE_ATOMIC);
3094 type->atomic.akind = atomic_type;
3096 } else if (type_specifiers != 0) {
3097 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3100 /* FIXME: check type qualifiers here */
3101 type->base.qualifiers = qualifiers;
3104 type = identify_new_type(type);
3106 type = typehash_insert(type);
3109 if (specifiers->attributes != NULL)
3110 type = handle_type_attributes(specifiers->attributes, type);
3111 specifiers->type = type;
3115 specifiers->type = type_error_type;
3118 static type_qualifiers_t parse_type_qualifiers(void)
3120 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3123 switch (token.kind) {
3124 /* type qualifiers */
3125 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3126 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3127 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3128 /* microsoft extended type modifiers */
3129 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3130 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3131 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3132 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3133 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3142 * Parses an K&R identifier list
3144 static void parse_identifier_list(scope_t *scope)
3146 assert(token.kind == T_IDENTIFIER);
3148 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.identifier.symbol, HERE);
3149 /* a K&R parameter has no type, yet */
3153 append_entity(scope, entity);
3154 } while (next_if(',') && token.kind == T_IDENTIFIER);
3157 static entity_t *parse_parameter(void)
3159 declaration_specifiers_t specifiers;
3160 parse_declaration_specifiers(&specifiers);
3162 entity_t *entity = parse_declarator(&specifiers,
3163 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3164 anonymous_entity = NULL;
3168 static void semantic_parameter_incomplete(const entity_t *entity)
3170 assert(entity->kind == ENTITY_PARAMETER);
3172 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3173 * list in a function declarator that is part of a
3174 * definition of that function shall not have
3175 * incomplete type. */
3176 type_t *type = skip_typeref(entity->declaration.type);
3177 if (is_type_incomplete(type)) {
3178 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3182 static bool has_parameters(void)
3184 /* func(void) is not a parameter */
3185 if (look_ahead(1)->kind != ')')
3187 if (token.kind == T_IDENTIFIER) {
3188 entity_t const *const entity
3189 = get_entity(token.identifier.symbol, NAMESPACE_NORMAL);
3192 if (entity->kind != ENTITY_TYPEDEF)
3194 type_t const *const type = skip_typeref(entity->typedefe.type);
3195 if (!is_type_void(type))
3197 if (c_mode & _CXX) {
3198 /* ISO/IEC 14882:1998(E) §8.3.5:2 It must be literally (void). A typedef
3199 * is not allowed. */
3200 errorf(HERE, "empty parameter list defined with a typedef of 'void' not allowed in C++");
3201 } else if (type->base.qualifiers != TYPE_QUALIFIER_NONE) {
3202 /* §6.7.5.3:10 Qualification is not allowed here. */
3203 errorf(HERE, "'void' as parameter must not have type qualifiers");
3205 } else if (token.kind != T_void) {
3213 * Parses function type parameters (and optionally creates variable_t entities
3214 * for them in a scope)
3216 static void parse_parameters(function_type_t *type, scope_t *scope)
3219 add_anchor_token(')');
3220 int saved_comma_state = save_and_reset_anchor_state(',');
3222 if (token.kind == T_IDENTIFIER
3223 && !is_typedef_symbol(token.identifier.symbol)) {
3224 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
3225 if (la1_type == ',' || la1_type == ')') {
3226 type->kr_style_parameters = true;
3227 parse_identifier_list(scope);
3228 goto parameters_finished;
3232 if (token.kind == ')') {
3233 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3234 if (!(c_mode & _CXX))
3235 type->unspecified_parameters = true;
3236 } else if (has_parameters()) {
3237 function_parameter_t **anchor = &type->parameters;
3239 switch (token.kind) {
3242 type->variadic = true;
3243 goto parameters_finished;
3248 entity_t *entity = parse_parameter();
3249 if (entity->kind == ENTITY_TYPEDEF) {
3250 errorf(&entity->base.source_position,
3251 "typedef not allowed as function parameter");
3254 assert(is_declaration(entity));
3256 semantic_parameter_incomplete(entity);
3258 function_parameter_t *const parameter =
3259 allocate_parameter(entity->declaration.type);
3261 if (scope != NULL) {
3262 append_entity(scope, entity);
3265 *anchor = parameter;
3266 anchor = ¶meter->next;
3271 goto parameters_finished;
3273 } while (next_if(','));
3276 parameters_finished:
3277 rem_anchor_token(')');
3278 expect(')', end_error);
3281 restore_anchor_state(',', saved_comma_state);
3284 typedef enum construct_type_kind_t {
3285 CONSTRUCT_POINTER = 1,
3286 CONSTRUCT_REFERENCE,
3289 } construct_type_kind_t;
3291 typedef union construct_type_t construct_type_t;
3293 typedef struct construct_type_base_t {
3294 construct_type_kind_t kind;
3295 source_position_t pos;
3296 construct_type_t *next;
3297 } construct_type_base_t;
3299 typedef struct parsed_pointer_t {
3300 construct_type_base_t base;
3301 type_qualifiers_t type_qualifiers;
3302 variable_t *base_variable; /**< MS __based extension. */
3305 typedef struct parsed_reference_t {
3306 construct_type_base_t base;
3307 } parsed_reference_t;
3309 typedef struct construct_function_type_t {
3310 construct_type_base_t base;
3311 type_t *function_type;
3312 } construct_function_type_t;
3314 typedef struct parsed_array_t {
3315 construct_type_base_t base;
3316 type_qualifiers_t type_qualifiers;
3322 union construct_type_t {
3323 construct_type_kind_t kind;
3324 construct_type_base_t base;
3325 parsed_pointer_t pointer;
3326 parsed_reference_t reference;
3327 construct_function_type_t function;
3328 parsed_array_t array;
3331 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3333 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3334 memset(cons, 0, size);
3336 cons->base.pos = *HERE;
3341 static construct_type_t *parse_pointer_declarator(void)
3343 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3345 cons->pointer.type_qualifiers = parse_type_qualifiers();
3346 //cons->pointer.base_variable = base_variable;
3351 /* ISO/IEC 14882:1998(E) §8.3.2 */
3352 static construct_type_t *parse_reference_declarator(void)
3354 if (!(c_mode & _CXX))
3355 errorf(HERE, "references are only available for C++");
3357 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3364 static construct_type_t *parse_array_declarator(void)
3366 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3367 parsed_array_t *const array = &cons->array;
3370 add_anchor_token(']');
3372 bool is_static = next_if(T_static);
3374 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3377 is_static = next_if(T_static);
3379 array->type_qualifiers = type_qualifiers;
3380 array->is_static = is_static;
3382 expression_t *size = NULL;
3383 if (token.kind == '*' && look_ahead(1)->kind == ']') {
3384 array->is_variable = true;
3386 } else if (token.kind != ']') {
3387 size = parse_assignment_expression();
3389 /* §6.7.5.2:1 Array size must have integer type */
3390 type_t *const orig_type = size->base.type;
3391 type_t *const type = skip_typeref(orig_type);
3392 if (!is_type_integer(type) && is_type_valid(type)) {
3393 errorf(&size->base.source_position,
3394 "array size '%E' must have integer type but has type '%T'",
3399 mark_vars_read(size, NULL);
3402 if (is_static && size == NULL)
3403 errorf(&array->base.pos, "static array parameters require a size");
3405 rem_anchor_token(']');
3406 expect(']', end_error);
3413 static construct_type_t *parse_function_declarator(scope_t *scope)
3415 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3417 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3418 function_type_t *ftype = &type->function;
3420 ftype->linkage = current_linkage;
3421 ftype->calling_convention = CC_DEFAULT;
3423 parse_parameters(ftype, scope);
3425 cons->function.function_type = type;
3430 typedef struct parse_declarator_env_t {
3431 bool may_be_abstract : 1;
3432 bool must_be_abstract : 1;
3433 decl_modifiers_t modifiers;
3435 source_position_t source_position;
3437 attribute_t *attributes;
3438 } parse_declarator_env_t;
3441 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3443 /* construct a single linked list of construct_type_t's which describe
3444 * how to construct the final declarator type */
3445 construct_type_t *first = NULL;
3446 construct_type_t **anchor = &first;
3448 env->attributes = parse_attributes(env->attributes);
3451 construct_type_t *type;
3452 //variable_t *based = NULL; /* MS __based extension */
3453 switch (token.kind) {
3455 type = parse_reference_declarator();
3459 panic("based not supported anymore");
3464 type = parse_pointer_declarator();
3468 goto ptr_operator_end;
3472 anchor = &type->base.next;
3474 /* TODO: find out if this is correct */
3475 env->attributes = parse_attributes(env->attributes);
3479 construct_type_t *inner_types = NULL;
3481 switch (token.kind) {
3483 if (env->must_be_abstract) {
3484 errorf(HERE, "no identifier expected in typename");
3486 env->symbol = token.identifier.symbol;
3487 env->source_position = token.base.source_position;
3493 /* Parenthesized declarator or function declarator? */
3494 token_t const *const la1 = look_ahead(1);
3495 switch (la1->kind) {
3497 if (is_typedef_symbol(la1->identifier.symbol)) {
3499 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3500 * interpreted as ``function with no parameter specification'', rather
3501 * than redundant parentheses around the omitted identifier. */
3503 /* Function declarator. */
3504 if (!env->may_be_abstract) {
3505 errorf(HERE, "function declarator must have a name");
3512 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3513 /* Paranthesized declarator. */
3515 add_anchor_token(')');
3516 inner_types = parse_inner_declarator(env);
3517 if (inner_types != NULL) {
3518 /* All later declarators only modify the return type */
3519 env->must_be_abstract = true;
3521 rem_anchor_token(')');
3522 expect(')', end_error);
3530 if (env->may_be_abstract)
3532 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3537 construct_type_t **const p = anchor;
3540 construct_type_t *type;
3541 switch (token.kind) {
3543 scope_t *scope = NULL;
3544 if (!env->must_be_abstract) {
3545 scope = &env->parameters;
3548 type = parse_function_declarator(scope);
3552 type = parse_array_declarator();
3555 goto declarator_finished;
3558 /* insert in the middle of the list (at p) */
3559 type->base.next = *p;
3562 anchor = &type->base.next;
3565 declarator_finished:
3566 /* append inner_types at the end of the list, we don't to set anchor anymore
3567 * as it's not needed anymore */
3568 *anchor = inner_types;
3575 static type_t *construct_declarator_type(construct_type_t *construct_list,
3578 construct_type_t *iter = construct_list;
3579 for (; iter != NULL; iter = iter->base.next) {
3580 source_position_t const* const pos = &iter->base.pos;
3581 switch (iter->kind) {
3582 case CONSTRUCT_FUNCTION: {
3583 construct_function_type_t *function = &iter->function;
3584 type_t *function_type = function->function_type;
3586 function_type->function.return_type = type;
3588 type_t *skipped_return_type = skip_typeref(type);
3590 if (is_type_function(skipped_return_type)) {
3591 errorf(pos, "function returning function is not allowed");
3592 } else if (is_type_array(skipped_return_type)) {
3593 errorf(pos, "function returning array is not allowed");
3595 if (skipped_return_type->base.qualifiers != 0) {
3596 warningf(WARN_IGNORED_QUALIFIERS, pos, "type qualifiers in return type of function type are meaningless");
3600 /* The function type was constructed earlier. Freeing it here will
3601 * destroy other types. */
3602 type = typehash_insert(function_type);
3606 case CONSTRUCT_POINTER: {
3607 if (is_type_reference(skip_typeref(type)))
3608 errorf(pos, "cannot declare a pointer to reference");
3610 parsed_pointer_t *pointer = &iter->pointer;
3611 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3615 case CONSTRUCT_REFERENCE:
3616 if (is_type_reference(skip_typeref(type)))
3617 errorf(pos, "cannot declare a reference to reference");
3619 type = make_reference_type(type);
3622 case CONSTRUCT_ARRAY: {
3623 if (is_type_reference(skip_typeref(type)))
3624 errorf(pos, "cannot declare an array of references");
3626 parsed_array_t *array = &iter->array;
3627 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3629 expression_t *size_expression = array->size;
3630 if (size_expression != NULL) {
3632 = create_implicit_cast(size_expression, type_size_t);
3635 array_type->base.qualifiers = array->type_qualifiers;
3636 array_type->array.element_type = type;
3637 array_type->array.is_static = array->is_static;
3638 array_type->array.is_variable = array->is_variable;
3639 array_type->array.size_expression = size_expression;
3641 if (size_expression != NULL) {
3642 switch (is_constant_expression(size_expression)) {
3643 case EXPR_CLASS_CONSTANT: {
3644 long const size = fold_constant_to_int(size_expression);
3645 array_type->array.size = size;
3646 array_type->array.size_constant = true;
3647 /* §6.7.5.2:1 If the expression is a constant expression,
3648 * it shall have a value greater than zero. */
3650 errorf(&size_expression->base.source_position,
3651 "size of array must be greater than zero");
3652 } else if (size == 0 && !GNU_MODE) {
3653 errorf(&size_expression->base.source_position,
3654 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3659 case EXPR_CLASS_VARIABLE:
3660 array_type->array.is_vla = true;
3663 case EXPR_CLASS_ERROR:
3668 type_t *skipped_type = skip_typeref(type);
3670 if (is_type_incomplete(skipped_type)) {
3671 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3672 } else if (is_type_function(skipped_type)) {
3673 errorf(pos, "array of functions is not allowed");
3675 type = identify_new_type(array_type);
3679 internal_errorf(pos, "invalid type construction found");
3685 static type_t *automatic_type_conversion(type_t *orig_type);
3687 static type_t *semantic_parameter(const source_position_t *pos,
3689 const declaration_specifiers_t *specifiers,
3690 entity_t const *const param)
3692 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3693 * shall be adjusted to ``qualified pointer to type'',
3695 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3696 * type'' shall be adjusted to ``pointer to function
3697 * returning type'', as in 6.3.2.1. */
3698 type = automatic_type_conversion(type);
3700 if (specifiers->is_inline && is_type_valid(type)) {
3701 errorf(pos, "'%N' declared 'inline'", param);
3704 /* §6.9.1:6 The declarations in the declaration list shall contain
3705 * no storage-class specifier other than register and no
3706 * initializations. */
3707 if (specifiers->thread_local || (
3708 specifiers->storage_class != STORAGE_CLASS_NONE &&
3709 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3711 errorf(pos, "invalid storage class for '%N'", param);
3714 /* delay test for incomplete type, because we might have (void)
3715 * which is legal but incomplete... */
3720 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3721 declarator_flags_t flags)
3723 parse_declarator_env_t env;
3724 memset(&env, 0, sizeof(env));
3725 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3727 construct_type_t *construct_type = parse_inner_declarator(&env);
3729 construct_declarator_type(construct_type, specifiers->type);
3730 type_t *type = skip_typeref(orig_type);
3732 if (construct_type != NULL) {
3733 obstack_free(&temp_obst, construct_type);
3736 attribute_t *attributes = parse_attributes(env.attributes);
3737 /* append (shared) specifier attribute behind attributes of this
3739 attribute_t **anchor = &attributes;
3740 while (*anchor != NULL)
3741 anchor = &(*anchor)->next;
3742 *anchor = specifiers->attributes;
3745 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3746 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol, &env.source_position);
3747 entity->typedefe.type = orig_type;
3749 if (anonymous_entity != NULL) {
3750 if (is_type_compound(type)) {
3751 assert(anonymous_entity->compound.alias == NULL);
3752 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3753 anonymous_entity->kind == ENTITY_UNION);
3754 anonymous_entity->compound.alias = entity;
3755 anonymous_entity = NULL;
3756 } else if (is_type_enum(type)) {
3757 assert(anonymous_entity->enume.alias == NULL);
3758 assert(anonymous_entity->kind == ENTITY_ENUM);
3759 anonymous_entity->enume.alias = entity;
3760 anonymous_entity = NULL;
3764 /* create a declaration type entity */
3765 source_position_t const *const pos = env.symbol ? &env.source_position : &specifiers->source_position;
3766 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3767 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol, pos);
3769 if (env.symbol != NULL) {
3770 if (specifiers->is_inline && is_type_valid(type)) {
3771 errorf(&env.source_position,
3772 "compound member '%Y' declared 'inline'", env.symbol);
3775 if (specifiers->thread_local ||
3776 specifiers->storage_class != STORAGE_CLASS_NONE) {
3777 errorf(&env.source_position,
3778 "compound member '%Y' must have no storage class",
3782 } else if (flags & DECL_IS_PARAMETER) {
3783 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol, pos);
3784 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3785 } else if (is_type_function(type)) {
3786 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol, pos);
3787 entity->function.is_inline = specifiers->is_inline;
3788 entity->function.elf_visibility = default_visibility;
3789 entity->function.parameters = env.parameters;
3791 if (env.symbol != NULL) {
3792 /* this needs fixes for C++ */
3793 bool in_function_scope = current_function != NULL;
3795 if (specifiers->thread_local || (
3796 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3797 specifiers->storage_class != STORAGE_CLASS_NONE &&
3798 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3800 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3804 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol, pos);
3805 entity->variable.elf_visibility = default_visibility;
3806 entity->variable.thread_local = specifiers->thread_local;
3808 if (env.symbol != NULL) {
3809 if (specifiers->is_inline && is_type_valid(type)) {
3810 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3813 bool invalid_storage_class = false;
3814 if (current_scope == file_scope) {
3815 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3816 specifiers->storage_class != STORAGE_CLASS_NONE &&
3817 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3818 invalid_storage_class = true;
3821 if (specifiers->thread_local &&
3822 specifiers->storage_class == STORAGE_CLASS_NONE) {
3823 invalid_storage_class = true;
3826 if (invalid_storage_class) {
3827 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3832 entity->declaration.type = orig_type;
3833 entity->declaration.alignment = get_type_alignment(orig_type);
3834 entity->declaration.modifiers = env.modifiers;
3835 entity->declaration.attributes = attributes;
3837 storage_class_t storage_class = specifiers->storage_class;
3838 entity->declaration.declared_storage_class = storage_class;
3840 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3841 storage_class = STORAGE_CLASS_AUTO;
3842 entity->declaration.storage_class = storage_class;
3845 if (attributes != NULL) {
3846 handle_entity_attributes(attributes, entity);
3849 if (entity->kind == ENTITY_FUNCTION && !freestanding) {
3850 adapt_special_functions(&entity->function);
3856 static type_t *parse_abstract_declarator(type_t *base_type)
3858 parse_declarator_env_t env;
3859 memset(&env, 0, sizeof(env));
3860 env.may_be_abstract = true;
3861 env.must_be_abstract = true;
3863 construct_type_t *construct_type = parse_inner_declarator(&env);
3865 type_t *result = construct_declarator_type(construct_type, base_type);
3866 if (construct_type != NULL) {
3867 obstack_free(&temp_obst, construct_type);
3869 result = handle_type_attributes(env.attributes, result);
3875 * Check if the declaration of main is suspicious. main should be a
3876 * function with external linkage, returning int, taking either zero
3877 * arguments, two, or three arguments of appropriate types, ie.
3879 * int main([ int argc, char **argv [, char **env ] ]).
3881 * @param decl the declaration to check
3882 * @param type the function type of the declaration
3884 static void check_main(const entity_t *entity)
3886 const source_position_t *pos = &entity->base.source_position;
3887 if (entity->kind != ENTITY_FUNCTION) {
3888 warningf(WARN_MAIN, pos, "'main' is not a function");
3892 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3893 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3896 type_t *type = skip_typeref(entity->declaration.type);
3897 assert(is_type_function(type));
3899 function_type_t const *const func_type = &type->function;
3900 type_t *const ret_type = func_type->return_type;
3901 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3902 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3904 const function_parameter_t *parm = func_type->parameters;
3906 type_t *const first_type = skip_typeref(parm->type);
3907 type_t *const first_type_unqual = get_unqualified_type(first_type);
3908 if (!types_compatible(first_type_unqual, type_int)) {
3909 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3913 type_t *const second_type = skip_typeref(parm->type);
3914 type_t *const second_type_unqual
3915 = get_unqualified_type(second_type);
3916 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3917 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3921 type_t *const third_type = skip_typeref(parm->type);
3922 type_t *const third_type_unqual
3923 = get_unqualified_type(third_type);
3924 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
3925 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
3929 goto warn_arg_count;
3933 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
3939 * Check if a symbol is the equal to "main".
3941 static bool is_sym_main(const symbol_t *const sym)
3943 return streq(sym->string, "main");
3946 static void error_redefined_as_different_kind(const source_position_t *pos,
3947 const entity_t *old, entity_kind_t new_kind)
3949 char const *const what = get_entity_kind_name(new_kind);
3950 source_position_t const *const ppos = &old->base.source_position;
3951 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
3954 static bool is_entity_valid(entity_t *const ent)
3956 if (is_declaration(ent)) {
3957 return is_type_valid(skip_typeref(ent->declaration.type));
3958 } else if (ent->kind == ENTITY_TYPEDEF) {
3959 return is_type_valid(skip_typeref(ent->typedefe.type));
3964 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
3966 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
3967 if (attributes_equal(tattr, attr))
3974 * test wether new_list contains any attributes not included in old_list
3976 static bool has_new_attributes(const attribute_t *old_list,
3977 const attribute_t *new_list)
3979 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
3980 if (!contains_attribute(old_list, attr))
3987 * Merge in attributes from an attribute list (probably from a previous
3988 * declaration with the same name). Warning: destroys the old structure
3989 * of the attribute list - don't reuse attributes after this call.
3991 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
3994 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
3996 if (contains_attribute(decl->attributes, attr))
3999 /* move attribute to new declarations attributes list */
4000 attr->next = decl->attributes;
4001 decl->attributes = attr;
4006 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4007 * for various problems that occur for multiple definitions
4009 entity_t *record_entity(entity_t *entity, const bool is_definition)
4011 const symbol_t *const symbol = entity->base.symbol;
4012 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4013 const source_position_t *pos = &entity->base.source_position;
4015 /* can happen in error cases */
4019 entity_t *const previous_entity = get_entity(symbol, namespc);
4020 /* pushing the same entity twice will break the stack structure */
4021 assert(previous_entity != entity);
4023 if (entity->kind == ENTITY_FUNCTION) {
4024 type_t *const orig_type = entity->declaration.type;
4025 type_t *const type = skip_typeref(orig_type);
4027 assert(is_type_function(type));
4028 if (type->function.unspecified_parameters &&
4029 previous_entity == NULL &&
4030 !entity->declaration.implicit) {
4031 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4034 if (current_scope == file_scope && is_sym_main(symbol)) {
4039 if (is_declaration(entity) &&
4040 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4041 current_scope != file_scope &&
4042 !entity->declaration.implicit) {
4043 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4046 if (previous_entity != NULL) {
4047 source_position_t const *const ppos = &previous_entity->base.source_position;
4049 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4050 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4051 assert(previous_entity->kind == ENTITY_PARAMETER);
4052 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4056 if (previous_entity->base.parent_scope == current_scope) {
4057 if (previous_entity->kind != entity->kind) {
4058 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4059 error_redefined_as_different_kind(pos, previous_entity,
4064 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4065 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4068 if (previous_entity->kind == ENTITY_TYPEDEF) {
4069 type_t *const type = skip_typeref(entity->typedefe.type);
4070 type_t *const prev_type
4071 = skip_typeref(previous_entity->typedefe.type);
4072 if (c_mode & _CXX) {
4073 /* C++ allows double typedef if they are identical
4074 * (after skipping typedefs) */
4075 if (type == prev_type)
4078 /* GCC extension: redef in system headers is allowed */
4079 if ((pos->is_system_header || ppos->is_system_header) &&
4080 types_compatible(type, prev_type))
4083 errorf(pos, "redefinition of '%N' (declared %P)",
4088 /* at this point we should have only VARIABLES or FUNCTIONS */
4089 assert(is_declaration(previous_entity) && is_declaration(entity));
4091 declaration_t *const prev_decl = &previous_entity->declaration;
4092 declaration_t *const decl = &entity->declaration;
4094 /* can happen for K&R style declarations */
4095 if (prev_decl->type == NULL &&
4096 previous_entity->kind == ENTITY_PARAMETER &&
4097 entity->kind == ENTITY_PARAMETER) {
4098 prev_decl->type = decl->type;
4099 prev_decl->storage_class = decl->storage_class;
4100 prev_decl->declared_storage_class = decl->declared_storage_class;
4101 prev_decl->modifiers = decl->modifiers;
4102 return previous_entity;
4105 type_t *const type = skip_typeref(decl->type);
4106 type_t *const prev_type = skip_typeref(prev_decl->type);
4108 if (!types_compatible(type, prev_type)) {
4109 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4111 unsigned old_storage_class = prev_decl->storage_class;
4113 if (is_definition &&
4115 !(prev_decl->modifiers & DM_USED) &&
4116 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4117 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4120 storage_class_t new_storage_class = decl->storage_class;
4122 /* pretend no storage class means extern for function
4123 * declarations (except if the previous declaration is neither
4124 * none nor extern) */
4125 if (entity->kind == ENTITY_FUNCTION) {
4126 /* the previous declaration could have unspecified parameters or
4127 * be a typedef, so use the new type */
4128 if (prev_type->function.unspecified_parameters || is_definition)
4129 prev_decl->type = type;
4131 switch (old_storage_class) {
4132 case STORAGE_CLASS_NONE:
4133 old_storage_class = STORAGE_CLASS_EXTERN;
4136 case STORAGE_CLASS_EXTERN:
4137 if (is_definition) {
4138 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4139 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4141 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4142 new_storage_class = STORAGE_CLASS_EXTERN;
4149 } else if (is_type_incomplete(prev_type)) {
4150 prev_decl->type = type;
4153 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4154 new_storage_class == STORAGE_CLASS_EXTERN) {
4156 warn_redundant_declaration: ;
4158 = has_new_attributes(prev_decl->attributes,
4160 if (has_new_attrs) {
4161 merge_in_attributes(decl, prev_decl->attributes);
4162 } else if (!is_definition &&
4163 is_type_valid(prev_type) &&
4164 !pos->is_system_header) {
4165 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4167 } else if (current_function == NULL) {
4168 if (old_storage_class != STORAGE_CLASS_STATIC &&
4169 new_storage_class == STORAGE_CLASS_STATIC) {
4170 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4171 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4172 prev_decl->storage_class = STORAGE_CLASS_NONE;
4173 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4175 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4177 goto error_redeclaration;
4178 goto warn_redundant_declaration;
4180 } else if (is_type_valid(prev_type)) {
4181 if (old_storage_class == new_storage_class) {
4182 error_redeclaration:
4183 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4185 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4190 prev_decl->modifiers |= decl->modifiers;
4191 if (entity->kind == ENTITY_FUNCTION) {
4192 previous_entity->function.is_inline |= entity->function.is_inline;
4194 return previous_entity;
4198 if (is_warn_on(why = WARN_SHADOW) ||
4199 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4200 char const *const what = get_entity_kind_name(previous_entity->kind);
4201 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4205 if (entity->kind == ENTITY_FUNCTION) {
4206 if (is_definition &&
4207 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4208 !is_sym_main(symbol)) {
4209 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4210 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4212 goto warn_missing_declaration;
4215 } else if (entity->kind == ENTITY_VARIABLE) {
4216 if (current_scope == file_scope &&
4217 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4218 !entity->declaration.implicit) {
4219 warn_missing_declaration:
4220 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4225 assert(entity->base.parent_scope == NULL);
4226 assert(current_scope != NULL);
4228 entity->base.parent_scope = current_scope;
4229 environment_push(entity);
4230 append_entity(current_scope, entity);
4235 static void parser_error_multiple_definition(entity_t *entity,
4236 const source_position_t *source_position)
4238 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4239 entity->base.symbol, &entity->base.source_position);
4242 static bool is_declaration_specifier(const token_t *token)
4244 switch (token->kind) {
4248 return is_typedef_symbol(token->identifier.symbol);
4255 static void parse_init_declarator_rest(entity_t *entity)
4257 type_t *orig_type = type_error_type;
4259 if (entity->base.kind == ENTITY_TYPEDEF) {
4260 source_position_t const *const pos = &entity->base.source_position;
4261 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4263 assert(is_declaration(entity));
4264 orig_type = entity->declaration.type;
4267 type_t *type = skip_typeref(orig_type);
4269 if (entity->kind == ENTITY_VARIABLE
4270 && entity->variable.initializer != NULL) {
4271 parser_error_multiple_definition(entity, HERE);
4275 declaration_t *const declaration = &entity->declaration;
4276 bool must_be_constant = false;
4277 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4278 entity->base.parent_scope == file_scope) {
4279 must_be_constant = true;
4282 if (is_type_function(type)) {
4283 source_position_t const *const pos = &entity->base.source_position;
4284 errorf(pos, "'%N' is initialized like a variable", entity);
4285 orig_type = type_error_type;
4288 parse_initializer_env_t env;
4289 env.type = orig_type;
4290 env.must_be_constant = must_be_constant;
4291 env.entity = entity;
4293 initializer_t *initializer = parse_initializer(&env);
4295 if (entity->kind == ENTITY_VARIABLE) {
4296 /* §6.7.5:22 array initializers for arrays with unknown size
4297 * determine the array type size */
4298 declaration->type = env.type;
4299 entity->variable.initializer = initializer;
4303 /* parse rest of a declaration without any declarator */
4304 static void parse_anonymous_declaration_rest(
4305 const declaration_specifiers_t *specifiers)
4308 anonymous_entity = NULL;
4310 source_position_t const *const pos = &specifiers->source_position;
4311 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4312 specifiers->thread_local) {
4313 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4316 type_t *type = specifiers->type;
4317 switch (type->kind) {
4318 case TYPE_COMPOUND_STRUCT:
4319 case TYPE_COMPOUND_UNION: {
4320 if (type->compound.compound->base.symbol == NULL) {
4321 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4330 warningf(WARN_OTHER, pos, "empty declaration");
4335 static void check_variable_type_complete(entity_t *ent)
4337 if (ent->kind != ENTITY_VARIABLE)
4340 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4341 * type for the object shall be complete [...] */
4342 declaration_t *decl = &ent->declaration;
4343 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4344 decl->storage_class == STORAGE_CLASS_STATIC)
4347 type_t *const type = skip_typeref(decl->type);
4348 if (!is_type_incomplete(type))
4351 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4352 * are given length one. */
4353 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4354 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4358 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4362 static void parse_declaration_rest(entity_t *ndeclaration,
4363 const declaration_specifiers_t *specifiers,
4364 parsed_declaration_func finished_declaration,
4365 declarator_flags_t flags)
4367 add_anchor_token(';');
4368 add_anchor_token(',');
4370 entity_t *entity = finished_declaration(ndeclaration, token.kind == '=');
4372 if (token.kind == '=') {
4373 parse_init_declarator_rest(entity);
4374 } else if (entity->kind == ENTITY_VARIABLE) {
4375 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4376 * [...] where the extern specifier is explicitly used. */
4377 declaration_t *decl = &entity->declaration;
4378 if (decl->storage_class != STORAGE_CLASS_EXTERN &&
4379 is_type_reference(skip_typeref(decl->type))) {
4380 source_position_t const *const pos = &entity->base.source_position;
4381 errorf(pos, "reference '%#N' must be initialized", entity);
4385 check_variable_type_complete(entity);
4390 add_anchor_token('=');
4391 ndeclaration = parse_declarator(specifiers, flags);
4392 rem_anchor_token('=');
4394 rem_anchor_token(',');
4395 rem_anchor_token(';');
4396 expect(';', end_error);
4399 anonymous_entity = NULL;
4402 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4404 symbol_t *symbol = entity->base.symbol;
4408 assert(entity->base.namespc == NAMESPACE_NORMAL);
4409 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4410 if (previous_entity == NULL
4411 || previous_entity->base.parent_scope != current_scope) {
4412 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4417 if (is_definition) {
4418 errorf(HERE, "'%N' is initialised", entity);
4421 return record_entity(entity, false);
4424 static void parse_declaration(parsed_declaration_func finished_declaration,
4425 declarator_flags_t flags)
4427 add_anchor_token(';');
4428 declaration_specifiers_t specifiers;
4429 parse_declaration_specifiers(&specifiers);
4430 rem_anchor_token(';');
4432 if (token.kind == ';') {
4433 parse_anonymous_declaration_rest(&specifiers);
4435 entity_t *entity = parse_declarator(&specifiers, flags);
4436 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4441 static type_t *get_default_promoted_type(type_t *orig_type)
4443 type_t *result = orig_type;
4445 type_t *type = skip_typeref(orig_type);
4446 if (is_type_integer(type)) {
4447 result = promote_integer(type);
4448 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4449 result = type_double;
4455 static void parse_kr_declaration_list(entity_t *entity)
4457 if (entity->kind != ENTITY_FUNCTION)
4460 type_t *type = skip_typeref(entity->declaration.type);
4461 assert(is_type_function(type));
4462 if (!type->function.kr_style_parameters)
4465 add_anchor_token('{');
4467 PUSH_SCOPE(&entity->function.parameters);
4469 entity_t *parameter = entity->function.parameters.entities;
4470 for ( ; parameter != NULL; parameter = parameter->base.next) {
4471 assert(parameter->base.parent_scope == NULL);
4472 parameter->base.parent_scope = current_scope;
4473 environment_push(parameter);
4476 /* parse declaration list */
4478 switch (token.kind) {
4480 /* This covers symbols, which are no type, too, and results in
4481 * better error messages. The typical cases are misspelled type
4482 * names and missing includes. */
4484 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4494 /* update function type */
4495 type_t *new_type = duplicate_type(type);
4497 function_parameter_t *parameters = NULL;
4498 function_parameter_t **anchor = ¶meters;
4500 /* did we have an earlier prototype? */
4501 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4502 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4505 function_parameter_t *proto_parameter = NULL;
4506 if (proto_type != NULL) {
4507 type_t *proto_type_type = proto_type->declaration.type;
4508 proto_parameter = proto_type_type->function.parameters;
4509 /* If a K&R function definition has a variadic prototype earlier, then
4510 * make the function definition variadic, too. This should conform to
4511 * §6.7.5.3:15 and §6.9.1:8. */
4512 new_type->function.variadic = proto_type_type->function.variadic;
4514 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4516 new_type->function.unspecified_parameters = true;
4519 bool need_incompatible_warning = false;
4520 parameter = entity->function.parameters.entities;
4521 for (; parameter != NULL; parameter = parameter->base.next,
4523 proto_parameter == NULL ? NULL : proto_parameter->next) {
4524 if (parameter->kind != ENTITY_PARAMETER)
4527 type_t *parameter_type = parameter->declaration.type;
4528 if (parameter_type == NULL) {
4529 source_position_t const* const pos = ¶meter->base.source_position;
4531 errorf(pos, "no type specified for function '%N'", parameter);
4532 parameter_type = type_error_type;
4534 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4535 parameter_type = type_int;
4537 parameter->declaration.type = parameter_type;
4540 semantic_parameter_incomplete(parameter);
4542 /* we need the default promoted types for the function type */
4543 type_t *not_promoted = parameter_type;
4544 parameter_type = get_default_promoted_type(parameter_type);
4546 /* gcc special: if the type of the prototype matches the unpromoted
4547 * type don't promote */
4548 if (!strict_mode && proto_parameter != NULL) {
4549 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4550 type_t *promo_skip = skip_typeref(parameter_type);
4551 type_t *param_skip = skip_typeref(not_promoted);
4552 if (!types_compatible(proto_p_type, promo_skip)
4553 && types_compatible(proto_p_type, param_skip)) {
4555 need_incompatible_warning = true;
4556 parameter_type = not_promoted;
4559 function_parameter_t *const function_parameter
4560 = allocate_parameter(parameter_type);
4562 *anchor = function_parameter;
4563 anchor = &function_parameter->next;
4566 new_type->function.parameters = parameters;
4567 new_type = identify_new_type(new_type);
4569 if (need_incompatible_warning) {
4570 symbol_t const *const sym = entity->base.symbol;
4571 source_position_t const *const pos = &entity->base.source_position;
4572 source_position_t const *const ppos = &proto_type->base.source_position;
4573 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4575 entity->declaration.type = new_type;
4577 rem_anchor_token('{');
4580 static bool first_err = true;
4583 * When called with first_err set, prints the name of the current function,
4586 static void print_in_function(void)
4590 char const *const file = current_function->base.base.source_position.input_name;
4591 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4596 * Check if all labels are defined in the current function.
4597 * Check if all labels are used in the current function.
4599 static void check_labels(void)
4601 for (const goto_statement_t *goto_statement = goto_first;
4602 goto_statement != NULL;
4603 goto_statement = goto_statement->next) {
4604 label_t *label = goto_statement->label;
4605 if (label->base.source_position.input_name == NULL) {
4606 print_in_function();
4607 source_position_t const *const pos = &goto_statement->base.source_position;
4608 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4612 if (is_warn_on(WARN_UNUSED_LABEL)) {
4613 for (const label_statement_t *label_statement = label_first;
4614 label_statement != NULL;
4615 label_statement = label_statement->next) {
4616 label_t *label = label_statement->label;
4618 if (! label->used) {
4619 print_in_function();
4620 source_position_t const *const pos = &label_statement->base.source_position;
4621 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4627 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4629 entity_t const *const end = last != NULL ? last->base.next : NULL;
4630 for (; entity != end; entity = entity->base.next) {
4631 if (!is_declaration(entity))
4634 declaration_t *declaration = &entity->declaration;
4635 if (declaration->implicit)
4638 if (!declaration->used) {
4639 print_in_function();
4640 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4641 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4642 print_in_function();
4643 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4648 static void check_unused_variables(statement_t *const stmt, void *const env)
4652 switch (stmt->kind) {
4653 case STATEMENT_DECLARATION: {
4654 declaration_statement_t const *const decls = &stmt->declaration;
4655 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4660 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4669 * Check declarations of current_function for unused entities.
4671 static void check_declarations(void)
4673 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4674 const scope_t *scope = ¤t_function->parameters;
4676 /* do not issue unused warnings for main */
4677 if (!is_sym_main(current_function->base.base.symbol)) {
4678 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4681 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4682 walk_statements(current_function->statement, check_unused_variables,
4687 static int determine_truth(expression_t const* const cond)
4690 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4691 fold_constant_to_bool(cond) ? 1 :
4695 static void check_reachable(statement_t *);
4696 static bool reaches_end;
4698 static bool expression_returns(expression_t const *const expr)
4700 switch (expr->kind) {
4702 expression_t const *const func = expr->call.function;
4703 type_t const *const type = skip_typeref(func->base.type);
4704 if (type->kind == TYPE_POINTER) {
4705 type_t const *const points_to
4706 = skip_typeref(type->pointer.points_to);
4707 if (points_to->kind == TYPE_FUNCTION
4708 && points_to->function.modifiers & DM_NORETURN)
4712 if (!expression_returns(func))
4715 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4716 if (!expression_returns(arg->expression))
4723 case EXPR_REFERENCE:
4724 case EXPR_ENUM_CONSTANT:
4725 case EXPR_LITERAL_CASES:
4726 case EXPR_STRING_LITERAL:
4727 case EXPR_WIDE_STRING_LITERAL:
4728 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4729 case EXPR_LABEL_ADDRESS:
4730 case EXPR_CLASSIFY_TYPE:
4731 case EXPR_SIZEOF: // TODO handle obscure VLA case
4734 case EXPR_BUILTIN_CONSTANT_P:
4735 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4740 case EXPR_STATEMENT: {
4741 bool old_reaches_end = reaches_end;
4742 reaches_end = false;
4743 check_reachable(expr->statement.statement);
4744 bool returns = reaches_end;
4745 reaches_end = old_reaches_end;
4749 case EXPR_CONDITIONAL:
4750 // TODO handle constant expression
4752 if (!expression_returns(expr->conditional.condition))
4755 if (expr->conditional.true_expression != NULL
4756 && expression_returns(expr->conditional.true_expression))
4759 return expression_returns(expr->conditional.false_expression);
4762 return expression_returns(expr->select.compound);
4764 case EXPR_ARRAY_ACCESS:
4766 expression_returns(expr->array_access.array_ref) &&
4767 expression_returns(expr->array_access.index);
4770 return expression_returns(expr->va_starte.ap);
4773 return expression_returns(expr->va_arge.ap);
4776 return expression_returns(expr->va_copye.src);
4778 case EXPR_UNARY_CASES_MANDATORY:
4779 return expression_returns(expr->unary.value);
4781 case EXPR_UNARY_THROW:
4784 case EXPR_BINARY_CASES:
4785 // TODO handle constant lhs of && and ||
4787 expression_returns(expr->binary.left) &&
4788 expression_returns(expr->binary.right);
4791 panic("unhandled expression");
4794 static bool initializer_returns(initializer_t const *const init)
4796 switch (init->kind) {
4797 case INITIALIZER_VALUE:
4798 return expression_returns(init->value.value);
4800 case INITIALIZER_LIST: {
4801 initializer_t * const* i = init->list.initializers;
4802 initializer_t * const* const end = i + init->list.len;
4803 bool returns = true;
4804 for (; i != end; ++i) {
4805 if (!initializer_returns(*i))
4811 case INITIALIZER_STRING:
4812 case INITIALIZER_WIDE_STRING:
4813 case INITIALIZER_DESIGNATOR: // designators have no payload
4816 panic("unhandled initializer");
4819 static bool noreturn_candidate;
4821 static void check_reachable(statement_t *const stmt)
4823 if (stmt->base.reachable)
4825 if (stmt->kind != STATEMENT_DO_WHILE)
4826 stmt->base.reachable = true;
4828 statement_t *last = stmt;
4830 switch (stmt->kind) {
4831 case STATEMENT_ERROR:
4832 case STATEMENT_EMPTY:
4834 next = stmt->base.next;
4837 case STATEMENT_DECLARATION: {
4838 declaration_statement_t const *const decl = &stmt->declaration;
4839 entity_t const * ent = decl->declarations_begin;
4840 entity_t const *const last_decl = decl->declarations_end;
4842 for (;; ent = ent->base.next) {
4843 if (ent->kind == ENTITY_VARIABLE &&
4844 ent->variable.initializer != NULL &&
4845 !initializer_returns(ent->variable.initializer)) {
4848 if (ent == last_decl)
4852 next = stmt->base.next;
4856 case STATEMENT_COMPOUND:
4857 next = stmt->compound.statements;
4859 next = stmt->base.next;
4862 case STATEMENT_RETURN: {
4863 expression_t const *const val = stmt->returns.value;
4864 if (val == NULL || expression_returns(val))
4865 noreturn_candidate = false;
4869 case STATEMENT_IF: {
4870 if_statement_t const *const ifs = &stmt->ifs;
4871 expression_t const *const cond = ifs->condition;
4873 if (!expression_returns(cond))
4876 int const val = determine_truth(cond);
4879 check_reachable(ifs->true_statement);
4884 if (ifs->false_statement != NULL) {
4885 check_reachable(ifs->false_statement);
4889 next = stmt->base.next;
4893 case STATEMENT_SWITCH: {
4894 switch_statement_t const *const switchs = &stmt->switchs;
4895 expression_t const *const expr = switchs->expression;
4897 if (!expression_returns(expr))
4900 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4901 long const val = fold_constant_to_int(expr);
4902 case_label_statement_t * defaults = NULL;
4903 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4904 if (i->expression == NULL) {
4909 if (i->first_case <= val && val <= i->last_case) {
4910 check_reachable((statement_t*)i);
4915 if (defaults != NULL) {
4916 check_reachable((statement_t*)defaults);
4920 bool has_default = false;
4921 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4922 if (i->expression == NULL)
4925 check_reachable((statement_t*)i);
4932 next = stmt->base.next;
4936 case STATEMENT_EXPRESSION: {
4937 /* Check for noreturn function call */
4938 expression_t const *const expr = stmt->expression.expression;
4939 if (!expression_returns(expr))
4942 next = stmt->base.next;
4946 case STATEMENT_CONTINUE:
4947 for (statement_t *parent = stmt;;) {
4948 parent = parent->base.parent;
4949 if (parent == NULL) /* continue not within loop */
4953 switch (parent->kind) {
4954 case STATEMENT_WHILE: goto continue_while;
4955 case STATEMENT_DO_WHILE: goto continue_do_while;
4956 case STATEMENT_FOR: goto continue_for;
4962 case STATEMENT_BREAK:
4963 for (statement_t *parent = stmt;;) {
4964 parent = parent->base.parent;
4965 if (parent == NULL) /* break not within loop/switch */
4968 switch (parent->kind) {
4969 case STATEMENT_SWITCH:
4970 case STATEMENT_WHILE:
4971 case STATEMENT_DO_WHILE:
4974 next = parent->base.next;
4975 goto found_break_parent;
4983 case STATEMENT_COMPUTED_GOTO: {
4984 if (!expression_returns(stmt->computed_goto.expression))
4987 statement_t *parent = stmt->base.parent;
4988 if (parent == NULL) /* top level goto */
4994 case STATEMENT_GOTO:
4995 next = stmt->gotos.label->statement;
4996 if (next == NULL) /* missing label */
5000 case STATEMENT_LABEL:
5001 next = stmt->label.statement;
5004 case STATEMENT_CASE_LABEL:
5005 next = stmt->case_label.statement;
5008 case STATEMENT_WHILE: {
5009 while_statement_t const *const whiles = &stmt->whiles;
5010 expression_t const *const cond = whiles->condition;
5012 if (!expression_returns(cond))
5015 int const val = determine_truth(cond);
5018 check_reachable(whiles->body);
5023 next = stmt->base.next;
5027 case STATEMENT_DO_WHILE:
5028 next = stmt->do_while.body;
5031 case STATEMENT_FOR: {
5032 for_statement_t *const fors = &stmt->fors;
5034 if (fors->condition_reachable)
5036 fors->condition_reachable = true;
5038 expression_t const *const cond = fors->condition;
5043 } else if (expression_returns(cond)) {
5044 val = determine_truth(cond);
5050 check_reachable(fors->body);
5055 next = stmt->base.next;
5059 case STATEMENT_MS_TRY: {
5060 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5061 check_reachable(ms_try->try_statement);
5062 next = ms_try->final_statement;
5066 case STATEMENT_LEAVE: {
5067 statement_t *parent = stmt;
5069 parent = parent->base.parent;
5070 if (parent == NULL) /* __leave not within __try */
5073 if (parent->kind == STATEMENT_MS_TRY) {
5075 next = parent->ms_try.final_statement;
5083 panic("invalid statement kind");
5086 while (next == NULL) {
5087 next = last->base.parent;
5089 noreturn_candidate = false;
5091 type_t *const type = skip_typeref(current_function->base.type);
5092 assert(is_type_function(type));
5093 type_t *const ret = skip_typeref(type->function.return_type);
5094 if (!is_type_void(ret) &&
5095 is_type_valid(ret) &&
5096 !is_sym_main(current_function->base.base.symbol)) {
5097 source_position_t const *const pos = &stmt->base.source_position;
5098 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5103 switch (next->kind) {
5104 case STATEMENT_ERROR:
5105 case STATEMENT_EMPTY:
5106 case STATEMENT_DECLARATION:
5107 case STATEMENT_EXPRESSION:
5109 case STATEMENT_RETURN:
5110 case STATEMENT_CONTINUE:
5111 case STATEMENT_BREAK:
5112 case STATEMENT_COMPUTED_GOTO:
5113 case STATEMENT_GOTO:
5114 case STATEMENT_LEAVE:
5115 panic("invalid control flow in function");
5117 case STATEMENT_COMPOUND:
5118 if (next->compound.stmt_expr) {
5124 case STATEMENT_SWITCH:
5125 case STATEMENT_LABEL:
5126 case STATEMENT_CASE_LABEL:
5128 next = next->base.next;
5131 case STATEMENT_WHILE: {
5133 if (next->base.reachable)
5135 next->base.reachable = true;
5137 while_statement_t const *const whiles = &next->whiles;
5138 expression_t const *const cond = whiles->condition;
5140 if (!expression_returns(cond))
5143 int const val = determine_truth(cond);
5146 check_reachable(whiles->body);
5152 next = next->base.next;
5156 case STATEMENT_DO_WHILE: {
5158 if (next->base.reachable)
5160 next->base.reachable = true;
5162 do_while_statement_t const *const dw = &next->do_while;
5163 expression_t const *const cond = dw->condition;
5165 if (!expression_returns(cond))
5168 int const val = determine_truth(cond);
5171 check_reachable(dw->body);
5177 next = next->base.next;
5181 case STATEMENT_FOR: {
5183 for_statement_t *const fors = &next->fors;
5185 fors->step_reachable = true;
5187 if (fors->condition_reachable)
5189 fors->condition_reachable = true;
5191 expression_t const *const cond = fors->condition;
5196 } else if (expression_returns(cond)) {
5197 val = determine_truth(cond);
5203 check_reachable(fors->body);
5209 next = next->base.next;
5213 case STATEMENT_MS_TRY:
5215 next = next->ms_try.final_statement;
5220 check_reachable(next);
5223 static void check_unreachable(statement_t* const stmt, void *const env)
5227 switch (stmt->kind) {
5228 case STATEMENT_DO_WHILE:
5229 if (!stmt->base.reachable) {
5230 expression_t const *const cond = stmt->do_while.condition;
5231 if (determine_truth(cond) >= 0) {
5232 source_position_t const *const pos = &cond->base.source_position;
5233 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5238 case STATEMENT_FOR: {
5239 for_statement_t const* const fors = &stmt->fors;
5241 // if init and step are unreachable, cond is unreachable, too
5242 if (!stmt->base.reachable && !fors->step_reachable) {
5243 goto warn_unreachable;
5245 if (!stmt->base.reachable && fors->initialisation != NULL) {
5246 source_position_t const *const pos = &fors->initialisation->base.source_position;
5247 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5250 if (!fors->condition_reachable && fors->condition != NULL) {
5251 source_position_t const *const pos = &fors->condition->base.source_position;
5252 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5255 if (!fors->step_reachable && fors->step != NULL) {
5256 source_position_t const *const pos = &fors->step->base.source_position;
5257 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5263 case STATEMENT_COMPOUND:
5264 if (stmt->compound.statements != NULL)
5266 goto warn_unreachable;
5268 case STATEMENT_DECLARATION: {
5269 /* Only warn if there is at least one declarator with an initializer.
5270 * This typically occurs in switch statements. */
5271 declaration_statement_t const *const decl = &stmt->declaration;
5272 entity_t const * ent = decl->declarations_begin;
5273 entity_t const *const last = decl->declarations_end;
5275 for (;; ent = ent->base.next) {
5276 if (ent->kind == ENTITY_VARIABLE &&
5277 ent->variable.initializer != NULL) {
5278 goto warn_unreachable;
5288 if (!stmt->base.reachable) {
5289 source_position_t const *const pos = &stmt->base.source_position;
5290 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5296 static bool is_main(entity_t *entity)
5298 static symbol_t *sym_main = NULL;
5299 if (sym_main == NULL) {
5300 sym_main = symbol_table_insert("main");
5303 if (entity->base.symbol != sym_main)
5305 /* must be in outermost scope */
5306 if (entity->base.parent_scope != file_scope)
5312 static void parse_external_declaration(void)
5314 /* function-definitions and declarations both start with declaration
5316 add_anchor_token(';');
5317 declaration_specifiers_t specifiers;
5318 parse_declaration_specifiers(&specifiers);
5319 rem_anchor_token(';');
5321 /* must be a declaration */
5322 if (token.kind == ';') {
5323 parse_anonymous_declaration_rest(&specifiers);
5327 add_anchor_token(',');
5328 add_anchor_token('=');
5329 add_anchor_token(';');
5330 add_anchor_token('{');
5332 /* declarator is common to both function-definitions and declarations */
5333 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5335 rem_anchor_token('{');
5336 rem_anchor_token(';');
5337 rem_anchor_token('=');
5338 rem_anchor_token(',');
5340 /* must be a declaration */
5341 switch (token.kind) {
5345 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5350 /* must be a function definition */
5351 parse_kr_declaration_list(ndeclaration);
5353 if (token.kind != '{') {
5354 parse_error_expected("while parsing function definition", '{', NULL);
5355 eat_until_matching_token(';');
5359 assert(is_declaration(ndeclaration));
5360 type_t *const orig_type = ndeclaration->declaration.type;
5361 type_t * type = skip_typeref(orig_type);
5363 if (!is_type_function(type)) {
5364 if (is_type_valid(type)) {
5365 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5371 source_position_t const *const pos = &ndeclaration->base.source_position;
5372 if (is_typeref(orig_type)) {
5374 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5377 if (is_type_compound(skip_typeref(type->function.return_type))) {
5378 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5380 if (type->function.unspecified_parameters) {
5381 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5383 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5386 /* §6.7.5.3:14 a function definition with () means no
5387 * parameters (and not unspecified parameters) */
5388 if (type->function.unspecified_parameters &&
5389 type->function.parameters == NULL) {
5390 type_t *copy = duplicate_type(type);
5391 copy->function.unspecified_parameters = false;
5392 type = identify_new_type(copy);
5394 ndeclaration->declaration.type = type;
5397 entity_t *const entity = record_entity(ndeclaration, true);
5398 assert(entity->kind == ENTITY_FUNCTION);
5399 assert(ndeclaration->kind == ENTITY_FUNCTION);
5401 function_t *const function = &entity->function;
5402 if (ndeclaration != entity) {
5403 function->parameters = ndeclaration->function.parameters;
5405 assert(is_declaration(entity));
5406 type = skip_typeref(entity->declaration.type);
5408 PUSH_SCOPE(&function->parameters);
5410 entity_t *parameter = function->parameters.entities;
5411 for (; parameter != NULL; parameter = parameter->base.next) {
5412 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5413 parameter->base.parent_scope = current_scope;
5415 assert(parameter->base.parent_scope == NULL
5416 || parameter->base.parent_scope == current_scope);
5417 parameter->base.parent_scope = current_scope;
5418 if (parameter->base.symbol == NULL) {
5419 errorf(¶meter->base.source_position, "parameter name omitted");
5422 environment_push(parameter);
5425 if (function->statement != NULL) {
5426 parser_error_multiple_definition(entity, HERE);
5429 /* parse function body */
5430 int label_stack_top = label_top();
5431 function_t *old_current_function = current_function;
5432 entity_t *old_current_entity = current_entity;
5433 current_function = function;
5434 current_entity = entity;
5438 goto_anchor = &goto_first;
5440 label_anchor = &label_first;
5442 statement_t *const body = parse_compound_statement(false);
5443 function->statement = body;
5446 check_declarations();
5447 if (is_warn_on(WARN_RETURN_TYPE) ||
5448 is_warn_on(WARN_UNREACHABLE_CODE) ||
5449 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5450 noreturn_candidate = true;
5451 check_reachable(body);
5452 if (is_warn_on(WARN_UNREACHABLE_CODE))
5453 walk_statements(body, check_unreachable, NULL);
5454 if (noreturn_candidate &&
5455 !(function->base.modifiers & DM_NORETURN)) {
5456 source_position_t const *const pos = &body->base.source_position;
5457 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5461 if (is_main(entity) && enable_main_collect2_hack)
5462 prepare_main_collect2(entity);
5465 assert(current_function == function);
5466 assert(current_entity == entity);
5467 current_entity = old_current_entity;
5468 current_function = old_current_function;
5469 label_pop_to(label_stack_top);
5475 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5477 entity_t *iter = compound->members.entities;
5478 for (; iter != NULL; iter = iter->base.next) {
5479 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5482 if (iter->base.symbol == symbol) {
5484 } else if (iter->base.symbol == NULL) {
5485 /* search in anonymous structs and unions */
5486 type_t *type = skip_typeref(iter->declaration.type);
5487 if (is_type_compound(type)) {
5488 if (find_compound_entry(type->compound.compound, symbol)
5499 static void check_deprecated(const source_position_t *source_position,
5500 const entity_t *entity)
5502 if (!is_declaration(entity))
5504 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5507 source_position_t const *const epos = &entity->base.source_position;
5508 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5510 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5512 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5517 static expression_t *create_select(const source_position_t *pos,
5519 type_qualifiers_t qualifiers,
5522 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5524 check_deprecated(pos, entry);
5526 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5527 select->select.compound = addr;
5528 select->select.compound_entry = entry;
5530 type_t *entry_type = entry->declaration.type;
5531 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5533 /* bitfields need special treatment */
5534 if (entry->compound_member.bitfield) {
5535 unsigned bit_size = entry->compound_member.bit_size;
5536 /* if fewer bits than an int, convert to int (see §6.3.1.1) */
5537 if (bit_size < get_atomic_type_size(ATOMIC_TYPE_INT) * BITS_PER_BYTE) {
5538 res_type = type_int;
5542 /* we always do the auto-type conversions; the & and sizeof parser contains
5543 * code to revert this! */
5544 select->base.type = automatic_type_conversion(res_type);
5551 * Find entry with symbol in compound. Search anonymous structs and unions and
5552 * creates implicit select expressions for them.
5553 * Returns the adress for the innermost compound.
5555 static expression_t *find_create_select(const source_position_t *pos,
5557 type_qualifiers_t qualifiers,
5558 compound_t *compound, symbol_t *symbol)
5560 entity_t *iter = compound->members.entities;
5561 for (; iter != NULL; iter = iter->base.next) {
5562 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5565 symbol_t *iter_symbol = iter->base.symbol;
5566 if (iter_symbol == NULL) {
5567 type_t *type = iter->declaration.type;
5568 if (type->kind != TYPE_COMPOUND_STRUCT
5569 && type->kind != TYPE_COMPOUND_UNION)
5572 compound_t *sub_compound = type->compound.compound;
5574 if (find_compound_entry(sub_compound, symbol) == NULL)
5577 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5578 sub_addr->base.source_position = *pos;
5579 sub_addr->base.implicit = true;
5580 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5584 if (iter_symbol == symbol) {
5585 return create_select(pos, addr, qualifiers, iter);
5592 static void parse_bitfield_member(entity_t *entity)
5596 expression_t *size = parse_constant_expression();
5599 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5600 type_t *type = entity->declaration.type;
5601 if (!is_type_integer(skip_typeref(type))) {
5602 errorf(HERE, "bitfield base type '%T' is not an integer type",
5606 if (is_constant_expression(size) != EXPR_CLASS_CONSTANT) {
5607 /* error already reported by parse_constant_expression */
5608 size_long = get_type_size(type) * 8;
5610 size_long = fold_constant_to_int(size);
5612 const symbol_t *symbol = entity->base.symbol;
5613 const symbol_t *user_symbol
5614 = symbol == NULL ? sym_anonymous : symbol;
5615 unsigned bit_size = get_type_size(type) * 8;
5616 if (size_long < 0) {
5617 errorf(HERE, "negative width in bit-field '%Y'", user_symbol);
5618 } else if (size_long == 0 && symbol != NULL) {
5619 errorf(HERE, "zero width for bit-field '%Y'", user_symbol);
5620 } else if (bit_size > 0 && (unsigned)size_long > bit_size) {
5621 errorf(HERE, "width of bitfield '%Y' exceeds its type",
5624 /* hope that people don't invent crazy types with more bits
5625 * than our struct can hold */
5627 (1 << sizeof(entity->compound_member.bit_size)*8));
5631 entity->compound_member.bitfield = true;
5632 entity->compound_member.bit_size = (unsigned char)size_long;
5635 static void parse_compound_declarators(compound_t *compound,
5636 const declaration_specifiers_t *specifiers)
5641 if (token.kind == ':') {
5642 /* anonymous bitfield */
5643 type_t *type = specifiers->type;
5644 entity_t *const entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL, HERE);
5645 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5646 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5647 entity->declaration.type = type;
5649 parse_bitfield_member(entity);
5651 attribute_t *attributes = parse_attributes(NULL);
5652 attribute_t **anchor = &attributes;
5653 while (*anchor != NULL)
5654 anchor = &(*anchor)->next;
5655 *anchor = specifiers->attributes;
5656 if (attributes != NULL) {
5657 handle_entity_attributes(attributes, entity);
5659 entity->declaration.attributes = attributes;
5661 append_entity(&compound->members, entity);
5663 entity = parse_declarator(specifiers,
5664 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5665 source_position_t const *const pos = &entity->base.source_position;
5666 if (entity->kind == ENTITY_TYPEDEF) {
5667 errorf(pos, "typedef not allowed as compound member");
5669 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5671 /* make sure we don't define a symbol multiple times */
5672 symbol_t *symbol = entity->base.symbol;
5673 if (symbol != NULL) {
5674 entity_t *prev = find_compound_entry(compound, symbol);
5676 source_position_t const *const ppos = &prev->base.source_position;
5677 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5681 if (token.kind == ':') {
5682 parse_bitfield_member(entity);
5684 attribute_t *attributes = parse_attributes(NULL);
5685 handle_entity_attributes(attributes, entity);
5687 type_t *orig_type = entity->declaration.type;
5688 type_t *type = skip_typeref(orig_type);
5689 if (is_type_function(type)) {
5690 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5691 } else if (is_type_incomplete(type)) {
5692 /* §6.7.2.1:16 flexible array member */
5693 if (!is_type_array(type) ||
5694 token.kind != ';' ||
5695 look_ahead(1)->kind != '}') {
5696 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5697 } else if (compound->members.entities == NULL) {
5698 errorf(pos, "flexible array member in otherwise empty struct");
5703 append_entity(&compound->members, entity);
5706 } while (next_if(','));
5707 expect(';', end_error);
5710 anonymous_entity = NULL;
5713 static void parse_compound_type_entries(compound_t *compound)
5716 add_anchor_token('}');
5719 switch (token.kind) {
5721 case T___extension__:
5722 case T_IDENTIFIER: {
5724 declaration_specifiers_t specifiers;
5725 parse_declaration_specifiers(&specifiers);
5726 parse_compound_declarators(compound, &specifiers);
5732 rem_anchor_token('}');
5733 expect('}', end_error);
5736 compound->complete = true;
5742 static type_t *parse_typename(void)
5744 declaration_specifiers_t specifiers;
5745 parse_declaration_specifiers(&specifiers);
5746 if (specifiers.storage_class != STORAGE_CLASS_NONE
5747 || specifiers.thread_local) {
5748 /* TODO: improve error message, user does probably not know what a
5749 * storage class is...
5751 errorf(&specifiers.source_position, "typename must not have a storage class");
5754 type_t *result = parse_abstract_declarator(specifiers.type);
5762 typedef expression_t* (*parse_expression_function)(void);
5763 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5765 typedef struct expression_parser_function_t expression_parser_function_t;
5766 struct expression_parser_function_t {
5767 parse_expression_function parser;
5768 precedence_t infix_precedence;
5769 parse_expression_infix_function infix_parser;
5772 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5775 * Prints an error message if an expression was expected but not read
5777 static expression_t *expected_expression_error(void)
5779 /* skip the error message if the error token was read */
5780 if (token.kind != T_ERROR) {
5781 errorf(HERE, "expected expression, got token %K", &token);
5785 return create_error_expression();
5788 static type_t *get_string_type(void)
5790 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5793 static type_t *get_wide_string_type(void)
5795 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5799 * Parse a string constant.
5801 static expression_t *parse_string_literal(void)
5803 source_position_t begin = token.base.source_position;
5804 string_t res = token.string.string;
5805 bool is_wide = (token.kind == T_WIDE_STRING_LITERAL);
5808 while (token.kind == T_STRING_LITERAL
5809 || token.kind == T_WIDE_STRING_LITERAL) {
5810 warn_string_concat(&token.base.source_position);
5811 res = concat_strings(&res, &token.string.string);
5813 is_wide |= token.kind == T_WIDE_STRING_LITERAL;
5816 expression_t *literal;
5818 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5819 literal->base.type = get_wide_string_type();
5821 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5822 literal->base.type = get_string_type();
5824 literal->base.source_position = begin;
5825 literal->literal.value = res;
5831 * Parse a boolean constant.
5833 static expression_t *parse_boolean_literal(bool value)
5835 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5836 literal->base.type = type_bool;
5837 literal->literal.value.begin = value ? "true" : "false";
5838 literal->literal.value.size = value ? 4 : 5;
5844 static void warn_traditional_suffix(void)
5846 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%S' suffix",
5847 &token.number.suffix);
5850 static void check_integer_suffix(void)
5852 const string_t *suffix = &token.number.suffix;
5853 if (suffix->size == 0)
5856 bool not_traditional = false;
5857 const char *c = suffix->begin;
5858 if (*c == 'l' || *c == 'L') {
5861 not_traditional = true;
5863 if (*c == 'u' || *c == 'U') {
5866 } else if (*c == 'u' || *c == 'U') {
5867 not_traditional = true;
5870 } else if (*c == 'u' || *c == 'U') {
5871 not_traditional = true;
5873 if (*c == 'l' || *c == 'L') {
5881 errorf(&token.base.source_position,
5882 "invalid suffix '%S' on integer constant", suffix);
5883 } else if (not_traditional) {
5884 warn_traditional_suffix();
5888 static type_t *check_floatingpoint_suffix(void)
5890 const string_t *suffix = &token.number.suffix;
5891 type_t *type = type_double;
5892 if (suffix->size == 0)
5895 bool not_traditional = false;
5896 const char *c = suffix->begin;
5897 if (*c == 'f' || *c == 'F') {
5900 } else if (*c == 'l' || *c == 'L') {
5902 type = type_long_double;
5905 errorf(&token.base.source_position,
5906 "invalid suffix '%S' on floatingpoint constant", suffix);
5907 } else if (not_traditional) {
5908 warn_traditional_suffix();
5915 * Parse an integer constant.
5917 static expression_t *parse_number_literal(void)
5919 expression_kind_t kind;
5922 switch (token.kind) {
5924 kind = EXPR_LITERAL_INTEGER;
5925 check_integer_suffix();
5928 case T_INTEGER_OCTAL:
5929 kind = EXPR_LITERAL_INTEGER_OCTAL;
5930 check_integer_suffix();
5933 case T_INTEGER_HEXADECIMAL:
5934 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5935 check_integer_suffix();
5938 case T_FLOATINGPOINT:
5939 kind = EXPR_LITERAL_FLOATINGPOINT;
5940 type = check_floatingpoint_suffix();
5942 case T_FLOATINGPOINT_HEXADECIMAL:
5943 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5944 type = check_floatingpoint_suffix();
5947 panic("unexpected token type in parse_number_literal");
5950 expression_t *literal = allocate_expression_zero(kind);
5951 literal->base.type = type;
5952 literal->literal.value = token.number.number;
5953 literal->literal.suffix = token.number.suffix;
5956 /* integer type depends on the size of the number and the size
5957 * representable by the types. The backend/codegeneration has to determine
5960 determine_literal_type(&literal->literal);
5965 * Parse a character constant.
5967 static expression_t *parse_character_constant(void)
5969 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
5970 literal->base.type = c_mode & _CXX ? type_char : type_int;
5971 literal->literal.value = token.string.string;
5973 size_t len = literal->literal.value.size;
5975 if (!GNU_MODE && !(c_mode & _C99)) {
5976 errorf(HERE, "more than 1 character in character constant");
5978 literal->base.type = type_int;
5979 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
5988 * Parse a wide character constant.
5990 static expression_t *parse_wide_character_constant(void)
5992 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
5993 literal->base.type = type_int;
5994 literal->literal.value = token.string.string;
5996 size_t len = wstrlen(&literal->literal.value);
5998 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6005 static entity_t *create_implicit_function(symbol_t *symbol, source_position_t const *const pos)
6007 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6008 ntype->function.return_type = type_int;
6009 ntype->function.unspecified_parameters = true;
6010 ntype->function.linkage = LINKAGE_C;
6011 type_t *type = identify_new_type(ntype);
6013 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol, pos);
6014 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6015 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6016 entity->declaration.type = type;
6017 entity->declaration.implicit = true;
6019 if (current_scope != NULL)
6020 record_entity(entity, false);
6026 * Performs automatic type cast as described in §6.3.2.1.
6028 * @param orig_type the original type
6030 static type_t *automatic_type_conversion(type_t *orig_type)
6032 type_t *type = skip_typeref(orig_type);
6033 if (is_type_array(type)) {
6034 array_type_t *array_type = &type->array;
6035 type_t *element_type = array_type->element_type;
6036 unsigned qualifiers = array_type->base.qualifiers;
6038 return make_pointer_type(element_type, qualifiers);
6041 if (is_type_function(type)) {
6042 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6049 * reverts the automatic casts of array to pointer types and function
6050 * to function-pointer types as defined §6.3.2.1
6052 type_t *revert_automatic_type_conversion(const expression_t *expression)
6054 switch (expression->kind) {
6055 case EXPR_REFERENCE: {
6056 entity_t *entity = expression->reference.entity;
6057 if (is_declaration(entity)) {
6058 return entity->declaration.type;
6059 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6060 return entity->enum_value.enum_type;
6062 panic("no declaration or enum in reference");
6067 entity_t *entity = expression->select.compound_entry;
6068 assert(is_declaration(entity));
6069 type_t *type = entity->declaration.type;
6070 return get_qualified_type(type, expression->base.type->base.qualifiers);
6073 case EXPR_UNARY_DEREFERENCE: {
6074 const expression_t *const value = expression->unary.value;
6075 type_t *const type = skip_typeref(value->base.type);
6076 if (!is_type_pointer(type))
6077 return type_error_type;
6078 return type->pointer.points_to;
6081 case EXPR_ARRAY_ACCESS: {
6082 const expression_t *array_ref = expression->array_access.array_ref;
6083 type_t *type_left = skip_typeref(array_ref->base.type);
6084 if (!is_type_pointer(type_left))
6085 return type_error_type;
6086 return type_left->pointer.points_to;
6089 case EXPR_STRING_LITERAL: {
6090 size_t size = expression->string_literal.value.size;
6091 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6094 case EXPR_WIDE_STRING_LITERAL: {
6095 size_t size = wstrlen(&expression->string_literal.value);
6096 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6099 case EXPR_COMPOUND_LITERAL:
6100 return expression->compound_literal.type;
6105 return expression->base.type;
6109 * Find an entity matching a symbol in a scope.
6110 * Uses current scope if scope is NULL
6112 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6113 namespace_tag_t namespc)
6115 if (scope == NULL) {
6116 return get_entity(symbol, namespc);
6119 /* we should optimize here, if scope grows above a certain size we should
6120 construct a hashmap here... */
6121 entity_t *entity = scope->entities;
6122 for ( ; entity != NULL; entity = entity->base.next) {
6123 if (entity->base.symbol == symbol
6124 && (namespace_tag_t)entity->base.namespc == namespc)
6131 static entity_t *parse_qualified_identifier(void)
6133 /* namespace containing the symbol */
6135 source_position_t pos;
6136 const scope_t *lookup_scope = NULL;
6138 if (next_if(T_COLONCOLON))
6139 lookup_scope = &unit->scope;
6143 if (token.kind != T_IDENTIFIER) {
6144 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6145 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6147 symbol = token.identifier.symbol;
6152 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6154 if (!next_if(T_COLONCOLON))
6157 switch (entity->kind) {
6158 case ENTITY_NAMESPACE:
6159 lookup_scope = &entity->namespacee.members;
6164 lookup_scope = &entity->compound.members;
6167 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6168 symbol, get_entity_kind_name(entity->kind));
6170 /* skip further qualifications */
6171 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6173 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6177 if (entity == NULL) {
6178 if (!strict_mode && token.kind == '(') {
6179 /* an implicitly declared function */
6180 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos,
6181 "implicit declaration of function '%Y'", symbol);
6182 entity = create_implicit_function(symbol, &pos);
6184 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6185 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6192 static expression_t *parse_reference(void)
6194 source_position_t const pos = token.base.source_position;
6195 entity_t *const entity = parse_qualified_identifier();
6198 if (is_declaration(entity)) {
6199 orig_type = entity->declaration.type;
6200 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6201 orig_type = entity->enum_value.enum_type;
6203 panic("expected declaration or enum value in reference");
6206 /* we always do the auto-type conversions; the & and sizeof parser contains
6207 * code to revert this! */
6208 type_t *type = automatic_type_conversion(orig_type);
6210 expression_kind_t kind = EXPR_REFERENCE;
6211 if (entity->kind == ENTITY_ENUM_VALUE)
6212 kind = EXPR_ENUM_CONSTANT;
6214 expression_t *expression = allocate_expression_zero(kind);
6215 expression->base.source_position = pos;
6216 expression->base.type = type;
6217 expression->reference.entity = entity;
6219 /* this declaration is used */
6220 if (is_declaration(entity)) {
6221 entity->declaration.used = true;
6224 if (entity->base.parent_scope != file_scope
6225 && (current_function != NULL
6226 && entity->base.parent_scope->depth < current_function->parameters.depth)
6227 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6228 if (entity->kind == ENTITY_VARIABLE) {
6229 /* access of a variable from an outer function */
6230 entity->variable.address_taken = true;
6231 } else if (entity->kind == ENTITY_PARAMETER) {
6232 entity->parameter.address_taken = true;
6234 current_function->need_closure = true;
6237 check_deprecated(&pos, entity);
6242 static bool semantic_cast(expression_t *cast)
6244 expression_t *expression = cast->unary.value;
6245 type_t *orig_dest_type = cast->base.type;
6246 type_t *orig_type_right = expression->base.type;
6247 type_t const *dst_type = skip_typeref(orig_dest_type);
6248 type_t const *src_type = skip_typeref(orig_type_right);
6249 source_position_t const *pos = &cast->base.source_position;
6251 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6252 if (is_type_void(dst_type))
6255 /* only integer and pointer can be casted to pointer */
6256 if (is_type_pointer(dst_type) &&
6257 !is_type_pointer(src_type) &&
6258 !is_type_integer(src_type) &&
6259 is_type_valid(src_type)) {
6260 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6264 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6265 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6269 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6270 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6274 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6275 type_t *src = skip_typeref(src_type->pointer.points_to);
6276 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6277 unsigned missing_qualifiers =
6278 src->base.qualifiers & ~dst->base.qualifiers;
6279 if (missing_qualifiers != 0) {
6280 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6286 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6288 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6289 expression->base.source_position = *pos;
6291 parse_initializer_env_t env;
6294 env.must_be_constant = false;
6295 initializer_t *initializer = parse_initializer(&env);
6298 expression->compound_literal.initializer = initializer;
6299 expression->compound_literal.type = type;
6300 expression->base.type = automatic_type_conversion(type);
6306 * Parse a cast expression.
6308 static expression_t *parse_cast(void)
6310 source_position_t const pos = *HERE;
6313 add_anchor_token(')');
6315 type_t *type = parse_typename();
6317 rem_anchor_token(')');
6318 expect(')', end_error);
6320 if (token.kind == '{') {
6321 return parse_compound_literal(&pos, type);
6324 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6325 cast->base.source_position = pos;
6327 expression_t *value = parse_subexpression(PREC_CAST);
6328 cast->base.type = type;
6329 cast->unary.value = value;
6331 if (! semantic_cast(cast)) {
6332 /* TODO: record the error in the AST. else it is impossible to detect it */
6337 return create_error_expression();
6341 * Parse a statement expression.
6343 static expression_t *parse_statement_expression(void)
6345 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6348 add_anchor_token(')');
6350 statement_t *statement = parse_compound_statement(true);
6351 statement->compound.stmt_expr = true;
6352 expression->statement.statement = statement;
6354 /* find last statement and use its type */
6355 type_t *type = type_void;
6356 const statement_t *stmt = statement->compound.statements;
6358 while (stmt->base.next != NULL)
6359 stmt = stmt->base.next;
6361 if (stmt->kind == STATEMENT_EXPRESSION) {
6362 type = stmt->expression.expression->base.type;
6365 source_position_t const *const pos = &expression->base.source_position;
6366 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6368 expression->base.type = type;
6370 rem_anchor_token(')');
6371 expect(')', end_error);
6378 * Parse a parenthesized expression.
6380 static expression_t *parse_parenthesized_expression(void)
6382 token_t const* const la1 = look_ahead(1);
6383 switch (la1->kind) {
6385 /* gcc extension: a statement expression */
6386 return parse_statement_expression();
6389 if (is_typedef_symbol(la1->identifier.symbol)) {
6391 return parse_cast();
6396 add_anchor_token(')');
6397 expression_t *result = parse_expression();
6398 result->base.parenthesized = true;
6399 rem_anchor_token(')');
6400 expect(')', end_error);
6406 static expression_t *parse_function_keyword(void)
6410 if (current_function == NULL) {
6411 errorf(HERE, "'__func__' used outside of a function");
6414 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6415 expression->base.type = type_char_ptr;
6416 expression->funcname.kind = FUNCNAME_FUNCTION;
6423 static expression_t *parse_pretty_function_keyword(void)
6425 if (current_function == NULL) {
6426 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6429 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6430 expression->base.type = type_char_ptr;
6431 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6433 eat(T___PRETTY_FUNCTION__);
6438 static expression_t *parse_funcsig_keyword(void)
6440 if (current_function == NULL) {
6441 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6444 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6445 expression->base.type = type_char_ptr;
6446 expression->funcname.kind = FUNCNAME_FUNCSIG;
6453 static expression_t *parse_funcdname_keyword(void)
6455 if (current_function == NULL) {
6456 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6459 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6460 expression->base.type = type_char_ptr;
6461 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6463 eat(T___FUNCDNAME__);
6468 static designator_t *parse_designator(void)
6470 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6471 result->source_position = *HERE;
6473 if (token.kind != T_IDENTIFIER) {
6474 parse_error_expected("while parsing member designator",
6475 T_IDENTIFIER, NULL);
6478 result->symbol = token.identifier.symbol;
6481 designator_t *last_designator = result;
6484 if (token.kind != T_IDENTIFIER) {
6485 parse_error_expected("while parsing member designator",
6486 T_IDENTIFIER, NULL);
6489 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6490 designator->source_position = *HERE;
6491 designator->symbol = token.identifier.symbol;
6494 last_designator->next = designator;
6495 last_designator = designator;
6499 add_anchor_token(']');
6500 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6501 designator->source_position = *HERE;
6502 designator->array_index = parse_expression();
6503 rem_anchor_token(']');
6504 expect(']', end_error);
6505 if (designator->array_index == NULL) {
6509 last_designator->next = designator;
6510 last_designator = designator;
6522 * Parse the __builtin_offsetof() expression.
6524 static expression_t *parse_offsetof(void)
6526 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6527 expression->base.type = type_size_t;
6529 eat(T___builtin_offsetof);
6531 expect('(', end_error);
6532 add_anchor_token(',');
6533 type_t *type = parse_typename();
6534 rem_anchor_token(',');
6535 expect(',', end_error);
6536 add_anchor_token(')');
6537 designator_t *designator = parse_designator();
6538 rem_anchor_token(')');
6539 expect(')', end_error);
6541 expression->offsetofe.type = type;
6542 expression->offsetofe.designator = designator;
6545 memset(&path, 0, sizeof(path));
6546 path.top_type = type;
6547 path.path = NEW_ARR_F(type_path_entry_t, 0);
6549 descend_into_subtype(&path);
6551 if (!walk_designator(&path, designator, true)) {
6552 return create_error_expression();
6555 DEL_ARR_F(path.path);
6559 return create_error_expression();
6563 * Parses a _builtin_va_start() expression.
6565 static expression_t *parse_va_start(void)
6567 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6569 eat(T___builtin_va_start);
6571 expect('(', end_error);
6572 add_anchor_token(',');
6573 expression->va_starte.ap = parse_assignment_expression();
6574 rem_anchor_token(',');
6575 expect(',', end_error);
6576 expression_t *const expr = parse_assignment_expression();
6577 if (expr->kind == EXPR_REFERENCE) {
6578 entity_t *const entity = expr->reference.entity;
6579 if (!current_function->base.type->function.variadic) {
6580 errorf(&expr->base.source_position,
6581 "'va_start' used in non-variadic function");
6582 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6583 entity->base.next != NULL ||
6584 entity->kind != ENTITY_PARAMETER) {
6585 errorf(&expr->base.source_position,
6586 "second argument of 'va_start' must be last parameter of the current function");
6588 expression->va_starte.parameter = &entity->variable;
6590 expect(')', end_error);
6593 expect(')', end_error);
6595 return create_error_expression();
6599 * Parses a __builtin_va_arg() expression.
6601 static expression_t *parse_va_arg(void)
6603 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6605 eat(T___builtin_va_arg);
6607 expect('(', end_error);
6609 ap.expression = parse_assignment_expression();
6610 expression->va_arge.ap = ap.expression;
6611 check_call_argument(type_valist, &ap, 1);
6613 expect(',', end_error);
6614 expression->base.type = parse_typename();
6615 expect(')', end_error);
6619 return create_error_expression();
6623 * Parses a __builtin_va_copy() expression.
6625 static expression_t *parse_va_copy(void)
6627 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6629 eat(T___builtin_va_copy);
6631 expect('(', end_error);
6632 expression_t *dst = parse_assignment_expression();
6633 assign_error_t error = semantic_assign(type_valist, dst);
6634 report_assign_error(error, type_valist, dst, "call argument 1",
6635 &dst->base.source_position);
6636 expression->va_copye.dst = dst;
6638 expect(',', end_error);
6640 call_argument_t src;
6641 src.expression = parse_assignment_expression();
6642 check_call_argument(type_valist, &src, 2);
6643 expression->va_copye.src = src.expression;
6644 expect(')', end_error);
6648 return create_error_expression();
6652 * Parses a __builtin_constant_p() expression.
6654 static expression_t *parse_builtin_constant(void)
6656 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6658 eat(T___builtin_constant_p);
6660 expect('(', end_error);
6661 add_anchor_token(')');
6662 expression->builtin_constant.value = parse_assignment_expression();
6663 rem_anchor_token(')');
6664 expect(')', end_error);
6665 expression->base.type = type_int;
6669 return create_error_expression();
6673 * Parses a __builtin_types_compatible_p() expression.
6675 static expression_t *parse_builtin_types_compatible(void)
6677 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6679 eat(T___builtin_types_compatible_p);
6681 expect('(', end_error);
6682 add_anchor_token(')');
6683 add_anchor_token(',');
6684 expression->builtin_types_compatible.left = parse_typename();
6685 rem_anchor_token(',');
6686 expect(',', end_error);
6687 expression->builtin_types_compatible.right = parse_typename();
6688 rem_anchor_token(')');
6689 expect(')', end_error);
6690 expression->base.type = type_int;
6694 return create_error_expression();
6698 * Parses a __builtin_is_*() compare expression.
6700 static expression_t *parse_compare_builtin(void)
6702 expression_t *expression;
6704 switch (token.kind) {
6705 case T___builtin_isgreater:
6706 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6708 case T___builtin_isgreaterequal:
6709 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6711 case T___builtin_isless:
6712 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6714 case T___builtin_islessequal:
6715 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6717 case T___builtin_islessgreater:
6718 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6720 case T___builtin_isunordered:
6721 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6724 internal_errorf(HERE, "invalid compare builtin found");
6726 expression->base.source_position = *HERE;
6729 expect('(', end_error);
6730 expression->binary.left = parse_assignment_expression();
6731 expect(',', end_error);
6732 expression->binary.right = parse_assignment_expression();
6733 expect(')', end_error);
6735 type_t *const orig_type_left = expression->binary.left->base.type;
6736 type_t *const orig_type_right = expression->binary.right->base.type;
6738 type_t *const type_left = skip_typeref(orig_type_left);
6739 type_t *const type_right = skip_typeref(orig_type_right);
6740 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6741 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6742 type_error_incompatible("invalid operands in comparison",
6743 &expression->base.source_position, orig_type_left, orig_type_right);
6746 semantic_comparison(&expression->binary);
6751 return create_error_expression();
6755 * Parses a MS assume() expression.
6757 static expression_t *parse_assume(void)
6759 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6763 expect('(', end_error);
6764 add_anchor_token(')');
6765 expression->unary.value = parse_assignment_expression();
6766 rem_anchor_token(')');
6767 expect(')', end_error);
6769 expression->base.type = type_void;
6772 return create_error_expression();
6776 * Return the label for the current symbol or create a new one.
6778 static label_t *get_label(void)
6780 assert(token.kind == T_IDENTIFIER);
6781 assert(current_function != NULL);
6783 entity_t *label = get_entity(token.identifier.symbol, NAMESPACE_LABEL);
6784 /* If we find a local label, we already created the declaration. */
6785 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6786 if (label->base.parent_scope != current_scope) {
6787 assert(label->base.parent_scope->depth < current_scope->depth);
6788 current_function->goto_to_outer = true;
6790 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6791 /* There is no matching label in the same function, so create a new one. */
6792 source_position_t const nowhere = { NULL, 0, 0, false };
6793 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.identifier.symbol, &nowhere);
6798 return &label->label;
6802 * Parses a GNU && label address expression.
6804 static expression_t *parse_label_address(void)
6806 source_position_t source_position = token.base.source_position;
6808 if (token.kind != T_IDENTIFIER) {
6809 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6810 return create_error_expression();
6813 label_t *const label = get_label();
6815 label->address_taken = true;
6817 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6818 expression->base.source_position = source_position;
6820 /* label address is treated as a void pointer */
6821 expression->base.type = type_void_ptr;
6822 expression->label_address.label = label;
6827 * Parse a microsoft __noop expression.
6829 static expression_t *parse_noop_expression(void)
6831 /* the result is a (int)0 */
6832 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6833 literal->base.type = type_int;
6834 literal->literal.value.begin = "__noop";
6835 literal->literal.value.size = 6;
6839 if (token.kind == '(') {
6840 /* parse arguments */
6842 add_anchor_token(')');
6843 add_anchor_token(',');
6845 if (token.kind != ')') do {
6846 (void)parse_assignment_expression();
6847 } while (next_if(','));
6849 rem_anchor_token(',');
6850 rem_anchor_token(')');
6852 expect(')', end_error);
6859 * Parses a primary expression.
6861 static expression_t *parse_primary_expression(void)
6863 switch (token.kind) {
6864 case T_false: return parse_boolean_literal(false);
6865 case T_true: return parse_boolean_literal(true);
6867 case T_INTEGER_OCTAL:
6868 case T_INTEGER_HEXADECIMAL:
6869 case T_FLOATINGPOINT:
6870 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6871 case T_CHARACTER_CONSTANT: return parse_character_constant();
6872 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6873 case T_STRING_LITERAL:
6874 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6875 case T___FUNCTION__:
6876 case T___func__: return parse_function_keyword();
6877 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6878 case T___FUNCSIG__: return parse_funcsig_keyword();
6879 case T___FUNCDNAME__: return parse_funcdname_keyword();
6880 case T___builtin_offsetof: return parse_offsetof();
6881 case T___builtin_va_start: return parse_va_start();
6882 case T___builtin_va_arg: return parse_va_arg();
6883 case T___builtin_va_copy: return parse_va_copy();
6884 case T___builtin_isgreater:
6885 case T___builtin_isgreaterequal:
6886 case T___builtin_isless:
6887 case T___builtin_islessequal:
6888 case T___builtin_islessgreater:
6889 case T___builtin_isunordered: return parse_compare_builtin();
6890 case T___builtin_constant_p: return parse_builtin_constant();
6891 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6892 case T__assume: return parse_assume();
6895 return parse_label_address();
6898 case '(': return parse_parenthesized_expression();
6899 case T___noop: return parse_noop_expression();
6901 /* Gracefully handle type names while parsing expressions. */
6903 return parse_reference();
6905 if (!is_typedef_symbol(token.identifier.symbol)) {
6906 return parse_reference();
6910 source_position_t const pos = *HERE;
6911 declaration_specifiers_t specifiers;
6912 parse_declaration_specifiers(&specifiers);
6913 type_t const *const type = parse_abstract_declarator(specifiers.type);
6914 errorf(&pos, "encountered type '%T' while parsing expression", type);
6915 return create_error_expression();
6919 errorf(HERE, "unexpected token %K, expected an expression", &token);
6921 return create_error_expression();
6924 static expression_t *parse_array_expression(expression_t *left)
6926 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6927 array_access_expression_t *const arr = &expr->array_access;
6930 add_anchor_token(']');
6932 expression_t *const inside = parse_expression();
6934 type_t *const orig_type_left = left->base.type;
6935 type_t *const orig_type_inside = inside->base.type;
6937 type_t *const type_left = skip_typeref(orig_type_left);
6938 type_t *const type_inside = skip_typeref(orig_type_inside);
6944 if (is_type_pointer(type_left)) {
6947 idx_type = type_inside;
6948 res_type = type_left->pointer.points_to;
6950 } else if (is_type_pointer(type_inside)) {
6951 arr->flipped = true;
6954 idx_type = type_left;
6955 res_type = type_inside->pointer.points_to;
6957 res_type = automatic_type_conversion(res_type);
6958 if (!is_type_integer(idx_type)) {
6959 errorf(&idx->base.source_position, "array subscript must have integer type");
6960 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
6961 source_position_t const *const pos = &idx->base.source_position;
6962 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
6965 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
6966 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
6968 res_type = type_error_type;
6973 arr->array_ref = ref;
6975 arr->base.type = res_type;
6977 rem_anchor_token(']');
6978 expect(']', end_error);
6983 static bool is_bitfield(const expression_t *expression)
6985 return expression->kind == EXPR_SELECT
6986 && expression->select.compound_entry->compound_member.bitfield;
6989 static expression_t *parse_typeprop(expression_kind_t const kind)
6991 expression_t *tp_expression = allocate_expression_zero(kind);
6992 tp_expression->base.type = type_size_t;
6994 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
6997 expression_t *expression;
6998 if (token.kind == '(' && is_declaration_specifier(look_ahead(1))) {
6999 source_position_t const pos = *HERE;
7001 add_anchor_token(')');
7002 orig_type = parse_typename();
7003 rem_anchor_token(')');
7004 expect(')', end_error);
7006 if (token.kind == '{') {
7007 /* It was not sizeof(type) after all. It is sizeof of an expression
7008 * starting with a compound literal */
7009 expression = parse_compound_literal(&pos, orig_type);
7010 goto typeprop_expression;
7013 expression = parse_subexpression(PREC_UNARY);
7015 typeprop_expression:
7016 if (is_bitfield(expression)) {
7017 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7018 errorf(&tp_expression->base.source_position,
7019 "operand of %s expression must not be a bitfield", what);
7022 tp_expression->typeprop.tp_expression = expression;
7024 orig_type = revert_automatic_type_conversion(expression);
7025 expression->base.type = orig_type;
7028 tp_expression->typeprop.type = orig_type;
7029 type_t const* const type = skip_typeref(orig_type);
7030 char const* wrong_type = NULL;
7031 if (is_type_incomplete(type)) {
7032 if (!is_type_void(type) || !GNU_MODE)
7033 wrong_type = "incomplete";
7034 } else if (type->kind == TYPE_FUNCTION) {
7036 /* function types are allowed (and return 1) */
7037 source_position_t const *const pos = &tp_expression->base.source_position;
7038 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7039 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7041 wrong_type = "function";
7045 if (wrong_type != NULL) {
7046 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7047 errorf(&tp_expression->base.source_position,
7048 "operand of %s expression must not be of %s type '%T'",
7049 what, wrong_type, orig_type);
7053 return tp_expression;
7056 static expression_t *parse_sizeof(void)
7058 return parse_typeprop(EXPR_SIZEOF);
7061 static expression_t *parse_alignof(void)
7063 return parse_typeprop(EXPR_ALIGNOF);
7066 static expression_t *parse_select_expression(expression_t *addr)
7068 assert(token.kind == '.' || token.kind == T_MINUSGREATER);
7069 bool select_left_arrow = (token.kind == T_MINUSGREATER);
7070 source_position_t const pos = *HERE;
7073 if (token.kind != T_IDENTIFIER) {
7074 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7075 return create_error_expression();
7077 symbol_t *symbol = token.identifier.symbol;
7080 type_t *const orig_type = addr->base.type;
7081 type_t *const type = skip_typeref(orig_type);
7084 bool saw_error = false;
7085 if (is_type_pointer(type)) {
7086 if (!select_left_arrow) {
7088 "request for member '%Y' in something not a struct or union, but '%T'",
7092 type_left = skip_typeref(type->pointer.points_to);
7094 if (select_left_arrow && is_type_valid(type)) {
7095 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7101 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7102 type_left->kind != TYPE_COMPOUND_UNION) {
7104 if (is_type_valid(type_left) && !saw_error) {
7106 "request for member '%Y' in something not a struct or union, but '%T'",
7109 return create_error_expression();
7112 compound_t *compound = type_left->compound.compound;
7113 if (!compound->complete) {
7114 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7116 return create_error_expression();
7119 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7120 expression_t *result =
7121 find_create_select(&pos, addr, qualifiers, compound, symbol);
7123 if (result == NULL) {
7124 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7125 return create_error_expression();
7131 static void check_call_argument(type_t *expected_type,
7132 call_argument_t *argument, unsigned pos)
7134 type_t *expected_type_skip = skip_typeref(expected_type);
7135 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7136 expression_t *arg_expr = argument->expression;
7137 type_t *arg_type = skip_typeref(arg_expr->base.type);
7139 /* handle transparent union gnu extension */
7140 if (is_type_union(expected_type_skip)
7141 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7142 compound_t *union_decl = expected_type_skip->compound.compound;
7143 type_t *best_type = NULL;
7144 entity_t *entry = union_decl->members.entities;
7145 for ( ; entry != NULL; entry = entry->base.next) {
7146 assert(is_declaration(entry));
7147 type_t *decl_type = entry->declaration.type;
7148 error = semantic_assign(decl_type, arg_expr);
7149 if (error == ASSIGN_ERROR_INCOMPATIBLE
7150 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7153 if (error == ASSIGN_SUCCESS) {
7154 best_type = decl_type;
7155 } else if (best_type == NULL) {
7156 best_type = decl_type;
7160 if (best_type != NULL) {
7161 expected_type = best_type;
7165 error = semantic_assign(expected_type, arg_expr);
7166 argument->expression = create_implicit_cast(arg_expr, expected_type);
7168 if (error != ASSIGN_SUCCESS) {
7169 /* report exact scope in error messages (like "in argument 3") */
7171 snprintf(buf, sizeof(buf), "call argument %u", pos);
7172 report_assign_error(error, expected_type, arg_expr, buf,
7173 &arg_expr->base.source_position);
7175 type_t *const promoted_type = get_default_promoted_type(arg_type);
7176 if (!types_compatible(expected_type_skip, promoted_type) &&
7177 !types_compatible(expected_type_skip, type_void_ptr) &&
7178 !types_compatible(type_void_ptr, promoted_type)) {
7179 /* Deliberately show the skipped types in this warning */
7180 source_position_t const *const apos = &arg_expr->base.source_position;
7181 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7187 * Handle the semantic restrictions of builtin calls
7189 static void handle_builtin_argument_restrictions(call_expression_t *call)
7191 entity_t *entity = call->function->reference.entity;
7192 switch (entity->function.btk) {
7194 switch (entity->function.b.firm_builtin_kind) {
7195 case ir_bk_return_address:
7196 case ir_bk_frame_address: {
7197 /* argument must be constant */
7198 call_argument_t *argument = call->arguments;
7200 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7201 errorf(&call->base.source_position,
7202 "argument of '%Y' must be a constant expression",
7203 call->function->reference.entity->base.symbol);
7207 case ir_bk_prefetch:
7208 /* second and third argument must be constant if existent */
7209 if (call->arguments == NULL)
7211 call_argument_t *rw = call->arguments->next;
7212 call_argument_t *locality = NULL;
7215 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7216 errorf(&call->base.source_position,
7217 "second argument of '%Y' must be a constant expression",
7218 call->function->reference.entity->base.symbol);
7220 locality = rw->next;
7222 if (locality != NULL) {
7223 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7224 errorf(&call->base.source_position,
7225 "third argument of '%Y' must be a constant expression",
7226 call->function->reference.entity->base.symbol);
7228 locality = rw->next;
7235 case BUILTIN_OBJECT_SIZE:
7236 if (call->arguments == NULL)
7239 call_argument_t *arg = call->arguments->next;
7240 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7241 errorf(&call->base.source_position,
7242 "second argument of '%Y' must be a constant expression",
7243 call->function->reference.entity->base.symbol);
7252 * Parse a call expression, ie. expression '( ... )'.
7254 * @param expression the function address
7256 static expression_t *parse_call_expression(expression_t *expression)
7258 expression_t *result = allocate_expression_zero(EXPR_CALL);
7259 call_expression_t *call = &result->call;
7260 call->function = expression;
7262 type_t *const orig_type = expression->base.type;
7263 type_t *const type = skip_typeref(orig_type);
7265 function_type_t *function_type = NULL;
7266 if (is_type_pointer(type)) {
7267 type_t *const to_type = skip_typeref(type->pointer.points_to);
7269 if (is_type_function(to_type)) {
7270 function_type = &to_type->function;
7271 call->base.type = function_type->return_type;
7275 if (function_type == NULL && is_type_valid(type)) {
7277 "called object '%E' (type '%T') is not a pointer to a function",
7278 expression, orig_type);
7281 /* parse arguments */
7283 add_anchor_token(')');
7284 add_anchor_token(',');
7286 if (token.kind != ')') {
7287 call_argument_t **anchor = &call->arguments;
7289 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7290 argument->expression = parse_assignment_expression();
7293 anchor = &argument->next;
7294 } while (next_if(','));
7296 rem_anchor_token(',');
7297 rem_anchor_token(')');
7298 expect(')', end_error);
7300 if (function_type == NULL)
7303 /* check type and count of call arguments */
7304 function_parameter_t *parameter = function_type->parameters;
7305 call_argument_t *argument = call->arguments;
7306 if (!function_type->unspecified_parameters) {
7307 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7308 parameter = parameter->next, argument = argument->next) {
7309 check_call_argument(parameter->type, argument, ++pos);
7312 if (parameter != NULL) {
7313 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7314 } else if (argument != NULL && !function_type->variadic) {
7315 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7319 /* do default promotion for other arguments */
7320 for (; argument != NULL; argument = argument->next) {
7321 type_t *argument_type = argument->expression->base.type;
7322 if (!is_type_object(skip_typeref(argument_type))) {
7323 errorf(&argument->expression->base.source_position,
7324 "call argument '%E' must not be void", argument->expression);
7327 argument_type = get_default_promoted_type(argument_type);
7329 argument->expression
7330 = create_implicit_cast(argument->expression, argument_type);
7335 if (is_type_compound(skip_typeref(function_type->return_type))) {
7336 source_position_t const *const pos = &expression->base.source_position;
7337 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7340 if (expression->kind == EXPR_REFERENCE) {
7341 reference_expression_t *reference = &expression->reference;
7342 if (reference->entity->kind == ENTITY_FUNCTION &&
7343 reference->entity->function.btk != BUILTIN_NONE)
7344 handle_builtin_argument_restrictions(call);
7351 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7353 static bool same_compound_type(const type_t *type1, const type_t *type2)
7356 is_type_compound(type1) &&
7357 type1->kind == type2->kind &&
7358 type1->compound.compound == type2->compound.compound;
7361 static expression_t const *get_reference_address(expression_t const *expr)
7363 bool regular_take_address = true;
7365 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7366 expr = expr->unary.value;
7368 regular_take_address = false;
7371 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7374 expr = expr->unary.value;
7377 if (expr->kind != EXPR_REFERENCE)
7380 /* special case for functions which are automatically converted to a
7381 * pointer to function without an extra TAKE_ADDRESS operation */
7382 if (!regular_take_address &&
7383 expr->reference.entity->kind != ENTITY_FUNCTION) {
7390 static void warn_reference_address_as_bool(expression_t const* expr)
7392 expr = get_reference_address(expr);
7394 source_position_t const *const pos = &expr->base.source_position;
7395 entity_t const *const ent = expr->reference.entity;
7396 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7400 static void warn_assignment_in_condition(const expression_t *const expr)
7402 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7404 if (expr->base.parenthesized)
7406 source_position_t const *const pos = &expr->base.source_position;
7407 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7410 static void semantic_condition(expression_t const *const expr,
7411 char const *const context)
7413 type_t *const type = skip_typeref(expr->base.type);
7414 if (is_type_scalar(type)) {
7415 warn_reference_address_as_bool(expr);
7416 warn_assignment_in_condition(expr);
7417 } else if (is_type_valid(type)) {
7418 errorf(&expr->base.source_position,
7419 "%s must have scalar type", context);
7424 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7426 * @param expression the conditional expression
7428 static expression_t *parse_conditional_expression(expression_t *expression)
7430 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7432 conditional_expression_t *conditional = &result->conditional;
7433 conditional->condition = expression;
7436 add_anchor_token(':');
7438 /* §6.5.15:2 The first operand shall have scalar type. */
7439 semantic_condition(expression, "condition of conditional operator");
7441 expression_t *true_expression = expression;
7442 bool gnu_cond = false;
7443 if (GNU_MODE && token.kind == ':') {
7446 true_expression = parse_expression();
7448 rem_anchor_token(':');
7449 expect(':', end_error);
7451 expression_t *false_expression =
7452 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7454 type_t *const orig_true_type = true_expression->base.type;
7455 type_t *const orig_false_type = false_expression->base.type;
7456 type_t *const true_type = skip_typeref(orig_true_type);
7457 type_t *const false_type = skip_typeref(orig_false_type);
7460 source_position_t const *const pos = &conditional->base.source_position;
7461 type_t *result_type;
7462 if (is_type_void(true_type) || is_type_void(false_type)) {
7463 /* ISO/IEC 14882:1998(E) §5.16:2 */
7464 if (true_expression->kind == EXPR_UNARY_THROW) {
7465 result_type = false_type;
7466 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7467 result_type = true_type;
7469 if (!is_type_void(true_type) || !is_type_void(false_type)) {
7470 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7472 result_type = type_void;
7474 } else if (is_type_arithmetic(true_type)
7475 && is_type_arithmetic(false_type)) {
7476 result_type = semantic_arithmetic(true_type, false_type);
7477 } else if (same_compound_type(true_type, false_type)) {
7478 /* just take 1 of the 2 types */
7479 result_type = true_type;
7480 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7481 type_t *pointer_type;
7483 expression_t *other_expression;
7484 if (is_type_pointer(true_type) &&
7485 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7486 pointer_type = true_type;
7487 other_type = false_type;
7488 other_expression = false_expression;
7490 pointer_type = false_type;
7491 other_type = true_type;
7492 other_expression = true_expression;
7495 if (is_null_pointer_constant(other_expression)) {
7496 result_type = pointer_type;
7497 } else if (is_type_pointer(other_type)) {
7498 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7499 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7502 if (is_type_void(to1) || is_type_void(to2)) {
7504 } else if (types_compatible(get_unqualified_type(to1),
7505 get_unqualified_type(to2))) {
7508 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7512 type_t *const type =
7513 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7514 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7515 } else if (is_type_integer(other_type)) {
7516 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7517 result_type = pointer_type;
7519 goto types_incompatible;
7523 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7524 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7526 result_type = type_error_type;
7529 conditional->true_expression
7530 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7531 conditional->false_expression
7532 = create_implicit_cast(false_expression, result_type);
7533 conditional->base.type = result_type;
7538 * Parse an extension expression.
7540 static expression_t *parse_extension(void)
7543 expression_t *expression = parse_subexpression(PREC_UNARY);
7549 * Parse a __builtin_classify_type() expression.
7551 static expression_t *parse_builtin_classify_type(void)
7553 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7554 result->base.type = type_int;
7556 eat(T___builtin_classify_type);
7558 expect('(', end_error);
7559 add_anchor_token(')');
7560 expression_t *expression = parse_expression();
7561 rem_anchor_token(')');
7562 expect(')', end_error);
7563 result->classify_type.type_expression = expression;
7567 return create_error_expression();
7571 * Parse a delete expression
7572 * ISO/IEC 14882:1998(E) §5.3.5
7574 static expression_t *parse_delete(void)
7576 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7577 result->base.type = type_void;
7582 result->kind = EXPR_UNARY_DELETE_ARRAY;
7583 expect(']', end_error);
7587 expression_t *const value = parse_subexpression(PREC_CAST);
7588 result->unary.value = value;
7590 type_t *const type = skip_typeref(value->base.type);
7591 if (!is_type_pointer(type)) {
7592 if (is_type_valid(type)) {
7593 errorf(&value->base.source_position,
7594 "operand of delete must have pointer type");
7596 } else if (is_type_void(skip_typeref(type->pointer.points_to))) {
7597 source_position_t const *const pos = &value->base.source_position;
7598 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7605 * Parse a throw expression
7606 * ISO/IEC 14882:1998(E) §15:1
7608 static expression_t *parse_throw(void)
7610 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7611 result->base.type = type_void;
7615 expression_t *value = NULL;
7616 switch (token.kind) {
7618 value = parse_assignment_expression();
7619 /* ISO/IEC 14882:1998(E) §15.1:3 */
7620 type_t *const orig_type = value->base.type;
7621 type_t *const type = skip_typeref(orig_type);
7622 if (is_type_incomplete(type)) {
7623 errorf(&value->base.source_position,
7624 "cannot throw object of incomplete type '%T'", orig_type);
7625 } else if (is_type_pointer(type)) {
7626 type_t *const points_to = skip_typeref(type->pointer.points_to);
7627 if (is_type_incomplete(points_to) && !is_type_void(points_to)) {
7628 errorf(&value->base.source_position,
7629 "cannot throw pointer to incomplete type '%T'", orig_type);
7637 result->unary.value = value;
7642 static bool check_pointer_arithmetic(const source_position_t *source_position,
7643 type_t *pointer_type,
7644 type_t *orig_pointer_type)
7646 type_t *points_to = pointer_type->pointer.points_to;
7647 points_to = skip_typeref(points_to);
7649 if (is_type_incomplete(points_to)) {
7650 if (!GNU_MODE || !is_type_void(points_to)) {
7651 errorf(source_position,
7652 "arithmetic with pointer to incomplete type '%T' not allowed",
7656 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7658 } else if (is_type_function(points_to)) {
7660 errorf(source_position,
7661 "arithmetic with pointer to function type '%T' not allowed",
7665 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7671 static bool is_lvalue(const expression_t *expression)
7673 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7674 switch (expression->kind) {
7675 case EXPR_ARRAY_ACCESS:
7676 case EXPR_COMPOUND_LITERAL:
7677 case EXPR_REFERENCE:
7679 case EXPR_UNARY_DEREFERENCE:
7683 type_t *type = skip_typeref(expression->base.type);
7685 /* ISO/IEC 14882:1998(E) §3.10:3 */
7686 is_type_reference(type) ||
7687 /* Claim it is an lvalue, if the type is invalid. There was a parse
7688 * error before, which maybe prevented properly recognizing it as
7690 !is_type_valid(type);
7695 static void semantic_incdec(unary_expression_t *expression)
7697 type_t *const orig_type = expression->value->base.type;
7698 type_t *const type = skip_typeref(orig_type);
7699 if (is_type_pointer(type)) {
7700 if (!check_pointer_arithmetic(&expression->base.source_position,
7704 } else if (!is_type_real(type) && is_type_valid(type)) {
7705 /* TODO: improve error message */
7706 errorf(&expression->base.source_position,
7707 "operation needs an arithmetic or pointer type");
7710 if (!is_lvalue(expression->value)) {
7711 /* TODO: improve error message */
7712 errorf(&expression->base.source_position, "lvalue required as operand");
7714 expression->base.type = orig_type;
7717 static void promote_unary_int_expr(unary_expression_t *const expr, type_t *const type)
7719 type_t *const res_type = promote_integer(type);
7720 expr->base.type = res_type;
7721 expr->value = create_implicit_cast(expr->value, res_type);
7724 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7726 type_t *const orig_type = expression->value->base.type;
7727 type_t *const type = skip_typeref(orig_type);
7728 if (!is_type_arithmetic(type)) {
7729 if (is_type_valid(type)) {
7730 /* TODO: improve error message */
7731 errorf(&expression->base.source_position,
7732 "operation needs an arithmetic type");
7735 } else if (is_type_integer(type)) {
7736 promote_unary_int_expr(expression, type);
7738 expression->base.type = orig_type;
7742 static void semantic_unexpr_plus(unary_expression_t *expression)
7744 semantic_unexpr_arithmetic(expression);
7745 source_position_t const *const pos = &expression->base.source_position;
7746 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7749 static void semantic_not(unary_expression_t *expression)
7751 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7752 semantic_condition(expression->value, "operand of !");
7753 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7756 static void semantic_unexpr_integer(unary_expression_t *expression)
7758 type_t *const orig_type = expression->value->base.type;
7759 type_t *const type = skip_typeref(orig_type);
7760 if (!is_type_integer(type)) {
7761 if (is_type_valid(type)) {
7762 errorf(&expression->base.source_position,
7763 "operand of ~ must be of integer type");
7768 promote_unary_int_expr(expression, type);
7771 static void semantic_dereference(unary_expression_t *expression)
7773 type_t *const orig_type = expression->value->base.type;
7774 type_t *const type = skip_typeref(orig_type);
7775 if (!is_type_pointer(type)) {
7776 if (is_type_valid(type)) {
7777 errorf(&expression->base.source_position,
7778 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7783 type_t *result_type = type->pointer.points_to;
7784 result_type = automatic_type_conversion(result_type);
7785 expression->base.type = result_type;
7789 * Record that an address is taken (expression represents an lvalue).
7791 * @param expression the expression
7792 * @param may_be_register if true, the expression might be an register
7794 static void set_address_taken(expression_t *expression, bool may_be_register)
7796 if (expression->kind != EXPR_REFERENCE)
7799 entity_t *const entity = expression->reference.entity;
7801 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7804 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7805 && !may_be_register) {
7806 source_position_t const *const pos = &expression->base.source_position;
7807 errorf(pos, "address of register '%N' requested", entity);
7810 if (entity->kind == ENTITY_VARIABLE) {
7811 entity->variable.address_taken = true;
7813 assert(entity->kind == ENTITY_PARAMETER);
7814 entity->parameter.address_taken = true;
7819 * Check the semantic of the address taken expression.
7821 static void semantic_take_addr(unary_expression_t *expression)
7823 expression_t *value = expression->value;
7824 value->base.type = revert_automatic_type_conversion(value);
7826 type_t *orig_type = value->base.type;
7827 type_t *type = skip_typeref(orig_type);
7828 if (!is_type_valid(type))
7832 if (!is_lvalue(value)) {
7833 errorf(&expression->base.source_position, "'&' requires an lvalue");
7835 if (is_bitfield(value)) {
7836 errorf(&expression->base.source_position,
7837 "'&' not allowed on bitfield");
7840 set_address_taken(value, false);
7842 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7845 #define CREATE_UNARY_EXPRESSION_PARSER(token_kind, unexpression_type, sfunc) \
7846 static expression_t *parse_##unexpression_type(void) \
7848 expression_t *unary_expression \
7849 = allocate_expression_zero(unexpression_type); \
7851 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7853 sfunc(&unary_expression->unary); \
7855 return unary_expression; \
7858 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7859 semantic_unexpr_arithmetic)
7860 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7861 semantic_unexpr_plus)
7862 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7864 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7865 semantic_dereference)
7866 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7868 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7869 semantic_unexpr_integer)
7870 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7872 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7875 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_kind, unexpression_type, \
7877 static expression_t *parse_##unexpression_type(expression_t *left) \
7879 expression_t *unary_expression \
7880 = allocate_expression_zero(unexpression_type); \
7882 unary_expression->unary.value = left; \
7884 sfunc(&unary_expression->unary); \
7886 return unary_expression; \
7889 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7890 EXPR_UNARY_POSTFIX_INCREMENT,
7892 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7893 EXPR_UNARY_POSTFIX_DECREMENT,
7896 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7898 /* TODO: handle complex + imaginary types */
7900 type_left = get_unqualified_type(type_left);
7901 type_right = get_unqualified_type(type_right);
7903 /* §6.3.1.8 Usual arithmetic conversions */
7904 if (type_left == type_long_double || type_right == type_long_double) {
7905 return type_long_double;
7906 } else if (type_left == type_double || type_right == type_double) {
7908 } else if (type_left == type_float || type_right == type_float) {
7912 type_left = promote_integer(type_left);
7913 type_right = promote_integer(type_right);
7915 if (type_left == type_right)
7918 bool const signed_left = is_type_signed(type_left);
7919 bool const signed_right = is_type_signed(type_right);
7920 unsigned const rank_left = get_akind_rank(get_akind(type_left));
7921 unsigned const rank_right = get_akind_rank(get_akind(type_right));
7923 if (signed_left == signed_right)
7924 return rank_left >= rank_right ? type_left : type_right;
7928 atomic_type_kind_t s_akind;
7929 atomic_type_kind_t u_akind;
7934 u_type = type_right;
7936 s_type = type_right;
7939 s_akind = get_akind(s_type);
7940 u_akind = get_akind(u_type);
7941 s_rank = get_akind_rank(s_akind);
7942 u_rank = get_akind_rank(u_akind);
7944 if (u_rank >= s_rank)
7947 if (get_atomic_type_size(s_akind) > get_atomic_type_size(u_akind))
7951 case ATOMIC_TYPE_INT: return type_unsigned_int;
7952 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7953 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7955 default: panic("invalid atomic type");
7960 * Check the semantic restrictions for a binary expression.
7962 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
7964 expression_t *const left = expression->left;
7965 expression_t *const right = expression->right;
7966 type_t *const orig_type_left = left->base.type;
7967 type_t *const orig_type_right = right->base.type;
7968 type_t *const type_left = skip_typeref(orig_type_left);
7969 type_t *const type_right = skip_typeref(orig_type_right);
7971 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
7972 /* TODO: improve error message */
7973 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7974 errorf(&expression->base.source_position,
7975 "operation needs arithmetic types");
7980 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
7981 expression->left = create_implicit_cast(left, arithmetic_type);
7982 expression->right = create_implicit_cast(right, arithmetic_type);
7983 expression->base.type = arithmetic_type;
7986 static void semantic_binexpr_integer(binary_expression_t *const expression)
7988 expression_t *const left = expression->left;
7989 expression_t *const right = expression->right;
7990 type_t *const orig_type_left = left->base.type;
7991 type_t *const orig_type_right = right->base.type;
7992 type_t *const type_left = skip_typeref(orig_type_left);
7993 type_t *const type_right = skip_typeref(orig_type_right);
7995 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
7996 /* TODO: improve error message */
7997 if (is_type_valid(type_left) && is_type_valid(type_right)) {
7998 errorf(&expression->base.source_position,
7999 "operation needs integer types");
8004 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8005 expression->left = create_implicit_cast(left, result_type);
8006 expression->right = create_implicit_cast(right, result_type);
8007 expression->base.type = result_type;
8010 static void warn_div_by_zero(binary_expression_t const *const expression)
8012 if (!is_type_integer(expression->base.type))
8015 expression_t const *const right = expression->right;
8016 /* The type of the right operand can be different for /= */
8017 if (is_type_integer(right->base.type) &&
8018 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8019 !fold_constant_to_bool(right)) {
8020 source_position_t const *const pos = &expression->base.source_position;
8021 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8026 * Check the semantic restrictions for a div/mod expression.
8028 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8030 semantic_binexpr_arithmetic(expression);
8031 warn_div_by_zero(expression);
8034 static void warn_addsub_in_shift(const expression_t *const expr)
8036 if (expr->base.parenthesized)
8040 switch (expr->kind) {
8041 case EXPR_BINARY_ADD: op = '+'; break;
8042 case EXPR_BINARY_SUB: op = '-'; break;
8046 source_position_t const *const pos = &expr->base.source_position;
8047 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8050 static bool semantic_shift(binary_expression_t *expression)
8052 expression_t *const left = expression->left;
8053 expression_t *const right = expression->right;
8054 type_t *const orig_type_left = left->base.type;
8055 type_t *const orig_type_right = right->base.type;
8056 type_t * type_left = skip_typeref(orig_type_left);
8057 type_t * type_right = skip_typeref(orig_type_right);
8059 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8060 /* TODO: improve error message */
8061 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8062 errorf(&expression->base.source_position,
8063 "operands of shift operation must have integer types");
8068 type_left = promote_integer(type_left);
8070 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8071 source_position_t const *const pos = &right->base.source_position;
8072 long const count = fold_constant_to_int(right);
8074 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8075 } else if ((unsigned long)count >=
8076 get_atomic_type_size(type_left->atomic.akind) * 8) {
8077 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8081 type_right = promote_integer(type_right);
8082 expression->right = create_implicit_cast(right, type_right);
8087 static void semantic_shift_op(binary_expression_t *expression)
8089 expression_t *const left = expression->left;
8090 expression_t *const right = expression->right;
8092 if (!semantic_shift(expression))
8095 warn_addsub_in_shift(left);
8096 warn_addsub_in_shift(right);
8098 type_t *const orig_type_left = left->base.type;
8099 type_t * type_left = skip_typeref(orig_type_left);
8101 type_left = promote_integer(type_left);
8102 expression->left = create_implicit_cast(left, type_left);
8103 expression->base.type = type_left;
8106 static void semantic_add(binary_expression_t *expression)
8108 expression_t *const left = expression->left;
8109 expression_t *const right = expression->right;
8110 type_t *const orig_type_left = left->base.type;
8111 type_t *const orig_type_right = right->base.type;
8112 type_t *const type_left = skip_typeref(orig_type_left);
8113 type_t *const type_right = skip_typeref(orig_type_right);
8116 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8117 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8118 expression->left = create_implicit_cast(left, arithmetic_type);
8119 expression->right = create_implicit_cast(right, arithmetic_type);
8120 expression->base.type = arithmetic_type;
8121 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8122 check_pointer_arithmetic(&expression->base.source_position,
8123 type_left, orig_type_left);
8124 expression->base.type = type_left;
8125 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8126 check_pointer_arithmetic(&expression->base.source_position,
8127 type_right, orig_type_right);
8128 expression->base.type = type_right;
8129 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8130 errorf(&expression->base.source_position,
8131 "invalid operands to binary + ('%T', '%T')",
8132 orig_type_left, orig_type_right);
8136 static void semantic_sub(binary_expression_t *expression)
8138 expression_t *const left = expression->left;
8139 expression_t *const right = expression->right;
8140 type_t *const orig_type_left = left->base.type;
8141 type_t *const orig_type_right = right->base.type;
8142 type_t *const type_left = skip_typeref(orig_type_left);
8143 type_t *const type_right = skip_typeref(orig_type_right);
8144 source_position_t const *const pos = &expression->base.source_position;
8147 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8148 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8149 expression->left = create_implicit_cast(left, arithmetic_type);
8150 expression->right = create_implicit_cast(right, arithmetic_type);
8151 expression->base.type = arithmetic_type;
8152 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8153 check_pointer_arithmetic(&expression->base.source_position,
8154 type_left, orig_type_left);
8155 expression->base.type = type_left;
8156 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8157 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8158 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8159 if (!types_compatible(unqual_left, unqual_right)) {
8161 "subtracting pointers to incompatible types '%T' and '%T'",
8162 orig_type_left, orig_type_right);
8163 } else if (!is_type_object(unqual_left)) {
8164 if (!is_type_void(unqual_left)) {
8165 errorf(pos, "subtracting pointers to non-object types '%T'",
8168 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8171 expression->base.type = type_ptrdiff_t;
8172 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8173 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8174 orig_type_left, orig_type_right);
8178 static void warn_string_literal_address(expression_t const* expr)
8180 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8181 expr = expr->unary.value;
8182 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8184 expr = expr->unary.value;
8187 if (expr->kind == EXPR_STRING_LITERAL
8188 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8189 source_position_t const *const pos = &expr->base.source_position;
8190 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8194 static bool maybe_negative(expression_t const *const expr)
8196 switch (is_constant_expression(expr)) {
8197 case EXPR_CLASS_ERROR: return false;
8198 case EXPR_CLASS_CONSTANT: return constant_is_negative(expr);
8199 default: return true;
8203 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8205 warn_string_literal_address(expr);
8207 expression_t const* const ref = get_reference_address(expr);
8208 if (ref != NULL && is_null_pointer_constant(other)) {
8209 entity_t const *const ent = ref->reference.entity;
8210 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8213 if (!expr->base.parenthesized) {
8214 switch (expr->base.kind) {
8215 case EXPR_BINARY_LESS:
8216 case EXPR_BINARY_GREATER:
8217 case EXPR_BINARY_LESSEQUAL:
8218 case EXPR_BINARY_GREATEREQUAL:
8219 case EXPR_BINARY_NOTEQUAL:
8220 case EXPR_BINARY_EQUAL:
8221 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8230 * Check the semantics of comparison expressions.
8232 * @param expression The expression to check.
8234 static void semantic_comparison(binary_expression_t *expression)
8236 source_position_t const *const pos = &expression->base.source_position;
8237 expression_t *const left = expression->left;
8238 expression_t *const right = expression->right;
8240 warn_comparison(pos, left, right);
8241 warn_comparison(pos, right, left);
8243 type_t *orig_type_left = left->base.type;
8244 type_t *orig_type_right = right->base.type;
8245 type_t *type_left = skip_typeref(orig_type_left);
8246 type_t *type_right = skip_typeref(orig_type_right);
8248 /* TODO non-arithmetic types */
8249 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8250 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8252 /* test for signed vs unsigned compares */
8253 if (is_type_integer(arithmetic_type)) {
8254 bool const signed_left = is_type_signed(type_left);
8255 bool const signed_right = is_type_signed(type_right);
8256 if (signed_left != signed_right) {
8257 /* FIXME long long needs better const folding magic */
8258 /* TODO check whether constant value can be represented by other type */
8259 if ((signed_left && maybe_negative(left)) ||
8260 (signed_right && maybe_negative(right))) {
8261 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8266 expression->left = create_implicit_cast(left, arithmetic_type);
8267 expression->right = create_implicit_cast(right, arithmetic_type);
8268 expression->base.type = arithmetic_type;
8269 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8270 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8271 is_type_float(arithmetic_type)) {
8272 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8274 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8275 /* TODO check compatibility */
8276 } else if (is_type_pointer(type_left)) {
8277 expression->right = create_implicit_cast(right, type_left);
8278 } else if (is_type_pointer(type_right)) {
8279 expression->left = create_implicit_cast(left, type_right);
8280 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8281 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8283 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8287 * Checks if a compound type has constant fields.
8289 static bool has_const_fields(const compound_type_t *type)
8291 compound_t *compound = type->compound;
8292 entity_t *entry = compound->members.entities;
8294 for (; entry != NULL; entry = entry->base.next) {
8295 if (!is_declaration(entry))
8298 const type_t *decl_type = skip_typeref(entry->declaration.type);
8299 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8306 static bool is_valid_assignment_lhs(expression_t const* const left)
8308 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8309 type_t *const type_left = skip_typeref(orig_type_left);
8311 if (!is_lvalue(left)) {
8312 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8317 if (left->kind == EXPR_REFERENCE
8318 && left->reference.entity->kind == ENTITY_FUNCTION) {
8319 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8323 if (is_type_array(type_left)) {
8324 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8327 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8328 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8332 if (is_type_incomplete(type_left)) {
8333 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8334 left, orig_type_left);
8337 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8338 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8339 left, orig_type_left);
8346 static void semantic_arithmetic_assign(binary_expression_t *expression)
8348 expression_t *left = expression->left;
8349 expression_t *right = expression->right;
8350 type_t *orig_type_left = left->base.type;
8351 type_t *orig_type_right = right->base.type;
8353 if (!is_valid_assignment_lhs(left))
8356 type_t *type_left = skip_typeref(orig_type_left);
8357 type_t *type_right = skip_typeref(orig_type_right);
8359 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8360 /* TODO: improve error message */
8361 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8362 errorf(&expression->base.source_position,
8363 "operation needs arithmetic types");
8368 /* combined instructions are tricky. We can't create an implicit cast on
8369 * the left side, because we need the uncasted form for the store.
8370 * The ast2firm pass has to know that left_type must be right_type
8371 * for the arithmetic operation and create a cast by itself */
8372 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8373 expression->right = create_implicit_cast(right, arithmetic_type);
8374 expression->base.type = type_left;
8377 static void semantic_divmod_assign(binary_expression_t *expression)
8379 semantic_arithmetic_assign(expression);
8380 warn_div_by_zero(expression);
8383 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8385 expression_t *const left = expression->left;
8386 expression_t *const right = expression->right;
8387 type_t *const orig_type_left = left->base.type;
8388 type_t *const orig_type_right = right->base.type;
8389 type_t *const type_left = skip_typeref(orig_type_left);
8390 type_t *const type_right = skip_typeref(orig_type_right);
8392 if (!is_valid_assignment_lhs(left))
8395 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8396 /* combined instructions are tricky. We can't create an implicit cast on
8397 * the left side, because we need the uncasted form for the store.
8398 * The ast2firm pass has to know that left_type must be right_type
8399 * for the arithmetic operation and create a cast by itself */
8400 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8401 expression->right = create_implicit_cast(right, arithmetic_type);
8402 expression->base.type = type_left;
8403 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8404 check_pointer_arithmetic(&expression->base.source_position,
8405 type_left, orig_type_left);
8406 expression->base.type = type_left;
8407 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8408 errorf(&expression->base.source_position,
8409 "incompatible types '%T' and '%T' in assignment",
8410 orig_type_left, orig_type_right);
8414 static void semantic_integer_assign(binary_expression_t *expression)
8416 expression_t *left = expression->left;
8417 expression_t *right = expression->right;
8418 type_t *orig_type_left = left->base.type;
8419 type_t *orig_type_right = right->base.type;
8421 if (!is_valid_assignment_lhs(left))
8424 type_t *type_left = skip_typeref(orig_type_left);
8425 type_t *type_right = skip_typeref(orig_type_right);
8427 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8428 /* TODO: improve error message */
8429 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8430 errorf(&expression->base.source_position,
8431 "operation needs integer types");
8436 /* combined instructions are tricky. We can't create an implicit cast on
8437 * the left side, because we need the uncasted form for the store.
8438 * The ast2firm pass has to know that left_type must be right_type
8439 * for the arithmetic operation and create a cast by itself */
8440 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8441 expression->right = create_implicit_cast(right, arithmetic_type);
8442 expression->base.type = type_left;
8445 static void semantic_shift_assign(binary_expression_t *expression)
8447 expression_t *left = expression->left;
8449 if (!is_valid_assignment_lhs(left))
8452 if (!semantic_shift(expression))
8455 expression->base.type = skip_typeref(left->base.type);
8458 static void warn_logical_and_within_or(const expression_t *const expr)
8460 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8462 if (expr->base.parenthesized)
8464 source_position_t const *const pos = &expr->base.source_position;
8465 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8469 * Check the semantic restrictions of a logical expression.
8471 static void semantic_logical_op(binary_expression_t *expression)
8473 /* §6.5.13:2 Each of the operands shall have scalar type.
8474 * §6.5.14:2 Each of the operands shall have scalar type. */
8475 semantic_condition(expression->left, "left operand of logical operator");
8476 semantic_condition(expression->right, "right operand of logical operator");
8477 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8478 warn_logical_and_within_or(expression->left);
8479 warn_logical_and_within_or(expression->right);
8481 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8485 * Check the semantic restrictions of a binary assign expression.
8487 static void semantic_binexpr_assign(binary_expression_t *expression)
8489 expression_t *left = expression->left;
8490 type_t *orig_type_left = left->base.type;
8492 if (!is_valid_assignment_lhs(left))
8495 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8496 report_assign_error(error, orig_type_left, expression->right,
8497 "assignment", &left->base.source_position);
8498 expression->right = create_implicit_cast(expression->right, orig_type_left);
8499 expression->base.type = orig_type_left;
8503 * Determine if the outermost operation (or parts thereof) of the given
8504 * expression has no effect in order to generate a warning about this fact.
8505 * Therefore in some cases this only examines some of the operands of the
8506 * expression (see comments in the function and examples below).
8508 * f() + 23; // warning, because + has no effect
8509 * x || f(); // no warning, because x controls execution of f()
8510 * x ? y : f(); // warning, because y has no effect
8511 * (void)x; // no warning to be able to suppress the warning
8512 * This function can NOT be used for an "expression has definitely no effect"-
8514 static bool expression_has_effect(const expression_t *const expr)
8516 switch (expr->kind) {
8517 case EXPR_ERROR: return true; /* do NOT warn */
8518 case EXPR_REFERENCE: return false;
8519 case EXPR_ENUM_CONSTANT: return false;
8520 case EXPR_LABEL_ADDRESS: return false;
8522 /* suppress the warning for microsoft __noop operations */
8523 case EXPR_LITERAL_MS_NOOP: return true;
8524 case EXPR_LITERAL_BOOLEAN:
8525 case EXPR_LITERAL_CHARACTER:
8526 case EXPR_LITERAL_WIDE_CHARACTER:
8527 case EXPR_LITERAL_INTEGER:
8528 case EXPR_LITERAL_INTEGER_OCTAL:
8529 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8530 case EXPR_LITERAL_FLOATINGPOINT:
8531 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8532 case EXPR_STRING_LITERAL: return false;
8533 case EXPR_WIDE_STRING_LITERAL: return false;
8536 const call_expression_t *const call = &expr->call;
8537 if (call->function->kind != EXPR_REFERENCE)
8540 switch (call->function->reference.entity->function.btk) {
8541 /* FIXME: which builtins have no effect? */
8542 default: return true;
8546 /* Generate the warning if either the left or right hand side of a
8547 * conditional expression has no effect */
8548 case EXPR_CONDITIONAL: {
8549 conditional_expression_t const *const cond = &expr->conditional;
8550 expression_t const *const t = cond->true_expression;
8552 (t == NULL || expression_has_effect(t)) &&
8553 expression_has_effect(cond->false_expression);
8556 case EXPR_SELECT: return false;
8557 case EXPR_ARRAY_ACCESS: return false;
8558 case EXPR_SIZEOF: return false;
8559 case EXPR_CLASSIFY_TYPE: return false;
8560 case EXPR_ALIGNOF: return false;
8562 case EXPR_FUNCNAME: return false;
8563 case EXPR_BUILTIN_CONSTANT_P: return false;
8564 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8565 case EXPR_OFFSETOF: return false;
8566 case EXPR_VA_START: return true;
8567 case EXPR_VA_ARG: return true;
8568 case EXPR_VA_COPY: return true;
8569 case EXPR_STATEMENT: return true; // TODO
8570 case EXPR_COMPOUND_LITERAL: return false;
8572 case EXPR_UNARY_NEGATE: return false;
8573 case EXPR_UNARY_PLUS: return false;
8574 case EXPR_UNARY_BITWISE_NEGATE: return false;
8575 case EXPR_UNARY_NOT: return false;
8576 case EXPR_UNARY_DEREFERENCE: return false;
8577 case EXPR_UNARY_TAKE_ADDRESS: return false;
8578 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8579 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8580 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8581 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8583 /* Treat void casts as if they have an effect in order to being able to
8584 * suppress the warning */
8585 case EXPR_UNARY_CAST: {
8586 type_t *const type = skip_typeref(expr->base.type);
8587 return is_type_void(type);
8590 case EXPR_UNARY_ASSUME: return true;
8591 case EXPR_UNARY_DELETE: return true;
8592 case EXPR_UNARY_DELETE_ARRAY: return true;
8593 case EXPR_UNARY_THROW: return true;
8595 case EXPR_BINARY_ADD: return false;
8596 case EXPR_BINARY_SUB: return false;
8597 case EXPR_BINARY_MUL: return false;
8598 case EXPR_BINARY_DIV: return false;
8599 case EXPR_BINARY_MOD: return false;
8600 case EXPR_BINARY_EQUAL: return false;
8601 case EXPR_BINARY_NOTEQUAL: return false;
8602 case EXPR_BINARY_LESS: return false;
8603 case EXPR_BINARY_LESSEQUAL: return false;
8604 case EXPR_BINARY_GREATER: return false;
8605 case EXPR_BINARY_GREATEREQUAL: return false;
8606 case EXPR_BINARY_BITWISE_AND: return false;
8607 case EXPR_BINARY_BITWISE_OR: return false;
8608 case EXPR_BINARY_BITWISE_XOR: return false;
8609 case EXPR_BINARY_SHIFTLEFT: return false;
8610 case EXPR_BINARY_SHIFTRIGHT: return false;
8611 case EXPR_BINARY_ASSIGN: return true;
8612 case EXPR_BINARY_MUL_ASSIGN: return true;
8613 case EXPR_BINARY_DIV_ASSIGN: return true;
8614 case EXPR_BINARY_MOD_ASSIGN: return true;
8615 case EXPR_BINARY_ADD_ASSIGN: return true;
8616 case EXPR_BINARY_SUB_ASSIGN: return true;
8617 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8618 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8619 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8620 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8621 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8623 /* Only examine the right hand side of && and ||, because the left hand
8624 * side already has the effect of controlling the execution of the right
8626 case EXPR_BINARY_LOGICAL_AND:
8627 case EXPR_BINARY_LOGICAL_OR:
8628 /* Only examine the right hand side of a comma expression, because the left
8629 * hand side has a separate warning */
8630 case EXPR_BINARY_COMMA:
8631 return expression_has_effect(expr->binary.right);
8633 case EXPR_BINARY_ISGREATER: return false;
8634 case EXPR_BINARY_ISGREATEREQUAL: return false;
8635 case EXPR_BINARY_ISLESS: return false;
8636 case EXPR_BINARY_ISLESSEQUAL: return false;
8637 case EXPR_BINARY_ISLESSGREATER: return false;
8638 case EXPR_BINARY_ISUNORDERED: return false;
8641 internal_errorf(HERE, "unexpected expression");
8644 static void semantic_comma(binary_expression_t *expression)
8646 const expression_t *const left = expression->left;
8647 if (!expression_has_effect(left)) {
8648 source_position_t const *const pos = &left->base.source_position;
8649 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8651 expression->base.type = expression->right->base.type;
8655 * @param prec_r precedence of the right operand
8657 #define CREATE_BINEXPR_PARSER(token_kind, binexpression_type, prec_r, sfunc) \
8658 static expression_t *parse_##binexpression_type(expression_t *left) \
8660 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8661 binexpr->binary.left = left; \
8664 expression_t *right = parse_subexpression(prec_r); \
8666 binexpr->binary.right = right; \
8667 sfunc(&binexpr->binary); \
8672 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8673 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8674 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8675 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8676 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8677 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8678 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8679 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8680 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8681 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8682 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8683 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8684 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8685 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8686 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8687 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8688 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8689 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8690 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8691 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8692 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8693 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8694 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8695 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8696 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8697 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8698 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8699 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8700 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8701 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8704 static expression_t *parse_subexpression(precedence_t precedence)
8706 if (token.kind < 0) {
8707 return expected_expression_error();
8710 expression_parser_function_t *parser
8711 = &expression_parsers[token.kind];
8714 if (parser->parser != NULL) {
8715 left = parser->parser();
8717 left = parse_primary_expression();
8719 assert(left != NULL);
8722 if (token.kind < 0) {
8723 return expected_expression_error();
8726 parser = &expression_parsers[token.kind];
8727 if (parser->infix_parser == NULL)
8729 if (parser->infix_precedence < precedence)
8732 left = parser->infix_parser(left);
8734 assert(left != NULL);
8741 * Parse an expression.
8743 static expression_t *parse_expression(void)
8745 return parse_subexpression(PREC_EXPRESSION);
8749 * Register a parser for a prefix-like operator.
8751 * @param parser the parser function
8752 * @param token_kind the token type of the prefix token
8754 static void register_expression_parser(parse_expression_function parser,
8757 expression_parser_function_t *entry = &expression_parsers[token_kind];
8759 if (entry->parser != NULL) {
8760 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8761 panic("trying to register multiple expression parsers for a token");
8763 entry->parser = parser;
8767 * Register a parser for an infix operator with given precedence.
8769 * @param parser the parser function
8770 * @param token_kind the token type of the infix operator
8771 * @param precedence the precedence of the operator
8773 static void register_infix_parser(parse_expression_infix_function parser,
8774 int token_kind, precedence_t precedence)
8776 expression_parser_function_t *entry = &expression_parsers[token_kind];
8778 if (entry->infix_parser != NULL) {
8779 diagnosticf("for token '%k'\n", (token_kind_t)token_kind);
8780 panic("trying to register multiple infix expression parsers for a "
8783 entry->infix_parser = parser;
8784 entry->infix_precedence = precedence;
8788 * Initialize the expression parsers.
8790 static void init_expression_parsers(void)
8792 memset(&expression_parsers, 0, sizeof(expression_parsers));
8794 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8795 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8796 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8797 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8798 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8799 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8800 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8801 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8802 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8803 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8804 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8805 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8806 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8807 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8808 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8809 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8810 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8811 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8812 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8813 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8814 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8815 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8816 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8817 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8818 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8819 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8820 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8821 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8822 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8823 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8824 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8825 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8826 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8827 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8828 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8829 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8830 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8832 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8833 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8834 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8835 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8836 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8837 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8838 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8839 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8840 register_expression_parser(parse_sizeof, T_sizeof);
8841 register_expression_parser(parse_alignof, T___alignof__);
8842 register_expression_parser(parse_extension, T___extension__);
8843 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8844 register_expression_parser(parse_delete, T_delete);
8845 register_expression_parser(parse_throw, T_throw);
8849 * Parse a asm statement arguments specification.
8851 static asm_argument_t *parse_asm_arguments(bool is_out)
8853 asm_argument_t *result = NULL;
8854 asm_argument_t **anchor = &result;
8856 while (token.kind == T_STRING_LITERAL || token.kind == '[') {
8857 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8860 if (token.kind != T_IDENTIFIER) {
8861 parse_error_expected("while parsing asm argument",
8862 T_IDENTIFIER, NULL);
8865 argument->symbol = token.identifier.symbol;
8867 expect(']', end_error);
8870 argument->constraints = parse_string_literals();
8871 expect('(', end_error);
8872 add_anchor_token(')');
8873 expression_t *expression = parse_expression();
8874 rem_anchor_token(')');
8876 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8877 * change size or type representation (e.g. int -> long is ok, but
8878 * int -> float is not) */
8879 if (expression->kind == EXPR_UNARY_CAST) {
8880 type_t *const type = expression->base.type;
8881 type_kind_t const kind = type->kind;
8882 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8885 if (kind == TYPE_ATOMIC) {
8886 atomic_type_kind_t const akind = type->atomic.akind;
8887 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8888 size = get_atomic_type_size(akind);
8890 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8891 size = get_type_size(type_void_ptr);
8895 expression_t *const value = expression->unary.value;
8896 type_t *const value_type = value->base.type;
8897 type_kind_t const value_kind = value_type->kind;
8899 unsigned value_flags;
8900 unsigned value_size;
8901 if (value_kind == TYPE_ATOMIC) {
8902 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8903 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8904 value_size = get_atomic_type_size(value_akind);
8905 } else if (value_kind == TYPE_POINTER) {
8906 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8907 value_size = get_type_size(type_void_ptr);
8912 if (value_flags != flags || value_size != size)
8916 } while (expression->kind == EXPR_UNARY_CAST);
8920 if (!is_lvalue(expression)) {
8921 errorf(&expression->base.source_position,
8922 "asm output argument is not an lvalue");
8925 if (argument->constraints.begin[0] == '=')
8926 determine_lhs_ent(expression, NULL);
8928 mark_vars_read(expression, NULL);
8930 mark_vars_read(expression, NULL);
8932 argument->expression = expression;
8933 expect(')', end_error);
8935 set_address_taken(expression, true);
8938 anchor = &argument->next;
8950 * Parse a asm statement clobber specification.
8952 static asm_clobber_t *parse_asm_clobbers(void)
8954 asm_clobber_t *result = NULL;
8955 asm_clobber_t **anchor = &result;
8957 while (token.kind == T_STRING_LITERAL) {
8958 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
8959 clobber->clobber = parse_string_literals();
8962 anchor = &clobber->next;
8972 * Parse an asm statement.
8974 static statement_t *parse_asm_statement(void)
8976 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
8977 asm_statement_t *asm_statement = &statement->asms;
8981 if (next_if(T_volatile))
8982 asm_statement->is_volatile = true;
8984 expect('(', end_error);
8985 add_anchor_token(')');
8986 if (token.kind != T_STRING_LITERAL) {
8987 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
8990 asm_statement->asm_text = parse_string_literals();
8992 add_anchor_token(':');
8993 if (!next_if(':')) {
8994 rem_anchor_token(':');
8998 asm_statement->outputs = parse_asm_arguments(true);
8999 if (!next_if(':')) {
9000 rem_anchor_token(':');
9004 asm_statement->inputs = parse_asm_arguments(false);
9005 if (!next_if(':')) {
9006 rem_anchor_token(':');
9009 rem_anchor_token(':');
9011 asm_statement->clobbers = parse_asm_clobbers();
9014 rem_anchor_token(')');
9015 expect(')', end_error);
9016 expect(';', end_error);
9019 if (asm_statement->outputs == NULL) {
9020 /* GCC: An 'asm' instruction without any output operands will be treated
9021 * identically to a volatile 'asm' instruction. */
9022 asm_statement->is_volatile = true;
9028 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9030 statement_t *inner_stmt;
9031 switch (token.kind) {
9033 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9034 inner_stmt = create_error_statement();
9038 if (label->kind == STATEMENT_LABEL) {
9039 /* Eat an empty statement here, to avoid the warning about an empty
9040 * statement after a label. label:; is commonly used to have a label
9041 * before a closing brace. */
9042 inner_stmt = create_empty_statement();
9049 inner_stmt = parse_statement();
9050 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9051 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9052 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9053 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9061 * Parse a case statement.
9063 static statement_t *parse_case_statement(void)
9065 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9066 source_position_t *const pos = &statement->base.source_position;
9070 expression_t *expression = parse_expression();
9071 type_t *expression_type = expression->base.type;
9072 type_t *skipped = skip_typeref(expression_type);
9073 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9074 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9075 expression, expression_type);
9078 type_t *type = expression_type;
9079 if (current_switch != NULL) {
9080 type_t *switch_type = current_switch->expression->base.type;
9081 if (is_type_valid(switch_type)) {
9082 expression = create_implicit_cast(expression, switch_type);
9086 statement->case_label.expression = expression;
9087 expression_classification_t const expr_class = is_constant_expression(expression);
9088 if (expr_class != EXPR_CLASS_CONSTANT) {
9089 if (expr_class != EXPR_CLASS_ERROR) {
9090 errorf(pos, "case label does not reduce to an integer constant");
9092 statement->case_label.is_bad = true;
9094 long const val = fold_constant_to_int(expression);
9095 statement->case_label.first_case = val;
9096 statement->case_label.last_case = val;
9100 if (next_if(T_DOTDOTDOT)) {
9101 expression_t *end_range = parse_expression();
9102 expression_type = expression->base.type;
9103 skipped = skip_typeref(expression_type);
9104 if (!is_type_integer(skipped) && is_type_valid(skipped)) {
9105 errorf(pos, "case expression '%E' must have integer type but has type '%T'",
9106 expression, expression_type);
9109 end_range = create_implicit_cast(end_range, type);
9110 statement->case_label.end_range = end_range;
9111 expression_classification_t const end_class = is_constant_expression(end_range);
9112 if (end_class != EXPR_CLASS_CONSTANT) {
9113 if (end_class != EXPR_CLASS_ERROR) {
9114 errorf(pos, "case range does not reduce to an integer constant");
9116 statement->case_label.is_bad = true;
9118 long const val = fold_constant_to_int(end_range);
9119 statement->case_label.last_case = val;
9121 if (val < statement->case_label.first_case) {
9122 statement->case_label.is_empty_range = true;
9123 warningf(WARN_OTHER, pos, "empty range specified");
9129 PUSH_PARENT(statement);
9131 expect(':', end_error);
9134 if (current_switch != NULL) {
9135 if (! statement->case_label.is_bad) {
9136 /* Check for duplicate case values */
9137 case_label_statement_t *c = &statement->case_label;
9138 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9139 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9142 if (c->last_case < l->first_case || c->first_case > l->last_case)
9145 errorf(pos, "duplicate case value (previously used %P)",
9146 &l->base.source_position);
9150 /* link all cases into the switch statement */
9151 if (current_switch->last_case == NULL) {
9152 current_switch->first_case = &statement->case_label;
9154 current_switch->last_case->next = &statement->case_label;
9156 current_switch->last_case = &statement->case_label;
9158 errorf(pos, "case label not within a switch statement");
9161 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9168 * Parse a default statement.
9170 static statement_t *parse_default_statement(void)
9172 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9176 PUSH_PARENT(statement);
9178 expect(':', end_error);
9181 if (current_switch != NULL) {
9182 const case_label_statement_t *def_label = current_switch->default_label;
9183 if (def_label != NULL) {
9184 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9186 current_switch->default_label = &statement->case_label;
9188 /* link all cases into the switch statement */
9189 if (current_switch->last_case == NULL) {
9190 current_switch->first_case = &statement->case_label;
9192 current_switch->last_case->next = &statement->case_label;
9194 current_switch->last_case = &statement->case_label;
9197 errorf(&statement->base.source_position,
9198 "'default' label not within a switch statement");
9201 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9208 * Parse a label statement.
9210 static statement_t *parse_label_statement(void)
9212 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9213 label_t *const label = get_label();
9214 statement->label.label = label;
9216 PUSH_PARENT(statement);
9218 /* if statement is already set then the label is defined twice,
9219 * otherwise it was just mentioned in a goto/local label declaration so far
9221 source_position_t const* const pos = &statement->base.source_position;
9222 if (label->statement != NULL) {
9223 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9225 label->base.source_position = *pos;
9226 label->statement = statement;
9231 if (token.kind == T___attribute__ && !(c_mode & _CXX)) {
9232 parse_attributes(NULL); // TODO process attributes
9235 statement->label.statement = parse_label_inner_statement(statement, "label");
9237 /* remember the labels in a list for later checking */
9238 *label_anchor = &statement->label;
9239 label_anchor = &statement->label.next;
9245 static statement_t *parse_inner_statement(void)
9247 statement_t *const stmt = parse_statement();
9248 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9249 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9250 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9251 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9257 * Parse an expression in parentheses and mark its variables as read.
9259 static expression_t *parse_condition(void)
9261 expect('(', end_error0);
9262 add_anchor_token(')');
9263 expression_t *const expr = parse_expression();
9264 mark_vars_read(expr, NULL);
9265 rem_anchor_token(')');
9266 expect(')', end_error1);
9270 return create_error_expression();
9274 * Parse an if statement.
9276 static statement_t *parse_if(void)
9278 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9282 PUSH_PARENT(statement);
9284 add_anchor_token('{');
9286 expression_t *const expr = parse_condition();
9287 statement->ifs.condition = expr;
9288 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9290 semantic_condition(expr, "condition of 'if'-statment");
9292 rem_anchor_token('{');
9294 add_anchor_token(T_else);
9295 statement_t *const true_stmt = parse_inner_statement();
9296 statement->ifs.true_statement = true_stmt;
9297 rem_anchor_token(T_else);
9299 if (true_stmt->kind == STATEMENT_EMPTY) {
9300 warningf(WARN_EMPTY_BODY, HERE,
9301 "suggest braces around empty body in an ‘if’ statement");
9304 if (next_if(T_else)) {
9305 statement->ifs.false_statement = parse_inner_statement();
9307 if (statement->ifs.false_statement->kind == STATEMENT_EMPTY) {
9308 warningf(WARN_EMPTY_BODY, HERE,
9309 "suggest braces around empty body in an ‘if’ statement");
9311 } else if (true_stmt->kind == STATEMENT_IF &&
9312 true_stmt->ifs.false_statement != NULL) {
9313 source_position_t const *const pos = &true_stmt->base.source_position;
9314 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9322 * Check that all enums are handled in a switch.
9324 * @param statement the switch statement to check
9326 static void check_enum_cases(const switch_statement_t *statement)
9328 if (!is_warn_on(WARN_SWITCH_ENUM))
9330 const type_t *type = skip_typeref(statement->expression->base.type);
9331 if (! is_type_enum(type))
9333 const enum_type_t *enumt = &type->enumt;
9335 /* if we have a default, no warnings */
9336 if (statement->default_label != NULL)
9339 /* FIXME: calculation of value should be done while parsing */
9340 /* TODO: quadratic algorithm here. Change to an n log n one */
9341 long last_value = -1;
9342 const entity_t *entry = enumt->enume->base.next;
9343 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9344 entry = entry->base.next) {
9345 const expression_t *expression = entry->enum_value.value;
9346 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9348 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9349 if (l->expression == NULL)
9351 if (l->first_case <= value && value <= l->last_case) {
9357 source_position_t const *const pos = &statement->base.source_position;
9358 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9365 * Parse a switch statement.
9367 static statement_t *parse_switch(void)
9369 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9373 PUSH_PARENT(statement);
9375 expression_t *const expr = parse_condition();
9376 type_t * type = skip_typeref(expr->base.type);
9377 if (is_type_integer(type)) {
9378 type = promote_integer(type);
9379 if (get_akind_rank(get_akind(type)) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9380 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9382 } else if (is_type_valid(type)) {
9383 errorf(&expr->base.source_position,
9384 "switch quantity is not an integer, but '%T'", type);
9385 type = type_error_type;
9387 statement->switchs.expression = create_implicit_cast(expr, type);
9389 switch_statement_t *rem = current_switch;
9390 current_switch = &statement->switchs;
9391 statement->switchs.body = parse_inner_statement();
9392 current_switch = rem;
9394 if (statement->switchs.default_label == NULL) {
9395 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9397 check_enum_cases(&statement->switchs);
9403 static statement_t *parse_loop_body(statement_t *const loop)
9405 statement_t *const rem = current_loop;
9406 current_loop = loop;
9408 statement_t *const body = parse_inner_statement();
9415 * Parse a while statement.
9417 static statement_t *parse_while(void)
9419 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9423 PUSH_PARENT(statement);
9425 expression_t *const cond = parse_condition();
9426 statement->whiles.condition = cond;
9427 /* §6.8.5:2 The controlling expression of an iteration statement shall
9428 * have scalar type. */
9429 semantic_condition(cond, "condition of 'while'-statement");
9431 statement->whiles.body = parse_loop_body(statement);
9438 * Parse a do statement.
9440 static statement_t *parse_do(void)
9442 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9446 PUSH_PARENT(statement);
9448 add_anchor_token(T_while);
9449 statement->do_while.body = parse_loop_body(statement);
9450 rem_anchor_token(T_while);
9452 expect(T_while, end_error0);
9454 expression_t *const cond = parse_condition();
9455 statement->do_while.condition = cond;
9456 /* §6.8.5:2 The controlling expression of an iteration statement shall
9457 * have scalar type. */
9458 semantic_condition(cond, "condition of 'do-while'-statement");
9459 expect(';', end_error1);
9467 * Parse a for statement.
9469 static statement_t *parse_for(void)
9471 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9475 PUSH_PARENT(statement);
9476 PUSH_SCOPE(&statement->fors.scope);
9478 expect('(', end_error1);
9479 add_anchor_token(')');
9484 } else if (is_declaration_specifier(&token)) {
9485 parse_declaration(record_entity, DECL_FLAGS_NONE);
9487 add_anchor_token(';');
9488 expression_t *const init = parse_expression();
9489 statement->fors.initialisation = init;
9490 mark_vars_read(init, ENT_ANY);
9491 if (!expression_has_effect(init)) {
9492 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9494 rem_anchor_token(';');
9495 expect(';', end_error3);
9501 if (token.kind != ';') {
9502 add_anchor_token(';');
9503 expression_t *const cond = parse_expression();
9504 statement->fors.condition = cond;
9505 /* §6.8.5:2 The controlling expression of an iteration statement
9506 * shall have scalar type. */
9507 semantic_condition(cond, "condition of 'for'-statement");
9508 mark_vars_read(cond, NULL);
9509 rem_anchor_token(';');
9511 expect(';', end_error2);
9513 if (token.kind != ')') {
9514 expression_t *const step = parse_expression();
9515 statement->fors.step = step;
9516 mark_vars_read(step, ENT_ANY);
9517 if (!expression_has_effect(step)) {
9518 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9521 rem_anchor_token(')');
9522 expect(')', end_error1);
9524 statement->fors.body = parse_loop_body(statement);
9532 * Parse a goto statement.
9534 static statement_t *parse_goto(void)
9536 statement_t *statement;
9537 if (GNU_MODE && look_ahead(1)->kind == '*') {
9538 statement = allocate_statement_zero(STATEMENT_COMPUTED_GOTO);
9542 expression_t *expression = parse_expression();
9543 mark_vars_read(expression, NULL);
9545 /* Argh: although documentation says the expression must be of type void*,
9546 * gcc accepts anything that can be casted into void* without error */
9547 type_t *type = expression->base.type;
9549 if (type != type_error_type) {
9550 if (!is_type_pointer(type) && !is_type_integer(type)) {
9551 errorf(&expression->base.source_position,
9552 "cannot convert to a pointer type");
9553 } else if (type != type_void_ptr) {
9554 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9556 expression = create_implicit_cast(expression, type_void_ptr);
9559 statement->computed_goto.expression = expression;
9561 statement = allocate_statement_zero(STATEMENT_GOTO);
9563 if (token.kind == T_IDENTIFIER) {
9564 label_t *const label = get_label();
9566 statement->gotos.label = label;
9568 /* remember the goto's in a list for later checking */
9569 *goto_anchor = &statement->gotos;
9570 goto_anchor = &statement->gotos.next;
9573 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9575 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9577 statement->gotos.label = &allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, sym_anonymous, &builtin_source_position)->label;
9581 expect(';', end_error);
9588 * Parse a continue statement.
9590 static statement_t *parse_continue(void)
9592 if (current_loop == NULL) {
9593 errorf(HERE, "continue statement not within loop");
9596 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9599 expect(';', end_error);
9606 * Parse a break statement.
9608 static statement_t *parse_break(void)
9610 if (current_switch == NULL && current_loop == NULL) {
9611 errorf(HERE, "break statement not within loop or switch");
9614 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9617 expect(';', end_error);
9624 * Parse a __leave statement.
9626 static statement_t *parse_leave_statement(void)
9628 if (current_try == NULL) {
9629 errorf(HERE, "__leave statement not within __try");
9632 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9635 expect(';', end_error);
9642 * Check if a given entity represents a local variable.
9644 static bool is_local_variable(const entity_t *entity)
9646 if (entity->kind != ENTITY_VARIABLE)
9649 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9650 case STORAGE_CLASS_AUTO:
9651 case STORAGE_CLASS_REGISTER: {
9652 const type_t *type = skip_typeref(entity->declaration.type);
9653 if (is_type_function(type)) {
9665 * Check if a given expression represents a local variable.
9667 static bool expression_is_local_variable(const expression_t *expression)
9669 if (expression->base.kind != EXPR_REFERENCE) {
9672 const entity_t *entity = expression->reference.entity;
9673 return is_local_variable(entity);
9677 * Check if a given expression represents a local variable and
9678 * return its declaration then, else return NULL.
9680 entity_t *expression_is_variable(const expression_t *expression)
9682 if (expression->base.kind != EXPR_REFERENCE) {
9685 entity_t *entity = expression->reference.entity;
9686 if (entity->kind != ENTITY_VARIABLE)
9692 static void err_or_warn(source_position_t const *const pos, char const *const msg)
9694 if (c_mode & _CXX || strict_mode) {
9697 warningf(WARN_OTHER, pos, msg);
9702 * Parse a return statement.
9704 static statement_t *parse_return(void)
9706 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9709 expression_t *return_value = NULL;
9710 if (token.kind != ';') {
9711 return_value = parse_expression();
9712 mark_vars_read(return_value, NULL);
9715 const type_t *const func_type = skip_typeref(current_function->base.type);
9716 assert(is_type_function(func_type));
9717 type_t *const return_type = skip_typeref(func_type->function.return_type);
9719 source_position_t const *const pos = &statement->base.source_position;
9720 if (return_value != NULL) {
9721 type_t *return_value_type = skip_typeref(return_value->base.type);
9723 if (is_type_void(return_type)) {
9724 if (!is_type_void(return_value_type)) {
9725 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9726 /* Only warn in C mode, because GCC does the same */
9727 err_or_warn(pos, "'return' with a value, in function returning 'void'");
9728 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9729 /* Only warn in C mode, because GCC does the same */
9730 err_or_warn(pos, "'return' with expression in function returning 'void'");
9733 assign_error_t error = semantic_assign(return_type, return_value);
9734 report_assign_error(error, return_type, return_value, "'return'",
9737 return_value = create_implicit_cast(return_value, return_type);
9738 /* check for returning address of a local var */
9739 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9740 const expression_t *expression = return_value->unary.value;
9741 if (expression_is_local_variable(expression)) {
9742 warningf(WARN_OTHER, pos, "function returns address of local variable");
9745 } else if (!is_type_void(return_type)) {
9746 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9747 err_or_warn(pos, "'return' without value, in function returning non-void");
9749 statement->returns.value = return_value;
9751 expect(';', end_error);
9758 * Parse a declaration statement.
9760 static statement_t *parse_declaration_statement(void)
9762 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9764 entity_t *before = current_scope->last_entity;
9766 parse_external_declaration();
9768 parse_declaration(record_entity, DECL_FLAGS_NONE);
9771 declaration_statement_t *const decl = &statement->declaration;
9772 entity_t *const begin =
9773 before != NULL ? before->base.next : current_scope->entities;
9774 decl->declarations_begin = begin;
9775 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9781 * Parse an expression statement, ie. expr ';'.
9783 static statement_t *parse_expression_statement(void)
9785 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9787 expression_t *const expr = parse_expression();
9788 statement->expression.expression = expr;
9789 mark_vars_read(expr, ENT_ANY);
9791 expect(';', end_error);
9798 * Parse a microsoft __try { } __finally { } or
9799 * __try{ } __except() { }
9801 static statement_t *parse_ms_try_statment(void)
9803 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9806 PUSH_PARENT(statement);
9808 ms_try_statement_t *rem = current_try;
9809 current_try = &statement->ms_try;
9810 statement->ms_try.try_statement = parse_compound_statement(false);
9815 if (next_if(T___except)) {
9816 expression_t *const expr = parse_condition();
9817 type_t * type = skip_typeref(expr->base.type);
9818 if (is_type_integer(type)) {
9819 type = promote_integer(type);
9820 } else if (is_type_valid(type)) {
9821 errorf(&expr->base.source_position,
9822 "__expect expression is not an integer, but '%T'", type);
9823 type = type_error_type;
9825 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9826 } else if (!next_if(T__finally)) {
9827 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9829 statement->ms_try.final_statement = parse_compound_statement(false);
9833 static statement_t *parse_empty_statement(void)
9835 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9836 statement_t *const statement = create_empty_statement();
9841 static statement_t *parse_local_label_declaration(void)
9843 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9847 entity_t *begin = NULL;
9848 entity_t *end = NULL;
9849 entity_t **anchor = &begin;
9851 if (token.kind != T_IDENTIFIER) {
9852 parse_error_expected("while parsing local label declaration",
9853 T_IDENTIFIER, NULL);
9856 symbol_t *symbol = token.identifier.symbol;
9857 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9858 if (entity != NULL && entity->base.parent_scope == current_scope) {
9859 source_position_t const *const ppos = &entity->base.source_position;
9860 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9862 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol, HERE);
9863 entity->base.parent_scope = current_scope;
9866 anchor = &entity->base.next;
9869 environment_push(entity);
9872 } while (next_if(','));
9873 expect(';', end_error);
9875 statement->declaration.declarations_begin = begin;
9876 statement->declaration.declarations_end = end;
9880 static void parse_namespace_definition(void)
9884 entity_t *entity = NULL;
9885 symbol_t *symbol = NULL;
9887 if (token.kind == T_IDENTIFIER) {
9888 symbol = token.identifier.symbol;
9891 entity = get_entity(symbol, NAMESPACE_NORMAL);
9893 && entity->kind != ENTITY_NAMESPACE
9894 && entity->base.parent_scope == current_scope) {
9895 if (is_entity_valid(entity)) {
9896 error_redefined_as_different_kind(&token.base.source_position,
9897 entity, ENTITY_NAMESPACE);
9903 if (entity == NULL) {
9904 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol, HERE);
9905 entity->base.parent_scope = current_scope;
9908 if (token.kind == '=') {
9909 /* TODO: parse namespace alias */
9910 panic("namespace alias definition not supported yet");
9913 environment_push(entity);
9914 append_entity(current_scope, entity);
9916 PUSH_SCOPE(&entity->namespacee.members);
9918 entity_t *old_current_entity = current_entity;
9919 current_entity = entity;
9921 expect('{', end_error);
9923 expect('}', end_error);
9926 assert(current_entity == entity);
9927 current_entity = old_current_entity;
9932 * Parse a statement.
9933 * There's also parse_statement() which additionally checks for
9934 * "statement has no effect" warnings
9936 static statement_t *intern_parse_statement(void)
9938 /* declaration or statement */
9939 statement_t *statement;
9940 switch (token.kind) {
9941 case T_IDENTIFIER: {
9942 token_kind_t la1_type = (token_kind_t)look_ahead(1)->kind;
9943 if (la1_type == ':') {
9944 statement = parse_label_statement();
9945 } else if (is_typedef_symbol(token.identifier.symbol)) {
9946 statement = parse_declaration_statement();
9948 /* it's an identifier, the grammar says this must be an
9949 * expression statement. However it is common that users mistype
9950 * declaration types, so we guess a bit here to improve robustness
9951 * for incorrect programs */
9955 if (get_entity(token.identifier.symbol, NAMESPACE_NORMAL) != NULL) {
9957 statement = parse_expression_statement();
9961 statement = parse_declaration_statement();
9969 case T___extension__: {
9970 /* This can be a prefix to a declaration or an expression statement.
9971 * We simply eat it now and parse the rest with tail recursion. */
9973 statement = intern_parse_statement();
9979 statement = parse_declaration_statement();
9983 statement = parse_local_label_declaration();
9986 case ';': statement = parse_empty_statement(); break;
9987 case '{': statement = parse_compound_statement(false); break;
9988 case T___leave: statement = parse_leave_statement(); break;
9989 case T___try: statement = parse_ms_try_statment(); break;
9990 case T_asm: statement = parse_asm_statement(); break;
9991 case T_break: statement = parse_break(); break;
9992 case T_case: statement = parse_case_statement(); break;
9993 case T_continue: statement = parse_continue(); break;
9994 case T_default: statement = parse_default_statement(); break;
9995 case T_do: statement = parse_do(); break;
9996 case T_for: statement = parse_for(); break;
9997 case T_goto: statement = parse_goto(); break;
9998 case T_if: statement = parse_if(); break;
9999 case T_return: statement = parse_return(); break;
10000 case T_switch: statement = parse_switch(); break;
10001 case T_while: statement = parse_while(); break;
10004 statement = parse_expression_statement();
10008 errorf(HERE, "unexpected token %K while parsing statement", &token);
10009 statement = create_error_statement();
10010 eat_until_anchor();
10018 * parse a statement and emits "statement has no effect" warning if needed
10019 * (This is really a wrapper around intern_parse_statement with check for 1
10020 * single warning. It is needed, because for statement expressions we have
10021 * to avoid the warning on the last statement)
10023 static statement_t *parse_statement(void)
10025 statement_t *statement = intern_parse_statement();
10027 if (statement->kind == STATEMENT_EXPRESSION) {
10028 expression_t *expression = statement->expression.expression;
10029 if (!expression_has_effect(expression)) {
10030 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10038 * Parse a compound statement.
10040 static statement_t *parse_compound_statement(bool inside_expression_statement)
10042 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10044 PUSH_PARENT(statement);
10045 PUSH_SCOPE(&statement->compound.scope);
10048 add_anchor_token('}');
10049 /* tokens, which can start a statement */
10050 /* TODO MS, __builtin_FOO */
10051 add_anchor_token('!');
10052 add_anchor_token('&');
10053 add_anchor_token('(');
10054 add_anchor_token('*');
10055 add_anchor_token('+');
10056 add_anchor_token('-');
10057 add_anchor_token(';');
10058 add_anchor_token('{');
10059 add_anchor_token('~');
10060 add_anchor_token(T_CHARACTER_CONSTANT);
10061 add_anchor_token(T_COLONCOLON);
10062 add_anchor_token(T_FLOATINGPOINT);
10063 add_anchor_token(T_IDENTIFIER);
10064 add_anchor_token(T_INTEGER);
10065 add_anchor_token(T_MINUSMINUS);
10066 add_anchor_token(T_PLUSPLUS);
10067 add_anchor_token(T_STRING_LITERAL);
10068 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10069 add_anchor_token(T_WIDE_STRING_LITERAL);
10070 add_anchor_token(T__Bool);
10071 add_anchor_token(T__Complex);
10072 add_anchor_token(T__Imaginary);
10073 add_anchor_token(T___FUNCTION__);
10074 add_anchor_token(T___PRETTY_FUNCTION__);
10075 add_anchor_token(T___alignof__);
10076 add_anchor_token(T___attribute__);
10077 add_anchor_token(T___builtin_va_start);
10078 add_anchor_token(T___extension__);
10079 add_anchor_token(T___func__);
10080 add_anchor_token(T___imag__);
10081 add_anchor_token(T___label__);
10082 add_anchor_token(T___real__);
10083 add_anchor_token(T___thread);
10084 add_anchor_token(T_asm);
10085 add_anchor_token(T_auto);
10086 add_anchor_token(T_bool);
10087 add_anchor_token(T_break);
10088 add_anchor_token(T_case);
10089 add_anchor_token(T_char);
10090 add_anchor_token(T_class);
10091 add_anchor_token(T_const);
10092 add_anchor_token(T_const_cast);
10093 add_anchor_token(T_continue);
10094 add_anchor_token(T_default);
10095 add_anchor_token(T_delete);
10096 add_anchor_token(T_double);
10097 add_anchor_token(T_do);
10098 add_anchor_token(T_dynamic_cast);
10099 add_anchor_token(T_enum);
10100 add_anchor_token(T_extern);
10101 add_anchor_token(T_false);
10102 add_anchor_token(T_float);
10103 add_anchor_token(T_for);
10104 add_anchor_token(T_goto);
10105 add_anchor_token(T_if);
10106 add_anchor_token(T_inline);
10107 add_anchor_token(T_int);
10108 add_anchor_token(T_long);
10109 add_anchor_token(T_new);
10110 add_anchor_token(T_operator);
10111 add_anchor_token(T_register);
10112 add_anchor_token(T_reinterpret_cast);
10113 add_anchor_token(T_restrict);
10114 add_anchor_token(T_return);
10115 add_anchor_token(T_short);
10116 add_anchor_token(T_signed);
10117 add_anchor_token(T_sizeof);
10118 add_anchor_token(T_static);
10119 add_anchor_token(T_static_cast);
10120 add_anchor_token(T_struct);
10121 add_anchor_token(T_switch);
10122 add_anchor_token(T_template);
10123 add_anchor_token(T_this);
10124 add_anchor_token(T_throw);
10125 add_anchor_token(T_true);
10126 add_anchor_token(T_try);
10127 add_anchor_token(T_typedef);
10128 add_anchor_token(T_typeid);
10129 add_anchor_token(T_typename);
10130 add_anchor_token(T_typeof);
10131 add_anchor_token(T_union);
10132 add_anchor_token(T_unsigned);
10133 add_anchor_token(T_using);
10134 add_anchor_token(T_void);
10135 add_anchor_token(T_volatile);
10136 add_anchor_token(T_wchar_t);
10137 add_anchor_token(T_while);
10139 statement_t **anchor = &statement->compound.statements;
10140 bool only_decls_so_far = true;
10141 while (token.kind != '}' && token.kind != T_EOF) {
10142 statement_t *sub_statement = intern_parse_statement();
10143 if (sub_statement->kind == STATEMENT_ERROR) {
10147 if (sub_statement->kind != STATEMENT_DECLARATION) {
10148 only_decls_so_far = false;
10149 } else if (!only_decls_so_far) {
10150 source_position_t const *const pos = &sub_statement->base.source_position;
10151 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10154 *anchor = sub_statement;
10155 anchor = &sub_statement->base.next;
10157 expect('}', end_error);
10160 /* look over all statements again to produce no effect warnings */
10161 if (is_warn_on(WARN_UNUSED_VALUE)) {
10162 statement_t *sub_statement = statement->compound.statements;
10163 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10164 if (sub_statement->kind != STATEMENT_EXPRESSION)
10166 /* don't emit a warning for the last expression in an expression
10167 * statement as it has always an effect */
10168 if (inside_expression_statement && sub_statement->base.next == NULL)
10171 expression_t *expression = sub_statement->expression.expression;
10172 if (!expression_has_effect(expression)) {
10173 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10178 rem_anchor_token(T_while);
10179 rem_anchor_token(T_wchar_t);
10180 rem_anchor_token(T_volatile);
10181 rem_anchor_token(T_void);
10182 rem_anchor_token(T_using);
10183 rem_anchor_token(T_unsigned);
10184 rem_anchor_token(T_union);
10185 rem_anchor_token(T_typeof);
10186 rem_anchor_token(T_typename);
10187 rem_anchor_token(T_typeid);
10188 rem_anchor_token(T_typedef);
10189 rem_anchor_token(T_try);
10190 rem_anchor_token(T_true);
10191 rem_anchor_token(T_throw);
10192 rem_anchor_token(T_this);
10193 rem_anchor_token(T_template);
10194 rem_anchor_token(T_switch);
10195 rem_anchor_token(T_struct);
10196 rem_anchor_token(T_static_cast);
10197 rem_anchor_token(T_static);
10198 rem_anchor_token(T_sizeof);
10199 rem_anchor_token(T_signed);
10200 rem_anchor_token(T_short);
10201 rem_anchor_token(T_return);
10202 rem_anchor_token(T_restrict);
10203 rem_anchor_token(T_reinterpret_cast);
10204 rem_anchor_token(T_register);
10205 rem_anchor_token(T_operator);
10206 rem_anchor_token(T_new);
10207 rem_anchor_token(T_long);
10208 rem_anchor_token(T_int);
10209 rem_anchor_token(T_inline);
10210 rem_anchor_token(T_if);
10211 rem_anchor_token(T_goto);
10212 rem_anchor_token(T_for);
10213 rem_anchor_token(T_float);
10214 rem_anchor_token(T_false);
10215 rem_anchor_token(T_extern);
10216 rem_anchor_token(T_enum);
10217 rem_anchor_token(T_dynamic_cast);
10218 rem_anchor_token(T_do);
10219 rem_anchor_token(T_double);
10220 rem_anchor_token(T_delete);
10221 rem_anchor_token(T_default);
10222 rem_anchor_token(T_continue);
10223 rem_anchor_token(T_const_cast);
10224 rem_anchor_token(T_const);
10225 rem_anchor_token(T_class);
10226 rem_anchor_token(T_char);
10227 rem_anchor_token(T_case);
10228 rem_anchor_token(T_break);
10229 rem_anchor_token(T_bool);
10230 rem_anchor_token(T_auto);
10231 rem_anchor_token(T_asm);
10232 rem_anchor_token(T___thread);
10233 rem_anchor_token(T___real__);
10234 rem_anchor_token(T___label__);
10235 rem_anchor_token(T___imag__);
10236 rem_anchor_token(T___func__);
10237 rem_anchor_token(T___extension__);
10238 rem_anchor_token(T___builtin_va_start);
10239 rem_anchor_token(T___attribute__);
10240 rem_anchor_token(T___alignof__);
10241 rem_anchor_token(T___PRETTY_FUNCTION__);
10242 rem_anchor_token(T___FUNCTION__);
10243 rem_anchor_token(T__Imaginary);
10244 rem_anchor_token(T__Complex);
10245 rem_anchor_token(T__Bool);
10246 rem_anchor_token(T_WIDE_STRING_LITERAL);
10247 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10248 rem_anchor_token(T_STRING_LITERAL);
10249 rem_anchor_token(T_PLUSPLUS);
10250 rem_anchor_token(T_MINUSMINUS);
10251 rem_anchor_token(T_INTEGER);
10252 rem_anchor_token(T_IDENTIFIER);
10253 rem_anchor_token(T_FLOATINGPOINT);
10254 rem_anchor_token(T_COLONCOLON);
10255 rem_anchor_token(T_CHARACTER_CONSTANT);
10256 rem_anchor_token('~');
10257 rem_anchor_token('{');
10258 rem_anchor_token(';');
10259 rem_anchor_token('-');
10260 rem_anchor_token('+');
10261 rem_anchor_token('*');
10262 rem_anchor_token('(');
10263 rem_anchor_token('&');
10264 rem_anchor_token('!');
10265 rem_anchor_token('}');
10273 * Check for unused global static functions and variables
10275 static void check_unused_globals(void)
10277 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10280 for (const entity_t *entity = file_scope->entities; entity != NULL;
10281 entity = entity->base.next) {
10282 if (!is_declaration(entity))
10285 const declaration_t *declaration = &entity->declaration;
10286 if (declaration->used ||
10287 declaration->modifiers & DM_UNUSED ||
10288 declaration->modifiers & DM_USED ||
10289 declaration->storage_class != STORAGE_CLASS_STATIC)
10294 if (entity->kind == ENTITY_FUNCTION) {
10295 /* inhibit warning for static inline functions */
10296 if (entity->function.is_inline)
10299 why = WARN_UNUSED_FUNCTION;
10300 s = entity->function.statement != NULL ? "defined" : "declared";
10302 why = WARN_UNUSED_VARIABLE;
10306 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10310 static void parse_global_asm(void)
10312 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10315 expect('(', end_error);
10317 statement->asms.asm_text = parse_string_literals();
10318 statement->base.next = unit->global_asm;
10319 unit->global_asm = statement;
10321 expect(')', end_error);
10322 expect(';', end_error);
10327 static void parse_linkage_specification(void)
10331 source_position_t const pos = *HERE;
10332 char const *const linkage = parse_string_literals().begin;
10334 linkage_kind_t old_linkage = current_linkage;
10335 linkage_kind_t new_linkage;
10336 if (streq(linkage, "C")) {
10337 new_linkage = LINKAGE_C;
10338 } else if (streq(linkage, "C++")) {
10339 new_linkage = LINKAGE_CXX;
10341 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10342 new_linkage = LINKAGE_C;
10344 current_linkage = new_linkage;
10346 if (next_if('{')) {
10348 expect('}', end_error);
10354 assert(current_linkage == new_linkage);
10355 current_linkage = old_linkage;
10358 static void parse_external(void)
10360 switch (token.kind) {
10362 if (look_ahead(1)->kind == T_STRING_LITERAL) {
10363 parse_linkage_specification();
10365 DECLARATION_START_NO_EXTERN
10367 case T___extension__:
10368 /* tokens below are for implicit int */
10369 case '&': /* & x; -> int& x; (and error later, because C++ has no
10371 case '*': /* * x; -> int* x; */
10372 case '(': /* (x); -> int (x); */
10374 parse_external_declaration();
10380 parse_global_asm();
10384 parse_namespace_definition();
10388 if (!strict_mode) {
10389 warningf(WARN_STRAY_SEMICOLON, HERE, "stray ';' outside of function");
10396 errorf(HERE, "stray %K outside of function", &token);
10397 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10398 eat_until_matching_token(token.kind);
10404 static void parse_externals(void)
10406 add_anchor_token('}');
10407 add_anchor_token(T_EOF);
10410 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10411 unsigned short token_anchor_copy[T_LAST_TOKEN];
10412 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10415 while (token.kind != T_EOF && token.kind != '}') {
10417 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10418 unsigned short count = token_anchor_set[i] - token_anchor_copy[i];
10420 /* the anchor set and its copy differs */
10421 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10424 if (in_gcc_extension) {
10425 /* an gcc extension scope was not closed */
10426 internal_errorf(HERE, "Leaked __extension__");
10433 rem_anchor_token(T_EOF);
10434 rem_anchor_token('}');
10438 * Parse a translation unit.
10440 static void parse_translation_unit(void)
10442 add_anchor_token(T_EOF);
10447 if (token.kind == T_EOF)
10450 errorf(HERE, "stray %K outside of function", &token);
10451 if (token.kind == '(' || token.kind == '{' || token.kind == '[')
10452 eat_until_matching_token(token.kind);
10457 void set_default_visibility(elf_visibility_tag_t visibility)
10459 default_visibility = visibility;
10465 * @return the translation unit or NULL if errors occurred.
10467 void start_parsing(void)
10469 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10470 label_stack = NEW_ARR_F(stack_entry_t, 0);
10471 diagnostic_count = 0;
10475 print_to_file(stderr);
10477 assert(unit == NULL);
10478 unit = allocate_ast_zero(sizeof(unit[0]));
10480 assert(file_scope == NULL);
10481 file_scope = &unit->scope;
10483 assert(current_scope == NULL);
10484 scope_push(&unit->scope);
10486 create_gnu_builtins();
10488 create_microsoft_intrinsics();
10491 translation_unit_t *finish_parsing(void)
10493 assert(current_scope == &unit->scope);
10496 assert(file_scope == &unit->scope);
10497 check_unused_globals();
10500 DEL_ARR_F(environment_stack);
10501 DEL_ARR_F(label_stack);
10503 translation_unit_t *result = unit;
10508 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10509 * are given length one. */
10510 static void complete_incomplete_arrays(void)
10512 size_t n = ARR_LEN(incomplete_arrays);
10513 for (size_t i = 0; i != n; ++i) {
10514 declaration_t *const decl = incomplete_arrays[i];
10515 type_t *const type = skip_typeref(decl->type);
10517 if (!is_type_incomplete(type))
10520 source_position_t const *const pos = &decl->base.source_position;
10521 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10523 type_t *const new_type = duplicate_type(type);
10524 new_type->array.size_constant = true;
10525 new_type->array.has_implicit_size = true;
10526 new_type->array.size = 1;
10528 type_t *const result = identify_new_type(new_type);
10530 decl->type = result;
10534 void prepare_main_collect2(entity_t *entity)
10536 PUSH_SCOPE(&entity->function.statement->compound.scope);
10538 // create call to __main
10539 symbol_t *symbol = symbol_table_insert("__main");
10540 entity_t *subsubmain_ent
10541 = create_implicit_function(symbol, &builtin_source_position);
10543 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10544 type_t *ftype = subsubmain_ent->declaration.type;
10545 ref->base.source_position = builtin_source_position;
10546 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10547 ref->reference.entity = subsubmain_ent;
10549 expression_t *call = allocate_expression_zero(EXPR_CALL);
10550 call->base.source_position = builtin_source_position;
10551 call->base.type = type_void;
10552 call->call.function = ref;
10554 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10555 expr_statement->base.source_position = builtin_source_position;
10556 expr_statement->expression.expression = call;
10558 statement_t *statement = entity->function.statement;
10559 assert(statement->kind == STATEMENT_COMPOUND);
10560 compound_statement_t *compounds = &statement->compound;
10562 expr_statement->base.next = compounds->statements;
10563 compounds->statements = expr_statement;
10570 lookahead_bufpos = 0;
10571 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10574 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10575 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10576 parse_translation_unit();
10577 complete_incomplete_arrays();
10578 DEL_ARR_F(incomplete_arrays);
10579 incomplete_arrays = NULL;
10583 * Initialize the parser.
10585 void init_parser(void)
10587 sym_anonymous = symbol_table_insert("<anonymous>");
10589 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10591 init_expression_parsers();
10592 obstack_init(&temp_obst);
10596 * Terminate the parser.
10598 void exit_parser(void)
10600 obstack_free(&temp_obst, NULL);