2 * This file is part of cparser.
3 * Copyright (C) 2007-2009 Matthias Braun <matze@braunis.de>
5 * This program is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU General Public License
7 * as published by the Free Software Foundation; either version 2
8 * of the License, or (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
27 #include "diagnostic.h"
28 #include "format_check.h"
34 #include "type_hash.h"
37 #include "attribute_t.h"
38 #include "lang_features.h"
39 #include "walk_statements.h"
42 #include "adt/bitfiddle.h"
43 #include "adt/error.h"
44 #include "adt/array.h"
46 //#define PRINT_TOKENS
47 #define MAX_LOOKAHEAD 1
52 entity_namespace_t namespc;
55 typedef struct declaration_specifiers_t declaration_specifiers_t;
56 struct declaration_specifiers_t {
57 source_position_t source_position;
58 storage_class_t storage_class;
59 unsigned char alignment; /**< Alignment, 0 if not set. */
61 bool thread_local : 1; /**< GCC __thread */
62 attribute_t *attributes; /**< list of attributes */
67 * An environment for parsing initializers (and compound literals).
69 typedef struct parse_initializer_env_t {
70 type_t *type; /**< the type of the initializer. In case of an
71 array type with unspecified size this gets
72 adjusted to the actual size. */
73 entity_t *entity; /**< the variable that is initialized if any */
74 bool must_be_constant;
75 } parse_initializer_env_t;
77 typedef entity_t* (*parsed_declaration_func) (entity_t *declaration, bool is_definition);
79 /** The current token. */
81 /** The lookahead ring-buffer. */
82 static token_t lookahead_buffer[MAX_LOOKAHEAD];
83 /** Position of the next token in the lookahead buffer. */
84 static size_t lookahead_bufpos;
85 static stack_entry_t *environment_stack = NULL;
86 static stack_entry_t *label_stack = NULL;
87 static scope_t *file_scope = NULL;
88 static scope_t *current_scope = NULL;
89 /** Point to the current function declaration if inside a function. */
90 static function_t *current_function = NULL;
91 static entity_t *current_entity = NULL;
92 static entity_t *current_init_decl = NULL;
93 static switch_statement_t *current_switch = NULL;
94 static statement_t *current_loop = NULL;
95 static statement_t *current_parent = NULL;
96 static ms_try_statement_t *current_try = NULL;
97 static linkage_kind_t current_linkage = LINKAGE_INVALID;
98 static goto_statement_t *goto_first = NULL;
99 static goto_statement_t **goto_anchor = NULL;
100 static label_statement_t *label_first = NULL;
101 static label_statement_t **label_anchor = NULL;
102 /** current translation unit. */
103 static translation_unit_t *unit = NULL;
104 /** true if we are in a type property context (evaluation only for type) */
105 static bool in_type_prop = false;
106 /** true if we are in an __extension__ context. */
107 static bool in_gcc_extension = false;
108 static struct obstack temp_obst;
109 static entity_t *anonymous_entity;
110 static declaration_t **incomplete_arrays;
111 static elf_visibility_tag_t default_visibility = ELF_VISIBILITY_DEFAULT;
114 #define PUSH_PARENT(stmt) \
115 statement_t *const new_parent = (stmt); \
116 statement_t *const old_parent = current_parent; \
117 ((void)(current_parent = new_parent))
118 #define POP_PARENT() (assert(current_parent == new_parent), (void)(current_parent = old_parent))
120 #define PUSH_SCOPE(scope) \
121 size_t const top = environment_top(); \
122 scope_t *const new_scope = (scope); \
123 scope_t *const old_scope = scope_push(new_scope)
124 #define POP_SCOPE() (assert(current_scope == new_scope), scope_pop(old_scope), environment_pop_to(top))
126 #define PUSH_EXTENSION() \
127 bool const old_gcc_extension = in_gcc_extension; \
128 while (next_if(T___extension__)) { \
129 in_gcc_extension = true; \
132 #define POP_EXTENSION() \
133 ((void)(in_gcc_extension = old_gcc_extension))
135 /** special symbol used for anonymous entities. */
136 static symbol_t *sym_anonymous = NULL;
138 /** The token anchor set */
139 static unsigned char token_anchor_set[T_LAST_TOKEN];
141 /** The current source position. */
142 #define HERE (&token.source_position)
144 /** true if we are in GCC mode. */
145 #define GNU_MODE ((c_mode & _GNUC) || in_gcc_extension)
147 static statement_t *parse_compound_statement(bool inside_expression_statement);
148 static statement_t *parse_statement(void);
150 static expression_t *parse_subexpression(precedence_t);
151 static expression_t *parse_expression(void);
152 static type_t *parse_typename(void);
153 static void parse_externals(void);
154 static void parse_external(void);
156 static void parse_compound_type_entries(compound_t *compound_declaration);
158 static void check_call_argument(type_t *expected_type,
159 call_argument_t *argument, unsigned pos);
161 typedef enum declarator_flags_t {
163 DECL_MAY_BE_ABSTRACT = 1U << 0,
164 DECL_CREATE_COMPOUND_MEMBER = 1U << 1,
165 DECL_IS_PARAMETER = 1U << 2
166 } declarator_flags_t;
168 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
169 declarator_flags_t flags);
171 static void semantic_comparison(binary_expression_t *expression);
173 #define STORAGE_CLASSES \
174 STORAGE_CLASSES_NO_EXTERN \
177 #define STORAGE_CLASSES_NO_EXTERN \
184 #define TYPE_QUALIFIERS \
189 case T__forceinline: \
190 case T___attribute__:
192 #define COMPLEX_SPECIFIERS \
194 #define IMAGINARY_SPECIFIERS \
197 #define TYPE_SPECIFIERS \
199 case T___builtin_va_list: \
224 #define DECLARATION_START \
229 #define DECLARATION_START_NO_EXTERN \
230 STORAGE_CLASSES_NO_EXTERN \
234 #define EXPRESSION_START \
243 case T_CHARACTER_CONSTANT: \
244 case T_FLOATINGPOINT: \
245 case T_FLOATINGPOINT_HEXADECIMAL: \
247 case T_INTEGER_HEXADECIMAL: \
248 case T_INTEGER_OCTAL: \
251 case T_STRING_LITERAL: \
252 case T_WIDE_CHARACTER_CONSTANT: \
253 case T_WIDE_STRING_LITERAL: \
254 case T___FUNCDNAME__: \
255 case T___FUNCSIG__: \
256 case T___FUNCTION__: \
257 case T___PRETTY_FUNCTION__: \
258 case T___alignof__: \
259 case T___builtin_classify_type: \
260 case T___builtin_constant_p: \
261 case T___builtin_isgreater: \
262 case T___builtin_isgreaterequal: \
263 case T___builtin_isless: \
264 case T___builtin_islessequal: \
265 case T___builtin_islessgreater: \
266 case T___builtin_isunordered: \
267 case T___builtin_offsetof: \
268 case T___builtin_va_arg: \
269 case T___builtin_va_copy: \
270 case T___builtin_va_start: \
281 * Returns the size of a statement node.
283 * @param kind the statement kind
285 static size_t get_statement_struct_size(statement_kind_t kind)
287 static const size_t sizes[] = {
288 [STATEMENT_INVALID] = sizeof(invalid_statement_t),
289 [STATEMENT_EMPTY] = sizeof(empty_statement_t),
290 [STATEMENT_COMPOUND] = sizeof(compound_statement_t),
291 [STATEMENT_RETURN] = sizeof(return_statement_t),
292 [STATEMENT_DECLARATION] = sizeof(declaration_statement_t),
293 [STATEMENT_IF] = sizeof(if_statement_t),
294 [STATEMENT_SWITCH] = sizeof(switch_statement_t),
295 [STATEMENT_EXPRESSION] = sizeof(expression_statement_t),
296 [STATEMENT_CONTINUE] = sizeof(statement_base_t),
297 [STATEMENT_BREAK] = sizeof(statement_base_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_INVALID] = sizeof(expression_base_t),
322 [EXPR_REFERENCE] = sizeof(reference_expression_t),
323 [EXPR_REFERENCE_ENUM_VALUE] = 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.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.source_position;
399 * Creates a new invalid expression at the source position
400 * of the current token.
402 static expression_t *create_invalid_expression(void)
404 return allocate_expression_zero(EXPR_INVALID);
408 * Creates a new invalid statement.
410 static statement_t *create_invalid_statement(void)
412 return allocate_statement_zero(STATEMENT_INVALID);
416 * Allocate a new empty statement.
418 static statement_t *create_empty_statement(void)
420 return allocate_statement_zero(STATEMENT_EMPTY);
424 * Returns the size of an initializer node.
426 * @param kind the initializer kind
428 static size_t get_initializer_size(initializer_kind_t kind)
430 static const size_t sizes[] = {
431 [INITIALIZER_VALUE] = sizeof(initializer_value_t),
432 [INITIALIZER_STRING] = sizeof(initializer_string_t),
433 [INITIALIZER_WIDE_STRING] = sizeof(initializer_wide_string_t),
434 [INITIALIZER_LIST] = sizeof(initializer_list_t),
435 [INITIALIZER_DESIGNATOR] = sizeof(initializer_designator_t)
437 assert((size_t)kind < lengthof(sizes));
438 assert(sizes[kind] != 0);
443 * Allocate an initializer node of given kind and initialize all
446 static initializer_t *allocate_initializer_zero(initializer_kind_t kind)
448 initializer_t *result = allocate_ast_zero(get_initializer_size(kind));
455 * Returns the index of the top element of the environment stack.
457 static size_t environment_top(void)
459 return ARR_LEN(environment_stack);
463 * Returns the index of the top element of the global label stack.
465 static size_t label_top(void)
467 return ARR_LEN(label_stack);
471 * Return the next token.
473 static inline void next_token(void)
475 token = lookahead_buffer[lookahead_bufpos];
476 lookahead_buffer[lookahead_bufpos] = lexer_token;
479 lookahead_bufpos = (lookahead_bufpos + 1) % MAX_LOOKAHEAD;
482 print_token(stderr, &token);
483 fprintf(stderr, "\n");
487 static inline bool next_if(int const type)
489 if (token.type == type) {
498 * Return the next token with a given lookahead.
500 static inline const token_t *look_ahead(size_t num)
502 assert(0 < num && num <= MAX_LOOKAHEAD);
503 size_t pos = (lookahead_bufpos + num - 1) % MAX_LOOKAHEAD;
504 return &lookahead_buffer[pos];
508 * Adds a token type to the token type anchor set (a multi-set).
510 static void add_anchor_token(int token_type)
512 assert(0 <= token_type && token_type < T_LAST_TOKEN);
513 ++token_anchor_set[token_type];
517 * Set the number of tokens types of the given type
518 * to zero and return the old count.
520 static int save_and_reset_anchor_state(int token_type)
522 assert(0 <= token_type && token_type < T_LAST_TOKEN);
523 int count = token_anchor_set[token_type];
524 token_anchor_set[token_type] = 0;
529 * Restore the number of token types to the given count.
531 static void restore_anchor_state(int token_type, int count)
533 assert(0 <= token_type && token_type < T_LAST_TOKEN);
534 token_anchor_set[token_type] = count;
538 * Remove a token type from the token type anchor set (a multi-set).
540 static void rem_anchor_token(int token_type)
542 assert(0 <= token_type && token_type < T_LAST_TOKEN);
543 assert(token_anchor_set[token_type] != 0);
544 --token_anchor_set[token_type];
548 * Return true if the token type of the current token is
551 static bool at_anchor(void)
555 return token_anchor_set[token.type];
559 * Eat tokens until a matching token type is found.
561 static void eat_until_matching_token(int type)
565 case '(': end_token = ')'; break;
566 case '{': end_token = '}'; break;
567 case '[': end_token = ']'; break;
568 default: end_token = type; break;
571 unsigned parenthesis_count = 0;
572 unsigned brace_count = 0;
573 unsigned bracket_count = 0;
574 while (token.type != end_token ||
575 parenthesis_count != 0 ||
577 bracket_count != 0) {
578 switch (token.type) {
580 case '(': ++parenthesis_count; break;
581 case '{': ++brace_count; break;
582 case '[': ++bracket_count; break;
585 if (parenthesis_count > 0)
595 if (bracket_count > 0)
598 if (token.type == end_token &&
599 parenthesis_count == 0 &&
613 * Eat input tokens until an anchor is found.
615 static void eat_until_anchor(void)
617 while (token_anchor_set[token.type] == 0) {
618 if (token.type == '(' || token.type == '{' || token.type == '[')
619 eat_until_matching_token(token.type);
625 * Eat a whole block from input tokens.
627 static void eat_block(void)
629 eat_until_matching_token('{');
633 #define eat(token_type) (assert(token.type == (token_type)), next_token())
636 * Report a parse error because an expected token was not found.
639 #if defined __GNUC__ && __GNUC__ >= 4
640 __attribute__((sentinel))
642 void parse_error_expected(const char *message, ...)
644 if (message != NULL) {
645 errorf(HERE, "%s", message);
648 va_start(ap, message);
649 errorf(HERE, "got %K, expected %#k", &token, &ap, ", ");
654 * Report an incompatible type.
656 static void type_error_incompatible(const char *msg,
657 const source_position_t *source_position, type_t *type1, type_t *type2)
659 errorf(source_position, "%s, incompatible types: '%T' - '%T'",
664 * Expect the current token is the expected token.
665 * If not, generate an error, eat the current statement,
666 * and goto the error_label label.
668 #define expect(expected, error_label) \
670 if (UNLIKELY(token.type != (expected))) { \
671 parse_error_expected(NULL, (expected), NULL); \
672 add_anchor_token(expected); \
673 eat_until_anchor(); \
674 rem_anchor_token(expected); \
675 if (token.type != (expected)) \
682 * Push a given scope on the scope stack and make it the
685 static scope_t *scope_push(scope_t *new_scope)
687 if (current_scope != NULL) {
688 new_scope->depth = current_scope->depth + 1;
691 scope_t *old_scope = current_scope;
692 current_scope = new_scope;
697 * Pop the current scope from the scope stack.
699 static void scope_pop(scope_t *old_scope)
701 current_scope = old_scope;
705 * Search an entity by its symbol in a given namespace.
707 static entity_t *get_entity(const symbol_t *const symbol,
708 namespace_tag_t namespc)
710 assert(namespc != NAMESPACE_INVALID);
711 entity_t *entity = symbol->entity;
712 for (; entity != NULL; entity = entity->base.symbol_next) {
713 if ((namespace_tag_t)entity->base.namespc == namespc)
720 /* §6.2.3:1 24) There is only one name space for tags even though three are
722 static entity_t *get_tag(symbol_t const *const symbol,
723 entity_kind_tag_t const kind)
725 entity_t *entity = get_entity(symbol, NAMESPACE_TAG);
726 if (entity != NULL && (entity_kind_tag_t)entity->kind != kind) {
728 "'%Y' defined as wrong kind of tag (previous definition %P)",
729 symbol, &entity->base.source_position);
736 * pushs an entity on the environment stack and links the corresponding symbol
739 static void stack_push(stack_entry_t **stack_ptr, entity_t *entity)
741 symbol_t *symbol = entity->base.symbol;
742 entity_namespace_t namespc = entity->base.namespc;
743 assert(namespc != NAMESPACE_INVALID);
745 /* replace/add entity into entity list of the symbol */
748 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
753 /* replace an entry? */
754 if (iter->base.namespc == namespc) {
755 entity->base.symbol_next = iter->base.symbol_next;
761 /* remember old declaration */
763 entry.symbol = symbol;
764 entry.old_entity = iter;
765 entry.namespc = namespc;
766 ARR_APP1(stack_entry_t, *stack_ptr, entry);
770 * Push an entity on the environment stack.
772 static void environment_push(entity_t *entity)
774 assert(entity->base.source_position.input_name != NULL);
775 assert(entity->base.parent_scope != NULL);
776 stack_push(&environment_stack, entity);
780 * Push a declaration on the global label stack.
782 * @param declaration the declaration
784 static void label_push(entity_t *label)
786 /* we abuse the parameters scope as parent for the labels */
787 label->base.parent_scope = ¤t_function->parameters;
788 stack_push(&label_stack, label);
792 * pops symbols from the environment stack until @p new_top is the top element
794 static void stack_pop_to(stack_entry_t **stack_ptr, size_t new_top)
796 stack_entry_t *stack = *stack_ptr;
797 size_t top = ARR_LEN(stack);
800 assert(new_top <= top);
804 for (i = top; i > new_top; --i) {
805 stack_entry_t *entry = &stack[i - 1];
807 entity_t *old_entity = entry->old_entity;
808 symbol_t *symbol = entry->symbol;
809 entity_namespace_t namespc = entry->namespc;
811 /* replace with old_entity/remove */
814 for (anchor = &symbol->entity; ; anchor = &iter->base.symbol_next) {
816 assert(iter != NULL);
817 /* replace an entry? */
818 if (iter->base.namespc == namespc)
822 /* restore definition from outer scopes (if there was one) */
823 if (old_entity != NULL) {
824 old_entity->base.symbol_next = iter->base.symbol_next;
825 *anchor = old_entity;
827 /* remove entry from list */
828 *anchor = iter->base.symbol_next;
832 ARR_SHRINKLEN(*stack_ptr, new_top);
836 * Pop all entries from the environment stack until the new_top
839 * @param new_top the new stack top
841 static void environment_pop_to(size_t new_top)
843 stack_pop_to(&environment_stack, new_top);
847 * Pop all entries from the global label stack until the new_top
850 * @param new_top the new stack top
852 static void label_pop_to(size_t new_top)
854 stack_pop_to(&label_stack, new_top);
857 static int get_akind_rank(atomic_type_kind_t akind)
863 * Return the type rank for an atomic type.
865 static int get_rank(const type_t *type)
867 assert(!is_typeref(type));
868 if (type->kind == TYPE_ENUM)
869 return get_akind_rank(type->enumt.akind);
871 assert(type->kind == TYPE_ATOMIC);
872 return get_akind_rank(type->atomic.akind);
876 * §6.3.1.1:2 Do integer promotion for a given type.
878 * @param type the type to promote
879 * @return the promoted type
881 static type_t *promote_integer(type_t *type)
883 if (type->kind == TYPE_BITFIELD)
884 type = type->bitfield.base_type;
886 if (get_rank(type) < get_akind_rank(ATOMIC_TYPE_INT))
893 * Create a cast expression.
895 * @param expression the expression to cast
896 * @param dest_type the destination type
898 static expression_t *create_cast_expression(expression_t *expression,
901 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST_IMPLICIT);
903 cast->unary.value = expression;
904 cast->base.type = dest_type;
910 * Check if a given expression represents a null pointer constant.
912 * @param expression the expression to check
914 static bool is_null_pointer_constant(const expression_t *expression)
916 /* skip void* cast */
917 if (expression->kind == EXPR_UNARY_CAST ||
918 expression->kind == EXPR_UNARY_CAST_IMPLICIT) {
919 type_t *const type = skip_typeref(expression->base.type);
920 if (types_compatible(type, type_void_ptr))
921 expression = expression->unary.value;
924 type_t *const type = skip_typeref(expression->base.type);
925 if (!is_type_integer(type))
927 switch (is_constant_expression(expression)) {
928 case EXPR_CLASS_ERROR: return true;
929 case EXPR_CLASS_CONSTANT: return !fold_constant_to_bool(expression);
930 default: return false;
935 * Create an implicit cast expression.
937 * @param expression the expression to cast
938 * @param dest_type the destination type
940 static expression_t *create_implicit_cast(expression_t *expression,
943 type_t *const source_type = expression->base.type;
945 if (source_type == dest_type)
948 return create_cast_expression(expression, dest_type);
951 typedef enum assign_error_t {
953 ASSIGN_ERROR_INCOMPATIBLE,
954 ASSIGN_ERROR_POINTER_QUALIFIER_MISSING,
955 ASSIGN_WARNING_POINTER_INCOMPATIBLE,
956 ASSIGN_WARNING_POINTER_FROM_INT,
957 ASSIGN_WARNING_INT_FROM_POINTER
960 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)
962 type_t *const orig_type_right = right->base.type;
963 type_t *const type_left = skip_typeref(orig_type_left);
964 type_t *const type_right = skip_typeref(orig_type_right);
969 case ASSIGN_ERROR_INCOMPATIBLE:
970 errorf(pos, "destination type '%T' in %s is incompatible with type '%T'", orig_type_left, context, orig_type_right);
973 case ASSIGN_ERROR_POINTER_QUALIFIER_MISSING: {
974 type_t *points_to_left = skip_typeref(type_left->pointer.points_to);
975 type_t *points_to_right = skip_typeref(type_right->pointer.points_to);
977 /* the left type has all qualifiers from the right type */
978 unsigned missing_qualifiers = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
979 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);
983 case ASSIGN_WARNING_POINTER_INCOMPATIBLE:
984 warningf(WARN_OTHER, pos, "destination type '%T' in %s is incompatible with '%E' of type '%T'", orig_type_left, context, right, orig_type_right);
987 case ASSIGN_WARNING_POINTER_FROM_INT:
988 warningf(WARN_OTHER, pos, "%s makes pointer '%T' from integer '%T' without a cast", context, orig_type_left, orig_type_right);
991 case ASSIGN_WARNING_INT_FROM_POINTER:
992 warningf(WARN_OTHER, pos, "%s makes integer '%T' from pointer '%T' without a cast", context, orig_type_left, orig_type_right);
996 panic("invalid error value");
1000 /** Implements the rules from §6.5.16.1 */
1001 static assign_error_t semantic_assign(type_t *orig_type_left,
1002 const expression_t *const right)
1004 type_t *const orig_type_right = right->base.type;
1005 type_t *const type_left = skip_typeref(orig_type_left);
1006 type_t *const type_right = skip_typeref(orig_type_right);
1008 if (is_type_pointer(type_left)) {
1009 if (is_null_pointer_constant(right)) {
1010 return ASSIGN_SUCCESS;
1011 } else if (is_type_pointer(type_right)) {
1012 type_t *points_to_left
1013 = skip_typeref(type_left->pointer.points_to);
1014 type_t *points_to_right
1015 = skip_typeref(type_right->pointer.points_to);
1016 assign_error_t res = ASSIGN_SUCCESS;
1018 /* the left type has all qualifiers from the right type */
1019 unsigned missing_qualifiers
1020 = points_to_right->base.qualifiers & ~points_to_left->base.qualifiers;
1021 if (missing_qualifiers != 0) {
1022 res = ASSIGN_ERROR_POINTER_QUALIFIER_MISSING;
1025 points_to_left = get_unqualified_type(points_to_left);
1026 points_to_right = get_unqualified_type(points_to_right);
1028 if (is_type_atomic(points_to_left, ATOMIC_TYPE_VOID))
1031 if (is_type_atomic(points_to_right, ATOMIC_TYPE_VOID)) {
1032 /* ISO/IEC 14882:1998(E) §C.1.2:6 */
1033 return c_mode & _CXX ? ASSIGN_ERROR_INCOMPATIBLE : res;
1036 if (!types_compatible(points_to_left, points_to_right)) {
1037 return ASSIGN_WARNING_POINTER_INCOMPATIBLE;
1041 } else if (is_type_integer(type_right)) {
1042 return ASSIGN_WARNING_POINTER_FROM_INT;
1044 } else if ((is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) ||
1045 (is_type_atomic(type_left, ATOMIC_TYPE_BOOL)
1046 && is_type_pointer(type_right))) {
1047 return ASSIGN_SUCCESS;
1048 } else if (is_type_compound(type_left) && is_type_compound(type_right)) {
1049 type_t *const unqual_type_left = get_unqualified_type(type_left);
1050 type_t *const unqual_type_right = get_unqualified_type(type_right);
1051 if (types_compatible(unqual_type_left, unqual_type_right)) {
1052 return ASSIGN_SUCCESS;
1054 } else if (is_type_integer(type_left) && is_type_pointer(type_right)) {
1055 return ASSIGN_WARNING_INT_FROM_POINTER;
1058 if (!is_type_valid(type_left) || !is_type_valid(type_right))
1059 return ASSIGN_SUCCESS;
1061 return ASSIGN_ERROR_INCOMPATIBLE;
1064 static expression_t *parse_constant_expression(void)
1066 expression_t *result = parse_subexpression(PREC_CONDITIONAL);
1068 if (is_constant_expression(result) == EXPR_CLASS_VARIABLE) {
1069 errorf(&result->base.source_position,
1070 "expression '%E' is not constant", result);
1076 static expression_t *parse_assignment_expression(void)
1078 return parse_subexpression(PREC_ASSIGNMENT);
1081 static void warn_string_concat(const source_position_t *pos)
1083 warningf(WARN_TRADITIONAL, pos, "traditional C rejects string constant concatenation");
1086 static string_t parse_string_literals(void)
1088 assert(token.type == T_STRING_LITERAL);
1089 string_t result = token.literal;
1093 while (token.type == T_STRING_LITERAL) {
1094 warn_string_concat(&token.source_position);
1095 result = concat_strings(&result, &token.literal);
1103 * compare two string, ignoring double underscores on the second.
1105 static int strcmp_underscore(const char *s1, const char *s2)
1107 if (s2[0] == '_' && s2[1] == '_') {
1108 size_t len2 = strlen(s2);
1109 size_t len1 = strlen(s1);
1110 if (len1 == len2-4 && s2[len2-2] == '_' && s2[len2-1] == '_') {
1111 return strncmp(s1, s2+2, len2-4);
1115 return strcmp(s1, s2);
1118 static attribute_t *allocate_attribute_zero(attribute_kind_t kind)
1120 attribute_t *attribute = allocate_ast_zero(sizeof(*attribute));
1121 attribute->kind = kind;
1122 attribute->source_position = *HERE;
1127 * Parse (gcc) attribute argument. From gcc comments in gcc source:
1130 * __attribute__ ( ( attribute-list ) )
1134 * attribute_list , attrib
1139 * any-word ( identifier )
1140 * any-word ( identifier , nonempty-expr-list )
1141 * any-word ( expr-list )
1143 * where the "identifier" must not be declared as a type, and
1144 * "any-word" may be any identifier (including one declared as a
1145 * type), a reserved word storage class specifier, type specifier or
1146 * type qualifier. ??? This still leaves out most reserved keywords
1147 * (following the old parser), shouldn't we include them, and why not
1148 * allow identifiers declared as types to start the arguments?
1150 * Matze: this all looks confusing and little systematic, so we're even less
1151 * strict and parse any list of things which are identifiers or
1152 * (assignment-)expressions.
1154 static attribute_argument_t *parse_attribute_arguments(void)
1156 attribute_argument_t *first = NULL;
1157 attribute_argument_t **anchor = &first;
1158 if (token.type != ')') do {
1159 attribute_argument_t *argument = allocate_ast_zero(sizeof(*argument));
1161 /* is it an identifier */
1162 if (token.type == T_IDENTIFIER
1163 && (look_ahead(1)->type == ',' || look_ahead(1)->type == ')')) {
1164 symbol_t *symbol = token.symbol;
1165 argument->kind = ATTRIBUTE_ARGUMENT_SYMBOL;
1166 argument->v.symbol = symbol;
1169 /* must be an expression */
1170 expression_t *expression = parse_assignment_expression();
1172 argument->kind = ATTRIBUTE_ARGUMENT_EXPRESSION;
1173 argument->v.expression = expression;
1176 /* append argument */
1178 anchor = &argument->next;
1179 } while (next_if(','));
1180 expect(')', end_error);
1189 static attribute_t *parse_attribute_asm(void)
1191 attribute_t *attribute = allocate_attribute_zero(ATTRIBUTE_GNU_ASM);
1194 expect('(', end_error);
1195 attribute->a.arguments = parse_attribute_arguments();
1202 static symbol_t *get_symbol_from_token(void)
1204 switch(token.type) {
1206 return token.symbol;
1235 /* maybe we need more tokens ... add them on demand */
1236 return get_token_symbol(&token);
1242 static attribute_t *parse_attribute_gnu_single(void)
1244 /* parse "any-word" */
1245 symbol_t *symbol = get_symbol_from_token();
1246 if (symbol == NULL) {
1247 parse_error_expected("while parsing attribute((", T_IDENTIFIER, NULL);
1251 attribute_kind_t kind;
1252 char const *const name = symbol->string;
1253 for (kind = ATTRIBUTE_GNU_FIRST;; ++kind) {
1254 if (kind > ATTRIBUTE_GNU_LAST) {
1255 warningf(WARN_ATTRIBUTE, HERE, "unknown attribute '%s' ignored", name);
1256 /* TODO: we should still save the attribute in the list... */
1257 kind = ATTRIBUTE_UNKNOWN;
1261 const char *attribute_name = get_attribute_name(kind);
1262 if (attribute_name != NULL
1263 && strcmp_underscore(attribute_name, name) == 0)
1267 attribute_t *attribute = allocate_attribute_zero(kind);
1270 /* parse arguments */
1272 attribute->a.arguments = parse_attribute_arguments();
1277 static attribute_t *parse_attribute_gnu(void)
1279 attribute_t *first = NULL;
1280 attribute_t **anchor = &first;
1282 eat(T___attribute__);
1283 expect('(', end_error);
1284 expect('(', end_error);
1286 if (token.type != ')') do {
1287 attribute_t *attribute = parse_attribute_gnu_single();
1288 if (attribute == NULL)
1291 *anchor = attribute;
1292 anchor = &attribute->next;
1293 } while (next_if(','));
1294 expect(')', end_error);
1295 expect(')', end_error);
1301 /** Parse attributes. */
1302 static attribute_t *parse_attributes(attribute_t *first)
1304 attribute_t **anchor = &first;
1306 while (*anchor != NULL)
1307 anchor = &(*anchor)->next;
1309 attribute_t *attribute;
1310 switch (token.type) {
1311 case T___attribute__:
1312 attribute = parse_attribute_gnu();
1313 if (attribute == NULL)
1318 attribute = parse_attribute_asm();
1322 attribute = allocate_attribute_zero(ATTRIBUTE_MS_CDECL);
1327 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FASTCALL);
1331 case T__forceinline:
1332 attribute = allocate_attribute_zero(ATTRIBUTE_MS_FORCEINLINE);
1333 eat(T__forceinline);
1337 attribute = allocate_attribute_zero(ATTRIBUTE_MS_STDCALL);
1342 /* TODO record modifier */
1343 warningf(WARN_OTHER, HERE, "Ignoring declaration modifier %K", &token);
1344 attribute = allocate_attribute_zero(ATTRIBUTE_MS_THISCALL);
1352 *anchor = attribute;
1353 anchor = &attribute->next;
1357 static void mark_vars_read(expression_t *expr, entity_t *lhs_ent);
1359 static entity_t *determine_lhs_ent(expression_t *const expr,
1362 switch (expr->kind) {
1363 case EXPR_REFERENCE: {
1364 entity_t *const entity = expr->reference.entity;
1365 /* we should only find variables as lvalues... */
1366 if (entity->base.kind != ENTITY_VARIABLE
1367 && entity->base.kind != ENTITY_PARAMETER)
1373 case EXPR_ARRAY_ACCESS: {
1374 expression_t *const ref = expr->array_access.array_ref;
1375 entity_t * ent = NULL;
1376 if (is_type_array(skip_typeref(revert_automatic_type_conversion(ref)))) {
1377 ent = determine_lhs_ent(ref, lhs_ent);
1380 mark_vars_read(expr->select.compound, lhs_ent);
1382 mark_vars_read(expr->array_access.index, lhs_ent);
1387 if (is_type_compound(skip_typeref(expr->base.type))) {
1388 return determine_lhs_ent(expr->select.compound, lhs_ent);
1390 mark_vars_read(expr->select.compound, lhs_ent);
1395 case EXPR_UNARY_DEREFERENCE: {
1396 expression_t *const val = expr->unary.value;
1397 if (val->kind == EXPR_UNARY_TAKE_ADDRESS) {
1399 return determine_lhs_ent(val->unary.value, lhs_ent);
1401 mark_vars_read(val, NULL);
1407 mark_vars_read(expr, NULL);
1412 #define ENT_ANY ((entity_t*)-1)
1415 * Mark declarations, which are read. This is used to detect variables, which
1419 * x is not marked as "read", because it is only read to calculate its own new
1423 * x and y are not detected as "not read", because multiple variables are
1426 static void mark_vars_read(expression_t *const expr, entity_t *lhs_ent)
1428 switch (expr->kind) {
1429 case EXPR_REFERENCE: {
1430 entity_t *const entity = expr->reference.entity;
1431 if (entity->kind != ENTITY_VARIABLE
1432 && entity->kind != ENTITY_PARAMETER)
1435 if (lhs_ent != entity && lhs_ent != ENT_ANY) {
1436 if (entity->kind == ENTITY_VARIABLE) {
1437 entity->variable.read = true;
1439 entity->parameter.read = true;
1446 // TODO respect pure/const
1447 mark_vars_read(expr->call.function, NULL);
1448 for (call_argument_t *arg = expr->call.arguments; arg != NULL; arg = arg->next) {
1449 mark_vars_read(arg->expression, NULL);
1453 case EXPR_CONDITIONAL:
1454 // TODO lhs_decl should depend on whether true/false have an effect
1455 mark_vars_read(expr->conditional.condition, NULL);
1456 if (expr->conditional.true_expression != NULL)
1457 mark_vars_read(expr->conditional.true_expression, lhs_ent);
1458 mark_vars_read(expr->conditional.false_expression, lhs_ent);
1462 if (lhs_ent == ENT_ANY
1463 && !is_type_compound(skip_typeref(expr->base.type)))
1465 mark_vars_read(expr->select.compound, lhs_ent);
1468 case EXPR_ARRAY_ACCESS: {
1469 expression_t *const ref = expr->array_access.array_ref;
1470 mark_vars_read(ref, lhs_ent);
1471 lhs_ent = determine_lhs_ent(ref, lhs_ent);
1472 mark_vars_read(expr->array_access.index, lhs_ent);
1477 mark_vars_read(expr->va_arge.ap, lhs_ent);
1481 mark_vars_read(expr->va_copye.src, lhs_ent);
1484 case EXPR_UNARY_CAST:
1485 /* Special case: Use void cast to mark a variable as "read" */
1486 if (is_type_atomic(skip_typeref(expr->base.type), ATOMIC_TYPE_VOID))
1491 case EXPR_UNARY_THROW:
1492 if (expr->unary.value == NULL)
1495 case EXPR_UNARY_DEREFERENCE:
1496 case EXPR_UNARY_DELETE:
1497 case EXPR_UNARY_DELETE_ARRAY:
1498 if (lhs_ent == ENT_ANY)
1502 case EXPR_UNARY_NEGATE:
1503 case EXPR_UNARY_PLUS:
1504 case EXPR_UNARY_BITWISE_NEGATE:
1505 case EXPR_UNARY_NOT:
1506 case EXPR_UNARY_TAKE_ADDRESS:
1507 case EXPR_UNARY_POSTFIX_INCREMENT:
1508 case EXPR_UNARY_POSTFIX_DECREMENT:
1509 case EXPR_UNARY_PREFIX_INCREMENT:
1510 case EXPR_UNARY_PREFIX_DECREMENT:
1511 case EXPR_UNARY_CAST_IMPLICIT:
1512 case EXPR_UNARY_ASSUME:
1514 mark_vars_read(expr->unary.value, lhs_ent);
1517 case EXPR_BINARY_ADD:
1518 case EXPR_BINARY_SUB:
1519 case EXPR_BINARY_MUL:
1520 case EXPR_BINARY_DIV:
1521 case EXPR_BINARY_MOD:
1522 case EXPR_BINARY_EQUAL:
1523 case EXPR_BINARY_NOTEQUAL:
1524 case EXPR_BINARY_LESS:
1525 case EXPR_BINARY_LESSEQUAL:
1526 case EXPR_BINARY_GREATER:
1527 case EXPR_BINARY_GREATEREQUAL:
1528 case EXPR_BINARY_BITWISE_AND:
1529 case EXPR_BINARY_BITWISE_OR:
1530 case EXPR_BINARY_BITWISE_XOR:
1531 case EXPR_BINARY_LOGICAL_AND:
1532 case EXPR_BINARY_LOGICAL_OR:
1533 case EXPR_BINARY_SHIFTLEFT:
1534 case EXPR_BINARY_SHIFTRIGHT:
1535 case EXPR_BINARY_COMMA:
1536 case EXPR_BINARY_ISGREATER:
1537 case EXPR_BINARY_ISGREATEREQUAL:
1538 case EXPR_BINARY_ISLESS:
1539 case EXPR_BINARY_ISLESSEQUAL:
1540 case EXPR_BINARY_ISLESSGREATER:
1541 case EXPR_BINARY_ISUNORDERED:
1542 mark_vars_read(expr->binary.left, lhs_ent);
1543 mark_vars_read(expr->binary.right, lhs_ent);
1546 case EXPR_BINARY_ASSIGN:
1547 case EXPR_BINARY_MUL_ASSIGN:
1548 case EXPR_BINARY_DIV_ASSIGN:
1549 case EXPR_BINARY_MOD_ASSIGN:
1550 case EXPR_BINARY_ADD_ASSIGN:
1551 case EXPR_BINARY_SUB_ASSIGN:
1552 case EXPR_BINARY_SHIFTLEFT_ASSIGN:
1553 case EXPR_BINARY_SHIFTRIGHT_ASSIGN:
1554 case EXPR_BINARY_BITWISE_AND_ASSIGN:
1555 case EXPR_BINARY_BITWISE_XOR_ASSIGN:
1556 case EXPR_BINARY_BITWISE_OR_ASSIGN: {
1557 if (lhs_ent == ENT_ANY)
1559 lhs_ent = determine_lhs_ent(expr->binary.left, lhs_ent);
1560 mark_vars_read(expr->binary.right, lhs_ent);
1565 determine_lhs_ent(expr->va_starte.ap, lhs_ent);
1571 case EXPR_STRING_LITERAL:
1572 case EXPR_WIDE_STRING_LITERAL:
1573 case EXPR_COMPOUND_LITERAL: // TODO init?
1575 case EXPR_CLASSIFY_TYPE:
1578 case EXPR_BUILTIN_CONSTANT_P:
1579 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
1581 case EXPR_STATEMENT: // TODO
1582 case EXPR_LABEL_ADDRESS:
1583 case EXPR_REFERENCE_ENUM_VALUE:
1587 panic("unhandled expression");
1590 static designator_t *parse_designation(void)
1592 designator_t *result = NULL;
1593 designator_t **anchor = &result;
1596 designator_t *designator;
1597 switch (token.type) {
1599 designator = allocate_ast_zero(sizeof(designator[0]));
1600 designator->source_position = token.source_position;
1602 add_anchor_token(']');
1603 designator->array_index = parse_constant_expression();
1604 rem_anchor_token(']');
1605 expect(']', end_error);
1608 designator = allocate_ast_zero(sizeof(designator[0]));
1609 designator->source_position = token.source_position;
1611 if (token.type != T_IDENTIFIER) {
1612 parse_error_expected("while parsing designator",
1613 T_IDENTIFIER, NULL);
1616 designator->symbol = token.symbol;
1620 expect('=', end_error);
1624 assert(designator != NULL);
1625 *anchor = designator;
1626 anchor = &designator->next;
1632 static initializer_t *initializer_from_string(array_type_t *const type,
1633 const string_t *const string)
1635 /* TODO: check len vs. size of array type */
1638 initializer_t *initializer = allocate_initializer_zero(INITIALIZER_STRING);
1639 initializer->string.string = *string;
1644 static initializer_t *initializer_from_wide_string(array_type_t *const type,
1645 const string_t *const string)
1647 /* TODO: check len vs. size of array type */
1650 initializer_t *const initializer =
1651 allocate_initializer_zero(INITIALIZER_WIDE_STRING);
1652 initializer->wide_string.string = *string;
1658 * Build an initializer from a given expression.
1660 static initializer_t *initializer_from_expression(type_t *orig_type,
1661 expression_t *expression)
1663 /* TODO check that expression is a constant expression */
1665 /* §6.7.8.14/15 char array may be initialized by string literals */
1666 type_t *type = skip_typeref(orig_type);
1667 type_t *expr_type_orig = expression->base.type;
1668 type_t *expr_type = skip_typeref(expr_type_orig);
1670 if (is_type_array(type) && expr_type->kind == TYPE_POINTER) {
1671 array_type_t *const array_type = &type->array;
1672 type_t *const element_type = skip_typeref(array_type->element_type);
1674 if (element_type->kind == TYPE_ATOMIC) {
1675 atomic_type_kind_t akind = element_type->atomic.akind;
1676 switch (expression->kind) {
1677 case EXPR_STRING_LITERAL:
1678 if (akind == ATOMIC_TYPE_CHAR
1679 || akind == ATOMIC_TYPE_SCHAR
1680 || akind == ATOMIC_TYPE_UCHAR) {
1681 return initializer_from_string(array_type,
1682 &expression->string_literal.value);
1686 case EXPR_WIDE_STRING_LITERAL: {
1687 type_t *bare_wchar_type = skip_typeref(type_wchar_t);
1688 if (get_unqualified_type(element_type) == bare_wchar_type) {
1689 return initializer_from_wide_string(array_type,
1690 &expression->string_literal.value);
1701 assign_error_t error = semantic_assign(type, expression);
1702 if (error == ASSIGN_ERROR_INCOMPATIBLE)
1704 report_assign_error(error, type, expression, "initializer",
1705 &expression->base.source_position);
1707 initializer_t *const result = allocate_initializer_zero(INITIALIZER_VALUE);
1708 result->value.value = create_implicit_cast(expression, type);
1714 * Checks if a given expression can be used as a constant initializer.
1716 static bool is_initializer_constant(const expression_t *expression)
1718 return is_constant_expression(expression) != EXPR_CLASS_VARIABLE ||
1719 is_linker_constant(expression) != EXPR_CLASS_VARIABLE;
1723 * Parses an scalar initializer.
1725 * §6.7.8.11; eat {} without warning
1727 static initializer_t *parse_scalar_initializer(type_t *type,
1728 bool must_be_constant)
1730 /* there might be extra {} hierarchies */
1732 if (token.type == '{') {
1733 warningf(WARN_OTHER, HERE, "extra curly braces around scalar initializer");
1737 } while (token.type == '{');
1740 expression_t *expression = parse_assignment_expression();
1741 mark_vars_read(expression, NULL);
1742 if (must_be_constant && !is_initializer_constant(expression)) {
1743 errorf(&expression->base.source_position,
1744 "initialisation expression '%E' is not constant",
1748 initializer_t *initializer = initializer_from_expression(type, expression);
1750 if (initializer == NULL) {
1751 errorf(&expression->base.source_position,
1752 "expression '%E' (type '%T') doesn't match expected type '%T'",
1753 expression, expression->base.type, type);
1758 bool additional_warning_displayed = false;
1759 while (braces > 0) {
1761 if (token.type != '}') {
1762 if (!additional_warning_displayed) {
1763 warningf(WARN_OTHER, HERE, "additional elements in scalar initializer");
1764 additional_warning_displayed = true;
1775 * An entry in the type path.
1777 typedef struct type_path_entry_t type_path_entry_t;
1778 struct type_path_entry_t {
1779 type_t *type; /**< the upper top type. restored to path->top_tye if this entry is popped. */
1781 size_t index; /**< For array types: the current index. */
1782 declaration_t *compound_entry; /**< For compound types: the current declaration. */
1787 * A type path expression a position inside compound or array types.
1789 typedef struct type_path_t type_path_t;
1790 struct type_path_t {
1791 type_path_entry_t *path; /**< An flexible array containing the current path. */
1792 type_t *top_type; /**< type of the element the path points */
1793 size_t max_index; /**< largest index in outermost array */
1797 * Prints a type path for debugging.
1799 static __attribute__((unused)) void debug_print_type_path(
1800 const type_path_t *path)
1802 size_t len = ARR_LEN(path->path);
1804 for (size_t i = 0; i < len; ++i) {
1805 const type_path_entry_t *entry = & path->path[i];
1807 type_t *type = skip_typeref(entry->type);
1808 if (is_type_compound(type)) {
1809 /* in gcc mode structs can have no members */
1810 if (entry->v.compound_entry == NULL) {
1814 fprintf(stderr, ".%s",
1815 entry->v.compound_entry->base.symbol->string);
1816 } else if (is_type_array(type)) {
1817 fprintf(stderr, "[%u]", (unsigned) entry->v.index);
1819 fprintf(stderr, "-INVALID-");
1822 if (path->top_type != NULL) {
1823 fprintf(stderr, " (");
1824 print_type(path->top_type);
1825 fprintf(stderr, ")");
1830 * Return the top type path entry, ie. in a path
1831 * (type).a.b returns the b.
1833 static type_path_entry_t *get_type_path_top(const type_path_t *path)
1835 size_t len = ARR_LEN(path->path);
1837 return &path->path[len-1];
1841 * Enlarge the type path by an (empty) element.
1843 static type_path_entry_t *append_to_type_path(type_path_t *path)
1845 size_t len = ARR_LEN(path->path);
1846 ARR_RESIZE(type_path_entry_t, path->path, len+1);
1848 type_path_entry_t *result = & path->path[len];
1849 memset(result, 0, sizeof(result[0]));
1854 * Descending into a sub-type. Enter the scope of the current top_type.
1856 static void descend_into_subtype(type_path_t *path)
1858 type_t *orig_top_type = path->top_type;
1859 type_t *top_type = skip_typeref(orig_top_type);
1861 type_path_entry_t *top = append_to_type_path(path);
1862 top->type = top_type;
1864 if (is_type_compound(top_type)) {
1865 compound_t *compound = top_type->compound.compound;
1866 entity_t *entry = compound->members.entities;
1868 if (entry != NULL) {
1869 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
1870 top->v.compound_entry = &entry->declaration;
1871 path->top_type = entry->declaration.type;
1873 path->top_type = NULL;
1875 } else if (is_type_array(top_type)) {
1877 path->top_type = top_type->array.element_type;
1879 assert(!is_type_valid(top_type));
1884 * Pop an entry from the given type path, ie. returning from
1885 * (type).a.b to (type).a
1887 static void ascend_from_subtype(type_path_t *path)
1889 type_path_entry_t *top = get_type_path_top(path);
1891 path->top_type = top->type;
1893 size_t len = ARR_LEN(path->path);
1894 ARR_RESIZE(type_path_entry_t, path->path, len-1);
1898 * Pop entries from the given type path until the given
1899 * path level is reached.
1901 static void ascend_to(type_path_t *path, size_t top_path_level)
1903 size_t len = ARR_LEN(path->path);
1905 while (len > top_path_level) {
1906 ascend_from_subtype(path);
1907 len = ARR_LEN(path->path);
1911 static bool walk_designator(type_path_t *path, const designator_t *designator,
1912 bool used_in_offsetof)
1914 for (; designator != NULL; designator = designator->next) {
1915 type_path_entry_t *top = get_type_path_top(path);
1916 type_t *orig_type = top->type;
1918 type_t *type = skip_typeref(orig_type);
1920 if (designator->symbol != NULL) {
1921 symbol_t *symbol = designator->symbol;
1922 if (!is_type_compound(type)) {
1923 if (is_type_valid(type)) {
1924 errorf(&designator->source_position,
1925 "'.%Y' designator used for non-compound type '%T'",
1929 top->type = type_error_type;
1930 top->v.compound_entry = NULL;
1931 orig_type = type_error_type;
1933 compound_t *compound = type->compound.compound;
1934 entity_t *iter = compound->members.entities;
1935 for (; iter != NULL; iter = iter->base.next) {
1936 if (iter->base.symbol == symbol) {
1941 errorf(&designator->source_position,
1942 "'%T' has no member named '%Y'", orig_type, symbol);
1945 assert(iter->kind == ENTITY_COMPOUND_MEMBER);
1946 if (used_in_offsetof) {
1947 type_t *real_type = skip_typeref(iter->declaration.type);
1948 if (real_type->kind == TYPE_BITFIELD) {
1949 errorf(&designator->source_position,
1950 "offsetof designator '%Y' must not specify bitfield",
1956 top->type = orig_type;
1957 top->v.compound_entry = &iter->declaration;
1958 orig_type = iter->declaration.type;
1961 expression_t *array_index = designator->array_index;
1962 assert(designator->array_index != NULL);
1964 if (!is_type_array(type)) {
1965 if (is_type_valid(type)) {
1966 errorf(&designator->source_position,
1967 "[%E] designator used for non-array type '%T'",
1968 array_index, orig_type);
1973 long index = fold_constant_to_int(array_index);
1974 if (!used_in_offsetof) {
1976 errorf(&designator->source_position,
1977 "array index [%E] must be positive", array_index);
1978 } else if (type->array.size_constant) {
1979 long array_size = type->array.size;
1980 if (index >= array_size) {
1981 errorf(&designator->source_position,
1982 "designator [%E] (%d) exceeds array size %d",
1983 array_index, index, array_size);
1988 top->type = orig_type;
1989 top->v.index = (size_t) index;
1990 orig_type = type->array.element_type;
1992 path->top_type = orig_type;
1994 if (designator->next != NULL) {
1995 descend_into_subtype(path);
2001 static void advance_current_object(type_path_t *path, size_t top_path_level)
2003 type_path_entry_t *top = get_type_path_top(path);
2005 type_t *type = skip_typeref(top->type);
2006 if (is_type_union(type)) {
2007 /* in unions only the first element is initialized */
2008 top->v.compound_entry = NULL;
2009 } else if (is_type_struct(type)) {
2010 declaration_t *entry = top->v.compound_entry;
2012 entity_t *next_entity = entry->base.next;
2013 if (next_entity != NULL) {
2014 assert(is_declaration(next_entity));
2015 entry = &next_entity->declaration;
2020 top->v.compound_entry = entry;
2021 if (entry != NULL) {
2022 path->top_type = entry->type;
2025 } else if (is_type_array(type)) {
2026 assert(is_type_array(type));
2030 if (!type->array.size_constant || top->v.index < type->array.size) {
2034 assert(!is_type_valid(type));
2038 /* we're past the last member of the current sub-aggregate, try if we
2039 * can ascend in the type hierarchy and continue with another subobject */
2040 size_t len = ARR_LEN(path->path);
2042 if (len > top_path_level) {
2043 ascend_from_subtype(path);
2044 advance_current_object(path, top_path_level);
2046 path->top_type = NULL;
2051 * skip any {...} blocks until a closing bracket is reached.
2053 static void skip_initializers(void)
2057 while (token.type != '}') {
2058 if (token.type == T_EOF)
2060 if (token.type == '{') {
2068 static initializer_t *create_empty_initializer(void)
2070 static initializer_t empty_initializer
2071 = { .list = { { INITIALIZER_LIST }, 0 } };
2072 return &empty_initializer;
2076 * Parse a part of an initialiser for a struct or union,
2078 static initializer_t *parse_sub_initializer(type_path_t *path,
2079 type_t *outer_type, size_t top_path_level,
2080 parse_initializer_env_t *env)
2082 if (token.type == '}') {
2083 /* empty initializer */
2084 return create_empty_initializer();
2087 type_t *orig_type = path->top_type;
2088 type_t *type = NULL;
2090 if (orig_type == NULL) {
2091 /* We are initializing an empty compound. */
2093 type = skip_typeref(orig_type);
2096 initializer_t **initializers = NEW_ARR_F(initializer_t*, 0);
2099 designator_t *designator = NULL;
2100 if (token.type == '.' || token.type == '[') {
2101 designator = parse_designation();
2102 goto finish_designator;
2103 } else if (token.type == T_IDENTIFIER && look_ahead(1)->type == ':') {
2104 /* GNU-style designator ("identifier: value") */
2105 designator = allocate_ast_zero(sizeof(designator[0]));
2106 designator->source_position = token.source_position;
2107 designator->symbol = token.symbol;
2112 /* reset path to toplevel, evaluate designator from there */
2113 ascend_to(path, top_path_level);
2114 if (!walk_designator(path, designator, false)) {
2115 /* can't continue after designation error */
2119 initializer_t *designator_initializer
2120 = allocate_initializer_zero(INITIALIZER_DESIGNATOR);
2121 designator_initializer->designator.designator = designator;
2122 ARR_APP1(initializer_t*, initializers, designator_initializer);
2124 orig_type = path->top_type;
2125 type = orig_type != NULL ? skip_typeref(orig_type) : NULL;
2130 if (token.type == '{') {
2131 if (type != NULL && is_type_scalar(type)) {
2132 sub = parse_scalar_initializer(type, env->must_be_constant);
2135 if (env->entity != NULL) {
2137 "extra brace group at end of initializer for '%Y'",
2138 env->entity->base.symbol);
2140 errorf(HERE, "extra brace group at end of initializer");
2145 descend_into_subtype(path);
2148 add_anchor_token('}');
2149 sub = parse_sub_initializer(path, orig_type, top_path_level+1,
2151 rem_anchor_token('}');
2154 ascend_from_subtype(path);
2155 expect('}', end_error);
2157 expect('}', end_error);
2158 goto error_parse_next;
2162 /* must be an expression */
2163 expression_t *expression = parse_assignment_expression();
2164 mark_vars_read(expression, NULL);
2166 if (env->must_be_constant && !is_initializer_constant(expression)) {
2167 errorf(&expression->base.source_position,
2168 "Initialisation expression '%E' is not constant",
2173 /* we are already outside, ... */
2174 if (outer_type == NULL)
2175 goto error_parse_next;
2176 type_t *const outer_type_skip = skip_typeref(outer_type);
2177 if (is_type_compound(outer_type_skip) &&
2178 !outer_type_skip->compound.compound->complete) {
2179 goto error_parse_next;
2182 source_position_t const* const pos = &expression->base.source_position;
2183 if (env->entity != NULL) {
2184 warningf(WARN_OTHER, pos, "excess elements in initializer for '%Y'", env->entity->base.symbol);
2186 warningf(WARN_OTHER, pos, "excess elements in initializer");
2188 goto error_parse_next;
2191 /* handle { "string" } special case */
2192 if ((expression->kind == EXPR_STRING_LITERAL
2193 || expression->kind == EXPR_WIDE_STRING_LITERAL)
2194 && outer_type != NULL) {
2195 sub = initializer_from_expression(outer_type, expression);
2198 if (token.type != '}') {
2199 warningf(WARN_OTHER, HERE, "excessive elements in initializer for type '%T'", orig_type);
2201 /* TODO: eat , ... */
2206 /* descend into subtypes until expression matches type */
2208 orig_type = path->top_type;
2209 type = skip_typeref(orig_type);
2211 sub = initializer_from_expression(orig_type, expression);
2215 if (!is_type_valid(type)) {
2218 if (is_type_scalar(type)) {
2219 errorf(&expression->base.source_position,
2220 "expression '%E' doesn't match expected type '%T'",
2221 expression, orig_type);
2225 descend_into_subtype(path);
2229 /* update largest index of top array */
2230 const type_path_entry_t *first = &path->path[0];
2231 type_t *first_type = first->type;
2232 first_type = skip_typeref(first_type);
2233 if (is_type_array(first_type)) {
2234 size_t index = first->v.index;
2235 if (index > path->max_index)
2236 path->max_index = index;
2239 /* append to initializers list */
2240 ARR_APP1(initializer_t*, initializers, sub);
2243 if (token.type == '}') {
2246 expect(',', end_error);
2247 if (token.type == '}') {
2252 /* advance to the next declaration if we are not at the end */
2253 advance_current_object(path, top_path_level);
2254 orig_type = path->top_type;
2255 if (orig_type != NULL)
2256 type = skip_typeref(orig_type);
2262 size_t len = ARR_LEN(initializers);
2263 size_t size = sizeof(initializer_list_t) + len * sizeof(initializers[0]);
2264 initializer_t *result = allocate_ast_zero(size);
2265 result->kind = INITIALIZER_LIST;
2266 result->list.len = len;
2267 memcpy(&result->list.initializers, initializers,
2268 len * sizeof(initializers[0]));
2270 DEL_ARR_F(initializers);
2271 ascend_to(path, top_path_level+1);
2276 skip_initializers();
2277 DEL_ARR_F(initializers);
2278 ascend_to(path, top_path_level+1);
2282 static expression_t *make_size_literal(size_t value)
2284 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_INTEGER);
2285 literal->base.type = type_size_t;
2288 snprintf(buf, sizeof(buf), "%u", (unsigned) value);
2289 literal->literal.value = make_string(buf);
2295 * Parses an initializer. Parsers either a compound literal
2296 * (env->declaration == NULL) or an initializer of a declaration.
2298 static initializer_t *parse_initializer(parse_initializer_env_t *env)
2300 type_t *type = skip_typeref(env->type);
2301 size_t max_index = 0;
2302 initializer_t *result;
2304 if (is_type_scalar(type)) {
2305 result = parse_scalar_initializer(type, env->must_be_constant);
2306 } else if (token.type == '{') {
2310 memset(&path, 0, sizeof(path));
2311 path.top_type = env->type;
2312 path.path = NEW_ARR_F(type_path_entry_t, 0);
2314 descend_into_subtype(&path);
2316 add_anchor_token('}');
2317 result = parse_sub_initializer(&path, env->type, 1, env);
2318 rem_anchor_token('}');
2320 max_index = path.max_index;
2321 DEL_ARR_F(path.path);
2323 expect('}', end_error);
2326 /* parse_scalar_initializer() also works in this case: we simply
2327 * have an expression without {} around it */
2328 result = parse_scalar_initializer(type, env->must_be_constant);
2331 /* §6.7.8:22 array initializers for arrays with unknown size determine
2332 * the array type size */
2333 if (is_type_array(type) && type->array.size_expression == NULL
2334 && result != NULL) {
2336 switch (result->kind) {
2337 case INITIALIZER_LIST:
2338 assert(max_index != 0xdeadbeaf);
2339 size = max_index + 1;
2342 case INITIALIZER_STRING:
2343 size = result->string.string.size;
2346 case INITIALIZER_WIDE_STRING:
2347 size = result->wide_string.string.size;
2350 case INITIALIZER_DESIGNATOR:
2351 case INITIALIZER_VALUE:
2352 /* can happen for parse errors */
2357 internal_errorf(HERE, "invalid initializer type");
2360 type_t *new_type = duplicate_type(type);
2362 new_type->array.size_expression = make_size_literal(size);
2363 new_type->array.size_constant = true;
2364 new_type->array.has_implicit_size = true;
2365 new_type->array.size = size;
2366 env->type = new_type;
2372 static void append_entity(scope_t *scope, entity_t *entity)
2374 if (scope->last_entity != NULL) {
2375 scope->last_entity->base.next = entity;
2377 scope->entities = entity;
2379 entity->base.parent_entity = current_entity;
2380 scope->last_entity = entity;
2384 static compound_t *parse_compound_type_specifier(bool is_struct)
2386 source_position_t const pos = *HERE;
2387 eat(is_struct ? T_struct : T_union);
2389 symbol_t *symbol = NULL;
2390 entity_t *entity = NULL;
2391 attribute_t *attributes = NULL;
2393 if (token.type == T___attribute__) {
2394 attributes = parse_attributes(NULL);
2397 entity_kind_tag_t const kind = is_struct ? ENTITY_STRUCT : ENTITY_UNION;
2398 if (token.type == T_IDENTIFIER) {
2399 /* the compound has a name, check if we have seen it already */
2400 symbol = token.symbol;
2401 entity = get_tag(symbol, kind);
2404 if (entity != NULL) {
2405 if (entity->base.parent_scope != current_scope &&
2406 (token.type == '{' || token.type == ';')) {
2407 /* we're in an inner scope and have a definition. Shadow
2408 * existing definition in outer scope */
2410 } else if (entity->compound.complete && token.type == '{') {
2411 source_position_t const *const ppos = &entity->base.source_position;
2412 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2413 /* clear members in the hope to avoid further errors */
2414 entity->compound.members.entities = NULL;
2417 } else if (token.type != '{') {
2418 char const *const msg =
2419 is_struct ? "while parsing struct type specifier" :
2420 "while parsing union type specifier";
2421 parse_error_expected(msg, T_IDENTIFIER, '{', NULL);
2426 if (entity == NULL) {
2427 entity = allocate_entity_zero(kind, NAMESPACE_TAG, symbol);
2428 entity->compound.alignment = 1;
2429 entity->base.source_position = pos;
2430 entity->base.parent_scope = current_scope;
2431 if (symbol != NULL) {
2432 environment_push(entity);
2434 append_entity(current_scope, entity);
2437 if (token.type == '{') {
2438 parse_compound_type_entries(&entity->compound);
2440 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2441 if (symbol == NULL) {
2442 assert(anonymous_entity == NULL);
2443 anonymous_entity = entity;
2447 if (attributes != NULL) {
2448 handle_entity_attributes(attributes, entity);
2451 return &entity->compound;
2454 static void parse_enum_entries(type_t *const enum_type)
2458 if (token.type == '}') {
2459 errorf(HERE, "empty enum not allowed");
2464 add_anchor_token('}');
2466 if (token.type != T_IDENTIFIER) {
2467 parse_error_expected("while parsing enum entry", T_IDENTIFIER, NULL);
2469 rem_anchor_token('}');
2473 entity_t *const entity = allocate_entity_zero(ENTITY_ENUM_VALUE, NAMESPACE_NORMAL, token.symbol);
2474 entity->enum_value.enum_type = enum_type;
2475 entity->base.source_position = token.source_position;
2479 expression_t *value = parse_constant_expression();
2481 value = create_implicit_cast(value, enum_type);
2482 entity->enum_value.value = value;
2487 record_entity(entity, false);
2488 } while (next_if(',') && token.type != '}');
2489 rem_anchor_token('}');
2491 expect('}', end_error);
2497 static type_t *parse_enum_specifier(void)
2499 source_position_t const pos = *HERE;
2504 switch (token.type) {
2506 symbol = token.symbol;
2507 entity = get_tag(symbol, ENTITY_ENUM);
2510 if (entity != NULL) {
2511 if (entity->base.parent_scope != current_scope &&
2512 (token.type == '{' || token.type == ';')) {
2513 /* we're in an inner scope and have a definition. Shadow
2514 * existing definition in outer scope */
2516 } else if (entity->enume.complete && token.type == '{') {
2517 source_position_t const *const ppos = &entity->base.source_position;
2518 errorf(&pos, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
2529 parse_error_expected("while parsing enum type specifier",
2530 T_IDENTIFIER, '{', NULL);
2534 if (entity == NULL) {
2535 entity = allocate_entity_zero(ENTITY_ENUM, NAMESPACE_TAG, symbol);
2536 entity->base.source_position = pos;
2537 entity->base.parent_scope = current_scope;
2540 type_t *const type = allocate_type_zero(TYPE_ENUM);
2541 type->enumt.enume = &entity->enume;
2542 type->enumt.akind = ATOMIC_TYPE_INT;
2544 if (token.type == '{') {
2545 if (symbol != NULL) {
2546 environment_push(entity);
2548 append_entity(current_scope, entity);
2549 entity->enume.complete = true;
2551 parse_enum_entries(type);
2552 parse_attributes(NULL);
2554 /* ISO/IEC 14882:1998(E) §7.1.3:5 */
2555 if (symbol == NULL) {
2556 assert(anonymous_entity == NULL);
2557 anonymous_entity = entity;
2559 } else if (!entity->enume.complete && !(c_mode & _GNUC)) {
2560 errorf(HERE, "'%T' used before definition (incomplete enums are a GNU extension)", type);
2567 * if a symbol is a typedef to another type, return true
2569 static bool is_typedef_symbol(symbol_t *symbol)
2571 const entity_t *const entity = get_entity(symbol, NAMESPACE_NORMAL);
2572 return entity != NULL && entity->kind == ENTITY_TYPEDEF;
2575 static type_t *parse_typeof(void)
2581 expect('(', end_error);
2582 add_anchor_token(')');
2584 expression_t *expression = NULL;
2586 bool old_type_prop = in_type_prop;
2587 in_type_prop = true;
2589 switch (token.type) {
2591 if (is_typedef_symbol(token.symbol)) {
2593 type = parse_typename();
2596 expression = parse_expression();
2597 type = revert_automatic_type_conversion(expression);
2601 in_type_prop = old_type_prop;
2603 rem_anchor_token(')');
2604 expect(')', end_error);
2606 type_t *typeof_type = allocate_type_zero(TYPE_TYPEOF);
2607 typeof_type->typeoft.expression = expression;
2608 typeof_type->typeoft.typeof_type = type;
2615 typedef enum specifiers_t {
2616 SPECIFIER_SIGNED = 1 << 0,
2617 SPECIFIER_UNSIGNED = 1 << 1,
2618 SPECIFIER_LONG = 1 << 2,
2619 SPECIFIER_INT = 1 << 3,
2620 SPECIFIER_DOUBLE = 1 << 4,
2621 SPECIFIER_CHAR = 1 << 5,
2622 SPECIFIER_WCHAR_T = 1 << 6,
2623 SPECIFIER_SHORT = 1 << 7,
2624 SPECIFIER_LONG_LONG = 1 << 8,
2625 SPECIFIER_FLOAT = 1 << 9,
2626 SPECIFIER_BOOL = 1 << 10,
2627 SPECIFIER_VOID = 1 << 11,
2628 SPECIFIER_INT8 = 1 << 12,
2629 SPECIFIER_INT16 = 1 << 13,
2630 SPECIFIER_INT32 = 1 << 14,
2631 SPECIFIER_INT64 = 1 << 15,
2632 SPECIFIER_INT128 = 1 << 16,
2633 SPECIFIER_COMPLEX = 1 << 17,
2634 SPECIFIER_IMAGINARY = 1 << 18,
2637 static type_t *get_typedef_type(symbol_t *symbol)
2639 entity_t *entity = get_entity(symbol, NAMESPACE_NORMAL);
2640 if (entity == NULL || entity->kind != ENTITY_TYPEDEF)
2643 type_t *type = allocate_type_zero(TYPE_TYPEDEF);
2644 type->typedeft.typedefe = &entity->typedefe;
2649 static attribute_t *parse_attribute_ms_property(attribute_t *attribute)
2651 expect('(', end_error);
2653 attribute_property_argument_t *property
2654 = allocate_ast_zero(sizeof(*property));
2657 if (token.type != T_IDENTIFIER) {
2658 parse_error_expected("while parsing property declspec",
2659 T_IDENTIFIER, NULL);
2664 symbol_t *symbol = token.symbol;
2665 if (strcmp(symbol->string, "put") == 0) {
2666 prop = &property->put_symbol;
2667 } else if (strcmp(symbol->string, "get") == 0) {
2668 prop = &property->get_symbol;
2670 errorf(HERE, "expected put or get in property declspec");
2674 expect('=', end_error);
2675 if (token.type != T_IDENTIFIER) {
2676 parse_error_expected("while parsing property declspec",
2677 T_IDENTIFIER, NULL);
2681 *prop = token.symbol;
2683 } while (next_if(','));
2685 attribute->a.property = property;
2687 expect(')', end_error);
2693 static attribute_t *parse_microsoft_extended_decl_modifier_single(void)
2695 attribute_kind_t kind = ATTRIBUTE_UNKNOWN;
2696 if (next_if(T_restrict)) {
2697 kind = ATTRIBUTE_MS_RESTRICT;
2698 } else if (token.type == T_IDENTIFIER) {
2699 const char *name = token.symbol->string;
2700 for (attribute_kind_t k = ATTRIBUTE_MS_FIRST; k <= ATTRIBUTE_MS_LAST;
2702 const char *attribute_name = get_attribute_name(k);
2703 if (attribute_name != NULL && strcmp(attribute_name, name) == 0) {
2709 if (kind == ATTRIBUTE_UNKNOWN) {
2710 warningf(WARN_ATTRIBUTE, HERE, "unknown __declspec '%s' ignored", name);
2713 parse_error_expected("while parsing __declspec", T_IDENTIFIER, NULL);
2717 attribute_t *attribute = allocate_attribute_zero(kind);
2720 if (kind == ATTRIBUTE_MS_PROPERTY) {
2721 return parse_attribute_ms_property(attribute);
2724 /* parse arguments */
2726 attribute->a.arguments = parse_attribute_arguments();
2731 static attribute_t *parse_microsoft_extended_decl_modifier(attribute_t *first)
2735 expect('(', end_error);
2740 add_anchor_token(')');
2742 attribute_t **anchor = &first;
2744 while (*anchor != NULL)
2745 anchor = &(*anchor)->next;
2747 attribute_t *attribute
2748 = parse_microsoft_extended_decl_modifier_single();
2749 if (attribute == NULL)
2752 *anchor = attribute;
2753 anchor = &attribute->next;
2754 } while (next_if(','));
2756 rem_anchor_token(')');
2757 expect(')', end_error);
2761 rem_anchor_token(')');
2765 static entity_t *create_error_entity(symbol_t *symbol, entity_kind_tag_t kind)
2767 entity_t *const entity = allocate_entity_zero(kind, NAMESPACE_NORMAL, symbol);
2768 entity->base.source_position = *HERE;
2769 if (is_declaration(entity)) {
2770 entity->declaration.type = type_error_type;
2771 entity->declaration.implicit = true;
2772 } else if (kind == ENTITY_TYPEDEF) {
2773 entity->typedefe.type = type_error_type;
2774 entity->typedefe.builtin = true;
2776 if (kind != ENTITY_COMPOUND_MEMBER)
2777 record_entity(entity, false);
2781 static void parse_declaration_specifiers(declaration_specifiers_t *specifiers)
2783 type_t *type = NULL;
2784 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
2785 unsigned type_specifiers = 0;
2786 bool newtype = false;
2787 bool saw_error = false;
2789 memset(specifiers, 0, sizeof(*specifiers));
2790 specifiers->source_position = token.source_position;
2793 specifiers->attributes = parse_attributes(specifiers->attributes);
2795 switch (token.type) {
2797 #define MATCH_STORAGE_CLASS(token, class) \
2799 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2800 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2802 specifiers->storage_class = class; \
2803 if (specifiers->thread_local) \
2804 goto check_thread_storage_class; \
2808 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2809 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2810 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2811 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2812 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2815 specifiers->attributes
2816 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2820 if (specifiers->thread_local) {
2821 errorf(HERE, "duplicate '__thread'");
2823 specifiers->thread_local = true;
2824 check_thread_storage_class:
2825 switch (specifiers->storage_class) {
2826 case STORAGE_CLASS_EXTERN:
2827 case STORAGE_CLASS_NONE:
2828 case STORAGE_CLASS_STATIC:
2832 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2833 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2834 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2835 wrong_thread_storage_class:
2836 errorf(HERE, "'__thread' used with '%s'", wrong);
2843 /* type qualifiers */
2844 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2846 qualifiers |= qualifier; \
2850 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2851 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2852 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2853 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2854 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2855 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2856 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2857 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2859 /* type specifiers */
2860 #define MATCH_SPECIFIER(token, specifier, name) \
2862 if (type_specifiers & specifier) { \
2863 errorf(HERE, "multiple " name " type specifiers given"); \
2865 type_specifiers |= specifier; \
2870 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2871 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2872 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2873 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2874 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2875 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2876 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2877 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2878 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2879 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2880 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2881 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2882 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2883 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2884 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2885 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2886 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2887 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2891 specifiers->is_inline = true;
2895 case T__forceinline:
2897 specifiers->modifiers |= DM_FORCEINLINE;
2902 if (type_specifiers & SPECIFIER_LONG_LONG) {
2903 errorf(HERE, "too many long type specifiers given");
2904 } else if (type_specifiers & SPECIFIER_LONG) {
2905 type_specifiers |= SPECIFIER_LONG_LONG;
2907 type_specifiers |= SPECIFIER_LONG;
2912 #define CHECK_DOUBLE_TYPE() \
2913 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2916 CHECK_DOUBLE_TYPE();
2917 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2919 type->compound.compound = parse_compound_type_specifier(true);
2922 CHECK_DOUBLE_TYPE();
2923 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2924 type->compound.compound = parse_compound_type_specifier(false);
2927 CHECK_DOUBLE_TYPE();
2928 type = parse_enum_specifier();
2931 CHECK_DOUBLE_TYPE();
2932 type = parse_typeof();
2934 case T___builtin_va_list:
2935 CHECK_DOUBLE_TYPE();
2936 type = duplicate_type(type_valist);
2940 case T_IDENTIFIER: {
2941 /* only parse identifier if we haven't found a type yet */
2942 if (type != NULL || type_specifiers != 0) {
2943 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2944 * declaration, so it doesn't generate errors about expecting '(' or
2946 switch (look_ahead(1)->type) {
2953 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2957 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2962 goto finish_specifiers;
2966 type_t *const typedef_type = get_typedef_type(token.symbol);
2967 if (typedef_type == NULL) {
2968 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2969 * declaration, so it doesn't generate 'implicit int' followed by more
2970 * errors later on. */
2971 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2977 errorf(HERE, "%K does not name a type", &token);
2980 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2982 type = allocate_type_zero(TYPE_TYPEDEF);
2983 type->typedeft.typedefe = &entity->typedefe;
2991 goto finish_specifiers;
2996 type = typedef_type;
3000 /* function specifier */
3002 goto finish_specifiers;
3007 specifiers->attributes = parse_attributes(specifiers->attributes);
3009 if (type == NULL || (saw_error && type_specifiers != 0)) {
3010 atomic_type_kind_t atomic_type;
3012 /* match valid basic types */
3013 switch (type_specifiers) {
3014 case SPECIFIER_VOID:
3015 atomic_type = ATOMIC_TYPE_VOID;
3017 case SPECIFIER_WCHAR_T:
3018 atomic_type = ATOMIC_TYPE_WCHAR_T;
3020 case SPECIFIER_CHAR:
3021 atomic_type = ATOMIC_TYPE_CHAR;
3023 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3024 atomic_type = ATOMIC_TYPE_SCHAR;
3026 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3027 atomic_type = ATOMIC_TYPE_UCHAR;
3029 case SPECIFIER_SHORT:
3030 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3031 case SPECIFIER_SHORT | SPECIFIER_INT:
3032 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3033 atomic_type = ATOMIC_TYPE_SHORT;
3035 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3036 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3037 atomic_type = ATOMIC_TYPE_USHORT;
3040 case SPECIFIER_SIGNED:
3041 case SPECIFIER_SIGNED | SPECIFIER_INT:
3042 atomic_type = ATOMIC_TYPE_INT;
3044 case SPECIFIER_UNSIGNED:
3045 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3046 atomic_type = ATOMIC_TYPE_UINT;
3048 case SPECIFIER_LONG:
3049 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3050 case SPECIFIER_LONG | SPECIFIER_INT:
3051 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3052 atomic_type = ATOMIC_TYPE_LONG;
3054 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3055 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3056 atomic_type = ATOMIC_TYPE_ULONG;
3059 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3060 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3061 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3062 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3064 atomic_type = ATOMIC_TYPE_LONGLONG;
3065 goto warn_about_long_long;
3067 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3068 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3070 atomic_type = ATOMIC_TYPE_ULONGLONG;
3071 warn_about_long_long:
3072 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3075 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3076 atomic_type = unsigned_int8_type_kind;
3079 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3080 atomic_type = unsigned_int16_type_kind;
3083 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3084 atomic_type = unsigned_int32_type_kind;
3087 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3088 atomic_type = unsigned_int64_type_kind;
3091 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3092 atomic_type = unsigned_int128_type_kind;
3095 case SPECIFIER_INT8:
3096 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3097 atomic_type = int8_type_kind;
3100 case SPECIFIER_INT16:
3101 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3102 atomic_type = int16_type_kind;
3105 case SPECIFIER_INT32:
3106 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3107 atomic_type = int32_type_kind;
3110 case SPECIFIER_INT64:
3111 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3112 atomic_type = int64_type_kind;
3115 case SPECIFIER_INT128:
3116 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3117 atomic_type = int128_type_kind;
3120 case SPECIFIER_FLOAT:
3121 atomic_type = ATOMIC_TYPE_FLOAT;
3123 case SPECIFIER_DOUBLE:
3124 atomic_type = ATOMIC_TYPE_DOUBLE;
3126 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3127 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3129 case SPECIFIER_BOOL:
3130 atomic_type = ATOMIC_TYPE_BOOL;
3132 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3133 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3134 atomic_type = ATOMIC_TYPE_FLOAT;
3136 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3137 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3138 atomic_type = ATOMIC_TYPE_DOUBLE;
3140 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3141 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3142 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3145 /* invalid specifier combination, give an error message */
3146 source_position_t const* const pos = &specifiers->source_position;
3147 if (type_specifiers == 0) {
3149 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3150 if (!(c_mode & _CXX) && !strict_mode) {
3151 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3152 atomic_type = ATOMIC_TYPE_INT;
3155 errorf(pos, "no type specifiers given in declaration");
3158 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3159 (type_specifiers & SPECIFIER_UNSIGNED)) {
3160 errorf(pos, "signed and unsigned specifiers given");
3161 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3162 errorf(pos, "only integer types can be signed or unsigned");
3164 errorf(pos, "multiple datatypes in declaration");
3170 if (type_specifiers & SPECIFIER_COMPLEX) {
3171 type = allocate_type_zero(TYPE_COMPLEX);
3172 type->complex.akind = atomic_type;
3173 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3174 type = allocate_type_zero(TYPE_IMAGINARY);
3175 type->imaginary.akind = atomic_type;
3177 type = allocate_type_zero(TYPE_ATOMIC);
3178 type->atomic.akind = atomic_type;
3181 } else if (type_specifiers != 0) {
3182 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3185 /* FIXME: check type qualifiers here */
3186 type->base.qualifiers = qualifiers;
3189 type = identify_new_type(type);
3191 type = typehash_insert(type);
3194 if (specifiers->attributes != NULL)
3195 type = handle_type_attributes(specifiers->attributes, type);
3196 specifiers->type = type;
3200 specifiers->type = type_error_type;
3203 static type_qualifiers_t parse_type_qualifiers(void)
3205 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3208 switch (token.type) {
3209 /* type qualifiers */
3210 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3211 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3212 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3213 /* microsoft extended type modifiers */
3214 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3215 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3216 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3217 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3218 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3227 * Parses an K&R identifier list
3229 static void parse_identifier_list(scope_t *scope)
3232 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3233 entity->base.source_position = token.source_position;
3234 /* a K&R parameter has no type, yet */
3238 append_entity(scope, entity);
3239 } while (next_if(',') && token.type == T_IDENTIFIER);
3242 static entity_t *parse_parameter(void)
3244 declaration_specifiers_t specifiers;
3245 parse_declaration_specifiers(&specifiers);
3247 entity_t *entity = parse_declarator(&specifiers,
3248 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3249 anonymous_entity = NULL;
3253 static void semantic_parameter_incomplete(const entity_t *entity)
3255 assert(entity->kind == ENTITY_PARAMETER);
3257 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3258 * list in a function declarator that is part of a
3259 * definition of that function shall not have
3260 * incomplete type. */
3261 type_t *type = skip_typeref(entity->declaration.type);
3262 if (is_type_incomplete(type)) {
3263 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3267 static bool has_parameters(void)
3269 /* func(void) is not a parameter */
3270 if (token.type == T_IDENTIFIER) {
3271 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3274 if (entity->kind != ENTITY_TYPEDEF)
3276 if (skip_typeref(entity->typedefe.type) != type_void)
3278 } else if (token.type != T_void) {
3281 if (look_ahead(1)->type != ')')
3288 * Parses function type parameters (and optionally creates variable_t entities
3289 * for them in a scope)
3291 static void parse_parameters(function_type_t *type, scope_t *scope)
3294 add_anchor_token(')');
3295 int saved_comma_state = save_and_reset_anchor_state(',');
3297 if (token.type == T_IDENTIFIER &&
3298 !is_typedef_symbol(token.symbol)) {
3299 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3300 if (la1_type == ',' || la1_type == ')') {
3301 type->kr_style_parameters = true;
3302 parse_identifier_list(scope);
3303 goto parameters_finished;
3307 if (token.type == ')') {
3308 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3309 if (!(c_mode & _CXX))
3310 type->unspecified_parameters = true;
3311 } else if (has_parameters()) {
3312 function_parameter_t **anchor = &type->parameters;
3314 switch (token.type) {
3317 type->variadic = true;
3318 goto parameters_finished;
3323 entity_t *entity = parse_parameter();
3324 if (entity->kind == ENTITY_TYPEDEF) {
3325 errorf(&entity->base.source_position,
3326 "typedef not allowed as function parameter");
3329 assert(is_declaration(entity));
3331 semantic_parameter_incomplete(entity);
3333 function_parameter_t *const parameter =
3334 allocate_parameter(entity->declaration.type);
3336 if (scope != NULL) {
3337 append_entity(scope, entity);
3340 *anchor = parameter;
3341 anchor = ¶meter->next;
3346 goto parameters_finished;
3348 } while (next_if(','));
3351 parameters_finished:
3352 rem_anchor_token(')');
3353 expect(')', end_error);
3356 restore_anchor_state(',', saved_comma_state);
3359 typedef enum construct_type_kind_t {
3362 CONSTRUCT_REFERENCE,
3365 } construct_type_kind_t;
3367 typedef union construct_type_t construct_type_t;
3369 typedef struct construct_type_base_t {
3370 construct_type_kind_t kind;
3371 source_position_t pos;
3372 construct_type_t *next;
3373 } construct_type_base_t;
3375 typedef struct parsed_pointer_t {
3376 construct_type_base_t base;
3377 type_qualifiers_t type_qualifiers;
3378 variable_t *base_variable; /**< MS __based extension. */
3381 typedef struct parsed_reference_t {
3382 construct_type_base_t base;
3383 } parsed_reference_t;
3385 typedef struct construct_function_type_t {
3386 construct_type_base_t base;
3387 type_t *function_type;
3388 } construct_function_type_t;
3390 typedef struct parsed_array_t {
3391 construct_type_base_t base;
3392 type_qualifiers_t type_qualifiers;
3398 union construct_type_t {
3399 construct_type_kind_t kind;
3400 construct_type_base_t base;
3401 parsed_pointer_t pointer;
3402 parsed_reference_t reference;
3403 construct_function_type_t function;
3404 parsed_array_t array;
3407 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3409 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3410 memset(cons, 0, size);
3412 cons->base.pos = *HERE;
3417 static construct_type_t *parse_pointer_declarator(void)
3419 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3421 cons->pointer.type_qualifiers = parse_type_qualifiers();
3422 //cons->pointer.base_variable = base_variable;
3427 /* ISO/IEC 14882:1998(E) §8.3.2 */
3428 static construct_type_t *parse_reference_declarator(void)
3430 if (!(c_mode & _CXX))
3431 errorf(HERE, "references are only available for C++");
3433 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3440 static construct_type_t *parse_array_declarator(void)
3442 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3443 parsed_array_t *const array = &cons->array;
3446 add_anchor_token(']');
3448 bool is_static = next_if(T_static);
3450 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3453 is_static = next_if(T_static);
3455 array->type_qualifiers = type_qualifiers;
3456 array->is_static = is_static;
3458 expression_t *size = NULL;
3459 if (token.type == '*' && look_ahead(1)->type == ']') {
3460 array->is_variable = true;
3462 } else if (token.type != ']') {
3463 size = parse_assignment_expression();
3465 /* §6.7.5.2:1 Array size must have integer type */
3466 type_t *const orig_type = size->base.type;
3467 type_t *const type = skip_typeref(orig_type);
3468 if (!is_type_integer(type) && is_type_valid(type)) {
3469 errorf(&size->base.source_position,
3470 "array size '%E' must have integer type but has type '%T'",
3475 mark_vars_read(size, NULL);
3478 if (is_static && size == NULL)
3479 errorf(&array->base.pos, "static array parameters require a size");
3481 rem_anchor_token(']');
3482 expect(']', end_error);
3489 static construct_type_t *parse_function_declarator(scope_t *scope)
3491 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3493 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3494 function_type_t *ftype = &type->function;
3496 ftype->linkage = current_linkage;
3497 ftype->calling_convention = CC_DEFAULT;
3499 parse_parameters(ftype, scope);
3501 cons->function.function_type = type;
3506 typedef struct parse_declarator_env_t {
3507 bool may_be_abstract : 1;
3508 bool must_be_abstract : 1;
3509 decl_modifiers_t modifiers;
3511 source_position_t source_position;
3513 attribute_t *attributes;
3514 } parse_declarator_env_t;
3517 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3519 /* construct a single linked list of construct_type_t's which describe
3520 * how to construct the final declarator type */
3521 construct_type_t *first = NULL;
3522 construct_type_t **anchor = &first;
3524 env->attributes = parse_attributes(env->attributes);
3527 construct_type_t *type;
3528 //variable_t *based = NULL; /* MS __based extension */
3529 switch (token.type) {
3531 type = parse_reference_declarator();
3535 panic("based not supported anymore");
3540 type = parse_pointer_declarator();
3544 goto ptr_operator_end;
3548 anchor = &type->base.next;
3550 /* TODO: find out if this is correct */
3551 env->attributes = parse_attributes(env->attributes);
3555 construct_type_t *inner_types = NULL;
3557 switch (token.type) {
3559 if (env->must_be_abstract) {
3560 errorf(HERE, "no identifier expected in typename");
3562 env->symbol = token.symbol;
3563 env->source_position = token.source_position;
3569 /* Parenthesized declarator or function declarator? */
3570 token_t const *const la1 = look_ahead(1);
3571 switch (la1->type) {
3573 if (is_typedef_symbol(la1->symbol)) {
3575 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3576 * interpreted as ``function with no parameter specification'', rather
3577 * than redundant parentheses around the omitted identifier. */
3579 /* Function declarator. */
3580 if (!env->may_be_abstract) {
3581 errorf(HERE, "function declarator must have a name");
3588 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3589 /* Paranthesized declarator. */
3591 add_anchor_token(')');
3592 inner_types = parse_inner_declarator(env);
3593 if (inner_types != NULL) {
3594 /* All later declarators only modify the return type */
3595 env->must_be_abstract = true;
3597 rem_anchor_token(')');
3598 expect(')', end_error);
3606 if (env->may_be_abstract)
3608 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3613 construct_type_t **const p = anchor;
3616 construct_type_t *type;
3617 switch (token.type) {
3619 scope_t *scope = NULL;
3620 if (!env->must_be_abstract) {
3621 scope = &env->parameters;
3624 type = parse_function_declarator(scope);
3628 type = parse_array_declarator();
3631 goto declarator_finished;
3634 /* insert in the middle of the list (at p) */
3635 type->base.next = *p;
3638 anchor = &type->base.next;
3641 declarator_finished:
3642 /* append inner_types at the end of the list, we don't to set anchor anymore
3643 * as it's not needed anymore */
3644 *anchor = inner_types;
3651 static type_t *construct_declarator_type(construct_type_t *construct_list,
3654 construct_type_t *iter = construct_list;
3655 for (; iter != NULL; iter = iter->base.next) {
3656 source_position_t const* const pos = &iter->base.pos;
3657 switch (iter->kind) {
3658 case CONSTRUCT_INVALID:
3660 case CONSTRUCT_FUNCTION: {
3661 construct_function_type_t *function = &iter->function;
3662 type_t *function_type = function->function_type;
3664 function_type->function.return_type = type;
3666 type_t *skipped_return_type = skip_typeref(type);
3668 if (is_type_function(skipped_return_type)) {
3669 errorf(pos, "function returning function is not allowed");
3670 } else if (is_type_array(skipped_return_type)) {
3671 errorf(pos, "function returning array is not allowed");
3673 if (skipped_return_type->base.qualifiers != 0) {
3674 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3678 /* The function type was constructed earlier. Freeing it here will
3679 * destroy other types. */
3680 type = typehash_insert(function_type);
3684 case CONSTRUCT_POINTER: {
3685 if (is_type_reference(skip_typeref(type)))
3686 errorf(pos, "cannot declare a pointer to reference");
3688 parsed_pointer_t *pointer = &iter->pointer;
3689 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3693 case CONSTRUCT_REFERENCE:
3694 if (is_type_reference(skip_typeref(type)))
3695 errorf(pos, "cannot declare a reference to reference");
3697 type = make_reference_type(type);
3700 case CONSTRUCT_ARRAY: {
3701 if (is_type_reference(skip_typeref(type)))
3702 errorf(pos, "cannot declare an array of references");
3704 parsed_array_t *array = &iter->array;
3705 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3707 expression_t *size_expression = array->size;
3708 if (size_expression != NULL) {
3710 = create_implicit_cast(size_expression, type_size_t);
3713 array_type->base.qualifiers = array->type_qualifiers;
3714 array_type->array.element_type = type;
3715 array_type->array.is_static = array->is_static;
3716 array_type->array.is_variable = array->is_variable;
3717 array_type->array.size_expression = size_expression;
3719 if (size_expression != NULL) {
3720 switch (is_constant_expression(size_expression)) {
3721 case EXPR_CLASS_CONSTANT: {
3722 long const size = fold_constant_to_int(size_expression);
3723 array_type->array.size = size;
3724 array_type->array.size_constant = true;
3725 /* §6.7.5.2:1 If the expression is a constant expression,
3726 * it shall have a value greater than zero. */
3728 errorf(&size_expression->base.source_position,
3729 "size of array must be greater than zero");
3730 } else if (size == 0 && !GNU_MODE) {
3731 errorf(&size_expression->base.source_position,
3732 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3737 case EXPR_CLASS_VARIABLE:
3738 array_type->array.is_vla = true;
3741 case EXPR_CLASS_ERROR:
3746 type_t *skipped_type = skip_typeref(type);
3748 if (is_type_incomplete(skipped_type)) {
3749 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3750 } else if (is_type_function(skipped_type)) {
3751 errorf(pos, "array of functions is not allowed");
3753 type = identify_new_type(array_type);
3757 internal_errorf(pos, "invalid type construction found");
3763 static type_t *automatic_type_conversion(type_t *orig_type);
3765 static type_t *semantic_parameter(const source_position_t *pos,
3767 const declaration_specifiers_t *specifiers,
3768 entity_t const *const param)
3770 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3771 * shall be adjusted to ``qualified pointer to type'',
3773 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3774 * type'' shall be adjusted to ``pointer to function
3775 * returning type'', as in 6.3.2.1. */
3776 type = automatic_type_conversion(type);
3778 if (specifiers->is_inline && is_type_valid(type)) {
3779 errorf(pos, "'%N' declared 'inline'", param);
3782 /* §6.9.1:6 The declarations in the declaration list shall contain
3783 * no storage-class specifier other than register and no
3784 * initializations. */
3785 if (specifiers->thread_local || (
3786 specifiers->storage_class != STORAGE_CLASS_NONE &&
3787 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3789 errorf(pos, "invalid storage class for '%N'", param);
3792 /* delay test for incomplete type, because we might have (void)
3793 * which is legal but incomplete... */
3798 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3799 declarator_flags_t flags)
3801 parse_declarator_env_t env;
3802 memset(&env, 0, sizeof(env));
3803 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3805 construct_type_t *construct_type = parse_inner_declarator(&env);
3807 construct_declarator_type(construct_type, specifiers->type);
3808 type_t *type = skip_typeref(orig_type);
3810 if (construct_type != NULL) {
3811 obstack_free(&temp_obst, construct_type);
3814 attribute_t *attributes = parse_attributes(env.attributes);
3815 /* append (shared) specifier attribute behind attributes of this
3817 attribute_t **anchor = &attributes;
3818 while (*anchor != NULL)
3819 anchor = &(*anchor)->next;
3820 *anchor = specifiers->attributes;
3823 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3824 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3825 entity->base.source_position = env.source_position;
3826 entity->typedefe.type = orig_type;
3828 if (anonymous_entity != NULL) {
3829 if (is_type_compound(type)) {
3830 assert(anonymous_entity->compound.alias == NULL);
3831 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3832 anonymous_entity->kind == ENTITY_UNION);
3833 anonymous_entity->compound.alias = entity;
3834 anonymous_entity = NULL;
3835 } else if (is_type_enum(type)) {
3836 assert(anonymous_entity->enume.alias == NULL);
3837 assert(anonymous_entity->kind == ENTITY_ENUM);
3838 anonymous_entity->enume.alias = entity;
3839 anonymous_entity = NULL;
3843 /* create a declaration type entity */
3844 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3845 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3847 if (env.symbol != NULL) {
3848 if (specifiers->is_inline && is_type_valid(type)) {
3849 errorf(&env.source_position,
3850 "compound member '%Y' declared 'inline'", env.symbol);
3853 if (specifiers->thread_local ||
3854 specifiers->storage_class != STORAGE_CLASS_NONE) {
3855 errorf(&env.source_position,
3856 "compound member '%Y' must have no storage class",
3860 } else if (flags & DECL_IS_PARAMETER) {
3861 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3862 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3863 } else if (is_type_function(type)) {
3864 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3865 entity->function.is_inline = specifiers->is_inline;
3866 entity->function.elf_visibility = default_visibility;
3867 entity->function.parameters = env.parameters;
3869 if (env.symbol != NULL) {
3870 /* this needs fixes for C++ */
3871 bool in_function_scope = current_function != NULL;
3873 if (specifiers->thread_local || (
3874 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3875 specifiers->storage_class != STORAGE_CLASS_NONE &&
3876 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3878 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3882 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3883 entity->variable.elf_visibility = default_visibility;
3884 entity->variable.thread_local = specifiers->thread_local;
3886 if (env.symbol != NULL) {
3887 if (specifiers->is_inline && is_type_valid(type)) {
3888 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3891 bool invalid_storage_class = false;
3892 if (current_scope == file_scope) {
3893 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3894 specifiers->storage_class != STORAGE_CLASS_NONE &&
3895 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3896 invalid_storage_class = true;
3899 if (specifiers->thread_local &&
3900 specifiers->storage_class == STORAGE_CLASS_NONE) {
3901 invalid_storage_class = true;
3904 if (invalid_storage_class) {
3905 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3910 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3911 entity->declaration.type = orig_type;
3912 entity->declaration.alignment = get_type_alignment(orig_type);
3913 entity->declaration.modifiers = env.modifiers;
3914 entity->declaration.attributes = attributes;
3916 storage_class_t storage_class = specifiers->storage_class;
3917 entity->declaration.declared_storage_class = storage_class;
3919 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3920 storage_class = STORAGE_CLASS_AUTO;
3921 entity->declaration.storage_class = storage_class;
3924 if (attributes != NULL) {
3925 handle_entity_attributes(attributes, entity);
3931 static type_t *parse_abstract_declarator(type_t *base_type)
3933 parse_declarator_env_t env;
3934 memset(&env, 0, sizeof(env));
3935 env.may_be_abstract = true;
3936 env.must_be_abstract = true;
3938 construct_type_t *construct_type = parse_inner_declarator(&env);
3940 type_t *result = construct_declarator_type(construct_type, base_type);
3941 if (construct_type != NULL) {
3942 obstack_free(&temp_obst, construct_type);
3944 result = handle_type_attributes(env.attributes, result);
3950 * Check if the declaration of main is suspicious. main should be a
3951 * function with external linkage, returning int, taking either zero
3952 * arguments, two, or three arguments of appropriate types, ie.
3954 * int main([ int argc, char **argv [, char **env ] ]).
3956 * @param decl the declaration to check
3957 * @param type the function type of the declaration
3959 static void check_main(const entity_t *entity)
3961 const source_position_t *pos = &entity->base.source_position;
3962 if (entity->kind != ENTITY_FUNCTION) {
3963 warningf(WARN_MAIN, pos, "'main' is not a function");
3967 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3968 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3971 type_t *type = skip_typeref(entity->declaration.type);
3972 assert(is_type_function(type));
3974 function_type_t const *const func_type = &type->function;
3975 type_t *const ret_type = func_type->return_type;
3976 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3977 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3979 const function_parameter_t *parm = func_type->parameters;
3981 type_t *const first_type = skip_typeref(parm->type);
3982 type_t *const first_type_unqual = get_unqualified_type(first_type);
3983 if (!types_compatible(first_type_unqual, type_int)) {
3984 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3988 type_t *const second_type = skip_typeref(parm->type);
3989 type_t *const second_type_unqual
3990 = get_unqualified_type(second_type);
3991 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
3992 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
3996 type_t *const third_type = skip_typeref(parm->type);
3997 type_t *const third_type_unqual
3998 = get_unqualified_type(third_type);
3999 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4000 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
4004 goto warn_arg_count;
4008 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4014 * Check if a symbol is the equal to "main".
4016 static bool is_sym_main(const symbol_t *const sym)
4018 return strcmp(sym->string, "main") == 0;
4021 static void error_redefined_as_different_kind(const source_position_t *pos,
4022 const entity_t *old, entity_kind_t new_kind)
4024 char const *const what = get_entity_kind_name(new_kind);
4025 source_position_t const *const ppos = &old->base.source_position;
4026 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4029 static bool is_entity_valid(entity_t *const ent)
4031 if (is_declaration(ent)) {
4032 return is_type_valid(skip_typeref(ent->declaration.type));
4033 } else if (ent->kind == ENTITY_TYPEDEF) {
4034 return is_type_valid(skip_typeref(ent->typedefe.type));
4039 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4041 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4042 if (attributes_equal(tattr, attr))
4049 * test wether new_list contains any attributes not included in old_list
4051 static bool has_new_attributes(const attribute_t *old_list,
4052 const attribute_t *new_list)
4054 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4055 if (!contains_attribute(old_list, attr))
4062 * Merge in attributes from an attribute list (probably from a previous
4063 * declaration with the same name). Warning: destroys the old structure
4064 * of the attribute list - don't reuse attributes after this call.
4066 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4069 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4071 if (contains_attribute(decl->attributes, attr))
4074 /* move attribute to new declarations attributes list */
4075 attr->next = decl->attributes;
4076 decl->attributes = attr;
4081 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4082 * for various problems that occur for multiple definitions
4084 entity_t *record_entity(entity_t *entity, const bool is_definition)
4086 const symbol_t *const symbol = entity->base.symbol;
4087 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4088 const source_position_t *pos = &entity->base.source_position;
4090 /* can happen in error cases */
4094 entity_t *const previous_entity = get_entity(symbol, namespc);
4095 /* pushing the same entity twice will break the stack structure */
4096 assert(previous_entity != entity);
4098 if (entity->kind == ENTITY_FUNCTION) {
4099 type_t *const orig_type = entity->declaration.type;
4100 type_t *const type = skip_typeref(orig_type);
4102 assert(is_type_function(type));
4103 if (type->function.unspecified_parameters &&
4104 previous_entity == NULL &&
4105 !entity->declaration.implicit) {
4106 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4109 if (current_scope == file_scope && is_sym_main(symbol)) {
4114 if (is_declaration(entity) &&
4115 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4116 current_scope != file_scope &&
4117 !entity->declaration.implicit) {
4118 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4121 if (previous_entity != NULL) {
4122 source_position_t const *const ppos = &previous_entity->base.source_position;
4124 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4125 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4126 assert(previous_entity->kind == ENTITY_PARAMETER);
4127 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4131 if (previous_entity->base.parent_scope == current_scope) {
4132 if (previous_entity->kind != entity->kind) {
4133 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4134 error_redefined_as_different_kind(pos, previous_entity,
4139 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4140 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4143 if (previous_entity->kind == ENTITY_TYPEDEF) {
4144 /* TODO: C++ allows this for exactly the same type */
4145 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4149 /* at this point we should have only VARIABLES or FUNCTIONS */
4150 assert(is_declaration(previous_entity) && is_declaration(entity));
4152 declaration_t *const prev_decl = &previous_entity->declaration;
4153 declaration_t *const decl = &entity->declaration;
4155 /* can happen for K&R style declarations */
4156 if (prev_decl->type == NULL &&
4157 previous_entity->kind == ENTITY_PARAMETER &&
4158 entity->kind == ENTITY_PARAMETER) {
4159 prev_decl->type = decl->type;
4160 prev_decl->storage_class = decl->storage_class;
4161 prev_decl->declared_storage_class = decl->declared_storage_class;
4162 prev_decl->modifiers = decl->modifiers;
4163 return previous_entity;
4166 type_t *const type = skip_typeref(decl->type);
4167 type_t *const prev_type = skip_typeref(prev_decl->type);
4169 if (!types_compatible(type, prev_type)) {
4170 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4172 unsigned old_storage_class = prev_decl->storage_class;
4174 if (is_definition &&
4176 !(prev_decl->modifiers & DM_USED) &&
4177 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4178 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4181 storage_class_t new_storage_class = decl->storage_class;
4183 /* pretend no storage class means extern for function
4184 * declarations (except if the previous declaration is neither
4185 * none nor extern) */
4186 if (entity->kind == ENTITY_FUNCTION) {
4187 /* the previous declaration could have unspecified parameters or
4188 * be a typedef, so use the new type */
4189 if (prev_type->function.unspecified_parameters || is_definition)
4190 prev_decl->type = type;
4192 switch (old_storage_class) {
4193 case STORAGE_CLASS_NONE:
4194 old_storage_class = STORAGE_CLASS_EXTERN;
4197 case STORAGE_CLASS_EXTERN:
4198 if (is_definition) {
4199 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4200 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4202 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4203 new_storage_class = STORAGE_CLASS_EXTERN;
4210 } else if (is_type_incomplete(prev_type)) {
4211 prev_decl->type = type;
4214 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4215 new_storage_class == STORAGE_CLASS_EXTERN) {
4217 warn_redundant_declaration: ;
4219 = has_new_attributes(prev_decl->attributes,
4221 if (has_new_attrs) {
4222 merge_in_attributes(decl, prev_decl->attributes);
4223 } else if (!is_definition &&
4224 is_type_valid(prev_type) &&
4225 strcmp(ppos->input_name, "<builtin>") != 0) {
4226 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4228 } else if (current_function == NULL) {
4229 if (old_storage_class != STORAGE_CLASS_STATIC &&
4230 new_storage_class == STORAGE_CLASS_STATIC) {
4231 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4232 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4233 prev_decl->storage_class = STORAGE_CLASS_NONE;
4234 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4236 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4238 goto error_redeclaration;
4239 goto warn_redundant_declaration;
4241 } else if (is_type_valid(prev_type)) {
4242 if (old_storage_class == new_storage_class) {
4243 error_redeclaration:
4244 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4246 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4251 prev_decl->modifiers |= decl->modifiers;
4252 if (entity->kind == ENTITY_FUNCTION) {
4253 previous_entity->function.is_inline |= entity->function.is_inline;
4255 return previous_entity;
4259 if (is_warn_on(why = WARN_SHADOW) ||
4260 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4261 char const *const what = get_entity_kind_name(previous_entity->kind);
4262 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4266 if (entity->kind == ENTITY_FUNCTION) {
4267 if (is_definition &&
4268 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4269 !is_sym_main(symbol)) {
4270 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4271 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4273 goto warn_missing_declaration;
4276 } else if (entity->kind == ENTITY_VARIABLE) {
4277 if (current_scope == file_scope &&
4278 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4279 !entity->declaration.implicit) {
4280 warn_missing_declaration:
4281 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4286 assert(entity->base.parent_scope == NULL);
4287 assert(current_scope != NULL);
4289 entity->base.parent_scope = current_scope;
4290 environment_push(entity);
4291 append_entity(current_scope, entity);
4296 static void parser_error_multiple_definition(entity_t *entity,
4297 const source_position_t *source_position)
4299 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4300 entity->base.symbol, &entity->base.source_position);
4303 static bool is_declaration_specifier(const token_t *token)
4305 switch (token->type) {
4309 return is_typedef_symbol(token->symbol);
4316 static void parse_init_declarator_rest(entity_t *entity)
4318 type_t *orig_type = type_error_type;
4320 if (entity->base.kind == ENTITY_TYPEDEF) {
4321 source_position_t const *const pos = &entity->base.source_position;
4322 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4324 assert(is_declaration(entity));
4325 orig_type = entity->declaration.type;
4328 type_t *type = skip_typeref(orig_type);
4330 if (entity->kind == ENTITY_VARIABLE
4331 && entity->variable.initializer != NULL) {
4332 parser_error_multiple_definition(entity, HERE);
4336 declaration_t *const declaration = &entity->declaration;
4337 bool must_be_constant = false;
4338 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4339 entity->base.parent_scope == file_scope) {
4340 must_be_constant = true;
4343 if (is_type_function(type)) {
4344 source_position_t const *const pos = &entity->base.source_position;
4345 errorf(pos, "'%N' is initialized like a variable", entity);
4346 orig_type = type_error_type;
4349 parse_initializer_env_t env;
4350 env.type = orig_type;
4351 env.must_be_constant = must_be_constant;
4352 env.entity = entity;
4353 current_init_decl = entity;
4355 initializer_t *initializer = parse_initializer(&env);
4356 current_init_decl = NULL;
4358 if (entity->kind == ENTITY_VARIABLE) {
4359 /* §6.7.5:22 array initializers for arrays with unknown size
4360 * determine the array type size */
4361 declaration->type = env.type;
4362 entity->variable.initializer = initializer;
4366 /* parse rest of a declaration without any declarator */
4367 static void parse_anonymous_declaration_rest(
4368 const declaration_specifiers_t *specifiers)
4371 anonymous_entity = NULL;
4373 source_position_t const *const pos = &specifiers->source_position;
4374 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4375 specifiers->thread_local) {
4376 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4379 type_t *type = specifiers->type;
4380 switch (type->kind) {
4381 case TYPE_COMPOUND_STRUCT:
4382 case TYPE_COMPOUND_UNION: {
4383 if (type->compound.compound->base.symbol == NULL) {
4384 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4393 warningf(WARN_OTHER, pos, "empty declaration");
4398 static void check_variable_type_complete(entity_t *ent)
4400 if (ent->kind != ENTITY_VARIABLE)
4403 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4404 * type for the object shall be complete [...] */
4405 declaration_t *decl = &ent->declaration;
4406 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4407 decl->storage_class == STORAGE_CLASS_STATIC)
4410 type_t *const type = skip_typeref(decl->type);
4411 if (!is_type_incomplete(type))
4414 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4415 * are given length one. */
4416 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4417 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4421 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4425 static void parse_declaration_rest(entity_t *ndeclaration,
4426 const declaration_specifiers_t *specifiers,
4427 parsed_declaration_func finished_declaration,
4428 declarator_flags_t flags)
4430 add_anchor_token(';');
4431 add_anchor_token(',');
4433 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4435 if (token.type == '=') {
4436 parse_init_declarator_rest(entity);
4437 } else if (entity->kind == ENTITY_VARIABLE) {
4438 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4439 * [...] where the extern specifier is explicitly used. */
4440 declaration_t *decl = &entity->declaration;
4441 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4442 type_t *type = decl->type;
4443 if (is_type_reference(skip_typeref(type))) {
4444 source_position_t const *const pos = &entity->base.source_position;
4445 errorf(pos, "reference '%#N' must be initialized", entity);
4450 check_variable_type_complete(entity);
4455 add_anchor_token('=');
4456 ndeclaration = parse_declarator(specifiers, flags);
4457 rem_anchor_token('=');
4459 expect(';', end_error);
4462 anonymous_entity = NULL;
4463 rem_anchor_token(';');
4464 rem_anchor_token(',');
4467 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4469 symbol_t *symbol = entity->base.symbol;
4473 assert(entity->base.namespc == NAMESPACE_NORMAL);
4474 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4475 if (previous_entity == NULL
4476 || previous_entity->base.parent_scope != current_scope) {
4477 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4482 if (is_definition) {
4483 errorf(HERE, "'%N' is initialised", entity);
4486 return record_entity(entity, false);
4489 static void parse_declaration(parsed_declaration_func finished_declaration,
4490 declarator_flags_t flags)
4492 add_anchor_token(';');
4493 declaration_specifiers_t specifiers;
4494 parse_declaration_specifiers(&specifiers);
4495 rem_anchor_token(';');
4497 if (token.type == ';') {
4498 parse_anonymous_declaration_rest(&specifiers);
4500 entity_t *entity = parse_declarator(&specifiers, flags);
4501 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4506 static type_t *get_default_promoted_type(type_t *orig_type)
4508 type_t *result = orig_type;
4510 type_t *type = skip_typeref(orig_type);
4511 if (is_type_integer(type)) {
4512 result = promote_integer(type);
4513 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4514 result = type_double;
4520 static void parse_kr_declaration_list(entity_t *entity)
4522 if (entity->kind != ENTITY_FUNCTION)
4525 type_t *type = skip_typeref(entity->declaration.type);
4526 assert(is_type_function(type));
4527 if (!type->function.kr_style_parameters)
4530 add_anchor_token('{');
4532 PUSH_SCOPE(&entity->function.parameters);
4534 entity_t *parameter = entity->function.parameters.entities;
4535 for ( ; parameter != NULL; parameter = parameter->base.next) {
4536 assert(parameter->base.parent_scope == NULL);
4537 parameter->base.parent_scope = current_scope;
4538 environment_push(parameter);
4541 /* parse declaration list */
4543 switch (token.type) {
4545 /* This covers symbols, which are no type, too, and results in
4546 * better error messages. The typical cases are misspelled type
4547 * names and missing includes. */
4549 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4559 /* update function type */
4560 type_t *new_type = duplicate_type(type);
4562 function_parameter_t *parameters = NULL;
4563 function_parameter_t **anchor = ¶meters;
4565 /* did we have an earlier prototype? */
4566 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4567 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4570 function_parameter_t *proto_parameter = NULL;
4571 if (proto_type != NULL) {
4572 type_t *proto_type_type = proto_type->declaration.type;
4573 proto_parameter = proto_type_type->function.parameters;
4574 /* If a K&R function definition has a variadic prototype earlier, then
4575 * make the function definition variadic, too. This should conform to
4576 * §6.7.5.3:15 and §6.9.1:8. */
4577 new_type->function.variadic = proto_type_type->function.variadic;
4579 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4581 new_type->function.unspecified_parameters = true;
4584 bool need_incompatible_warning = false;
4585 parameter = entity->function.parameters.entities;
4586 for (; parameter != NULL; parameter = parameter->base.next,
4588 proto_parameter == NULL ? NULL : proto_parameter->next) {
4589 if (parameter->kind != ENTITY_PARAMETER)
4592 type_t *parameter_type = parameter->declaration.type;
4593 if (parameter_type == NULL) {
4594 source_position_t const* const pos = ¶meter->base.source_position;
4596 errorf(pos, "no type specified for function '%N'", parameter);
4597 parameter_type = type_error_type;
4599 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4600 parameter_type = type_int;
4602 parameter->declaration.type = parameter_type;
4605 semantic_parameter_incomplete(parameter);
4607 /* we need the default promoted types for the function type */
4608 type_t *not_promoted = parameter_type;
4609 parameter_type = get_default_promoted_type(parameter_type);
4611 /* gcc special: if the type of the prototype matches the unpromoted
4612 * type don't promote */
4613 if (!strict_mode && proto_parameter != NULL) {
4614 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4615 type_t *promo_skip = skip_typeref(parameter_type);
4616 type_t *param_skip = skip_typeref(not_promoted);
4617 if (!types_compatible(proto_p_type, promo_skip)
4618 && types_compatible(proto_p_type, param_skip)) {
4620 need_incompatible_warning = true;
4621 parameter_type = not_promoted;
4624 function_parameter_t *const function_parameter
4625 = allocate_parameter(parameter_type);
4627 *anchor = function_parameter;
4628 anchor = &function_parameter->next;
4631 new_type->function.parameters = parameters;
4632 new_type = identify_new_type(new_type);
4634 if (need_incompatible_warning) {
4635 symbol_t const *const sym = entity->base.symbol;
4636 source_position_t const *const pos = &entity->base.source_position;
4637 source_position_t const *const ppos = &proto_type->base.source_position;
4638 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4640 entity->declaration.type = new_type;
4642 rem_anchor_token('{');
4645 static bool first_err = true;
4648 * When called with first_err set, prints the name of the current function,
4651 static void print_in_function(void)
4655 char const *const file = current_function->base.base.source_position.input_name;
4656 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4661 * Check if all labels are defined in the current function.
4662 * Check if all labels are used in the current function.
4664 static void check_labels(void)
4666 for (const goto_statement_t *goto_statement = goto_first;
4667 goto_statement != NULL;
4668 goto_statement = goto_statement->next) {
4669 /* skip computed gotos */
4670 if (goto_statement->expression != NULL)
4673 label_t *label = goto_statement->label;
4674 if (label->base.source_position.input_name == NULL) {
4675 print_in_function();
4676 source_position_t const *const pos = &goto_statement->base.source_position;
4677 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4681 if (is_warn_on(WARN_UNUSED_LABEL)) {
4682 for (const label_statement_t *label_statement = label_first;
4683 label_statement != NULL;
4684 label_statement = label_statement->next) {
4685 label_t *label = label_statement->label;
4687 if (! label->used) {
4688 print_in_function();
4689 source_position_t const *const pos = &label_statement->base.source_position;
4690 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4696 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4698 entity_t const *const end = last != NULL ? last->base.next : NULL;
4699 for (; entity != end; entity = entity->base.next) {
4700 if (!is_declaration(entity))
4703 declaration_t *declaration = &entity->declaration;
4704 if (declaration->implicit)
4707 if (!declaration->used) {
4708 print_in_function();
4709 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4710 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4711 print_in_function();
4712 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4717 static void check_unused_variables(statement_t *const stmt, void *const env)
4721 switch (stmt->kind) {
4722 case STATEMENT_DECLARATION: {
4723 declaration_statement_t const *const decls = &stmt->declaration;
4724 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4729 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4738 * Check declarations of current_function for unused entities.
4740 static void check_declarations(void)
4742 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4743 const scope_t *scope = ¤t_function->parameters;
4745 /* do not issue unused warnings for main */
4746 if (!is_sym_main(current_function->base.base.symbol)) {
4747 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4750 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4751 walk_statements(current_function->statement, check_unused_variables,
4756 static int determine_truth(expression_t const* const cond)
4759 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4760 fold_constant_to_bool(cond) ? 1 :
4764 static void check_reachable(statement_t *);
4765 static bool reaches_end;
4767 static bool expression_returns(expression_t const *const expr)
4769 switch (expr->kind) {
4771 expression_t const *const func = expr->call.function;
4772 if (func->kind == EXPR_REFERENCE) {
4773 entity_t *entity = func->reference.entity;
4774 if (entity->kind == ENTITY_FUNCTION
4775 && entity->declaration.modifiers & DM_NORETURN)
4779 if (!expression_returns(func))
4782 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4783 if (!expression_returns(arg->expression))
4790 case EXPR_REFERENCE:
4791 case EXPR_REFERENCE_ENUM_VALUE:
4793 case EXPR_STRING_LITERAL:
4794 case EXPR_WIDE_STRING_LITERAL:
4795 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4796 case EXPR_LABEL_ADDRESS:
4797 case EXPR_CLASSIFY_TYPE:
4798 case EXPR_SIZEOF: // TODO handle obscure VLA case
4801 case EXPR_BUILTIN_CONSTANT_P:
4802 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4807 case EXPR_STATEMENT: {
4808 bool old_reaches_end = reaches_end;
4809 reaches_end = false;
4810 check_reachable(expr->statement.statement);
4811 bool returns = reaches_end;
4812 reaches_end = old_reaches_end;
4816 case EXPR_CONDITIONAL:
4817 // TODO handle constant expression
4819 if (!expression_returns(expr->conditional.condition))
4822 if (expr->conditional.true_expression != NULL
4823 && expression_returns(expr->conditional.true_expression))
4826 return expression_returns(expr->conditional.false_expression);
4829 return expression_returns(expr->select.compound);
4831 case EXPR_ARRAY_ACCESS:
4833 expression_returns(expr->array_access.array_ref) &&
4834 expression_returns(expr->array_access.index);
4837 return expression_returns(expr->va_starte.ap);
4840 return expression_returns(expr->va_arge.ap);
4843 return expression_returns(expr->va_copye.src);
4845 EXPR_UNARY_CASES_MANDATORY
4846 return expression_returns(expr->unary.value);
4848 case EXPR_UNARY_THROW:
4852 // TODO handle constant lhs of && and ||
4854 expression_returns(expr->binary.left) &&
4855 expression_returns(expr->binary.right);
4861 panic("unhandled expression");
4864 static bool initializer_returns(initializer_t const *const init)
4866 switch (init->kind) {
4867 case INITIALIZER_VALUE:
4868 return expression_returns(init->value.value);
4870 case INITIALIZER_LIST: {
4871 initializer_t * const* i = init->list.initializers;
4872 initializer_t * const* const end = i + init->list.len;
4873 bool returns = true;
4874 for (; i != end; ++i) {
4875 if (!initializer_returns(*i))
4881 case INITIALIZER_STRING:
4882 case INITIALIZER_WIDE_STRING:
4883 case INITIALIZER_DESIGNATOR: // designators have no payload
4886 panic("unhandled initializer");
4889 static bool noreturn_candidate;
4891 static void check_reachable(statement_t *const stmt)
4893 if (stmt->base.reachable)
4895 if (stmt->kind != STATEMENT_DO_WHILE)
4896 stmt->base.reachable = true;
4898 statement_t *last = stmt;
4900 switch (stmt->kind) {
4901 case STATEMENT_INVALID:
4902 case STATEMENT_EMPTY:
4904 next = stmt->base.next;
4907 case STATEMENT_DECLARATION: {
4908 declaration_statement_t const *const decl = &stmt->declaration;
4909 entity_t const * ent = decl->declarations_begin;
4910 entity_t const *const last_decl = decl->declarations_end;
4912 for (;; ent = ent->base.next) {
4913 if (ent->kind == ENTITY_VARIABLE &&
4914 ent->variable.initializer != NULL &&
4915 !initializer_returns(ent->variable.initializer)) {
4918 if (ent == last_decl)
4922 next = stmt->base.next;
4926 case STATEMENT_COMPOUND:
4927 next = stmt->compound.statements;
4929 next = stmt->base.next;
4932 case STATEMENT_RETURN: {
4933 expression_t const *const val = stmt->returns.value;
4934 if (val == NULL || expression_returns(val))
4935 noreturn_candidate = false;
4939 case STATEMENT_IF: {
4940 if_statement_t const *const ifs = &stmt->ifs;
4941 expression_t const *const cond = ifs->condition;
4943 if (!expression_returns(cond))
4946 int const val = determine_truth(cond);
4949 check_reachable(ifs->true_statement);
4954 if (ifs->false_statement != NULL) {
4955 check_reachable(ifs->false_statement);
4959 next = stmt->base.next;
4963 case STATEMENT_SWITCH: {
4964 switch_statement_t const *const switchs = &stmt->switchs;
4965 expression_t const *const expr = switchs->expression;
4967 if (!expression_returns(expr))
4970 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4971 long const val = fold_constant_to_int(expr);
4972 case_label_statement_t * defaults = NULL;
4973 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4974 if (i->expression == NULL) {
4979 if (i->first_case <= val && val <= i->last_case) {
4980 check_reachable((statement_t*)i);
4985 if (defaults != NULL) {
4986 check_reachable((statement_t*)defaults);
4990 bool has_default = false;
4991 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4992 if (i->expression == NULL)
4995 check_reachable((statement_t*)i);
5002 next = stmt->base.next;
5006 case STATEMENT_EXPRESSION: {
5007 /* Check for noreturn function call */
5008 expression_t const *const expr = stmt->expression.expression;
5009 if (!expression_returns(expr))
5012 next = stmt->base.next;
5016 case STATEMENT_CONTINUE:
5017 for (statement_t *parent = stmt;;) {
5018 parent = parent->base.parent;
5019 if (parent == NULL) /* continue not within loop */
5023 switch (parent->kind) {
5024 case STATEMENT_WHILE: goto continue_while;
5025 case STATEMENT_DO_WHILE: goto continue_do_while;
5026 case STATEMENT_FOR: goto continue_for;
5032 case STATEMENT_BREAK:
5033 for (statement_t *parent = stmt;;) {
5034 parent = parent->base.parent;
5035 if (parent == NULL) /* break not within loop/switch */
5038 switch (parent->kind) {
5039 case STATEMENT_SWITCH:
5040 case STATEMENT_WHILE:
5041 case STATEMENT_DO_WHILE:
5044 next = parent->base.next;
5045 goto found_break_parent;
5053 case STATEMENT_GOTO:
5054 if (stmt->gotos.expression) {
5055 if (!expression_returns(stmt->gotos.expression))
5058 statement_t *parent = stmt->base.parent;
5059 if (parent == NULL) /* top level goto */
5063 next = stmt->gotos.label->statement;
5064 if (next == NULL) /* missing label */
5069 case STATEMENT_LABEL:
5070 next = stmt->label.statement;
5073 case STATEMENT_CASE_LABEL:
5074 next = stmt->case_label.statement;
5077 case STATEMENT_WHILE: {
5078 while_statement_t const *const whiles = &stmt->whiles;
5079 expression_t const *const cond = whiles->condition;
5081 if (!expression_returns(cond))
5084 int const val = determine_truth(cond);
5087 check_reachable(whiles->body);
5092 next = stmt->base.next;
5096 case STATEMENT_DO_WHILE:
5097 next = stmt->do_while.body;
5100 case STATEMENT_FOR: {
5101 for_statement_t *const fors = &stmt->fors;
5103 if (fors->condition_reachable)
5105 fors->condition_reachable = true;
5107 expression_t const *const cond = fors->condition;
5112 } else if (expression_returns(cond)) {
5113 val = determine_truth(cond);
5119 check_reachable(fors->body);
5124 next = stmt->base.next;
5128 case STATEMENT_MS_TRY: {
5129 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5130 check_reachable(ms_try->try_statement);
5131 next = ms_try->final_statement;
5135 case STATEMENT_LEAVE: {
5136 statement_t *parent = stmt;
5138 parent = parent->base.parent;
5139 if (parent == NULL) /* __leave not within __try */
5142 if (parent->kind == STATEMENT_MS_TRY) {
5144 next = parent->ms_try.final_statement;
5152 panic("invalid statement kind");
5155 while (next == NULL) {
5156 next = last->base.parent;
5158 noreturn_candidate = false;
5160 type_t *const type = skip_typeref(current_function->base.type);
5161 assert(is_type_function(type));
5162 type_t *const ret = skip_typeref(type->function.return_type);
5163 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5164 is_type_valid(ret) &&
5165 !is_sym_main(current_function->base.base.symbol)) {
5166 source_position_t const *const pos = &stmt->base.source_position;
5167 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5172 switch (next->kind) {
5173 case STATEMENT_INVALID:
5174 case STATEMENT_EMPTY:
5175 case STATEMENT_DECLARATION:
5176 case STATEMENT_EXPRESSION:
5178 case STATEMENT_RETURN:
5179 case STATEMENT_CONTINUE:
5180 case STATEMENT_BREAK:
5181 case STATEMENT_GOTO:
5182 case STATEMENT_LEAVE:
5183 panic("invalid control flow in function");
5185 case STATEMENT_COMPOUND:
5186 if (next->compound.stmt_expr) {
5192 case STATEMENT_SWITCH:
5193 case STATEMENT_LABEL:
5194 case STATEMENT_CASE_LABEL:
5196 next = next->base.next;
5199 case STATEMENT_WHILE: {
5201 if (next->base.reachable)
5203 next->base.reachable = true;
5205 while_statement_t const *const whiles = &next->whiles;
5206 expression_t const *const cond = whiles->condition;
5208 if (!expression_returns(cond))
5211 int const val = determine_truth(cond);
5214 check_reachable(whiles->body);
5220 next = next->base.next;
5224 case STATEMENT_DO_WHILE: {
5226 if (next->base.reachable)
5228 next->base.reachable = true;
5230 do_while_statement_t const *const dw = &next->do_while;
5231 expression_t const *const cond = dw->condition;
5233 if (!expression_returns(cond))
5236 int const val = determine_truth(cond);
5239 check_reachable(dw->body);
5245 next = next->base.next;
5249 case STATEMENT_FOR: {
5251 for_statement_t *const fors = &next->fors;
5253 fors->step_reachable = true;
5255 if (fors->condition_reachable)
5257 fors->condition_reachable = true;
5259 expression_t const *const cond = fors->condition;
5264 } else if (expression_returns(cond)) {
5265 val = determine_truth(cond);
5271 check_reachable(fors->body);
5277 next = next->base.next;
5281 case STATEMENT_MS_TRY:
5283 next = next->ms_try.final_statement;
5288 check_reachable(next);
5291 static void check_unreachable(statement_t* const stmt, void *const env)
5295 switch (stmt->kind) {
5296 case STATEMENT_DO_WHILE:
5297 if (!stmt->base.reachable) {
5298 expression_t const *const cond = stmt->do_while.condition;
5299 if (determine_truth(cond) >= 0) {
5300 source_position_t const *const pos = &cond->base.source_position;
5301 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5306 case STATEMENT_FOR: {
5307 for_statement_t const* const fors = &stmt->fors;
5309 // if init and step are unreachable, cond is unreachable, too
5310 if (!stmt->base.reachable && !fors->step_reachable) {
5311 goto warn_unreachable;
5313 if (!stmt->base.reachable && fors->initialisation != NULL) {
5314 source_position_t const *const pos = &fors->initialisation->base.source_position;
5315 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5318 if (!fors->condition_reachable && fors->condition != NULL) {
5319 source_position_t const *const pos = &fors->condition->base.source_position;
5320 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5323 if (!fors->step_reachable && fors->step != NULL) {
5324 source_position_t const *const pos = &fors->step->base.source_position;
5325 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5331 case STATEMENT_COMPOUND:
5332 if (stmt->compound.statements != NULL)
5334 goto warn_unreachable;
5336 case STATEMENT_DECLARATION: {
5337 /* Only warn if there is at least one declarator with an initializer.
5338 * This typically occurs in switch statements. */
5339 declaration_statement_t const *const decl = &stmt->declaration;
5340 entity_t const * ent = decl->declarations_begin;
5341 entity_t const *const last = decl->declarations_end;
5343 for (;; ent = ent->base.next) {
5344 if (ent->kind == ENTITY_VARIABLE &&
5345 ent->variable.initializer != NULL) {
5346 goto warn_unreachable;
5356 if (!stmt->base.reachable) {
5357 source_position_t const *const pos = &stmt->base.source_position;
5358 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5364 static void parse_external_declaration(void)
5366 /* function-definitions and declarations both start with declaration
5368 add_anchor_token(';');
5369 declaration_specifiers_t specifiers;
5370 parse_declaration_specifiers(&specifiers);
5371 rem_anchor_token(';');
5373 /* must be a declaration */
5374 if (token.type == ';') {
5375 parse_anonymous_declaration_rest(&specifiers);
5379 add_anchor_token(',');
5380 add_anchor_token('=');
5381 add_anchor_token(';');
5382 add_anchor_token('{');
5384 /* declarator is common to both function-definitions and declarations */
5385 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5387 rem_anchor_token('{');
5388 rem_anchor_token(';');
5389 rem_anchor_token('=');
5390 rem_anchor_token(',');
5392 /* must be a declaration */
5393 switch (token.type) {
5397 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5402 /* must be a function definition */
5403 parse_kr_declaration_list(ndeclaration);
5405 if (token.type != '{') {
5406 parse_error_expected("while parsing function definition", '{', NULL);
5407 eat_until_matching_token(';');
5411 assert(is_declaration(ndeclaration));
5412 type_t *const orig_type = ndeclaration->declaration.type;
5413 type_t * type = skip_typeref(orig_type);
5415 if (!is_type_function(type)) {
5416 if (is_type_valid(type)) {
5417 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5423 source_position_t const *const pos = &ndeclaration->base.source_position;
5424 if (is_typeref(orig_type)) {
5426 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5429 if (is_type_compound(skip_typeref(type->function.return_type))) {
5430 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5432 if (type->function.unspecified_parameters) {
5433 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5435 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5438 /* §6.7.5.3:14 a function definition with () means no
5439 * parameters (and not unspecified parameters) */
5440 if (type->function.unspecified_parameters &&
5441 type->function.parameters == NULL) {
5442 type_t *copy = duplicate_type(type);
5443 copy->function.unspecified_parameters = false;
5444 type = identify_new_type(copy);
5446 ndeclaration->declaration.type = type;
5449 entity_t *const entity = record_entity(ndeclaration, true);
5450 assert(entity->kind == ENTITY_FUNCTION);
5451 assert(ndeclaration->kind == ENTITY_FUNCTION);
5453 function_t *const function = &entity->function;
5454 if (ndeclaration != entity) {
5455 function->parameters = ndeclaration->function.parameters;
5457 assert(is_declaration(entity));
5458 type = skip_typeref(entity->declaration.type);
5460 PUSH_SCOPE(&function->parameters);
5462 entity_t *parameter = function->parameters.entities;
5463 for (; parameter != NULL; parameter = parameter->base.next) {
5464 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5465 parameter->base.parent_scope = current_scope;
5467 assert(parameter->base.parent_scope == NULL
5468 || parameter->base.parent_scope == current_scope);
5469 parameter->base.parent_scope = current_scope;
5470 if (parameter->base.symbol == NULL) {
5471 errorf(¶meter->base.source_position, "parameter name omitted");
5474 environment_push(parameter);
5477 if (function->statement != NULL) {
5478 parser_error_multiple_definition(entity, HERE);
5481 /* parse function body */
5482 int label_stack_top = label_top();
5483 function_t *old_current_function = current_function;
5484 entity_t *old_current_entity = current_entity;
5485 current_function = function;
5486 current_entity = entity;
5490 goto_anchor = &goto_first;
5492 label_anchor = &label_first;
5494 statement_t *const body = parse_compound_statement(false);
5495 function->statement = body;
5498 check_declarations();
5499 if (is_warn_on(WARN_RETURN_TYPE) ||
5500 is_warn_on(WARN_UNREACHABLE_CODE) ||
5501 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5502 noreturn_candidate = true;
5503 check_reachable(body);
5504 if (is_warn_on(WARN_UNREACHABLE_CODE))
5505 walk_statements(body, check_unreachable, NULL);
5506 if (noreturn_candidate &&
5507 !(function->base.modifiers & DM_NORETURN)) {
5508 source_position_t const *const pos = &body->base.source_position;
5509 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5514 assert(current_function == function);
5515 assert(current_entity == entity);
5516 current_entity = old_current_entity;
5517 current_function = old_current_function;
5518 label_pop_to(label_stack_top);
5524 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5525 source_position_t *source_position,
5526 const symbol_t *symbol)
5528 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5530 type->bitfield.base_type = base_type;
5531 type->bitfield.size_expression = size;
5534 type_t *skipped_type = skip_typeref(base_type);
5535 if (!is_type_integer(skipped_type)) {
5536 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5539 bit_size = get_type_size(base_type) * 8;
5542 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5543 long v = fold_constant_to_int(size);
5544 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5547 errorf(source_position, "negative width in bit-field '%Y'",
5549 } else if (v == 0 && symbol != NULL) {
5550 errorf(source_position, "zero width for bit-field '%Y'",
5552 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5553 errorf(source_position, "width of '%Y' exceeds its type",
5556 type->bitfield.bit_size = v;
5563 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5565 entity_t *iter = compound->members.entities;
5566 for (; iter != NULL; iter = iter->base.next) {
5567 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5570 if (iter->base.symbol == symbol) {
5572 } else if (iter->base.symbol == NULL) {
5573 /* search in anonymous structs and unions */
5574 type_t *type = skip_typeref(iter->declaration.type);
5575 if (is_type_compound(type)) {
5576 if (find_compound_entry(type->compound.compound, symbol)
5587 static void check_deprecated(const source_position_t *source_position,
5588 const entity_t *entity)
5590 if (!is_declaration(entity))
5592 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5595 source_position_t const *const epos = &entity->base.source_position;
5596 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5598 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5600 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5605 static expression_t *create_select(const source_position_t *pos,
5607 type_qualifiers_t qualifiers,
5610 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5612 check_deprecated(pos, entry);
5614 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5615 select->select.compound = addr;
5616 select->select.compound_entry = entry;
5618 type_t *entry_type = entry->declaration.type;
5619 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5621 /* we always do the auto-type conversions; the & and sizeof parser contains
5622 * code to revert this! */
5623 select->base.type = automatic_type_conversion(res_type);
5624 if (res_type->kind == TYPE_BITFIELD) {
5625 select->base.type = res_type->bitfield.base_type;
5632 * Find entry with symbol in compound. Search anonymous structs and unions and
5633 * creates implicit select expressions for them.
5634 * Returns the adress for the innermost compound.
5636 static expression_t *find_create_select(const source_position_t *pos,
5638 type_qualifiers_t qualifiers,
5639 compound_t *compound, symbol_t *symbol)
5641 entity_t *iter = compound->members.entities;
5642 for (; iter != NULL; iter = iter->base.next) {
5643 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5646 symbol_t *iter_symbol = iter->base.symbol;
5647 if (iter_symbol == NULL) {
5648 type_t *type = iter->declaration.type;
5649 if (type->kind != TYPE_COMPOUND_STRUCT
5650 && type->kind != TYPE_COMPOUND_UNION)
5653 compound_t *sub_compound = type->compound.compound;
5655 if (find_compound_entry(sub_compound, symbol) == NULL)
5658 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5659 sub_addr->base.source_position = *pos;
5660 sub_addr->select.implicit = true;
5661 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5665 if (iter_symbol == symbol) {
5666 return create_select(pos, addr, qualifiers, iter);
5673 static void parse_compound_declarators(compound_t *compound,
5674 const declaration_specifiers_t *specifiers)
5679 if (token.type == ':') {
5680 source_position_t source_position = *HERE;
5683 type_t *base_type = specifiers->type;
5684 expression_t *size = parse_constant_expression();
5686 type_t *type = make_bitfield_type(base_type, size,
5687 &source_position, NULL);
5689 attribute_t *attributes = parse_attributes(NULL);
5690 attribute_t **anchor = &attributes;
5691 while (*anchor != NULL)
5692 anchor = &(*anchor)->next;
5693 *anchor = specifiers->attributes;
5695 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5696 entity->base.source_position = source_position;
5697 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5698 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5699 entity->declaration.type = type;
5700 entity->declaration.attributes = attributes;
5702 if (attributes != NULL) {
5703 handle_entity_attributes(attributes, entity);
5705 append_entity(&compound->members, entity);
5707 entity = parse_declarator(specifiers,
5708 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5709 source_position_t const *const pos = &entity->base.source_position;
5710 if (entity->kind == ENTITY_TYPEDEF) {
5711 errorf(pos, "typedef not allowed as compound member");
5713 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5715 /* make sure we don't define a symbol multiple times */
5716 symbol_t *symbol = entity->base.symbol;
5717 if (symbol != NULL) {
5718 entity_t *prev = find_compound_entry(compound, symbol);
5720 source_position_t const *const ppos = &prev->base.source_position;
5721 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5725 if (token.type == ':') {
5726 source_position_t source_position = *HERE;
5728 expression_t *size = parse_constant_expression();
5730 type_t *type = entity->declaration.type;
5731 type_t *bitfield_type = make_bitfield_type(type, size,
5732 &source_position, entity->base.symbol);
5734 attribute_t *attributes = parse_attributes(NULL);
5735 entity->declaration.type = bitfield_type;
5736 handle_entity_attributes(attributes, entity);
5738 type_t *orig_type = entity->declaration.type;
5739 type_t *type = skip_typeref(orig_type);
5740 if (is_type_function(type)) {
5741 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5742 } else if (is_type_incomplete(type)) {
5743 /* §6.7.2.1:16 flexible array member */
5744 if (!is_type_array(type) ||
5745 token.type != ';' ||
5746 look_ahead(1)->type != '}') {
5747 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5752 append_entity(&compound->members, entity);
5755 } while (next_if(','));
5756 expect(';', end_error);
5759 anonymous_entity = NULL;
5762 static void parse_compound_type_entries(compound_t *compound)
5765 add_anchor_token('}');
5768 switch (token.type) {
5770 case T___extension__:
5771 case T_IDENTIFIER: {
5773 declaration_specifiers_t specifiers;
5774 parse_declaration_specifiers(&specifiers);
5775 parse_compound_declarators(compound, &specifiers);
5781 rem_anchor_token('}');
5782 expect('}', end_error);
5785 compound->complete = true;
5791 static type_t *parse_typename(void)
5793 declaration_specifiers_t specifiers;
5794 parse_declaration_specifiers(&specifiers);
5795 if (specifiers.storage_class != STORAGE_CLASS_NONE
5796 || specifiers.thread_local) {
5797 /* TODO: improve error message, user does probably not know what a
5798 * storage class is...
5800 errorf(&specifiers.source_position, "typename must not have a storage class");
5803 type_t *result = parse_abstract_declarator(specifiers.type);
5811 typedef expression_t* (*parse_expression_function)(void);
5812 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5814 typedef struct expression_parser_function_t expression_parser_function_t;
5815 struct expression_parser_function_t {
5816 parse_expression_function parser;
5817 precedence_t infix_precedence;
5818 parse_expression_infix_function infix_parser;
5821 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5824 * Prints an error message if an expression was expected but not read
5826 static expression_t *expected_expression_error(void)
5828 /* skip the error message if the error token was read */
5829 if (token.type != T_ERROR) {
5830 errorf(HERE, "expected expression, got token %K", &token);
5834 return create_invalid_expression();
5837 static type_t *get_string_type(void)
5839 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5842 static type_t *get_wide_string_type(void)
5844 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5848 * Parse a string constant.
5850 static expression_t *parse_string_literal(void)
5852 source_position_t begin = token.source_position;
5853 string_t res = token.literal;
5854 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5857 while (token.type == T_STRING_LITERAL
5858 || token.type == T_WIDE_STRING_LITERAL) {
5859 warn_string_concat(&token.source_position);
5860 res = concat_strings(&res, &token.literal);
5862 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5865 expression_t *literal;
5867 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5868 literal->base.type = get_wide_string_type();
5870 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5871 literal->base.type = get_string_type();
5873 literal->base.source_position = begin;
5874 literal->literal.value = res;
5880 * Parse a boolean constant.
5882 static expression_t *parse_boolean_literal(bool value)
5884 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5885 literal->base.type = type_bool;
5886 literal->literal.value.begin = value ? "true" : "false";
5887 literal->literal.value.size = value ? 4 : 5;
5893 static void warn_traditional_suffix(void)
5895 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5898 static void check_integer_suffix(void)
5900 symbol_t *suffix = token.symbol;
5904 bool not_traditional = false;
5905 const char *c = suffix->string;
5906 if (*c == 'l' || *c == 'L') {
5909 not_traditional = true;
5911 if (*c == 'u' || *c == 'U') {
5914 } else if (*c == 'u' || *c == 'U') {
5915 not_traditional = true;
5918 } else if (*c == 'u' || *c == 'U') {
5919 not_traditional = true;
5921 if (*c == 'l' || *c == 'L') {
5929 errorf(&token.source_position,
5930 "invalid suffix '%s' on integer constant", suffix->string);
5931 } else if (not_traditional) {
5932 warn_traditional_suffix();
5936 static type_t *check_floatingpoint_suffix(void)
5938 symbol_t *suffix = token.symbol;
5939 type_t *type = type_double;
5943 bool not_traditional = false;
5944 const char *c = suffix->string;
5945 if (*c == 'f' || *c == 'F') {
5948 } else if (*c == 'l' || *c == 'L') {
5950 type = type_long_double;
5953 errorf(&token.source_position,
5954 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5955 } else if (not_traditional) {
5956 warn_traditional_suffix();
5963 * Parse an integer constant.
5965 static expression_t *parse_number_literal(void)
5967 expression_kind_t kind;
5970 switch (token.type) {
5972 kind = EXPR_LITERAL_INTEGER;
5973 check_integer_suffix();
5976 case T_INTEGER_OCTAL:
5977 kind = EXPR_LITERAL_INTEGER_OCTAL;
5978 check_integer_suffix();
5981 case T_INTEGER_HEXADECIMAL:
5982 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5983 check_integer_suffix();
5986 case T_FLOATINGPOINT:
5987 kind = EXPR_LITERAL_FLOATINGPOINT;
5988 type = check_floatingpoint_suffix();
5990 case T_FLOATINGPOINT_HEXADECIMAL:
5991 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
5992 type = check_floatingpoint_suffix();
5995 panic("unexpected token type in parse_number_literal");
5998 expression_t *literal = allocate_expression_zero(kind);
5999 literal->base.type = type;
6000 literal->literal.value = token.literal;
6001 literal->literal.suffix = token.symbol;
6004 /* integer type depends on the size of the number and the size
6005 * representable by the types. The backend/codegeneration has to determine
6008 determine_literal_type(&literal->literal);
6013 * Parse a character constant.
6015 static expression_t *parse_character_constant(void)
6017 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6018 literal->base.type = c_mode & _CXX ? type_char : type_int;
6019 literal->literal.value = token.literal;
6021 size_t len = literal->literal.value.size;
6023 if (!GNU_MODE && !(c_mode & _C99)) {
6024 errorf(HERE, "more than 1 character in character constant");
6026 literal->base.type = type_int;
6027 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6036 * Parse a wide character constant.
6038 static expression_t *parse_wide_character_constant(void)
6040 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6041 literal->base.type = type_int;
6042 literal->literal.value = token.literal;
6044 size_t len = wstrlen(&literal->literal.value);
6046 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6053 static entity_t *create_implicit_function(symbol_t *symbol,
6054 const source_position_t *source_position)
6056 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6057 ntype->function.return_type = type_int;
6058 ntype->function.unspecified_parameters = true;
6059 ntype->function.linkage = LINKAGE_C;
6060 type_t *type = identify_new_type(ntype);
6062 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6063 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6064 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6065 entity->declaration.type = type;
6066 entity->declaration.implicit = true;
6067 entity->base.source_position = *source_position;
6069 if (current_scope != NULL)
6070 record_entity(entity, false);
6076 * Performs automatic type cast as described in §6.3.2.1.
6078 * @param orig_type the original type
6080 static type_t *automatic_type_conversion(type_t *orig_type)
6082 type_t *type = skip_typeref(orig_type);
6083 if (is_type_array(type)) {
6084 array_type_t *array_type = &type->array;
6085 type_t *element_type = array_type->element_type;
6086 unsigned qualifiers = array_type->base.qualifiers;
6088 return make_pointer_type(element_type, qualifiers);
6091 if (is_type_function(type)) {
6092 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6099 * reverts the automatic casts of array to pointer types and function
6100 * to function-pointer types as defined §6.3.2.1
6102 type_t *revert_automatic_type_conversion(const expression_t *expression)
6104 switch (expression->kind) {
6105 case EXPR_REFERENCE: {
6106 entity_t *entity = expression->reference.entity;
6107 if (is_declaration(entity)) {
6108 return entity->declaration.type;
6109 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6110 return entity->enum_value.enum_type;
6112 panic("no declaration or enum in reference");
6117 entity_t *entity = expression->select.compound_entry;
6118 assert(is_declaration(entity));
6119 type_t *type = entity->declaration.type;
6120 return get_qualified_type(type,
6121 expression->base.type->base.qualifiers);
6124 case EXPR_UNARY_DEREFERENCE: {
6125 const expression_t *const value = expression->unary.value;
6126 type_t *const type = skip_typeref(value->base.type);
6127 if (!is_type_pointer(type))
6128 return type_error_type;
6129 return type->pointer.points_to;
6132 case EXPR_ARRAY_ACCESS: {
6133 const expression_t *array_ref = expression->array_access.array_ref;
6134 type_t *type_left = skip_typeref(array_ref->base.type);
6135 if (!is_type_pointer(type_left))
6136 return type_error_type;
6137 return type_left->pointer.points_to;
6140 case EXPR_STRING_LITERAL: {
6141 size_t size = expression->string_literal.value.size;
6142 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6145 case EXPR_WIDE_STRING_LITERAL: {
6146 size_t size = wstrlen(&expression->string_literal.value);
6147 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6150 case EXPR_COMPOUND_LITERAL:
6151 return expression->compound_literal.type;
6156 return expression->base.type;
6160 * Find an entity matching a symbol in a scope.
6161 * Uses current scope if scope is NULL
6163 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6164 namespace_tag_t namespc)
6166 if (scope == NULL) {
6167 return get_entity(symbol, namespc);
6170 /* we should optimize here, if scope grows above a certain size we should
6171 construct a hashmap here... */
6172 entity_t *entity = scope->entities;
6173 for ( ; entity != NULL; entity = entity->base.next) {
6174 if (entity->base.symbol == symbol
6175 && (namespace_tag_t)entity->base.namespc == namespc)
6182 static entity_t *parse_qualified_identifier(void)
6184 /* namespace containing the symbol */
6186 source_position_t pos;
6187 const scope_t *lookup_scope = NULL;
6189 if (next_if(T_COLONCOLON))
6190 lookup_scope = &unit->scope;
6194 if (token.type != T_IDENTIFIER) {
6195 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6196 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6198 symbol = token.symbol;
6203 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6205 if (!next_if(T_COLONCOLON))
6208 switch (entity->kind) {
6209 case ENTITY_NAMESPACE:
6210 lookup_scope = &entity->namespacee.members;
6215 lookup_scope = &entity->compound.members;
6218 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6219 symbol, get_entity_kind_name(entity->kind));
6221 /* skip further qualifications */
6222 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6224 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6228 if (entity == NULL) {
6229 if (!strict_mode && token.type == '(') {
6230 /* an implicitly declared function */
6231 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6232 entity = create_implicit_function(symbol, &pos);
6234 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6235 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6242 static expression_t *parse_reference(void)
6244 source_position_t const pos = token.source_position;
6245 entity_t *const entity = parse_qualified_identifier();
6248 if (is_declaration(entity)) {
6249 orig_type = entity->declaration.type;
6250 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6251 orig_type = entity->enum_value.enum_type;
6253 panic("expected declaration or enum value in reference");
6256 /* we always do the auto-type conversions; the & and sizeof parser contains
6257 * code to revert this! */
6258 type_t *type = automatic_type_conversion(orig_type);
6260 expression_kind_t kind = EXPR_REFERENCE;
6261 if (entity->kind == ENTITY_ENUM_VALUE)
6262 kind = EXPR_REFERENCE_ENUM_VALUE;
6264 expression_t *expression = allocate_expression_zero(kind);
6265 expression->base.source_position = pos;
6266 expression->base.type = type;
6267 expression->reference.entity = entity;
6269 /* this declaration is used */
6270 if (is_declaration(entity)) {
6271 entity->declaration.used = true;
6274 if (entity->base.parent_scope != file_scope
6275 && (current_function != NULL
6276 && entity->base.parent_scope->depth < current_function->parameters.depth)
6277 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6278 if (entity->kind == ENTITY_VARIABLE) {
6279 /* access of a variable from an outer function */
6280 entity->variable.address_taken = true;
6281 } else if (entity->kind == ENTITY_PARAMETER) {
6282 entity->parameter.address_taken = true;
6284 current_function->need_closure = true;
6287 check_deprecated(&pos, entity);
6289 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6290 current_init_decl = NULL;
6291 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6297 static bool semantic_cast(expression_t *cast)
6299 expression_t *expression = cast->unary.value;
6300 type_t *orig_dest_type = cast->base.type;
6301 type_t *orig_type_right = expression->base.type;
6302 type_t const *dst_type = skip_typeref(orig_dest_type);
6303 type_t const *src_type = skip_typeref(orig_type_right);
6304 source_position_t const *pos = &cast->base.source_position;
6306 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6307 if (dst_type == type_void)
6310 /* only integer and pointer can be casted to pointer */
6311 if (is_type_pointer(dst_type) &&
6312 !is_type_pointer(src_type) &&
6313 !is_type_integer(src_type) &&
6314 is_type_valid(src_type)) {
6315 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6319 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6320 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6324 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6325 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6329 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6330 type_t *src = skip_typeref(src_type->pointer.points_to);
6331 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6332 unsigned missing_qualifiers =
6333 src->base.qualifiers & ~dst->base.qualifiers;
6334 if (missing_qualifiers != 0) {
6335 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6341 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6343 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6344 expression->base.source_position = *pos;
6346 parse_initializer_env_t env;
6349 env.must_be_constant = false;
6350 initializer_t *initializer = parse_initializer(&env);
6353 expression->compound_literal.initializer = initializer;
6354 expression->compound_literal.type = type;
6355 expression->base.type = automatic_type_conversion(type);
6361 * Parse a cast expression.
6363 static expression_t *parse_cast(void)
6365 source_position_t const pos = *HERE;
6368 add_anchor_token(')');
6370 type_t *type = parse_typename();
6372 rem_anchor_token(')');
6373 expect(')', end_error);
6375 if (token.type == '{') {
6376 return parse_compound_literal(&pos, type);
6379 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6380 cast->base.source_position = pos;
6382 expression_t *value = parse_subexpression(PREC_CAST);
6383 cast->base.type = type;
6384 cast->unary.value = value;
6386 if (! semantic_cast(cast)) {
6387 /* TODO: record the error in the AST. else it is impossible to detect it */
6392 return create_invalid_expression();
6396 * Parse a statement expression.
6398 static expression_t *parse_statement_expression(void)
6400 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6403 add_anchor_token(')');
6405 statement_t *statement = parse_compound_statement(true);
6406 statement->compound.stmt_expr = true;
6407 expression->statement.statement = statement;
6409 /* find last statement and use its type */
6410 type_t *type = type_void;
6411 const statement_t *stmt = statement->compound.statements;
6413 while (stmt->base.next != NULL)
6414 stmt = stmt->base.next;
6416 if (stmt->kind == STATEMENT_EXPRESSION) {
6417 type = stmt->expression.expression->base.type;
6420 source_position_t const *const pos = &expression->base.source_position;
6421 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6423 expression->base.type = type;
6425 rem_anchor_token(')');
6426 expect(')', end_error);
6433 * Parse a parenthesized expression.
6435 static expression_t *parse_parenthesized_expression(void)
6437 token_t const* const la1 = look_ahead(1);
6438 switch (la1->type) {
6440 /* gcc extension: a statement expression */
6441 return parse_statement_expression();
6444 if (is_typedef_symbol(la1->symbol)) {
6446 return parse_cast();
6451 add_anchor_token(')');
6452 expression_t *result = parse_expression();
6453 result->base.parenthesized = true;
6454 rem_anchor_token(')');
6455 expect(')', end_error);
6461 static expression_t *parse_function_keyword(void)
6465 if (current_function == NULL) {
6466 errorf(HERE, "'__func__' used outside of a function");
6469 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6470 expression->base.type = type_char_ptr;
6471 expression->funcname.kind = FUNCNAME_FUNCTION;
6478 static expression_t *parse_pretty_function_keyword(void)
6480 if (current_function == NULL) {
6481 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6484 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6485 expression->base.type = type_char_ptr;
6486 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6488 eat(T___PRETTY_FUNCTION__);
6493 static expression_t *parse_funcsig_keyword(void)
6495 if (current_function == NULL) {
6496 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6499 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6500 expression->base.type = type_char_ptr;
6501 expression->funcname.kind = FUNCNAME_FUNCSIG;
6508 static expression_t *parse_funcdname_keyword(void)
6510 if (current_function == NULL) {
6511 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6514 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6515 expression->base.type = type_char_ptr;
6516 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6518 eat(T___FUNCDNAME__);
6523 static designator_t *parse_designator(void)
6525 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6526 result->source_position = *HERE;
6528 if (token.type != T_IDENTIFIER) {
6529 parse_error_expected("while parsing member designator",
6530 T_IDENTIFIER, NULL);
6533 result->symbol = token.symbol;
6536 designator_t *last_designator = result;
6539 if (token.type != T_IDENTIFIER) {
6540 parse_error_expected("while parsing member designator",
6541 T_IDENTIFIER, NULL);
6544 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6545 designator->source_position = *HERE;
6546 designator->symbol = token.symbol;
6549 last_designator->next = designator;
6550 last_designator = designator;
6554 add_anchor_token(']');
6555 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6556 designator->source_position = *HERE;
6557 designator->array_index = parse_expression();
6558 rem_anchor_token(']');
6559 expect(']', end_error);
6560 if (designator->array_index == NULL) {
6564 last_designator->next = designator;
6565 last_designator = designator;
6577 * Parse the __builtin_offsetof() expression.
6579 static expression_t *parse_offsetof(void)
6581 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6582 expression->base.type = type_size_t;
6584 eat(T___builtin_offsetof);
6586 expect('(', end_error);
6587 add_anchor_token(',');
6588 type_t *type = parse_typename();
6589 rem_anchor_token(',');
6590 expect(',', end_error);
6591 add_anchor_token(')');
6592 designator_t *designator = parse_designator();
6593 rem_anchor_token(')');
6594 expect(')', end_error);
6596 expression->offsetofe.type = type;
6597 expression->offsetofe.designator = designator;
6600 memset(&path, 0, sizeof(path));
6601 path.top_type = type;
6602 path.path = NEW_ARR_F(type_path_entry_t, 0);
6604 descend_into_subtype(&path);
6606 if (!walk_designator(&path, designator, true)) {
6607 return create_invalid_expression();
6610 DEL_ARR_F(path.path);
6614 return create_invalid_expression();
6618 * Parses a _builtin_va_start() expression.
6620 static expression_t *parse_va_start(void)
6622 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6624 eat(T___builtin_va_start);
6626 expect('(', end_error);
6627 add_anchor_token(',');
6628 expression->va_starte.ap = parse_assignment_expression();
6629 rem_anchor_token(',');
6630 expect(',', end_error);
6631 expression_t *const expr = parse_assignment_expression();
6632 if (expr->kind == EXPR_REFERENCE) {
6633 entity_t *const entity = expr->reference.entity;
6634 if (!current_function->base.type->function.variadic) {
6635 errorf(&expr->base.source_position,
6636 "'va_start' used in non-variadic function");
6637 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6638 entity->base.next != NULL ||
6639 entity->kind != ENTITY_PARAMETER) {
6640 errorf(&expr->base.source_position,
6641 "second argument of 'va_start' must be last parameter of the current function");
6643 expression->va_starte.parameter = &entity->variable;
6645 expect(')', end_error);
6648 expect(')', end_error);
6650 return create_invalid_expression();
6654 * Parses a __builtin_va_arg() expression.
6656 static expression_t *parse_va_arg(void)
6658 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6660 eat(T___builtin_va_arg);
6662 expect('(', end_error);
6664 ap.expression = parse_assignment_expression();
6665 expression->va_arge.ap = ap.expression;
6666 check_call_argument(type_valist, &ap, 1);
6668 expect(',', end_error);
6669 expression->base.type = parse_typename();
6670 expect(')', end_error);
6674 return create_invalid_expression();
6678 * Parses a __builtin_va_copy() expression.
6680 static expression_t *parse_va_copy(void)
6682 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6684 eat(T___builtin_va_copy);
6686 expect('(', end_error);
6687 expression_t *dst = parse_assignment_expression();
6688 assign_error_t error = semantic_assign(type_valist, dst);
6689 report_assign_error(error, type_valist, dst, "call argument 1",
6690 &dst->base.source_position);
6691 expression->va_copye.dst = dst;
6693 expect(',', end_error);
6695 call_argument_t src;
6696 src.expression = parse_assignment_expression();
6697 check_call_argument(type_valist, &src, 2);
6698 expression->va_copye.src = src.expression;
6699 expect(')', end_error);
6703 return create_invalid_expression();
6707 * Parses a __builtin_constant_p() expression.
6709 static expression_t *parse_builtin_constant(void)
6711 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6713 eat(T___builtin_constant_p);
6715 expect('(', end_error);
6716 add_anchor_token(')');
6717 expression->builtin_constant.value = parse_assignment_expression();
6718 rem_anchor_token(')');
6719 expect(')', end_error);
6720 expression->base.type = type_int;
6724 return create_invalid_expression();
6728 * Parses a __builtin_types_compatible_p() expression.
6730 static expression_t *parse_builtin_types_compatible(void)
6732 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6734 eat(T___builtin_types_compatible_p);
6736 expect('(', end_error);
6737 add_anchor_token(')');
6738 add_anchor_token(',');
6739 expression->builtin_types_compatible.left = parse_typename();
6740 rem_anchor_token(',');
6741 expect(',', end_error);
6742 expression->builtin_types_compatible.right = parse_typename();
6743 rem_anchor_token(')');
6744 expect(')', end_error);
6745 expression->base.type = type_int;
6749 return create_invalid_expression();
6753 * Parses a __builtin_is_*() compare expression.
6755 static expression_t *parse_compare_builtin(void)
6757 expression_t *expression;
6759 switch (token.type) {
6760 case T___builtin_isgreater:
6761 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6763 case T___builtin_isgreaterequal:
6764 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6766 case T___builtin_isless:
6767 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6769 case T___builtin_islessequal:
6770 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6772 case T___builtin_islessgreater:
6773 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6775 case T___builtin_isunordered:
6776 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6779 internal_errorf(HERE, "invalid compare builtin found");
6781 expression->base.source_position = *HERE;
6784 expect('(', end_error);
6785 expression->binary.left = parse_assignment_expression();
6786 expect(',', end_error);
6787 expression->binary.right = parse_assignment_expression();
6788 expect(')', end_error);
6790 type_t *const orig_type_left = expression->binary.left->base.type;
6791 type_t *const orig_type_right = expression->binary.right->base.type;
6793 type_t *const type_left = skip_typeref(orig_type_left);
6794 type_t *const type_right = skip_typeref(orig_type_right);
6795 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6796 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6797 type_error_incompatible("invalid operands in comparison",
6798 &expression->base.source_position, orig_type_left, orig_type_right);
6801 semantic_comparison(&expression->binary);
6806 return create_invalid_expression();
6810 * Parses a MS assume() expression.
6812 static expression_t *parse_assume(void)
6814 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6818 expect('(', end_error);
6819 add_anchor_token(')');
6820 expression->unary.value = parse_assignment_expression();
6821 rem_anchor_token(')');
6822 expect(')', end_error);
6824 expression->base.type = type_void;
6827 return create_invalid_expression();
6831 * Return the label for the current symbol or create a new one.
6833 static label_t *get_label(void)
6835 assert(token.type == T_IDENTIFIER);
6836 assert(current_function != NULL);
6838 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6839 /* If we find a local label, we already created the declaration. */
6840 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6841 if (label->base.parent_scope != current_scope) {
6842 assert(label->base.parent_scope->depth < current_scope->depth);
6843 current_function->goto_to_outer = true;
6845 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6846 /* There is no matching label in the same function, so create a new one. */
6847 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6852 return &label->label;
6856 * Parses a GNU && label address expression.
6858 static expression_t *parse_label_address(void)
6860 source_position_t source_position = token.source_position;
6862 if (token.type != T_IDENTIFIER) {
6863 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6864 return create_invalid_expression();
6867 label_t *const label = get_label();
6869 label->address_taken = true;
6871 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6872 expression->base.source_position = source_position;
6874 /* label address is treated as a void pointer */
6875 expression->base.type = type_void_ptr;
6876 expression->label_address.label = label;
6881 * Parse a microsoft __noop expression.
6883 static expression_t *parse_noop_expression(void)
6885 /* the result is a (int)0 */
6886 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6887 literal->base.type = type_int;
6888 literal->literal.value.begin = "__noop";
6889 literal->literal.value.size = 6;
6893 if (token.type == '(') {
6894 /* parse arguments */
6896 add_anchor_token(')');
6897 add_anchor_token(',');
6899 if (token.type != ')') do {
6900 (void)parse_assignment_expression();
6901 } while (next_if(','));
6903 rem_anchor_token(',');
6904 rem_anchor_token(')');
6905 expect(')', end_error);
6912 * Parses a primary expression.
6914 static expression_t *parse_primary_expression(void)
6916 switch (token.type) {
6917 case T_false: return parse_boolean_literal(false);
6918 case T_true: return parse_boolean_literal(true);
6920 case T_INTEGER_OCTAL:
6921 case T_INTEGER_HEXADECIMAL:
6922 case T_FLOATINGPOINT:
6923 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6924 case T_CHARACTER_CONSTANT: return parse_character_constant();
6925 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6926 case T_STRING_LITERAL:
6927 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6928 case T___FUNCTION__:
6929 case T___func__: return parse_function_keyword();
6930 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6931 case T___FUNCSIG__: return parse_funcsig_keyword();
6932 case T___FUNCDNAME__: return parse_funcdname_keyword();
6933 case T___builtin_offsetof: return parse_offsetof();
6934 case T___builtin_va_start: return parse_va_start();
6935 case T___builtin_va_arg: return parse_va_arg();
6936 case T___builtin_va_copy: return parse_va_copy();
6937 case T___builtin_isgreater:
6938 case T___builtin_isgreaterequal:
6939 case T___builtin_isless:
6940 case T___builtin_islessequal:
6941 case T___builtin_islessgreater:
6942 case T___builtin_isunordered: return parse_compare_builtin();
6943 case T___builtin_constant_p: return parse_builtin_constant();
6944 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6945 case T__assume: return parse_assume();
6948 return parse_label_address();
6951 case '(': return parse_parenthesized_expression();
6952 case T___noop: return parse_noop_expression();
6954 /* Gracefully handle type names while parsing expressions. */
6956 return parse_reference();
6958 if (!is_typedef_symbol(token.symbol)) {
6959 return parse_reference();
6963 source_position_t const pos = *HERE;
6964 declaration_specifiers_t specifiers;
6965 parse_declaration_specifiers(&specifiers);
6966 type_t const *const type = parse_abstract_declarator(specifiers.type);
6967 errorf(&pos, "encountered type '%T' while parsing expression", type);
6968 return create_invalid_expression();
6972 errorf(HERE, "unexpected token %K, expected an expression", &token);
6974 return create_invalid_expression();
6977 static expression_t *parse_array_expression(expression_t *left)
6979 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6980 array_access_expression_t *const arr = &expr->array_access;
6983 add_anchor_token(']');
6985 expression_t *const inside = parse_expression();
6987 type_t *const orig_type_left = left->base.type;
6988 type_t *const orig_type_inside = inside->base.type;
6990 type_t *const type_left = skip_typeref(orig_type_left);
6991 type_t *const type_inside = skip_typeref(orig_type_inside);
6997 if (is_type_pointer(type_left)) {
7000 idx_type = type_inside;
7001 res_type = type_left->pointer.points_to;
7003 } else if (is_type_pointer(type_inside)) {
7004 arr->flipped = true;
7007 idx_type = type_left;
7008 res_type = type_inside->pointer.points_to;
7010 res_type = automatic_type_conversion(res_type);
7011 if (!is_type_integer(idx_type)) {
7012 errorf(&idx->base.source_position, "array subscript must have integer type");
7013 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7014 source_position_t const *const pos = &idx->base.source_position;
7015 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7018 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7019 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7021 res_type = type_error_type;
7026 arr->array_ref = ref;
7028 arr->base.type = res_type;
7030 rem_anchor_token(']');
7031 expect(']', end_error);
7036 static expression_t *parse_typeprop(expression_kind_t const kind)
7038 expression_t *tp_expression = allocate_expression_zero(kind);
7039 tp_expression->base.type = type_size_t;
7041 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7043 /* we only refer to a type property, mark this case */
7044 bool old = in_type_prop;
7045 in_type_prop = true;
7048 expression_t *expression;
7049 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7050 source_position_t const pos = *HERE;
7052 add_anchor_token(')');
7053 orig_type = parse_typename();
7054 rem_anchor_token(')');
7055 expect(')', end_error);
7057 if (token.type == '{') {
7058 /* It was not sizeof(type) after all. It is sizeof of an expression
7059 * starting with a compound literal */
7060 expression = parse_compound_literal(&pos, orig_type);
7061 goto typeprop_expression;
7064 expression = parse_subexpression(PREC_UNARY);
7066 typeprop_expression:
7067 tp_expression->typeprop.tp_expression = expression;
7069 orig_type = revert_automatic_type_conversion(expression);
7070 expression->base.type = orig_type;
7073 tp_expression->typeprop.type = orig_type;
7074 type_t const* const type = skip_typeref(orig_type);
7075 char const* wrong_type = NULL;
7076 if (is_type_incomplete(type)) {
7077 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7078 wrong_type = "incomplete";
7079 } else if (type->kind == TYPE_FUNCTION) {
7081 /* function types are allowed (and return 1) */
7082 source_position_t const *const pos = &tp_expression->base.source_position;
7083 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7084 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7086 wrong_type = "function";
7089 if (is_type_incomplete(type))
7090 wrong_type = "incomplete";
7092 if (type->kind == TYPE_BITFIELD)
7093 wrong_type = "bitfield";
7095 if (wrong_type != NULL) {
7096 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7097 errorf(&tp_expression->base.source_position,
7098 "operand of %s expression must not be of %s type '%T'",
7099 what, wrong_type, orig_type);
7104 return tp_expression;
7107 static expression_t *parse_sizeof(void)
7109 return parse_typeprop(EXPR_SIZEOF);
7112 static expression_t *parse_alignof(void)
7114 return parse_typeprop(EXPR_ALIGNOF);
7117 static expression_t *parse_select_expression(expression_t *addr)
7119 assert(token.type == '.' || token.type == T_MINUSGREATER);
7120 bool select_left_arrow = (token.type == T_MINUSGREATER);
7121 source_position_t const pos = *HERE;
7124 if (token.type != T_IDENTIFIER) {
7125 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7126 return create_invalid_expression();
7128 symbol_t *symbol = token.symbol;
7131 type_t *const orig_type = addr->base.type;
7132 type_t *const type = skip_typeref(orig_type);
7135 bool saw_error = false;
7136 if (is_type_pointer(type)) {
7137 if (!select_left_arrow) {
7139 "request for member '%Y' in something not a struct or union, but '%T'",
7143 type_left = skip_typeref(type->pointer.points_to);
7145 if (select_left_arrow && is_type_valid(type)) {
7146 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7152 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7153 type_left->kind != TYPE_COMPOUND_UNION) {
7155 if (is_type_valid(type_left) && !saw_error) {
7157 "request for member '%Y' in something not a struct or union, but '%T'",
7160 return create_invalid_expression();
7163 compound_t *compound = type_left->compound.compound;
7164 if (!compound->complete) {
7165 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7167 return create_invalid_expression();
7170 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7171 expression_t *result =
7172 find_create_select(&pos, addr, qualifiers, compound, symbol);
7174 if (result == NULL) {
7175 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7176 return create_invalid_expression();
7182 static void check_call_argument(type_t *expected_type,
7183 call_argument_t *argument, unsigned pos)
7185 type_t *expected_type_skip = skip_typeref(expected_type);
7186 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7187 expression_t *arg_expr = argument->expression;
7188 type_t *arg_type = skip_typeref(arg_expr->base.type);
7190 /* handle transparent union gnu extension */
7191 if (is_type_union(expected_type_skip)
7192 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7193 compound_t *union_decl = expected_type_skip->compound.compound;
7194 type_t *best_type = NULL;
7195 entity_t *entry = union_decl->members.entities;
7196 for ( ; entry != NULL; entry = entry->base.next) {
7197 assert(is_declaration(entry));
7198 type_t *decl_type = entry->declaration.type;
7199 error = semantic_assign(decl_type, arg_expr);
7200 if (error == ASSIGN_ERROR_INCOMPATIBLE
7201 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7204 if (error == ASSIGN_SUCCESS) {
7205 best_type = decl_type;
7206 } else if (best_type == NULL) {
7207 best_type = decl_type;
7211 if (best_type != NULL) {
7212 expected_type = best_type;
7216 error = semantic_assign(expected_type, arg_expr);
7217 argument->expression = create_implicit_cast(arg_expr, expected_type);
7219 if (error != ASSIGN_SUCCESS) {
7220 /* report exact scope in error messages (like "in argument 3") */
7222 snprintf(buf, sizeof(buf), "call argument %u", pos);
7223 report_assign_error(error, expected_type, arg_expr, buf,
7224 &arg_expr->base.source_position);
7226 type_t *const promoted_type = get_default_promoted_type(arg_type);
7227 if (!types_compatible(expected_type_skip, promoted_type) &&
7228 !types_compatible(expected_type_skip, type_void_ptr) &&
7229 !types_compatible(type_void_ptr, promoted_type)) {
7230 /* Deliberately show the skipped types in this warning */
7231 source_position_t const *const apos = &arg_expr->base.source_position;
7232 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7238 * Handle the semantic restrictions of builtin calls
7240 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7241 switch (call->function->reference.entity->function.btk) {
7242 case bk_gnu_builtin_return_address:
7243 case bk_gnu_builtin_frame_address: {
7244 /* argument must be constant */
7245 call_argument_t *argument = call->arguments;
7247 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7248 errorf(&call->base.source_position,
7249 "argument of '%Y' must be a constant expression",
7250 call->function->reference.entity->base.symbol);
7254 case bk_gnu_builtin_object_size:
7255 if (call->arguments == NULL)
7258 call_argument_t *arg = call->arguments->next;
7259 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7260 errorf(&call->base.source_position,
7261 "second argument of '%Y' must be a constant expression",
7262 call->function->reference.entity->base.symbol);
7265 case bk_gnu_builtin_prefetch:
7266 /* second and third argument must be constant if existent */
7267 if (call->arguments == NULL)
7269 call_argument_t *rw = call->arguments->next;
7270 call_argument_t *locality = NULL;
7273 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7274 errorf(&call->base.source_position,
7275 "second argument of '%Y' must be a constant expression",
7276 call->function->reference.entity->base.symbol);
7278 locality = rw->next;
7280 if (locality != NULL) {
7281 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7282 errorf(&call->base.source_position,
7283 "third argument of '%Y' must be a constant expression",
7284 call->function->reference.entity->base.symbol);
7286 locality = rw->next;
7295 * Parse a call expression, ie. expression '( ... )'.
7297 * @param expression the function address
7299 static expression_t *parse_call_expression(expression_t *expression)
7301 expression_t *result = allocate_expression_zero(EXPR_CALL);
7302 call_expression_t *call = &result->call;
7303 call->function = expression;
7305 type_t *const orig_type = expression->base.type;
7306 type_t *const type = skip_typeref(orig_type);
7308 function_type_t *function_type = NULL;
7309 if (is_type_pointer(type)) {
7310 type_t *const to_type = skip_typeref(type->pointer.points_to);
7312 if (is_type_function(to_type)) {
7313 function_type = &to_type->function;
7314 call->base.type = function_type->return_type;
7318 if (function_type == NULL && is_type_valid(type)) {
7320 "called object '%E' (type '%T') is not a pointer to a function",
7321 expression, orig_type);
7324 /* parse arguments */
7326 add_anchor_token(')');
7327 add_anchor_token(',');
7329 if (token.type != ')') {
7330 call_argument_t **anchor = &call->arguments;
7332 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7333 argument->expression = parse_assignment_expression();
7336 anchor = &argument->next;
7337 } while (next_if(','));
7339 rem_anchor_token(',');
7340 rem_anchor_token(')');
7341 expect(')', end_error);
7343 if (function_type == NULL)
7346 /* check type and count of call arguments */
7347 function_parameter_t *parameter = function_type->parameters;
7348 call_argument_t *argument = call->arguments;
7349 if (!function_type->unspecified_parameters) {
7350 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7351 parameter = parameter->next, argument = argument->next) {
7352 check_call_argument(parameter->type, argument, ++pos);
7355 if (parameter != NULL) {
7356 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7357 } else if (argument != NULL && !function_type->variadic) {
7358 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7362 /* do default promotion for other arguments */
7363 for (; argument != NULL; argument = argument->next) {
7364 type_t *argument_type = argument->expression->base.type;
7365 if (!is_type_object(skip_typeref(argument_type))) {
7366 errorf(&argument->expression->base.source_position,
7367 "call argument '%E' must not be void", argument->expression);
7370 argument_type = get_default_promoted_type(argument_type);
7372 argument->expression
7373 = create_implicit_cast(argument->expression, argument_type);
7378 if (is_type_compound(skip_typeref(function_type->return_type))) {
7379 source_position_t const *const pos = &expression->base.source_position;
7380 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7383 if (expression->kind == EXPR_REFERENCE) {
7384 reference_expression_t *reference = &expression->reference;
7385 if (reference->entity->kind == ENTITY_FUNCTION &&
7386 reference->entity->function.btk != bk_none)
7387 handle_builtin_argument_restrictions(call);
7394 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7396 static bool same_compound_type(const type_t *type1, const type_t *type2)
7399 is_type_compound(type1) &&
7400 type1->kind == type2->kind &&
7401 type1->compound.compound == type2->compound.compound;
7404 static expression_t const *get_reference_address(expression_t const *expr)
7406 bool regular_take_address = true;
7408 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7409 expr = expr->unary.value;
7411 regular_take_address = false;
7414 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7417 expr = expr->unary.value;
7420 if (expr->kind != EXPR_REFERENCE)
7423 /* special case for functions which are automatically converted to a
7424 * pointer to function without an extra TAKE_ADDRESS operation */
7425 if (!regular_take_address &&
7426 expr->reference.entity->kind != ENTITY_FUNCTION) {
7433 static void warn_reference_address_as_bool(expression_t const* expr)
7435 expr = get_reference_address(expr);
7437 source_position_t const *const pos = &expr->base.source_position;
7438 entity_t const *const ent = expr->reference.entity;
7439 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7443 static void warn_assignment_in_condition(const expression_t *const expr)
7445 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7447 if (expr->base.parenthesized)
7449 source_position_t const *const pos = &expr->base.source_position;
7450 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7453 static void semantic_condition(expression_t const *const expr,
7454 char const *const context)
7456 type_t *const type = skip_typeref(expr->base.type);
7457 if (is_type_scalar(type)) {
7458 warn_reference_address_as_bool(expr);
7459 warn_assignment_in_condition(expr);
7460 } else if (is_type_valid(type)) {
7461 errorf(&expr->base.source_position,
7462 "%s must have scalar type", context);
7467 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7469 * @param expression the conditional expression
7471 static expression_t *parse_conditional_expression(expression_t *expression)
7473 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7475 conditional_expression_t *conditional = &result->conditional;
7476 conditional->condition = expression;
7479 add_anchor_token(':');
7481 /* §6.5.15:2 The first operand shall have scalar type. */
7482 semantic_condition(expression, "condition of conditional operator");
7484 expression_t *true_expression = expression;
7485 bool gnu_cond = false;
7486 if (GNU_MODE && token.type == ':') {
7489 true_expression = parse_expression();
7491 rem_anchor_token(':');
7492 expect(':', end_error);
7494 expression_t *false_expression =
7495 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7497 type_t *const orig_true_type = true_expression->base.type;
7498 type_t *const orig_false_type = false_expression->base.type;
7499 type_t *const true_type = skip_typeref(orig_true_type);
7500 type_t *const false_type = skip_typeref(orig_false_type);
7503 source_position_t const *const pos = &conditional->base.source_position;
7504 type_t *result_type;
7505 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7506 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7507 /* ISO/IEC 14882:1998(E) §5.16:2 */
7508 if (true_expression->kind == EXPR_UNARY_THROW) {
7509 result_type = false_type;
7510 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7511 result_type = true_type;
7513 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7514 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7515 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7517 result_type = type_void;
7519 } else if (is_type_arithmetic(true_type)
7520 && is_type_arithmetic(false_type)) {
7521 result_type = semantic_arithmetic(true_type, false_type);
7522 } else if (same_compound_type(true_type, false_type)) {
7523 /* just take 1 of the 2 types */
7524 result_type = true_type;
7525 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7526 type_t *pointer_type;
7528 expression_t *other_expression;
7529 if (is_type_pointer(true_type) &&
7530 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7531 pointer_type = true_type;
7532 other_type = false_type;
7533 other_expression = false_expression;
7535 pointer_type = false_type;
7536 other_type = true_type;
7537 other_expression = true_expression;
7540 if (is_null_pointer_constant(other_expression)) {
7541 result_type = pointer_type;
7542 } else if (is_type_pointer(other_type)) {
7543 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7544 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7547 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7548 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7550 } else if (types_compatible(get_unqualified_type(to1),
7551 get_unqualified_type(to2))) {
7554 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7558 type_t *const type =
7559 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7560 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7561 } else if (is_type_integer(other_type)) {
7562 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7563 result_type = pointer_type;
7565 goto types_incompatible;
7569 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7570 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7572 result_type = type_error_type;
7575 conditional->true_expression
7576 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7577 conditional->false_expression
7578 = create_implicit_cast(false_expression, result_type);
7579 conditional->base.type = result_type;
7584 * Parse an extension expression.
7586 static expression_t *parse_extension(void)
7589 expression_t *expression = parse_subexpression(PREC_UNARY);
7595 * Parse a __builtin_classify_type() expression.
7597 static expression_t *parse_builtin_classify_type(void)
7599 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7600 result->base.type = type_int;
7602 eat(T___builtin_classify_type);
7604 expect('(', end_error);
7605 add_anchor_token(')');
7606 expression_t *expression = parse_expression();
7607 rem_anchor_token(')');
7608 expect(')', end_error);
7609 result->classify_type.type_expression = expression;
7613 return create_invalid_expression();
7617 * Parse a delete expression
7618 * ISO/IEC 14882:1998(E) §5.3.5
7620 static expression_t *parse_delete(void)
7622 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7623 result->base.type = type_void;
7628 result->kind = EXPR_UNARY_DELETE_ARRAY;
7629 expect(']', end_error);
7633 expression_t *const value = parse_subexpression(PREC_CAST);
7634 result->unary.value = value;
7636 type_t *const type = skip_typeref(value->base.type);
7637 if (!is_type_pointer(type)) {
7638 if (is_type_valid(type)) {
7639 errorf(&value->base.source_position,
7640 "operand of delete must have pointer type");
7642 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7643 source_position_t const *const pos = &value->base.source_position;
7644 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7651 * Parse a throw expression
7652 * ISO/IEC 14882:1998(E) §15:1
7654 static expression_t *parse_throw(void)
7656 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7657 result->base.type = type_void;
7661 expression_t *value = NULL;
7662 switch (token.type) {
7664 value = parse_assignment_expression();
7665 /* ISO/IEC 14882:1998(E) §15.1:3 */
7666 type_t *const orig_type = value->base.type;
7667 type_t *const type = skip_typeref(orig_type);
7668 if (is_type_incomplete(type)) {
7669 errorf(&value->base.source_position,
7670 "cannot throw object of incomplete type '%T'", orig_type);
7671 } else if (is_type_pointer(type)) {
7672 type_t *const points_to = skip_typeref(type->pointer.points_to);
7673 if (is_type_incomplete(points_to) &&
7674 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7675 errorf(&value->base.source_position,
7676 "cannot throw pointer to incomplete type '%T'", orig_type);
7684 result->unary.value = value;
7689 static bool check_pointer_arithmetic(const source_position_t *source_position,
7690 type_t *pointer_type,
7691 type_t *orig_pointer_type)
7693 type_t *points_to = pointer_type->pointer.points_to;
7694 points_to = skip_typeref(points_to);
7696 if (is_type_incomplete(points_to)) {
7697 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7698 errorf(source_position,
7699 "arithmetic with pointer to incomplete type '%T' not allowed",
7703 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7705 } else if (is_type_function(points_to)) {
7707 errorf(source_position,
7708 "arithmetic with pointer to function type '%T' not allowed",
7712 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7718 static bool is_lvalue(const expression_t *expression)
7720 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7721 switch (expression->kind) {
7722 case EXPR_ARRAY_ACCESS:
7723 case EXPR_COMPOUND_LITERAL:
7724 case EXPR_REFERENCE:
7726 case EXPR_UNARY_DEREFERENCE:
7730 type_t *type = skip_typeref(expression->base.type);
7732 /* ISO/IEC 14882:1998(E) §3.10:3 */
7733 is_type_reference(type) ||
7734 /* Claim it is an lvalue, if the type is invalid. There was a parse
7735 * error before, which maybe prevented properly recognizing it as
7737 !is_type_valid(type);
7742 static void semantic_incdec(unary_expression_t *expression)
7744 type_t *const orig_type = expression->value->base.type;
7745 type_t *const type = skip_typeref(orig_type);
7746 if (is_type_pointer(type)) {
7747 if (!check_pointer_arithmetic(&expression->base.source_position,
7751 } else if (!is_type_real(type) && is_type_valid(type)) {
7752 /* TODO: improve error message */
7753 errorf(&expression->base.source_position,
7754 "operation needs an arithmetic or pointer type");
7757 if (!is_lvalue(expression->value)) {
7758 /* TODO: improve error message */
7759 errorf(&expression->base.source_position, "lvalue required as operand");
7761 expression->base.type = orig_type;
7764 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7766 type_t *const orig_type = expression->value->base.type;
7767 type_t *const type = skip_typeref(orig_type);
7768 if (!is_type_arithmetic(type)) {
7769 if (is_type_valid(type)) {
7770 /* TODO: improve error message */
7771 errorf(&expression->base.source_position,
7772 "operation needs an arithmetic type");
7777 expression->base.type = orig_type;
7780 static void semantic_unexpr_plus(unary_expression_t *expression)
7782 semantic_unexpr_arithmetic(expression);
7783 source_position_t const *const pos = &expression->base.source_position;
7784 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7787 static void semantic_not(unary_expression_t *expression)
7789 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7790 semantic_condition(expression->value, "operand of !");
7791 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7794 static void semantic_unexpr_integer(unary_expression_t *expression)
7796 type_t *const orig_type = expression->value->base.type;
7797 type_t *const type = skip_typeref(orig_type);
7798 if (!is_type_integer(type)) {
7799 if (is_type_valid(type)) {
7800 errorf(&expression->base.source_position,
7801 "operand of ~ must be of integer type");
7806 expression->base.type = orig_type;
7809 static void semantic_dereference(unary_expression_t *expression)
7811 type_t *const orig_type = expression->value->base.type;
7812 type_t *const type = skip_typeref(orig_type);
7813 if (!is_type_pointer(type)) {
7814 if (is_type_valid(type)) {
7815 errorf(&expression->base.source_position,
7816 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7821 type_t *result_type = type->pointer.points_to;
7822 result_type = automatic_type_conversion(result_type);
7823 expression->base.type = result_type;
7827 * Record that an address is taken (expression represents an lvalue).
7829 * @param expression the expression
7830 * @param may_be_register if true, the expression might be an register
7832 static void set_address_taken(expression_t *expression, bool may_be_register)
7834 if (expression->kind != EXPR_REFERENCE)
7837 entity_t *const entity = expression->reference.entity;
7839 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7842 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7843 && !may_be_register) {
7844 source_position_t const *const pos = &expression->base.source_position;
7845 errorf(pos, "address of register '%N' requested", entity);
7848 if (entity->kind == ENTITY_VARIABLE) {
7849 entity->variable.address_taken = true;
7851 assert(entity->kind == ENTITY_PARAMETER);
7852 entity->parameter.address_taken = true;
7857 * Check the semantic of the address taken expression.
7859 static void semantic_take_addr(unary_expression_t *expression)
7861 expression_t *value = expression->value;
7862 value->base.type = revert_automatic_type_conversion(value);
7864 type_t *orig_type = value->base.type;
7865 type_t *type = skip_typeref(orig_type);
7866 if (!is_type_valid(type))
7870 if (!is_lvalue(value)) {
7871 errorf(&expression->base.source_position, "'&' requires an lvalue");
7873 if (type->kind == TYPE_BITFIELD) {
7874 errorf(&expression->base.source_position,
7875 "'&' not allowed on object with bitfield type '%T'",
7879 set_address_taken(value, false);
7881 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7884 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7885 static expression_t *parse_##unexpression_type(void) \
7887 expression_t *unary_expression \
7888 = allocate_expression_zero(unexpression_type); \
7890 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7892 sfunc(&unary_expression->unary); \
7894 return unary_expression; \
7897 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7898 semantic_unexpr_arithmetic)
7899 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7900 semantic_unexpr_plus)
7901 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7903 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7904 semantic_dereference)
7905 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7907 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7908 semantic_unexpr_integer)
7909 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7911 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7914 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7916 static expression_t *parse_##unexpression_type(expression_t *left) \
7918 expression_t *unary_expression \
7919 = allocate_expression_zero(unexpression_type); \
7921 unary_expression->unary.value = left; \
7923 sfunc(&unary_expression->unary); \
7925 return unary_expression; \
7928 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7929 EXPR_UNARY_POSTFIX_INCREMENT,
7931 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7932 EXPR_UNARY_POSTFIX_DECREMENT,
7935 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7937 /* TODO: handle complex + imaginary types */
7939 type_left = get_unqualified_type(type_left);
7940 type_right = get_unqualified_type(type_right);
7942 /* §6.3.1.8 Usual arithmetic conversions */
7943 if (type_left == type_long_double || type_right == type_long_double) {
7944 return type_long_double;
7945 } else if (type_left == type_double || type_right == type_double) {
7947 } else if (type_left == type_float || type_right == type_float) {
7951 type_left = promote_integer(type_left);
7952 type_right = promote_integer(type_right);
7954 if (type_left == type_right)
7957 bool const signed_left = is_type_signed(type_left);
7958 bool const signed_right = is_type_signed(type_right);
7959 int const rank_left = get_rank(type_left);
7960 int const rank_right = get_rank(type_right);
7962 if (signed_left == signed_right)
7963 return rank_left >= rank_right ? type_left : type_right;
7972 u_rank = rank_right;
7973 u_type = type_right;
7975 s_rank = rank_right;
7976 s_type = type_right;
7981 if (u_rank >= s_rank)
7984 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7986 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7987 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7991 case ATOMIC_TYPE_INT: return type_unsigned_int;
7992 case ATOMIC_TYPE_LONG: return type_unsigned_long;
7993 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
7995 default: panic("invalid atomic type");
8000 * Check the semantic restrictions for a binary expression.
8002 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8004 expression_t *const left = expression->left;
8005 expression_t *const right = expression->right;
8006 type_t *const orig_type_left = left->base.type;
8007 type_t *const orig_type_right = right->base.type;
8008 type_t *const type_left = skip_typeref(orig_type_left);
8009 type_t *const type_right = skip_typeref(orig_type_right);
8011 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8012 /* TODO: improve error message */
8013 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8014 errorf(&expression->base.source_position,
8015 "operation needs arithmetic types");
8020 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8021 expression->left = create_implicit_cast(left, arithmetic_type);
8022 expression->right = create_implicit_cast(right, arithmetic_type);
8023 expression->base.type = arithmetic_type;
8026 static void semantic_binexpr_integer(binary_expression_t *const expression)
8028 expression_t *const left = expression->left;
8029 expression_t *const right = expression->right;
8030 type_t *const orig_type_left = left->base.type;
8031 type_t *const orig_type_right = right->base.type;
8032 type_t *const type_left = skip_typeref(orig_type_left);
8033 type_t *const type_right = skip_typeref(orig_type_right);
8035 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8036 /* TODO: improve error message */
8037 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8038 errorf(&expression->base.source_position,
8039 "operation needs integer types");
8044 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8045 expression->left = create_implicit_cast(left, result_type);
8046 expression->right = create_implicit_cast(right, result_type);
8047 expression->base.type = result_type;
8050 static void warn_div_by_zero(binary_expression_t const *const expression)
8052 if (!is_type_integer(expression->base.type))
8055 expression_t const *const right = expression->right;
8056 /* The type of the right operand can be different for /= */
8057 if (is_type_integer(right->base.type) &&
8058 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8059 !fold_constant_to_bool(right)) {
8060 source_position_t const *const pos = &expression->base.source_position;
8061 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8066 * Check the semantic restrictions for a div/mod expression.
8068 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8070 semantic_binexpr_arithmetic(expression);
8071 warn_div_by_zero(expression);
8074 static void warn_addsub_in_shift(const expression_t *const expr)
8076 if (expr->base.parenthesized)
8080 switch (expr->kind) {
8081 case EXPR_BINARY_ADD: op = '+'; break;
8082 case EXPR_BINARY_SUB: op = '-'; break;
8086 source_position_t const *const pos = &expr->base.source_position;
8087 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8090 static bool semantic_shift(binary_expression_t *expression)
8092 expression_t *const left = expression->left;
8093 expression_t *const right = expression->right;
8094 type_t *const orig_type_left = left->base.type;
8095 type_t *const orig_type_right = right->base.type;
8096 type_t * type_left = skip_typeref(orig_type_left);
8097 type_t * type_right = skip_typeref(orig_type_right);
8099 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8100 /* TODO: improve error message */
8101 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8102 errorf(&expression->base.source_position,
8103 "operands of shift operation must have integer types");
8108 type_left = promote_integer(type_left);
8110 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8111 source_position_t const *const pos = &right->base.source_position;
8112 long const count = fold_constant_to_int(right);
8114 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8115 } else if ((unsigned long)count >=
8116 get_atomic_type_size(type_left->atomic.akind) * 8) {
8117 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8121 type_right = promote_integer(type_right);
8122 expression->right = create_implicit_cast(right, type_right);
8127 static void semantic_shift_op(binary_expression_t *expression)
8129 expression_t *const left = expression->left;
8130 expression_t *const right = expression->right;
8132 if (!semantic_shift(expression))
8135 warn_addsub_in_shift(left);
8136 warn_addsub_in_shift(right);
8138 type_t *const orig_type_left = left->base.type;
8139 type_t * type_left = skip_typeref(orig_type_left);
8141 type_left = promote_integer(type_left);
8142 expression->left = create_implicit_cast(left, type_left);
8143 expression->base.type = type_left;
8146 static void semantic_add(binary_expression_t *expression)
8148 expression_t *const left = expression->left;
8149 expression_t *const right = expression->right;
8150 type_t *const orig_type_left = left->base.type;
8151 type_t *const orig_type_right = right->base.type;
8152 type_t *const type_left = skip_typeref(orig_type_left);
8153 type_t *const type_right = skip_typeref(orig_type_right);
8156 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8157 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8158 expression->left = create_implicit_cast(left, arithmetic_type);
8159 expression->right = create_implicit_cast(right, arithmetic_type);
8160 expression->base.type = arithmetic_type;
8161 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8162 check_pointer_arithmetic(&expression->base.source_position,
8163 type_left, orig_type_left);
8164 expression->base.type = type_left;
8165 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8166 check_pointer_arithmetic(&expression->base.source_position,
8167 type_right, orig_type_right);
8168 expression->base.type = type_right;
8169 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8170 errorf(&expression->base.source_position,
8171 "invalid operands to binary + ('%T', '%T')",
8172 orig_type_left, orig_type_right);
8176 static void semantic_sub(binary_expression_t *expression)
8178 expression_t *const left = expression->left;
8179 expression_t *const right = expression->right;
8180 type_t *const orig_type_left = left->base.type;
8181 type_t *const orig_type_right = right->base.type;
8182 type_t *const type_left = skip_typeref(orig_type_left);
8183 type_t *const type_right = skip_typeref(orig_type_right);
8184 source_position_t const *const pos = &expression->base.source_position;
8187 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8188 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8189 expression->left = create_implicit_cast(left, arithmetic_type);
8190 expression->right = create_implicit_cast(right, arithmetic_type);
8191 expression->base.type = arithmetic_type;
8192 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8193 check_pointer_arithmetic(&expression->base.source_position,
8194 type_left, orig_type_left);
8195 expression->base.type = type_left;
8196 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8197 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8198 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8199 if (!types_compatible(unqual_left, unqual_right)) {
8201 "subtracting pointers to incompatible types '%T' and '%T'",
8202 orig_type_left, orig_type_right);
8203 } else if (!is_type_object(unqual_left)) {
8204 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8205 errorf(pos, "subtracting pointers to non-object types '%T'",
8208 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8211 expression->base.type = type_ptrdiff_t;
8212 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8213 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8214 orig_type_left, orig_type_right);
8218 static void warn_string_literal_address(expression_t const* expr)
8220 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8221 expr = expr->unary.value;
8222 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8224 expr = expr->unary.value;
8227 if (expr->kind == EXPR_STRING_LITERAL
8228 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8229 source_position_t const *const pos = &expr->base.source_position;
8230 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8234 static bool maybe_negative(expression_t const *const expr)
8236 switch (is_constant_expression(expr)) {
8237 case EXPR_CLASS_ERROR: return false;
8238 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8239 default: return true;
8243 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8245 warn_string_literal_address(expr);
8247 expression_t const* const ref = get_reference_address(expr);
8248 if (ref != NULL && is_null_pointer_constant(other)) {
8249 entity_t const *const ent = ref->reference.entity;
8250 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8253 if (!expr->base.parenthesized) {
8254 switch (expr->base.kind) {
8255 case EXPR_BINARY_LESS:
8256 case EXPR_BINARY_GREATER:
8257 case EXPR_BINARY_LESSEQUAL:
8258 case EXPR_BINARY_GREATEREQUAL:
8259 case EXPR_BINARY_NOTEQUAL:
8260 case EXPR_BINARY_EQUAL:
8261 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8270 * Check the semantics of comparison expressions.
8272 * @param expression The expression to check.
8274 static void semantic_comparison(binary_expression_t *expression)
8276 source_position_t const *const pos = &expression->base.source_position;
8277 expression_t *const left = expression->left;
8278 expression_t *const right = expression->right;
8280 warn_comparison(pos, left, right);
8281 warn_comparison(pos, right, left);
8283 type_t *orig_type_left = left->base.type;
8284 type_t *orig_type_right = right->base.type;
8285 type_t *type_left = skip_typeref(orig_type_left);
8286 type_t *type_right = skip_typeref(orig_type_right);
8288 /* TODO non-arithmetic types */
8289 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8290 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8292 /* test for signed vs unsigned compares */
8293 if (is_type_integer(arithmetic_type)) {
8294 bool const signed_left = is_type_signed(type_left);
8295 bool const signed_right = is_type_signed(type_right);
8296 if (signed_left != signed_right) {
8297 /* FIXME long long needs better const folding magic */
8298 /* TODO check whether constant value can be represented by other type */
8299 if ((signed_left && maybe_negative(left)) ||
8300 (signed_right && maybe_negative(right))) {
8301 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8306 expression->left = create_implicit_cast(left, arithmetic_type);
8307 expression->right = create_implicit_cast(right, arithmetic_type);
8308 expression->base.type = arithmetic_type;
8309 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8310 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8311 is_type_float(arithmetic_type)) {
8312 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8314 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8315 /* TODO check compatibility */
8316 } else if (is_type_pointer(type_left)) {
8317 expression->right = create_implicit_cast(right, type_left);
8318 } else if (is_type_pointer(type_right)) {
8319 expression->left = create_implicit_cast(left, type_right);
8320 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8321 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8323 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8327 * Checks if a compound type has constant fields.
8329 static bool has_const_fields(const compound_type_t *type)
8331 compound_t *compound = type->compound;
8332 entity_t *entry = compound->members.entities;
8334 for (; entry != NULL; entry = entry->base.next) {
8335 if (!is_declaration(entry))
8338 const type_t *decl_type = skip_typeref(entry->declaration.type);
8339 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8346 static bool is_valid_assignment_lhs(expression_t const* const left)
8348 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8349 type_t *const type_left = skip_typeref(orig_type_left);
8351 if (!is_lvalue(left)) {
8352 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8357 if (left->kind == EXPR_REFERENCE
8358 && left->reference.entity->kind == ENTITY_FUNCTION) {
8359 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8363 if (is_type_array(type_left)) {
8364 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8367 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8368 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8372 if (is_type_incomplete(type_left)) {
8373 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8374 left, orig_type_left);
8377 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8378 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8379 left, orig_type_left);
8386 static void semantic_arithmetic_assign(binary_expression_t *expression)
8388 expression_t *left = expression->left;
8389 expression_t *right = expression->right;
8390 type_t *orig_type_left = left->base.type;
8391 type_t *orig_type_right = right->base.type;
8393 if (!is_valid_assignment_lhs(left))
8396 type_t *type_left = skip_typeref(orig_type_left);
8397 type_t *type_right = skip_typeref(orig_type_right);
8399 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8400 /* TODO: improve error message */
8401 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8402 errorf(&expression->base.source_position,
8403 "operation needs arithmetic types");
8408 /* combined instructions are tricky. We can't create an implicit cast on
8409 * the left side, because we need the uncasted form for the store.
8410 * The ast2firm pass has to know that left_type must be right_type
8411 * for the arithmetic operation and create a cast by itself */
8412 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8413 expression->right = create_implicit_cast(right, arithmetic_type);
8414 expression->base.type = type_left;
8417 static void semantic_divmod_assign(binary_expression_t *expression)
8419 semantic_arithmetic_assign(expression);
8420 warn_div_by_zero(expression);
8423 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8425 expression_t *const left = expression->left;
8426 expression_t *const right = expression->right;
8427 type_t *const orig_type_left = left->base.type;
8428 type_t *const orig_type_right = right->base.type;
8429 type_t *const type_left = skip_typeref(orig_type_left);
8430 type_t *const type_right = skip_typeref(orig_type_right);
8432 if (!is_valid_assignment_lhs(left))
8435 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
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 *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8441 expression->right = create_implicit_cast(right, arithmetic_type);
8442 expression->base.type = type_left;
8443 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8444 check_pointer_arithmetic(&expression->base.source_position,
8445 type_left, orig_type_left);
8446 expression->base.type = type_left;
8447 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8448 errorf(&expression->base.source_position,
8449 "incompatible types '%T' and '%T' in assignment",
8450 orig_type_left, orig_type_right);
8454 static void semantic_integer_assign(binary_expression_t *expression)
8456 expression_t *left = expression->left;
8457 expression_t *right = expression->right;
8458 type_t *orig_type_left = left->base.type;
8459 type_t *orig_type_right = right->base.type;
8461 if (!is_valid_assignment_lhs(left))
8464 type_t *type_left = skip_typeref(orig_type_left);
8465 type_t *type_right = skip_typeref(orig_type_right);
8467 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8468 /* TODO: improve error message */
8469 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8470 errorf(&expression->base.source_position,
8471 "operation needs integer types");
8476 /* combined instructions are tricky. We can't create an implicit cast on
8477 * the left side, because we need the uncasted form for the store.
8478 * The ast2firm pass has to know that left_type must be right_type
8479 * for the arithmetic operation and create a cast by itself */
8480 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8481 expression->right = create_implicit_cast(right, arithmetic_type);
8482 expression->base.type = type_left;
8485 static void semantic_shift_assign(binary_expression_t *expression)
8487 expression_t *left = expression->left;
8489 if (!is_valid_assignment_lhs(left))
8492 if (!semantic_shift(expression))
8495 expression->base.type = skip_typeref(left->base.type);
8498 static void warn_logical_and_within_or(const expression_t *const expr)
8500 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8502 if (expr->base.parenthesized)
8504 source_position_t const *const pos = &expr->base.source_position;
8505 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8509 * Check the semantic restrictions of a logical expression.
8511 static void semantic_logical_op(binary_expression_t *expression)
8513 /* §6.5.13:2 Each of the operands shall have scalar type.
8514 * §6.5.14:2 Each of the operands shall have scalar type. */
8515 semantic_condition(expression->left, "left operand of logical operator");
8516 semantic_condition(expression->right, "right operand of logical operator");
8517 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8518 warn_logical_and_within_or(expression->left);
8519 warn_logical_and_within_or(expression->right);
8521 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8525 * Check the semantic restrictions of a binary assign expression.
8527 static void semantic_binexpr_assign(binary_expression_t *expression)
8529 expression_t *left = expression->left;
8530 type_t *orig_type_left = left->base.type;
8532 if (!is_valid_assignment_lhs(left))
8535 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8536 report_assign_error(error, orig_type_left, expression->right,
8537 "assignment", &left->base.source_position);
8538 expression->right = create_implicit_cast(expression->right, orig_type_left);
8539 expression->base.type = orig_type_left;
8543 * Determine if the outermost operation (or parts thereof) of the given
8544 * expression has no effect in order to generate a warning about this fact.
8545 * Therefore in some cases this only examines some of the operands of the
8546 * expression (see comments in the function and examples below).
8548 * f() + 23; // warning, because + has no effect
8549 * x || f(); // no warning, because x controls execution of f()
8550 * x ? y : f(); // warning, because y has no effect
8551 * (void)x; // no warning to be able to suppress the warning
8552 * This function can NOT be used for an "expression has definitely no effect"-
8554 static bool expression_has_effect(const expression_t *const expr)
8556 switch (expr->kind) {
8557 case EXPR_UNKNOWN: break;
8558 case EXPR_INVALID: return true; /* do NOT warn */
8559 case EXPR_REFERENCE: return false;
8560 case EXPR_REFERENCE_ENUM_VALUE: return false;
8561 case EXPR_LABEL_ADDRESS: return false;
8563 /* suppress the warning for microsoft __noop operations */
8564 case EXPR_LITERAL_MS_NOOP: return true;
8565 case EXPR_LITERAL_BOOLEAN:
8566 case EXPR_LITERAL_CHARACTER:
8567 case EXPR_LITERAL_WIDE_CHARACTER:
8568 case EXPR_LITERAL_INTEGER:
8569 case EXPR_LITERAL_INTEGER_OCTAL:
8570 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8571 case EXPR_LITERAL_FLOATINGPOINT:
8572 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8573 case EXPR_STRING_LITERAL: return false;
8574 case EXPR_WIDE_STRING_LITERAL: return false;
8577 const call_expression_t *const call = &expr->call;
8578 if (call->function->kind != EXPR_REFERENCE)
8581 switch (call->function->reference.entity->function.btk) {
8582 /* FIXME: which builtins have no effect? */
8583 default: return true;
8587 /* Generate the warning if either the left or right hand side of a
8588 * conditional expression has no effect */
8589 case EXPR_CONDITIONAL: {
8590 conditional_expression_t const *const cond = &expr->conditional;
8591 expression_t const *const t = cond->true_expression;
8593 (t == NULL || expression_has_effect(t)) &&
8594 expression_has_effect(cond->false_expression);
8597 case EXPR_SELECT: return false;
8598 case EXPR_ARRAY_ACCESS: return false;
8599 case EXPR_SIZEOF: return false;
8600 case EXPR_CLASSIFY_TYPE: return false;
8601 case EXPR_ALIGNOF: return false;
8603 case EXPR_FUNCNAME: return false;
8604 case EXPR_BUILTIN_CONSTANT_P: return false;
8605 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8606 case EXPR_OFFSETOF: return false;
8607 case EXPR_VA_START: return true;
8608 case EXPR_VA_ARG: return true;
8609 case EXPR_VA_COPY: return true;
8610 case EXPR_STATEMENT: return true; // TODO
8611 case EXPR_COMPOUND_LITERAL: return false;
8613 case EXPR_UNARY_NEGATE: return false;
8614 case EXPR_UNARY_PLUS: return false;
8615 case EXPR_UNARY_BITWISE_NEGATE: return false;
8616 case EXPR_UNARY_NOT: return false;
8617 case EXPR_UNARY_DEREFERENCE: return false;
8618 case EXPR_UNARY_TAKE_ADDRESS: return false;
8619 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8620 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8621 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8622 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8624 /* Treat void casts as if they have an effect in order to being able to
8625 * suppress the warning */
8626 case EXPR_UNARY_CAST: {
8627 type_t *const type = skip_typeref(expr->base.type);
8628 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8631 case EXPR_UNARY_CAST_IMPLICIT: return true;
8632 case EXPR_UNARY_ASSUME: return true;
8633 case EXPR_UNARY_DELETE: return true;
8634 case EXPR_UNARY_DELETE_ARRAY: return true;
8635 case EXPR_UNARY_THROW: return true;
8637 case EXPR_BINARY_ADD: return false;
8638 case EXPR_BINARY_SUB: return false;
8639 case EXPR_BINARY_MUL: return false;
8640 case EXPR_BINARY_DIV: return false;
8641 case EXPR_BINARY_MOD: return false;
8642 case EXPR_BINARY_EQUAL: return false;
8643 case EXPR_BINARY_NOTEQUAL: return false;
8644 case EXPR_BINARY_LESS: return false;
8645 case EXPR_BINARY_LESSEQUAL: return false;
8646 case EXPR_BINARY_GREATER: return false;
8647 case EXPR_BINARY_GREATEREQUAL: return false;
8648 case EXPR_BINARY_BITWISE_AND: return false;
8649 case EXPR_BINARY_BITWISE_OR: return false;
8650 case EXPR_BINARY_BITWISE_XOR: return false;
8651 case EXPR_BINARY_SHIFTLEFT: return false;
8652 case EXPR_BINARY_SHIFTRIGHT: return false;
8653 case EXPR_BINARY_ASSIGN: return true;
8654 case EXPR_BINARY_MUL_ASSIGN: return true;
8655 case EXPR_BINARY_DIV_ASSIGN: return true;
8656 case EXPR_BINARY_MOD_ASSIGN: return true;
8657 case EXPR_BINARY_ADD_ASSIGN: return true;
8658 case EXPR_BINARY_SUB_ASSIGN: return true;
8659 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8660 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8661 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8662 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8663 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8665 /* Only examine the right hand side of && and ||, because the left hand
8666 * side already has the effect of controlling the execution of the right
8668 case EXPR_BINARY_LOGICAL_AND:
8669 case EXPR_BINARY_LOGICAL_OR:
8670 /* Only examine the right hand side of a comma expression, because the left
8671 * hand side has a separate warning */
8672 case EXPR_BINARY_COMMA:
8673 return expression_has_effect(expr->binary.right);
8675 case EXPR_BINARY_ISGREATER: return false;
8676 case EXPR_BINARY_ISGREATEREQUAL: return false;
8677 case EXPR_BINARY_ISLESS: return false;
8678 case EXPR_BINARY_ISLESSEQUAL: return false;
8679 case EXPR_BINARY_ISLESSGREATER: return false;
8680 case EXPR_BINARY_ISUNORDERED: return false;
8683 internal_errorf(HERE, "unexpected expression");
8686 static void semantic_comma(binary_expression_t *expression)
8688 const expression_t *const left = expression->left;
8689 if (!expression_has_effect(left)) {
8690 source_position_t const *const pos = &left->base.source_position;
8691 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8693 expression->base.type = expression->right->base.type;
8697 * @param prec_r precedence of the right operand
8699 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8700 static expression_t *parse_##binexpression_type(expression_t *left) \
8702 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8703 binexpr->binary.left = left; \
8706 expression_t *right = parse_subexpression(prec_r); \
8708 binexpr->binary.right = right; \
8709 sfunc(&binexpr->binary); \
8714 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8715 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8716 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8717 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8718 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8719 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8720 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8721 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8722 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8723 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8724 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8725 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8726 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8727 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8728 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8729 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8730 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8731 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8732 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8733 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8734 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8735 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8736 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8737 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8738 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8739 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8740 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8741 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8742 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8743 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8746 static expression_t *parse_subexpression(precedence_t precedence)
8748 if (token.type < 0) {
8749 return expected_expression_error();
8752 expression_parser_function_t *parser
8753 = &expression_parsers[token.type];
8756 if (parser->parser != NULL) {
8757 left = parser->parser();
8759 left = parse_primary_expression();
8761 assert(left != NULL);
8764 if (token.type < 0) {
8765 return expected_expression_error();
8768 parser = &expression_parsers[token.type];
8769 if (parser->infix_parser == NULL)
8771 if (parser->infix_precedence < precedence)
8774 left = parser->infix_parser(left);
8776 assert(left != NULL);
8777 assert(left->kind != EXPR_UNKNOWN);
8784 * Parse an expression.
8786 static expression_t *parse_expression(void)
8788 return parse_subexpression(PREC_EXPRESSION);
8792 * Register a parser for a prefix-like operator.
8794 * @param parser the parser function
8795 * @param token_type the token type of the prefix token
8797 static void register_expression_parser(parse_expression_function parser,
8800 expression_parser_function_t *entry = &expression_parsers[token_type];
8802 if (entry->parser != NULL) {
8803 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8804 panic("trying to register multiple expression parsers for a token");
8806 entry->parser = parser;
8810 * Register a parser for an infix operator with given precedence.
8812 * @param parser the parser function
8813 * @param token_type the token type of the infix operator
8814 * @param precedence the precedence of the operator
8816 static void register_infix_parser(parse_expression_infix_function parser,
8817 int token_type, precedence_t precedence)
8819 expression_parser_function_t *entry = &expression_parsers[token_type];
8821 if (entry->infix_parser != NULL) {
8822 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8823 panic("trying to register multiple infix expression parsers for a "
8826 entry->infix_parser = parser;
8827 entry->infix_precedence = precedence;
8831 * Initialize the expression parsers.
8833 static void init_expression_parsers(void)
8835 memset(&expression_parsers, 0, sizeof(expression_parsers));
8837 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8838 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8839 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8840 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8841 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8842 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8843 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8844 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8845 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8846 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8847 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8848 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8849 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8850 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8851 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8852 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8853 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8854 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8855 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8856 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8857 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8858 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8859 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8860 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8861 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8862 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8863 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8864 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8865 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8866 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8867 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8868 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8869 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8870 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8871 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8872 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8873 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8875 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8876 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8877 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8878 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8879 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8880 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8881 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8882 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8883 register_expression_parser(parse_sizeof, T_sizeof);
8884 register_expression_parser(parse_alignof, T___alignof__);
8885 register_expression_parser(parse_extension, T___extension__);
8886 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8887 register_expression_parser(parse_delete, T_delete);
8888 register_expression_parser(parse_throw, T_throw);
8892 * Parse a asm statement arguments specification.
8894 static asm_argument_t *parse_asm_arguments(bool is_out)
8896 asm_argument_t *result = NULL;
8897 asm_argument_t **anchor = &result;
8899 while (token.type == T_STRING_LITERAL || token.type == '[') {
8900 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8901 memset(argument, 0, sizeof(argument[0]));
8904 if (token.type != T_IDENTIFIER) {
8905 parse_error_expected("while parsing asm argument",
8906 T_IDENTIFIER, NULL);
8909 argument->symbol = token.symbol;
8911 expect(']', end_error);
8914 argument->constraints = parse_string_literals();
8915 expect('(', end_error);
8916 add_anchor_token(')');
8917 expression_t *expression = parse_expression();
8918 rem_anchor_token(')');
8920 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8921 * change size or type representation (e.g. int -> long is ok, but
8922 * int -> float is not) */
8923 if (expression->kind == EXPR_UNARY_CAST) {
8924 type_t *const type = expression->base.type;
8925 type_kind_t const kind = type->kind;
8926 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8929 if (kind == TYPE_ATOMIC) {
8930 atomic_type_kind_t const akind = type->atomic.akind;
8931 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8932 size = get_atomic_type_size(akind);
8934 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8935 size = get_atomic_type_size(get_intptr_kind());
8939 expression_t *const value = expression->unary.value;
8940 type_t *const value_type = value->base.type;
8941 type_kind_t const value_kind = value_type->kind;
8943 unsigned value_flags;
8944 unsigned value_size;
8945 if (value_kind == TYPE_ATOMIC) {
8946 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8947 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8948 value_size = get_atomic_type_size(value_akind);
8949 } else if (value_kind == TYPE_POINTER) {
8950 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8951 value_size = get_atomic_type_size(get_intptr_kind());
8956 if (value_flags != flags || value_size != size)
8960 } while (expression->kind == EXPR_UNARY_CAST);
8964 if (!is_lvalue(expression)) {
8965 errorf(&expression->base.source_position,
8966 "asm output argument is not an lvalue");
8969 if (argument->constraints.begin[0] == '=')
8970 determine_lhs_ent(expression, NULL);
8972 mark_vars_read(expression, NULL);
8974 mark_vars_read(expression, NULL);
8976 argument->expression = expression;
8977 expect(')', end_error);
8979 set_address_taken(expression, true);
8982 anchor = &argument->next;
8994 * Parse a asm statement clobber specification.
8996 static asm_clobber_t *parse_asm_clobbers(void)
8998 asm_clobber_t *result = NULL;
8999 asm_clobber_t **anchor = &result;
9001 while (token.type == T_STRING_LITERAL) {
9002 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9003 clobber->clobber = parse_string_literals();
9006 anchor = &clobber->next;
9016 * Parse an asm statement.
9018 static statement_t *parse_asm_statement(void)
9020 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9021 asm_statement_t *asm_statement = &statement->asms;
9025 if (next_if(T_volatile))
9026 asm_statement->is_volatile = true;
9028 expect('(', end_error);
9029 add_anchor_token(')');
9030 if (token.type != T_STRING_LITERAL) {
9031 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9034 asm_statement->asm_text = parse_string_literals();
9036 add_anchor_token(':');
9037 if (!next_if(':')) {
9038 rem_anchor_token(':');
9042 asm_statement->outputs = parse_asm_arguments(true);
9043 if (!next_if(':')) {
9044 rem_anchor_token(':');
9048 asm_statement->inputs = parse_asm_arguments(false);
9049 if (!next_if(':')) {
9050 rem_anchor_token(':');
9053 rem_anchor_token(':');
9055 asm_statement->clobbers = parse_asm_clobbers();
9058 rem_anchor_token(')');
9059 expect(')', end_error);
9060 expect(';', end_error);
9062 if (asm_statement->outputs == NULL) {
9063 /* GCC: An 'asm' instruction without any output operands will be treated
9064 * identically to a volatile 'asm' instruction. */
9065 asm_statement->is_volatile = true;
9070 return create_invalid_statement();
9073 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9075 statement_t *inner_stmt;
9076 switch (token.type) {
9078 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9079 inner_stmt = create_invalid_statement();
9083 if (label->kind == STATEMENT_LABEL) {
9084 /* Eat an empty statement here, to avoid the warning about an empty
9085 * statement after a label. label:; is commonly used to have a label
9086 * before a closing brace. */
9087 inner_stmt = create_empty_statement();
9094 inner_stmt = parse_statement();
9095 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9096 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9097 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9098 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9106 * Parse a case statement.
9108 static statement_t *parse_case_statement(void)
9110 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9111 source_position_t *const pos = &statement->base.source_position;
9115 expression_t *const expression = parse_expression();
9116 statement->case_label.expression = expression;
9117 expression_classification_t const expr_class = is_constant_expression(expression);
9118 if (expr_class != EXPR_CLASS_CONSTANT) {
9119 if (expr_class != EXPR_CLASS_ERROR) {
9120 errorf(pos, "case label does not reduce to an integer constant");
9122 statement->case_label.is_bad = true;
9124 long const val = fold_constant_to_int(expression);
9125 statement->case_label.first_case = val;
9126 statement->case_label.last_case = val;
9130 if (next_if(T_DOTDOTDOT)) {
9131 expression_t *const end_range = parse_expression();
9132 statement->case_label.end_range = end_range;
9133 expression_classification_t const end_class = is_constant_expression(end_range);
9134 if (end_class != EXPR_CLASS_CONSTANT) {
9135 if (end_class != EXPR_CLASS_ERROR) {
9136 errorf(pos, "case range does not reduce to an integer constant");
9138 statement->case_label.is_bad = true;
9140 long const val = fold_constant_to_int(end_range);
9141 statement->case_label.last_case = val;
9143 if (val < statement->case_label.first_case) {
9144 statement->case_label.is_empty_range = true;
9145 warningf(WARN_OTHER, pos, "empty range specified");
9151 PUSH_PARENT(statement);
9153 expect(':', end_error);
9156 if (current_switch != NULL) {
9157 if (! statement->case_label.is_bad) {
9158 /* Check for duplicate case values */
9159 case_label_statement_t *c = &statement->case_label;
9160 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9161 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9164 if (c->last_case < l->first_case || c->first_case > l->last_case)
9167 errorf(pos, "duplicate case value (previously used %P)",
9168 &l->base.source_position);
9172 /* link all cases into the switch statement */
9173 if (current_switch->last_case == NULL) {
9174 current_switch->first_case = &statement->case_label;
9176 current_switch->last_case->next = &statement->case_label;
9178 current_switch->last_case = &statement->case_label;
9180 errorf(pos, "case label not within a switch statement");
9183 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9190 * Parse a default statement.
9192 static statement_t *parse_default_statement(void)
9194 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9198 PUSH_PARENT(statement);
9200 expect(':', end_error);
9203 if (current_switch != NULL) {
9204 const case_label_statement_t *def_label = current_switch->default_label;
9205 if (def_label != NULL) {
9206 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9208 current_switch->default_label = &statement->case_label;
9210 /* link all cases into the switch statement */
9211 if (current_switch->last_case == NULL) {
9212 current_switch->first_case = &statement->case_label;
9214 current_switch->last_case->next = &statement->case_label;
9216 current_switch->last_case = &statement->case_label;
9219 errorf(&statement->base.source_position,
9220 "'default' label not within a switch statement");
9223 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9230 * Parse a label statement.
9232 static statement_t *parse_label_statement(void)
9234 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9235 label_t *const label = get_label();
9236 statement->label.label = label;
9238 PUSH_PARENT(statement);
9240 /* if statement is already set then the label is defined twice,
9241 * otherwise it was just mentioned in a goto/local label declaration so far
9243 source_position_t const* const pos = &statement->base.source_position;
9244 if (label->statement != NULL) {
9245 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9247 label->base.source_position = *pos;
9248 label->statement = statement;
9253 statement->label.statement = parse_label_inner_statement(statement, "label");
9255 /* remember the labels in a list for later checking */
9256 *label_anchor = &statement->label;
9257 label_anchor = &statement->label.next;
9263 static statement_t *parse_inner_statement(void)
9265 statement_t *const stmt = parse_statement();
9266 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9267 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9268 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9269 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9275 * Parse an if statement.
9277 static statement_t *parse_if(void)
9279 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9283 PUSH_PARENT(statement);
9285 add_anchor_token('{');
9287 expect('(', end_error);
9288 add_anchor_token(')');
9289 expression_t *const expr = parse_expression();
9290 statement->ifs.condition = expr;
9291 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9293 semantic_condition(expr, "condition of 'if'-statment");
9294 mark_vars_read(expr, NULL);
9295 rem_anchor_token(')');
9296 expect(')', end_error);
9299 rem_anchor_token('{');
9301 add_anchor_token(T_else);
9302 statement_t *const true_stmt = parse_inner_statement();
9303 statement->ifs.true_statement = true_stmt;
9304 rem_anchor_token(T_else);
9306 if (next_if(T_else)) {
9307 statement->ifs.false_statement = parse_inner_statement();
9308 } else if (true_stmt->kind == STATEMENT_IF &&
9309 true_stmt->ifs.false_statement != NULL) {
9310 source_position_t const *const pos = &true_stmt->base.source_position;
9311 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9319 * Check that all enums are handled in a switch.
9321 * @param statement the switch statement to check
9323 static void check_enum_cases(const switch_statement_t *statement)
9325 if (!is_warn_on(WARN_SWITCH_ENUM))
9327 const type_t *type = skip_typeref(statement->expression->base.type);
9328 if (! is_type_enum(type))
9330 const enum_type_t *enumt = &type->enumt;
9332 /* if we have a default, no warnings */
9333 if (statement->default_label != NULL)
9336 /* FIXME: calculation of value should be done while parsing */
9337 /* TODO: quadratic algorithm here. Change to an n log n one */
9338 long last_value = -1;
9339 const entity_t *entry = enumt->enume->base.next;
9340 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9341 entry = entry->base.next) {
9342 const expression_t *expression = entry->enum_value.value;
9343 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9345 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9346 if (l->expression == NULL)
9348 if (l->first_case <= value && value <= l->last_case) {
9354 source_position_t const *const pos = &statement->base.source_position;
9355 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9362 * Parse a switch statement.
9364 static statement_t *parse_switch(void)
9366 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9370 PUSH_PARENT(statement);
9372 expect('(', end_error);
9373 add_anchor_token(')');
9374 expression_t *const expr = parse_expression();
9375 mark_vars_read(expr, NULL);
9376 type_t * type = skip_typeref(expr->base.type);
9377 if (is_type_integer(type)) {
9378 type = promote_integer(type);
9379 if (get_rank(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);
9388 expect(')', end_error);
9389 rem_anchor_token(')');
9391 switch_statement_t *rem = current_switch;
9392 current_switch = &statement->switchs;
9393 statement->switchs.body = parse_inner_statement();
9394 current_switch = rem;
9396 if (statement->switchs.default_label == NULL) {
9397 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9399 check_enum_cases(&statement->switchs);
9405 return create_invalid_statement();
9408 static statement_t *parse_loop_body(statement_t *const loop)
9410 statement_t *const rem = current_loop;
9411 current_loop = loop;
9413 statement_t *const body = parse_inner_statement();
9420 * Parse a while statement.
9422 static statement_t *parse_while(void)
9424 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9428 PUSH_PARENT(statement);
9430 expect('(', end_error);
9431 add_anchor_token(')');
9432 expression_t *const cond = parse_expression();
9433 statement->whiles.condition = cond;
9434 /* §6.8.5:2 The controlling expression of an iteration statement shall
9435 * have scalar type. */
9436 semantic_condition(cond, "condition of 'while'-statement");
9437 mark_vars_read(cond, NULL);
9438 rem_anchor_token(')');
9439 expect(')', end_error);
9441 statement->whiles.body = parse_loop_body(statement);
9447 return create_invalid_statement();
9451 * Parse a do statement.
9453 static statement_t *parse_do(void)
9455 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9459 PUSH_PARENT(statement);
9461 add_anchor_token(T_while);
9462 statement->do_while.body = parse_loop_body(statement);
9463 rem_anchor_token(T_while);
9465 expect(T_while, end_error);
9466 expect('(', end_error);
9467 add_anchor_token(')');
9468 expression_t *const cond = parse_expression();
9469 statement->do_while.condition = cond;
9470 /* §6.8.5:2 The controlling expression of an iteration statement shall
9471 * have scalar type. */
9472 semantic_condition(cond, "condition of 'do-while'-statement");
9473 mark_vars_read(cond, NULL);
9474 rem_anchor_token(')');
9475 expect(')', end_error);
9476 expect(';', end_error);
9482 return create_invalid_statement();
9486 * Parse a for statement.
9488 static statement_t *parse_for(void)
9490 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9494 expect('(', end_error1);
9495 add_anchor_token(')');
9497 PUSH_PARENT(statement);
9498 PUSH_SCOPE(&statement->fors.scope);
9503 } else if (is_declaration_specifier(&token)) {
9504 parse_declaration(record_entity, DECL_FLAGS_NONE);
9506 add_anchor_token(';');
9507 expression_t *const init = parse_expression();
9508 statement->fors.initialisation = init;
9509 mark_vars_read(init, ENT_ANY);
9510 if (!expression_has_effect(init)) {
9511 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9513 rem_anchor_token(';');
9514 expect(';', end_error2);
9519 if (token.type != ';') {
9520 add_anchor_token(';');
9521 expression_t *const cond = parse_expression();
9522 statement->fors.condition = cond;
9523 /* §6.8.5:2 The controlling expression of an iteration statement
9524 * shall have scalar type. */
9525 semantic_condition(cond, "condition of 'for'-statement");
9526 mark_vars_read(cond, NULL);
9527 rem_anchor_token(';');
9529 expect(';', end_error2);
9530 if (token.type != ')') {
9531 expression_t *const step = parse_expression();
9532 statement->fors.step = step;
9533 mark_vars_read(step, ENT_ANY);
9534 if (!expression_has_effect(step)) {
9535 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9538 expect(')', end_error2);
9539 rem_anchor_token(')');
9540 statement->fors.body = parse_loop_body(statement);
9548 rem_anchor_token(')');
9553 return create_invalid_statement();
9557 * Parse a goto statement.
9559 static statement_t *parse_goto(void)
9561 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9564 if (GNU_MODE && next_if('*')) {
9565 expression_t *expression = parse_expression();
9566 mark_vars_read(expression, NULL);
9568 /* Argh: although documentation says the expression must be of type void*,
9569 * gcc accepts anything that can be casted into void* without error */
9570 type_t *type = expression->base.type;
9572 if (type != type_error_type) {
9573 if (!is_type_pointer(type) && !is_type_integer(type)) {
9574 errorf(&expression->base.source_position,
9575 "cannot convert to a pointer type");
9576 } else if (type != type_void_ptr) {
9577 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9579 expression = create_implicit_cast(expression, type_void_ptr);
9582 statement->gotos.expression = expression;
9583 } else if (token.type == T_IDENTIFIER) {
9584 label_t *const label = get_label();
9586 statement->gotos.label = label;
9589 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9591 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9593 return create_invalid_statement();
9596 /* remember the goto's in a list for later checking */
9597 *goto_anchor = &statement->gotos;
9598 goto_anchor = &statement->gotos.next;
9600 expect(';', end_error);
9607 * Parse a continue statement.
9609 static statement_t *parse_continue(void)
9611 if (current_loop == NULL) {
9612 errorf(HERE, "continue statement not within loop");
9615 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9618 expect(';', end_error);
9625 * Parse a break statement.
9627 static statement_t *parse_break(void)
9629 if (current_switch == NULL && current_loop == NULL) {
9630 errorf(HERE, "break statement not within loop or switch");
9633 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9636 expect(';', end_error);
9643 * Parse a __leave statement.
9645 static statement_t *parse_leave_statement(void)
9647 if (current_try == NULL) {
9648 errorf(HERE, "__leave statement not within __try");
9651 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9654 expect(';', end_error);
9661 * Check if a given entity represents a local variable.
9663 static bool is_local_variable(const entity_t *entity)
9665 if (entity->kind != ENTITY_VARIABLE)
9668 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9669 case STORAGE_CLASS_AUTO:
9670 case STORAGE_CLASS_REGISTER: {
9671 const type_t *type = skip_typeref(entity->declaration.type);
9672 if (is_type_function(type)) {
9684 * Check if a given expression represents a local variable.
9686 static bool expression_is_local_variable(const expression_t *expression)
9688 if (expression->base.kind != EXPR_REFERENCE) {
9691 const entity_t *entity = expression->reference.entity;
9692 return is_local_variable(entity);
9696 * Check if a given expression represents a local variable and
9697 * return its declaration then, else return NULL.
9699 entity_t *expression_is_variable(const expression_t *expression)
9701 if (expression->base.kind != EXPR_REFERENCE) {
9704 entity_t *entity = expression->reference.entity;
9705 if (entity->kind != ENTITY_VARIABLE)
9712 * Parse a return statement.
9714 static statement_t *parse_return(void)
9716 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9719 expression_t *return_value = NULL;
9720 if (token.type != ';') {
9721 return_value = parse_expression();
9722 mark_vars_read(return_value, NULL);
9725 const type_t *const func_type = skip_typeref(current_function->base.type);
9726 assert(is_type_function(func_type));
9727 type_t *const return_type = skip_typeref(func_type->function.return_type);
9729 source_position_t const *const pos = &statement->base.source_position;
9730 if (return_value != NULL) {
9731 type_t *return_value_type = skip_typeref(return_value->base.type);
9733 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9734 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9735 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9736 /* Only warn in C mode, because GCC does the same */
9737 if (c_mode & _CXX || strict_mode) {
9739 "'return' with a value, in function returning 'void'");
9741 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9743 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9744 /* Only warn in C mode, because GCC does the same */
9747 "'return' with expression in function returning 'void'");
9749 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9753 assign_error_t error = semantic_assign(return_type, return_value);
9754 report_assign_error(error, return_type, return_value, "'return'",
9757 return_value = create_implicit_cast(return_value, return_type);
9758 /* check for returning address of a local var */
9759 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9760 const expression_t *expression = return_value->unary.value;
9761 if (expression_is_local_variable(expression)) {
9762 warningf(WARN_OTHER, pos, "function returns address of local variable");
9765 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9766 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9767 if (c_mode & _CXX || strict_mode) {
9769 "'return' without value, in function returning non-void");
9771 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9774 statement->returns.value = return_value;
9776 expect(';', end_error);
9783 * Parse a declaration statement.
9785 static statement_t *parse_declaration_statement(void)
9787 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9789 entity_t *before = current_scope->last_entity;
9791 parse_external_declaration();
9793 parse_declaration(record_entity, DECL_FLAGS_NONE);
9796 declaration_statement_t *const decl = &statement->declaration;
9797 entity_t *const begin =
9798 before != NULL ? before->base.next : current_scope->entities;
9799 decl->declarations_begin = begin;
9800 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9806 * Parse an expression statement, ie. expr ';'.
9808 static statement_t *parse_expression_statement(void)
9810 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9812 expression_t *const expr = parse_expression();
9813 statement->expression.expression = expr;
9814 mark_vars_read(expr, ENT_ANY);
9816 expect(';', end_error);
9823 * Parse a microsoft __try { } __finally { } or
9824 * __try{ } __except() { }
9826 static statement_t *parse_ms_try_statment(void)
9828 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9831 PUSH_PARENT(statement);
9833 ms_try_statement_t *rem = current_try;
9834 current_try = &statement->ms_try;
9835 statement->ms_try.try_statement = parse_compound_statement(false);
9840 if (next_if(T___except)) {
9841 expect('(', end_error);
9842 add_anchor_token(')');
9843 expression_t *const expr = parse_expression();
9844 mark_vars_read(expr, NULL);
9845 type_t * type = skip_typeref(expr->base.type);
9846 if (is_type_integer(type)) {
9847 type = promote_integer(type);
9848 } else if (is_type_valid(type)) {
9849 errorf(&expr->base.source_position,
9850 "__expect expression is not an integer, but '%T'", type);
9851 type = type_error_type;
9853 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9854 rem_anchor_token(')');
9855 expect(')', end_error);
9856 statement->ms_try.final_statement = parse_compound_statement(false);
9857 } else if (next_if(T__finally)) {
9858 statement->ms_try.final_statement = parse_compound_statement(false);
9860 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9861 return create_invalid_statement();
9865 return create_invalid_statement();
9868 static statement_t *parse_empty_statement(void)
9870 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9871 statement_t *const statement = create_empty_statement();
9876 static statement_t *parse_local_label_declaration(void)
9878 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9882 entity_t *begin = NULL;
9883 entity_t *end = NULL;
9884 entity_t **anchor = &begin;
9886 if (token.type != T_IDENTIFIER) {
9887 parse_error_expected("while parsing local label declaration",
9888 T_IDENTIFIER, NULL);
9891 symbol_t *symbol = token.symbol;
9892 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9893 if (entity != NULL && entity->base.parent_scope == current_scope) {
9894 source_position_t const *const ppos = &entity->base.source_position;
9895 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9897 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9898 entity->base.parent_scope = current_scope;
9899 entity->base.source_position = token.source_position;
9902 anchor = &entity->base.next;
9905 environment_push(entity);
9908 } while (next_if(','));
9909 expect(';', end_error);
9911 statement->declaration.declarations_begin = begin;
9912 statement->declaration.declarations_end = end;
9916 static void parse_namespace_definition(void)
9920 entity_t *entity = NULL;
9921 symbol_t *symbol = NULL;
9923 if (token.type == T_IDENTIFIER) {
9924 symbol = token.symbol;
9927 entity = get_entity(symbol, NAMESPACE_NORMAL);
9929 && entity->kind != ENTITY_NAMESPACE
9930 && entity->base.parent_scope == current_scope) {
9931 if (is_entity_valid(entity)) {
9932 error_redefined_as_different_kind(&token.source_position,
9933 entity, ENTITY_NAMESPACE);
9939 if (entity == NULL) {
9940 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9941 entity->base.source_position = token.source_position;
9942 entity->base.parent_scope = current_scope;
9945 if (token.type == '=') {
9946 /* TODO: parse namespace alias */
9947 panic("namespace alias definition not supported yet");
9950 environment_push(entity);
9951 append_entity(current_scope, entity);
9953 PUSH_SCOPE(&entity->namespacee.members);
9955 entity_t *old_current_entity = current_entity;
9956 current_entity = entity;
9958 expect('{', end_error);
9960 expect('}', end_error);
9963 assert(current_entity == entity);
9964 current_entity = old_current_entity;
9969 * Parse a statement.
9970 * There's also parse_statement() which additionally checks for
9971 * "statement has no effect" warnings
9973 static statement_t *intern_parse_statement(void)
9975 statement_t *statement = NULL;
9977 /* declaration or statement */
9978 add_anchor_token(';');
9979 switch (token.type) {
9980 case T_IDENTIFIER: {
9981 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9982 if (la1_type == ':') {
9983 statement = parse_label_statement();
9984 } else if (is_typedef_symbol(token.symbol)) {
9985 statement = parse_declaration_statement();
9987 /* it's an identifier, the grammar says this must be an
9988 * expression statement. However it is common that users mistype
9989 * declaration types, so we guess a bit here to improve robustness
9990 * for incorrect programs */
9994 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
9996 statement = parse_expression_statement();
10000 statement = parse_declaration_statement();
10008 case T___extension__: {
10009 /* This can be a prefix to a declaration or an expression statement.
10010 * We simply eat it now and parse the rest with tail recursion. */
10012 statement = intern_parse_statement();
10018 statement = parse_declaration_statement();
10022 statement = parse_local_label_declaration();
10025 case ';': statement = parse_empty_statement(); break;
10026 case '{': statement = parse_compound_statement(false); break;
10027 case T___leave: statement = parse_leave_statement(); break;
10028 case T___try: statement = parse_ms_try_statment(); break;
10029 case T_asm: statement = parse_asm_statement(); break;
10030 case T_break: statement = parse_break(); break;
10031 case T_case: statement = parse_case_statement(); break;
10032 case T_continue: statement = parse_continue(); break;
10033 case T_default: statement = parse_default_statement(); break;
10034 case T_do: statement = parse_do(); break;
10035 case T_for: statement = parse_for(); break;
10036 case T_goto: statement = parse_goto(); break;
10037 case T_if: statement = parse_if(); break;
10038 case T_return: statement = parse_return(); break;
10039 case T_switch: statement = parse_switch(); break;
10040 case T_while: statement = parse_while(); break;
10043 statement = parse_expression_statement();
10047 errorf(HERE, "unexpected token %K while parsing statement", &token);
10048 statement = create_invalid_statement();
10053 rem_anchor_token(';');
10055 assert(statement != NULL
10056 && statement->base.source_position.input_name != NULL);
10062 * parse a statement and emits "statement has no effect" warning if needed
10063 * (This is really a wrapper around intern_parse_statement with check for 1
10064 * single warning. It is needed, because for statement expressions we have
10065 * to avoid the warning on the last statement)
10067 static statement_t *parse_statement(void)
10069 statement_t *statement = intern_parse_statement();
10071 if (statement->kind == STATEMENT_EXPRESSION) {
10072 expression_t *expression = statement->expression.expression;
10073 if (!expression_has_effect(expression)) {
10074 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10082 * Parse a compound statement.
10084 static statement_t *parse_compound_statement(bool inside_expression_statement)
10086 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10088 PUSH_PARENT(statement);
10089 PUSH_SCOPE(&statement->compound.scope);
10092 add_anchor_token('}');
10093 /* tokens, which can start a statement */
10094 /* TODO MS, __builtin_FOO */
10095 add_anchor_token('!');
10096 add_anchor_token('&');
10097 add_anchor_token('(');
10098 add_anchor_token('*');
10099 add_anchor_token('+');
10100 add_anchor_token('-');
10101 add_anchor_token('{');
10102 add_anchor_token('~');
10103 add_anchor_token(T_CHARACTER_CONSTANT);
10104 add_anchor_token(T_COLONCOLON);
10105 add_anchor_token(T_FLOATINGPOINT);
10106 add_anchor_token(T_IDENTIFIER);
10107 add_anchor_token(T_INTEGER);
10108 add_anchor_token(T_MINUSMINUS);
10109 add_anchor_token(T_PLUSPLUS);
10110 add_anchor_token(T_STRING_LITERAL);
10111 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10112 add_anchor_token(T_WIDE_STRING_LITERAL);
10113 add_anchor_token(T__Bool);
10114 add_anchor_token(T__Complex);
10115 add_anchor_token(T__Imaginary);
10116 add_anchor_token(T___FUNCTION__);
10117 add_anchor_token(T___PRETTY_FUNCTION__);
10118 add_anchor_token(T___alignof__);
10119 add_anchor_token(T___attribute__);
10120 add_anchor_token(T___builtin_va_start);
10121 add_anchor_token(T___extension__);
10122 add_anchor_token(T___func__);
10123 add_anchor_token(T___imag__);
10124 add_anchor_token(T___label__);
10125 add_anchor_token(T___real__);
10126 add_anchor_token(T___thread);
10127 add_anchor_token(T_asm);
10128 add_anchor_token(T_auto);
10129 add_anchor_token(T_bool);
10130 add_anchor_token(T_break);
10131 add_anchor_token(T_case);
10132 add_anchor_token(T_char);
10133 add_anchor_token(T_class);
10134 add_anchor_token(T_const);
10135 add_anchor_token(T_const_cast);
10136 add_anchor_token(T_continue);
10137 add_anchor_token(T_default);
10138 add_anchor_token(T_delete);
10139 add_anchor_token(T_double);
10140 add_anchor_token(T_do);
10141 add_anchor_token(T_dynamic_cast);
10142 add_anchor_token(T_enum);
10143 add_anchor_token(T_extern);
10144 add_anchor_token(T_false);
10145 add_anchor_token(T_float);
10146 add_anchor_token(T_for);
10147 add_anchor_token(T_goto);
10148 add_anchor_token(T_if);
10149 add_anchor_token(T_inline);
10150 add_anchor_token(T_int);
10151 add_anchor_token(T_long);
10152 add_anchor_token(T_new);
10153 add_anchor_token(T_operator);
10154 add_anchor_token(T_register);
10155 add_anchor_token(T_reinterpret_cast);
10156 add_anchor_token(T_restrict);
10157 add_anchor_token(T_return);
10158 add_anchor_token(T_short);
10159 add_anchor_token(T_signed);
10160 add_anchor_token(T_sizeof);
10161 add_anchor_token(T_static);
10162 add_anchor_token(T_static_cast);
10163 add_anchor_token(T_struct);
10164 add_anchor_token(T_switch);
10165 add_anchor_token(T_template);
10166 add_anchor_token(T_this);
10167 add_anchor_token(T_throw);
10168 add_anchor_token(T_true);
10169 add_anchor_token(T_try);
10170 add_anchor_token(T_typedef);
10171 add_anchor_token(T_typeid);
10172 add_anchor_token(T_typename);
10173 add_anchor_token(T_typeof);
10174 add_anchor_token(T_union);
10175 add_anchor_token(T_unsigned);
10176 add_anchor_token(T_using);
10177 add_anchor_token(T_void);
10178 add_anchor_token(T_volatile);
10179 add_anchor_token(T_wchar_t);
10180 add_anchor_token(T_while);
10182 statement_t **anchor = &statement->compound.statements;
10183 bool only_decls_so_far = true;
10184 while (token.type != '}') {
10185 if (token.type == T_EOF) {
10186 errorf(&statement->base.source_position,
10187 "EOF while parsing compound statement");
10190 statement_t *sub_statement = intern_parse_statement();
10191 if (is_invalid_statement(sub_statement)) {
10192 /* an error occurred. if we are at an anchor, return */
10198 if (sub_statement->kind != STATEMENT_DECLARATION) {
10199 only_decls_so_far = false;
10200 } else if (!only_decls_so_far) {
10201 source_position_t const *const pos = &sub_statement->base.source_position;
10202 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10205 *anchor = sub_statement;
10207 while (sub_statement->base.next != NULL)
10208 sub_statement = sub_statement->base.next;
10210 anchor = &sub_statement->base.next;
10214 /* look over all statements again to produce no effect warnings */
10215 if (is_warn_on(WARN_UNUSED_VALUE)) {
10216 statement_t *sub_statement = statement->compound.statements;
10217 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10218 if (sub_statement->kind != STATEMENT_EXPRESSION)
10220 /* don't emit a warning for the last expression in an expression
10221 * statement as it has always an effect */
10222 if (inside_expression_statement && sub_statement->base.next == NULL)
10225 expression_t *expression = sub_statement->expression.expression;
10226 if (!expression_has_effect(expression)) {
10227 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10233 rem_anchor_token(T_while);
10234 rem_anchor_token(T_wchar_t);
10235 rem_anchor_token(T_volatile);
10236 rem_anchor_token(T_void);
10237 rem_anchor_token(T_using);
10238 rem_anchor_token(T_unsigned);
10239 rem_anchor_token(T_union);
10240 rem_anchor_token(T_typeof);
10241 rem_anchor_token(T_typename);
10242 rem_anchor_token(T_typeid);
10243 rem_anchor_token(T_typedef);
10244 rem_anchor_token(T_try);
10245 rem_anchor_token(T_true);
10246 rem_anchor_token(T_throw);
10247 rem_anchor_token(T_this);
10248 rem_anchor_token(T_template);
10249 rem_anchor_token(T_switch);
10250 rem_anchor_token(T_struct);
10251 rem_anchor_token(T_static_cast);
10252 rem_anchor_token(T_static);
10253 rem_anchor_token(T_sizeof);
10254 rem_anchor_token(T_signed);
10255 rem_anchor_token(T_short);
10256 rem_anchor_token(T_return);
10257 rem_anchor_token(T_restrict);
10258 rem_anchor_token(T_reinterpret_cast);
10259 rem_anchor_token(T_register);
10260 rem_anchor_token(T_operator);
10261 rem_anchor_token(T_new);
10262 rem_anchor_token(T_long);
10263 rem_anchor_token(T_int);
10264 rem_anchor_token(T_inline);
10265 rem_anchor_token(T_if);
10266 rem_anchor_token(T_goto);
10267 rem_anchor_token(T_for);
10268 rem_anchor_token(T_float);
10269 rem_anchor_token(T_false);
10270 rem_anchor_token(T_extern);
10271 rem_anchor_token(T_enum);
10272 rem_anchor_token(T_dynamic_cast);
10273 rem_anchor_token(T_do);
10274 rem_anchor_token(T_double);
10275 rem_anchor_token(T_delete);
10276 rem_anchor_token(T_default);
10277 rem_anchor_token(T_continue);
10278 rem_anchor_token(T_const_cast);
10279 rem_anchor_token(T_const);
10280 rem_anchor_token(T_class);
10281 rem_anchor_token(T_char);
10282 rem_anchor_token(T_case);
10283 rem_anchor_token(T_break);
10284 rem_anchor_token(T_bool);
10285 rem_anchor_token(T_auto);
10286 rem_anchor_token(T_asm);
10287 rem_anchor_token(T___thread);
10288 rem_anchor_token(T___real__);
10289 rem_anchor_token(T___label__);
10290 rem_anchor_token(T___imag__);
10291 rem_anchor_token(T___func__);
10292 rem_anchor_token(T___extension__);
10293 rem_anchor_token(T___builtin_va_start);
10294 rem_anchor_token(T___attribute__);
10295 rem_anchor_token(T___alignof__);
10296 rem_anchor_token(T___PRETTY_FUNCTION__);
10297 rem_anchor_token(T___FUNCTION__);
10298 rem_anchor_token(T__Imaginary);
10299 rem_anchor_token(T__Complex);
10300 rem_anchor_token(T__Bool);
10301 rem_anchor_token(T_WIDE_STRING_LITERAL);
10302 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10303 rem_anchor_token(T_STRING_LITERAL);
10304 rem_anchor_token(T_PLUSPLUS);
10305 rem_anchor_token(T_MINUSMINUS);
10306 rem_anchor_token(T_INTEGER);
10307 rem_anchor_token(T_IDENTIFIER);
10308 rem_anchor_token(T_FLOATINGPOINT);
10309 rem_anchor_token(T_COLONCOLON);
10310 rem_anchor_token(T_CHARACTER_CONSTANT);
10311 rem_anchor_token('~');
10312 rem_anchor_token('{');
10313 rem_anchor_token('-');
10314 rem_anchor_token('+');
10315 rem_anchor_token('*');
10316 rem_anchor_token('(');
10317 rem_anchor_token('&');
10318 rem_anchor_token('!');
10319 rem_anchor_token('}');
10327 * Check for unused global static functions and variables
10329 static void check_unused_globals(void)
10331 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10334 for (const entity_t *entity = file_scope->entities; entity != NULL;
10335 entity = entity->base.next) {
10336 if (!is_declaration(entity))
10339 const declaration_t *declaration = &entity->declaration;
10340 if (declaration->used ||
10341 declaration->modifiers & DM_UNUSED ||
10342 declaration->modifiers & DM_USED ||
10343 declaration->storage_class != STORAGE_CLASS_STATIC)
10348 if (entity->kind == ENTITY_FUNCTION) {
10349 /* inhibit warning for static inline functions */
10350 if (entity->function.is_inline)
10353 why = WARN_UNUSED_FUNCTION;
10354 s = entity->function.statement != NULL ? "defined" : "declared";
10356 why = WARN_UNUSED_VARIABLE;
10360 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10364 static void parse_global_asm(void)
10366 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10369 expect('(', end_error);
10371 statement->asms.asm_text = parse_string_literals();
10372 statement->base.next = unit->global_asm;
10373 unit->global_asm = statement;
10375 expect(')', end_error);
10376 expect(';', end_error);
10381 static void parse_linkage_specification(void)
10385 source_position_t const pos = *HERE;
10386 char const *const linkage = parse_string_literals().begin;
10388 linkage_kind_t old_linkage = current_linkage;
10389 linkage_kind_t new_linkage;
10390 if (strcmp(linkage, "C") == 0) {
10391 new_linkage = LINKAGE_C;
10392 } else if (strcmp(linkage, "C++") == 0) {
10393 new_linkage = LINKAGE_CXX;
10395 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10396 new_linkage = LINKAGE_INVALID;
10398 current_linkage = new_linkage;
10400 if (next_if('{')) {
10402 expect('}', end_error);
10408 assert(current_linkage == new_linkage);
10409 current_linkage = old_linkage;
10412 static void parse_external(void)
10414 switch (token.type) {
10416 if (look_ahead(1)->type == T_STRING_LITERAL) {
10417 parse_linkage_specification();
10419 DECLARATION_START_NO_EXTERN
10421 case T___extension__:
10422 /* tokens below are for implicit int */
10423 case '&': /* & x; -> int& x; (and error later, because C++ has no
10425 case '*': /* * x; -> int* x; */
10426 case '(':; /* (x); -> int (x); */
10428 parse_external_declaration();
10434 parse_global_asm();
10438 parse_namespace_definition();
10442 if (!strict_mode) {
10443 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10450 errorf(HERE, "stray %K outside of function", &token);
10451 if (token.type == '(' || token.type == '{' || token.type == '[')
10452 eat_until_matching_token(token.type);
10458 static void parse_externals(void)
10460 add_anchor_token('}');
10461 add_anchor_token(T_EOF);
10464 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10465 unsigned char token_anchor_copy[T_LAST_TOKEN];
10466 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10469 while (token.type != T_EOF && token.type != '}') {
10471 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10472 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10474 /* the anchor set and its copy differs */
10475 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10478 if (in_gcc_extension) {
10479 /* an gcc extension scope was not closed */
10480 internal_errorf(HERE, "Leaked __extension__");
10487 rem_anchor_token(T_EOF);
10488 rem_anchor_token('}');
10492 * Parse a translation unit.
10494 static void parse_translation_unit(void)
10496 add_anchor_token(T_EOF);
10501 if (token.type == T_EOF)
10504 errorf(HERE, "stray %K outside of function", &token);
10505 if (token.type == '(' || token.type == '{' || token.type == '[')
10506 eat_until_matching_token(token.type);
10511 void set_default_visibility(elf_visibility_tag_t visibility)
10513 default_visibility = visibility;
10519 * @return the translation unit or NULL if errors occurred.
10521 void start_parsing(void)
10523 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10524 label_stack = NEW_ARR_F(stack_entry_t, 0);
10525 diagnostic_count = 0;
10529 print_to_file(stderr);
10531 assert(unit == NULL);
10532 unit = allocate_ast_zero(sizeof(unit[0]));
10534 assert(file_scope == NULL);
10535 file_scope = &unit->scope;
10537 assert(current_scope == NULL);
10538 scope_push(&unit->scope);
10540 create_gnu_builtins();
10542 create_microsoft_intrinsics();
10545 translation_unit_t *finish_parsing(void)
10547 assert(current_scope == &unit->scope);
10550 assert(file_scope == &unit->scope);
10551 check_unused_globals();
10554 DEL_ARR_F(environment_stack);
10555 DEL_ARR_F(label_stack);
10557 translation_unit_t *result = unit;
10562 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10563 * are given length one. */
10564 static void complete_incomplete_arrays(void)
10566 size_t n = ARR_LEN(incomplete_arrays);
10567 for (size_t i = 0; i != n; ++i) {
10568 declaration_t *const decl = incomplete_arrays[i];
10569 type_t *const type = skip_typeref(decl->type);
10571 if (!is_type_incomplete(type))
10574 source_position_t const *const pos = &decl->base.source_position;
10575 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10577 type_t *const new_type = duplicate_type(type);
10578 new_type->array.size_constant = true;
10579 new_type->array.has_implicit_size = true;
10580 new_type->array.size = 1;
10582 type_t *const result = identify_new_type(new_type);
10584 decl->type = result;
10588 void prepare_main_collect2(entity_t *entity)
10590 // create call to __main
10591 symbol_t *symbol = symbol_table_insert("__main");
10592 entity_t *subsubmain_ent
10593 = create_implicit_function(symbol, &builtin_source_position);
10595 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10596 type_t *ftype = subsubmain_ent->declaration.type;
10597 ref->base.source_position = builtin_source_position;
10598 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10599 ref->reference.entity = subsubmain_ent;
10601 expression_t *call = allocate_expression_zero(EXPR_CALL);
10602 call->base.source_position = builtin_source_position;
10603 call->base.type = type_void;
10604 call->call.function = ref;
10606 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10607 expr_statement->base.source_position = builtin_source_position;
10608 expr_statement->expression.expression = call;
10610 statement_t *statement = entity->function.statement;
10611 assert(statement->kind == STATEMENT_COMPOUND);
10612 compound_statement_t *compounds = &statement->compound;
10614 expr_statement->base.next = compounds->statements;
10615 compounds->statements = expr_statement;
10620 lookahead_bufpos = 0;
10621 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10624 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10625 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10626 parse_translation_unit();
10627 complete_incomplete_arrays();
10628 DEL_ARR_F(incomplete_arrays);
10629 incomplete_arrays = NULL;
10633 * Initialize the parser.
10635 void init_parser(void)
10637 sym_anonymous = symbol_table_insert("<anonymous>");
10639 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10641 init_expression_parsers();
10642 obstack_init(&temp_obst);
10646 * Terminate the parser.
10648 void exit_parser(void)
10650 obstack_free(&temp_obst, NULL);