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;
2788 bool old_gcc_extension = in_gcc_extension;
2790 memset(specifiers, 0, sizeof(*specifiers));
2791 specifiers->source_position = token.source_position;
2794 specifiers->attributes = parse_attributes(specifiers->attributes);
2796 switch (token.type) {
2798 #define MATCH_STORAGE_CLASS(token, class) \
2800 if (specifiers->storage_class != STORAGE_CLASS_NONE) { \
2801 errorf(HERE, "multiple storage classes in declaration specifiers"); \
2803 specifiers->storage_class = class; \
2804 if (specifiers->thread_local) \
2805 goto check_thread_storage_class; \
2809 MATCH_STORAGE_CLASS(T_typedef, STORAGE_CLASS_TYPEDEF)
2810 MATCH_STORAGE_CLASS(T_extern, STORAGE_CLASS_EXTERN)
2811 MATCH_STORAGE_CLASS(T_static, STORAGE_CLASS_STATIC)
2812 MATCH_STORAGE_CLASS(T_auto, STORAGE_CLASS_AUTO)
2813 MATCH_STORAGE_CLASS(T_register, STORAGE_CLASS_REGISTER)
2816 specifiers->attributes
2817 = parse_microsoft_extended_decl_modifier(specifiers->attributes);
2821 if (specifiers->thread_local) {
2822 errorf(HERE, "duplicate '__thread'");
2824 specifiers->thread_local = true;
2825 check_thread_storage_class:
2826 switch (specifiers->storage_class) {
2827 case STORAGE_CLASS_EXTERN:
2828 case STORAGE_CLASS_NONE:
2829 case STORAGE_CLASS_STATIC:
2833 case STORAGE_CLASS_AUTO: wrong = "auto"; goto wrong_thread_storage_class;
2834 case STORAGE_CLASS_REGISTER: wrong = "register"; goto wrong_thread_storage_class;
2835 case STORAGE_CLASS_TYPEDEF: wrong = "typedef"; goto wrong_thread_storage_class;
2836 wrong_thread_storage_class:
2837 errorf(HERE, "'__thread' used with '%s'", wrong);
2844 /* type qualifiers */
2845 #define MATCH_TYPE_QUALIFIER(token, qualifier) \
2847 qualifiers |= qualifier; \
2851 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
2852 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
2853 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
2854 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
2855 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
2856 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
2857 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
2858 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
2860 case T___extension__:
2862 in_gcc_extension = true;
2865 /* type specifiers */
2866 #define MATCH_SPECIFIER(token, specifier, name) \
2868 if (type_specifiers & specifier) { \
2869 errorf(HERE, "multiple " name " type specifiers given"); \
2871 type_specifiers |= specifier; \
2876 MATCH_SPECIFIER(T__Bool, SPECIFIER_BOOL, "_Bool");
2877 MATCH_SPECIFIER(T__Complex, SPECIFIER_COMPLEX, "_Complex");
2878 MATCH_SPECIFIER(T__Imaginary, SPECIFIER_IMAGINARY, "_Imaginary");
2879 MATCH_SPECIFIER(T__int128, SPECIFIER_INT128, "_int128");
2880 MATCH_SPECIFIER(T__int16, SPECIFIER_INT16, "_int16");
2881 MATCH_SPECIFIER(T__int32, SPECIFIER_INT32, "_int32");
2882 MATCH_SPECIFIER(T__int64, SPECIFIER_INT64, "_int64");
2883 MATCH_SPECIFIER(T__int8, SPECIFIER_INT8, "_int8");
2884 MATCH_SPECIFIER(T_bool, SPECIFIER_BOOL, "bool");
2885 MATCH_SPECIFIER(T_char, SPECIFIER_CHAR, "char");
2886 MATCH_SPECIFIER(T_double, SPECIFIER_DOUBLE, "double");
2887 MATCH_SPECIFIER(T_float, SPECIFIER_FLOAT, "float");
2888 MATCH_SPECIFIER(T_int, SPECIFIER_INT, "int");
2889 MATCH_SPECIFIER(T_short, SPECIFIER_SHORT, "short");
2890 MATCH_SPECIFIER(T_signed, SPECIFIER_SIGNED, "signed");
2891 MATCH_SPECIFIER(T_unsigned, SPECIFIER_UNSIGNED, "unsigned");
2892 MATCH_SPECIFIER(T_void, SPECIFIER_VOID, "void");
2893 MATCH_SPECIFIER(T_wchar_t, SPECIFIER_WCHAR_T, "wchar_t");
2897 specifiers->is_inline = true;
2901 case T__forceinline:
2903 specifiers->modifiers |= DM_FORCEINLINE;
2908 if (type_specifiers & SPECIFIER_LONG_LONG) {
2909 errorf(HERE, "too many long type specifiers given");
2910 } else if (type_specifiers & SPECIFIER_LONG) {
2911 type_specifiers |= SPECIFIER_LONG_LONG;
2913 type_specifiers |= SPECIFIER_LONG;
2918 #define CHECK_DOUBLE_TYPE() \
2919 (type != NULL ? errorf(HERE, "multiple types in declaration specifiers") : (void)0)
2922 CHECK_DOUBLE_TYPE();
2923 type = allocate_type_zero(TYPE_COMPOUND_STRUCT);
2925 type->compound.compound = parse_compound_type_specifier(true);
2928 CHECK_DOUBLE_TYPE();
2929 type = allocate_type_zero(TYPE_COMPOUND_UNION);
2930 type->compound.compound = parse_compound_type_specifier(false);
2933 CHECK_DOUBLE_TYPE();
2934 type = parse_enum_specifier();
2937 CHECK_DOUBLE_TYPE();
2938 type = parse_typeof();
2940 case T___builtin_va_list:
2941 CHECK_DOUBLE_TYPE();
2942 type = duplicate_type(type_valist);
2946 case T_IDENTIFIER: {
2947 /* only parse identifier if we haven't found a type yet */
2948 if (type != NULL || type_specifiers != 0) {
2949 /* Be somewhat resilient to typos like 'unsigned lng* f()' in a
2950 * declaration, so it doesn't generate errors about expecting '(' or
2952 switch (look_ahead(1)->type) {
2959 case T__forceinline: /* ^ DECLARATION_START except for __attribute__ */
2963 errorf(HERE, "discarding stray %K in declaration specifier", &token);
2968 goto finish_specifiers;
2972 type_t *const typedef_type = get_typedef_type(token.symbol);
2973 if (typedef_type == NULL) {
2974 /* Be somewhat resilient to typos like 'vodi f()' at the beginning of a
2975 * declaration, so it doesn't generate 'implicit int' followed by more
2976 * errors later on. */
2977 token_type_t const la1_type = (token_type_t)look_ahead(1)->type;
2983 errorf(HERE, "%K does not name a type", &token);
2986 create_error_entity(token.symbol, ENTITY_TYPEDEF);
2988 type = allocate_type_zero(TYPE_TYPEDEF);
2989 type->typedeft.typedefe = &entity->typedefe;
2997 goto finish_specifiers;
3002 type = typedef_type;
3006 /* function specifier */
3008 goto finish_specifiers;
3013 specifiers->attributes = parse_attributes(specifiers->attributes);
3015 in_gcc_extension = old_gcc_extension;
3017 if (type == NULL || (saw_error && type_specifiers != 0)) {
3018 atomic_type_kind_t atomic_type;
3020 /* match valid basic types */
3021 switch (type_specifiers) {
3022 case SPECIFIER_VOID:
3023 atomic_type = ATOMIC_TYPE_VOID;
3025 case SPECIFIER_WCHAR_T:
3026 atomic_type = ATOMIC_TYPE_WCHAR_T;
3028 case SPECIFIER_CHAR:
3029 atomic_type = ATOMIC_TYPE_CHAR;
3031 case SPECIFIER_SIGNED | SPECIFIER_CHAR:
3032 atomic_type = ATOMIC_TYPE_SCHAR;
3034 case SPECIFIER_UNSIGNED | SPECIFIER_CHAR:
3035 atomic_type = ATOMIC_TYPE_UCHAR;
3037 case SPECIFIER_SHORT:
3038 case SPECIFIER_SIGNED | SPECIFIER_SHORT:
3039 case SPECIFIER_SHORT | SPECIFIER_INT:
3040 case SPECIFIER_SIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3041 atomic_type = ATOMIC_TYPE_SHORT;
3043 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT:
3044 case SPECIFIER_UNSIGNED | SPECIFIER_SHORT | SPECIFIER_INT:
3045 atomic_type = ATOMIC_TYPE_USHORT;
3048 case SPECIFIER_SIGNED:
3049 case SPECIFIER_SIGNED | SPECIFIER_INT:
3050 atomic_type = ATOMIC_TYPE_INT;
3052 case SPECIFIER_UNSIGNED:
3053 case SPECIFIER_UNSIGNED | SPECIFIER_INT:
3054 atomic_type = ATOMIC_TYPE_UINT;
3056 case SPECIFIER_LONG:
3057 case SPECIFIER_SIGNED | SPECIFIER_LONG:
3058 case SPECIFIER_LONG | SPECIFIER_INT:
3059 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3060 atomic_type = ATOMIC_TYPE_LONG;
3062 case SPECIFIER_UNSIGNED | SPECIFIER_LONG:
3063 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_INT:
3064 atomic_type = ATOMIC_TYPE_ULONG;
3067 case SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3068 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3069 case SPECIFIER_LONG | SPECIFIER_LONG_LONG | SPECIFIER_INT:
3070 case SPECIFIER_SIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3072 atomic_type = ATOMIC_TYPE_LONGLONG;
3073 goto warn_about_long_long;
3075 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG:
3076 case SPECIFIER_UNSIGNED | SPECIFIER_LONG | SPECIFIER_LONG_LONG
3078 atomic_type = ATOMIC_TYPE_ULONGLONG;
3079 warn_about_long_long:
3080 warningf(WARN_LONG_LONG, &specifiers->source_position, "ISO C90 does not support 'long long'");
3083 case SPECIFIER_UNSIGNED | SPECIFIER_INT8:
3084 atomic_type = unsigned_int8_type_kind;
3087 case SPECIFIER_UNSIGNED | SPECIFIER_INT16:
3088 atomic_type = unsigned_int16_type_kind;
3091 case SPECIFIER_UNSIGNED | SPECIFIER_INT32:
3092 atomic_type = unsigned_int32_type_kind;
3095 case SPECIFIER_UNSIGNED | SPECIFIER_INT64:
3096 atomic_type = unsigned_int64_type_kind;
3099 case SPECIFIER_UNSIGNED | SPECIFIER_INT128:
3100 atomic_type = unsigned_int128_type_kind;
3103 case SPECIFIER_INT8:
3104 case SPECIFIER_SIGNED | SPECIFIER_INT8:
3105 atomic_type = int8_type_kind;
3108 case SPECIFIER_INT16:
3109 case SPECIFIER_SIGNED | SPECIFIER_INT16:
3110 atomic_type = int16_type_kind;
3113 case SPECIFIER_INT32:
3114 case SPECIFIER_SIGNED | SPECIFIER_INT32:
3115 atomic_type = int32_type_kind;
3118 case SPECIFIER_INT64:
3119 case SPECIFIER_SIGNED | SPECIFIER_INT64:
3120 atomic_type = int64_type_kind;
3123 case SPECIFIER_INT128:
3124 case SPECIFIER_SIGNED | SPECIFIER_INT128:
3125 atomic_type = int128_type_kind;
3128 case SPECIFIER_FLOAT:
3129 atomic_type = ATOMIC_TYPE_FLOAT;
3131 case SPECIFIER_DOUBLE:
3132 atomic_type = ATOMIC_TYPE_DOUBLE;
3134 case SPECIFIER_LONG | SPECIFIER_DOUBLE:
3135 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3137 case SPECIFIER_BOOL:
3138 atomic_type = ATOMIC_TYPE_BOOL;
3140 case SPECIFIER_FLOAT | SPECIFIER_COMPLEX:
3141 case SPECIFIER_FLOAT | SPECIFIER_IMAGINARY:
3142 atomic_type = ATOMIC_TYPE_FLOAT;
3144 case SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3145 case SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3146 atomic_type = ATOMIC_TYPE_DOUBLE;
3148 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_COMPLEX:
3149 case SPECIFIER_LONG | SPECIFIER_DOUBLE | SPECIFIER_IMAGINARY:
3150 atomic_type = ATOMIC_TYPE_LONG_DOUBLE;
3153 /* invalid specifier combination, give an error message */
3154 source_position_t const* const pos = &specifiers->source_position;
3155 if (type_specifiers == 0) {
3157 /* ISO/IEC 14882:1998(E) §C.1.5:4 */
3158 if (!(c_mode & _CXX) && !strict_mode) {
3159 warningf(WARN_IMPLICIT_INT, pos, "no type specifiers in declaration, using 'int'");
3160 atomic_type = ATOMIC_TYPE_INT;
3163 errorf(pos, "no type specifiers given in declaration");
3166 } else if ((type_specifiers & SPECIFIER_SIGNED) &&
3167 (type_specifiers & SPECIFIER_UNSIGNED)) {
3168 errorf(pos, "signed and unsigned specifiers given");
3169 } else if (type_specifiers & (SPECIFIER_SIGNED | SPECIFIER_UNSIGNED)) {
3170 errorf(pos, "only integer types can be signed or unsigned");
3172 errorf(pos, "multiple datatypes in declaration");
3178 if (type_specifiers & SPECIFIER_COMPLEX) {
3179 type = allocate_type_zero(TYPE_COMPLEX);
3180 type->complex.akind = atomic_type;
3181 } else if (type_specifiers & SPECIFIER_IMAGINARY) {
3182 type = allocate_type_zero(TYPE_IMAGINARY);
3183 type->imaginary.akind = atomic_type;
3185 type = allocate_type_zero(TYPE_ATOMIC);
3186 type->atomic.akind = atomic_type;
3189 } else if (type_specifiers != 0) {
3190 errorf(&specifiers->source_position, "multiple datatypes in declaration");
3193 /* FIXME: check type qualifiers here */
3194 type->base.qualifiers = qualifiers;
3197 type = identify_new_type(type);
3199 type = typehash_insert(type);
3202 if (specifiers->attributes != NULL)
3203 type = handle_type_attributes(specifiers->attributes, type);
3204 specifiers->type = type;
3208 specifiers->type = type_error_type;
3211 static type_qualifiers_t parse_type_qualifiers(void)
3213 type_qualifiers_t qualifiers = TYPE_QUALIFIER_NONE;
3216 switch (token.type) {
3217 /* type qualifiers */
3218 MATCH_TYPE_QUALIFIER(T_const, TYPE_QUALIFIER_CONST);
3219 MATCH_TYPE_QUALIFIER(T_restrict, TYPE_QUALIFIER_RESTRICT);
3220 MATCH_TYPE_QUALIFIER(T_volatile, TYPE_QUALIFIER_VOLATILE);
3221 /* microsoft extended type modifiers */
3222 MATCH_TYPE_QUALIFIER(T__w64, TYPE_QUALIFIER_W64);
3223 MATCH_TYPE_QUALIFIER(T___ptr32, TYPE_QUALIFIER_PTR32);
3224 MATCH_TYPE_QUALIFIER(T___ptr64, TYPE_QUALIFIER_PTR64);
3225 MATCH_TYPE_QUALIFIER(T___uptr, TYPE_QUALIFIER_UPTR);
3226 MATCH_TYPE_QUALIFIER(T___sptr, TYPE_QUALIFIER_SPTR);
3235 * Parses an K&R identifier list
3237 static void parse_identifier_list(scope_t *scope)
3240 entity_t *const entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, token.symbol);
3241 entity->base.source_position = token.source_position;
3242 /* a K&R parameter has no type, yet */
3246 append_entity(scope, entity);
3247 } while (next_if(',') && token.type == T_IDENTIFIER);
3250 static entity_t *parse_parameter(void)
3252 declaration_specifiers_t specifiers;
3253 parse_declaration_specifiers(&specifiers);
3255 entity_t *entity = parse_declarator(&specifiers,
3256 DECL_MAY_BE_ABSTRACT | DECL_IS_PARAMETER);
3257 anonymous_entity = NULL;
3261 static void semantic_parameter_incomplete(const entity_t *entity)
3263 assert(entity->kind == ENTITY_PARAMETER);
3265 /* §6.7.5.3:4 After adjustment, the parameters in a parameter type
3266 * list in a function declarator that is part of a
3267 * definition of that function shall not have
3268 * incomplete type. */
3269 type_t *type = skip_typeref(entity->declaration.type);
3270 if (is_type_incomplete(type)) {
3271 errorf(&entity->base.source_position, "'%N' has incomplete type", entity);
3275 static bool has_parameters(void)
3277 /* func(void) is not a parameter */
3278 if (token.type == T_IDENTIFIER) {
3279 entity_t const *const entity = get_entity(token.symbol, NAMESPACE_NORMAL);
3282 if (entity->kind != ENTITY_TYPEDEF)
3284 if (skip_typeref(entity->typedefe.type) != type_void)
3286 } else if (token.type != T_void) {
3289 if (look_ahead(1)->type != ')')
3296 * Parses function type parameters (and optionally creates variable_t entities
3297 * for them in a scope)
3299 static void parse_parameters(function_type_t *type, scope_t *scope)
3302 add_anchor_token(')');
3303 int saved_comma_state = save_and_reset_anchor_state(',');
3305 if (token.type == T_IDENTIFIER &&
3306 !is_typedef_symbol(token.symbol)) {
3307 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
3308 if (la1_type == ',' || la1_type == ')') {
3309 type->kr_style_parameters = true;
3310 parse_identifier_list(scope);
3311 goto parameters_finished;
3315 if (token.type == ')') {
3316 /* ISO/IEC 14882:1998(E) §C.1.6:1 */
3317 if (!(c_mode & _CXX))
3318 type->unspecified_parameters = true;
3319 } else if (has_parameters()) {
3320 function_parameter_t **anchor = &type->parameters;
3322 switch (token.type) {
3325 type->variadic = true;
3326 goto parameters_finished;
3331 entity_t *entity = parse_parameter();
3332 if (entity->kind == ENTITY_TYPEDEF) {
3333 errorf(&entity->base.source_position,
3334 "typedef not allowed as function parameter");
3337 assert(is_declaration(entity));
3339 semantic_parameter_incomplete(entity);
3341 function_parameter_t *const parameter =
3342 allocate_parameter(entity->declaration.type);
3344 if (scope != NULL) {
3345 append_entity(scope, entity);
3348 *anchor = parameter;
3349 anchor = ¶meter->next;
3354 goto parameters_finished;
3356 } while (next_if(','));
3359 parameters_finished:
3360 rem_anchor_token(')');
3361 expect(')', end_error);
3364 restore_anchor_state(',', saved_comma_state);
3367 typedef enum construct_type_kind_t {
3370 CONSTRUCT_REFERENCE,
3373 } construct_type_kind_t;
3375 typedef union construct_type_t construct_type_t;
3377 typedef struct construct_type_base_t {
3378 construct_type_kind_t kind;
3379 source_position_t pos;
3380 construct_type_t *next;
3381 } construct_type_base_t;
3383 typedef struct parsed_pointer_t {
3384 construct_type_base_t base;
3385 type_qualifiers_t type_qualifiers;
3386 variable_t *base_variable; /**< MS __based extension. */
3389 typedef struct parsed_reference_t {
3390 construct_type_base_t base;
3391 } parsed_reference_t;
3393 typedef struct construct_function_type_t {
3394 construct_type_base_t base;
3395 type_t *function_type;
3396 } construct_function_type_t;
3398 typedef struct parsed_array_t {
3399 construct_type_base_t base;
3400 type_qualifiers_t type_qualifiers;
3406 union construct_type_t {
3407 construct_type_kind_t kind;
3408 construct_type_base_t base;
3409 parsed_pointer_t pointer;
3410 parsed_reference_t reference;
3411 construct_function_type_t function;
3412 parsed_array_t array;
3415 static construct_type_t *allocate_declarator_zero(construct_type_kind_t const kind, size_t const size)
3417 construct_type_t *const cons = obstack_alloc(&temp_obst, size);
3418 memset(cons, 0, size);
3420 cons->base.pos = *HERE;
3425 static construct_type_t *parse_pointer_declarator(void)
3427 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_POINTER, sizeof(parsed_pointer_t));
3429 cons->pointer.type_qualifiers = parse_type_qualifiers();
3430 //cons->pointer.base_variable = base_variable;
3435 /* ISO/IEC 14882:1998(E) §8.3.2 */
3436 static construct_type_t *parse_reference_declarator(void)
3438 if (!(c_mode & _CXX))
3439 errorf(HERE, "references are only available for C++");
3441 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_REFERENCE, sizeof(parsed_reference_t));
3448 static construct_type_t *parse_array_declarator(void)
3450 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_ARRAY, sizeof(parsed_array_t));
3451 parsed_array_t *const array = &cons->array;
3454 add_anchor_token(']');
3456 bool is_static = next_if(T_static);
3458 type_qualifiers_t type_qualifiers = parse_type_qualifiers();
3461 is_static = next_if(T_static);
3463 array->type_qualifiers = type_qualifiers;
3464 array->is_static = is_static;
3466 expression_t *size = NULL;
3467 if (token.type == '*' && look_ahead(1)->type == ']') {
3468 array->is_variable = true;
3470 } else if (token.type != ']') {
3471 size = parse_assignment_expression();
3473 /* §6.7.5.2:1 Array size must have integer type */
3474 type_t *const orig_type = size->base.type;
3475 type_t *const type = skip_typeref(orig_type);
3476 if (!is_type_integer(type) && is_type_valid(type)) {
3477 errorf(&size->base.source_position,
3478 "array size '%E' must have integer type but has type '%T'",
3483 mark_vars_read(size, NULL);
3486 if (is_static && size == NULL)
3487 errorf(&array->base.pos, "static array parameters require a size");
3489 rem_anchor_token(']');
3490 expect(']', end_error);
3497 static construct_type_t *parse_function_declarator(scope_t *scope)
3499 construct_type_t *const cons = allocate_declarator_zero(CONSTRUCT_FUNCTION, sizeof(construct_function_type_t));
3501 type_t *type = allocate_type_zero(TYPE_FUNCTION);
3502 function_type_t *ftype = &type->function;
3504 ftype->linkage = current_linkage;
3505 ftype->calling_convention = CC_DEFAULT;
3507 parse_parameters(ftype, scope);
3509 cons->function.function_type = type;
3514 typedef struct parse_declarator_env_t {
3515 bool may_be_abstract : 1;
3516 bool must_be_abstract : 1;
3517 decl_modifiers_t modifiers;
3519 source_position_t source_position;
3521 attribute_t *attributes;
3522 } parse_declarator_env_t;
3525 static construct_type_t *parse_inner_declarator(parse_declarator_env_t *env)
3527 /* construct a single linked list of construct_type_t's which describe
3528 * how to construct the final declarator type */
3529 construct_type_t *first = NULL;
3530 construct_type_t **anchor = &first;
3532 env->attributes = parse_attributes(env->attributes);
3535 construct_type_t *type;
3536 //variable_t *based = NULL; /* MS __based extension */
3537 switch (token.type) {
3539 type = parse_reference_declarator();
3543 panic("based not supported anymore");
3548 type = parse_pointer_declarator();
3552 goto ptr_operator_end;
3556 anchor = &type->base.next;
3558 /* TODO: find out if this is correct */
3559 env->attributes = parse_attributes(env->attributes);
3563 construct_type_t *inner_types = NULL;
3565 switch (token.type) {
3567 if (env->must_be_abstract) {
3568 errorf(HERE, "no identifier expected in typename");
3570 env->symbol = token.symbol;
3571 env->source_position = token.source_position;
3577 /* Parenthesized declarator or function declarator? */
3578 token_t const *const la1 = look_ahead(1);
3579 switch (la1->type) {
3581 if (is_typedef_symbol(la1->symbol)) {
3583 /* §6.7.6:2 footnote 126: Empty parentheses in a type name are
3584 * interpreted as ``function with no parameter specification'', rather
3585 * than redundant parentheses around the omitted identifier. */
3587 /* Function declarator. */
3588 if (!env->may_be_abstract) {
3589 errorf(HERE, "function declarator must have a name");
3596 case T___attribute__: /* FIXME __attribute__ might also introduce a parameter of a function declarator. */
3597 /* Paranthesized declarator. */
3599 add_anchor_token(')');
3600 inner_types = parse_inner_declarator(env);
3601 if (inner_types != NULL) {
3602 /* All later declarators only modify the return type */
3603 env->must_be_abstract = true;
3605 rem_anchor_token(')');
3606 expect(')', end_error);
3614 if (env->may_be_abstract)
3616 parse_error_expected("while parsing declarator", T_IDENTIFIER, '(', NULL);
3621 construct_type_t **const p = anchor;
3624 construct_type_t *type;
3625 switch (token.type) {
3627 scope_t *scope = NULL;
3628 if (!env->must_be_abstract) {
3629 scope = &env->parameters;
3632 type = parse_function_declarator(scope);
3636 type = parse_array_declarator();
3639 goto declarator_finished;
3642 /* insert in the middle of the list (at p) */
3643 type->base.next = *p;
3646 anchor = &type->base.next;
3649 declarator_finished:
3650 /* append inner_types at the end of the list, we don't to set anchor anymore
3651 * as it's not needed anymore */
3652 *anchor = inner_types;
3659 static type_t *construct_declarator_type(construct_type_t *construct_list,
3662 construct_type_t *iter = construct_list;
3663 for (; iter != NULL; iter = iter->base.next) {
3664 source_position_t const* const pos = &iter->base.pos;
3665 switch (iter->kind) {
3666 case CONSTRUCT_INVALID:
3668 case CONSTRUCT_FUNCTION: {
3669 construct_function_type_t *function = &iter->function;
3670 type_t *function_type = function->function_type;
3672 function_type->function.return_type = type;
3674 type_t *skipped_return_type = skip_typeref(type);
3676 if (is_type_function(skipped_return_type)) {
3677 errorf(pos, "function returning function is not allowed");
3678 } else if (is_type_array(skipped_return_type)) {
3679 errorf(pos, "function returning array is not allowed");
3681 if (skipped_return_type->base.qualifiers != 0) {
3682 warningf(WARN_OTHER, pos, "type qualifiers in return type of function type are meaningless");
3686 /* The function type was constructed earlier. Freeing it here will
3687 * destroy other types. */
3688 type = typehash_insert(function_type);
3692 case CONSTRUCT_POINTER: {
3693 if (is_type_reference(skip_typeref(type)))
3694 errorf(pos, "cannot declare a pointer to reference");
3696 parsed_pointer_t *pointer = &iter->pointer;
3697 type = make_based_pointer_type(type, pointer->type_qualifiers, pointer->base_variable);
3701 case CONSTRUCT_REFERENCE:
3702 if (is_type_reference(skip_typeref(type)))
3703 errorf(pos, "cannot declare a reference to reference");
3705 type = make_reference_type(type);
3708 case CONSTRUCT_ARRAY: {
3709 if (is_type_reference(skip_typeref(type)))
3710 errorf(pos, "cannot declare an array of references");
3712 parsed_array_t *array = &iter->array;
3713 type_t *array_type = allocate_type_zero(TYPE_ARRAY);
3715 expression_t *size_expression = array->size;
3716 if (size_expression != NULL) {
3718 = create_implicit_cast(size_expression, type_size_t);
3721 array_type->base.qualifiers = array->type_qualifiers;
3722 array_type->array.element_type = type;
3723 array_type->array.is_static = array->is_static;
3724 array_type->array.is_variable = array->is_variable;
3725 array_type->array.size_expression = size_expression;
3727 if (size_expression != NULL) {
3728 switch (is_constant_expression(size_expression)) {
3729 case EXPR_CLASS_CONSTANT: {
3730 long const size = fold_constant_to_int(size_expression);
3731 array_type->array.size = size;
3732 array_type->array.size_constant = true;
3733 /* §6.7.5.2:1 If the expression is a constant expression,
3734 * it shall have a value greater than zero. */
3736 errorf(&size_expression->base.source_position,
3737 "size of array must be greater than zero");
3738 } else if (size == 0 && !GNU_MODE) {
3739 errorf(&size_expression->base.source_position,
3740 "size of array must be greater than zero (zero length arrays are a GCC extension)");
3745 case EXPR_CLASS_VARIABLE:
3746 array_type->array.is_vla = true;
3749 case EXPR_CLASS_ERROR:
3754 type_t *skipped_type = skip_typeref(type);
3756 if (is_type_incomplete(skipped_type)) {
3757 errorf(pos, "array of incomplete type '%T' is not allowed", type);
3758 } else if (is_type_function(skipped_type)) {
3759 errorf(pos, "array of functions is not allowed");
3761 type = identify_new_type(array_type);
3765 internal_errorf(pos, "invalid type construction found");
3771 static type_t *automatic_type_conversion(type_t *orig_type);
3773 static type_t *semantic_parameter(const source_position_t *pos,
3775 const declaration_specifiers_t *specifiers,
3776 entity_t const *const param)
3778 /* §6.7.5.3:7 A declaration of a parameter as ``array of type''
3779 * shall be adjusted to ``qualified pointer to type'',
3781 * §6.7.5.3:8 A declaration of a parameter as ``function returning
3782 * type'' shall be adjusted to ``pointer to function
3783 * returning type'', as in 6.3.2.1. */
3784 type = automatic_type_conversion(type);
3786 if (specifiers->is_inline && is_type_valid(type)) {
3787 errorf(pos, "'%N' declared 'inline'", param);
3790 /* §6.9.1:6 The declarations in the declaration list shall contain
3791 * no storage-class specifier other than register and no
3792 * initializations. */
3793 if (specifiers->thread_local || (
3794 specifiers->storage_class != STORAGE_CLASS_NONE &&
3795 specifiers->storage_class != STORAGE_CLASS_REGISTER)
3797 errorf(pos, "invalid storage class for '%N'", param);
3800 /* delay test for incomplete type, because we might have (void)
3801 * which is legal but incomplete... */
3806 static entity_t *parse_declarator(const declaration_specifiers_t *specifiers,
3807 declarator_flags_t flags)
3809 parse_declarator_env_t env;
3810 memset(&env, 0, sizeof(env));
3811 env.may_be_abstract = (flags & DECL_MAY_BE_ABSTRACT) != 0;
3813 construct_type_t *construct_type = parse_inner_declarator(&env);
3815 construct_declarator_type(construct_type, specifiers->type);
3816 type_t *type = skip_typeref(orig_type);
3818 if (construct_type != NULL) {
3819 obstack_free(&temp_obst, construct_type);
3822 attribute_t *attributes = parse_attributes(env.attributes);
3823 /* append (shared) specifier attribute behind attributes of this
3825 attribute_t **anchor = &attributes;
3826 while (*anchor != NULL)
3827 anchor = &(*anchor)->next;
3828 *anchor = specifiers->attributes;
3831 if (specifiers->storage_class == STORAGE_CLASS_TYPEDEF) {
3832 entity = allocate_entity_zero(ENTITY_TYPEDEF, NAMESPACE_NORMAL, env.symbol);
3833 entity->base.source_position = env.source_position;
3834 entity->typedefe.type = orig_type;
3836 if (anonymous_entity != NULL) {
3837 if (is_type_compound(type)) {
3838 assert(anonymous_entity->compound.alias == NULL);
3839 assert(anonymous_entity->kind == ENTITY_STRUCT ||
3840 anonymous_entity->kind == ENTITY_UNION);
3841 anonymous_entity->compound.alias = entity;
3842 anonymous_entity = NULL;
3843 } else if (is_type_enum(type)) {
3844 assert(anonymous_entity->enume.alias == NULL);
3845 assert(anonymous_entity->kind == ENTITY_ENUM);
3846 anonymous_entity->enume.alias = entity;
3847 anonymous_entity = NULL;
3851 /* create a declaration type entity */
3852 if (flags & DECL_CREATE_COMPOUND_MEMBER) {
3853 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, env.symbol);
3855 if (env.symbol != NULL) {
3856 if (specifiers->is_inline && is_type_valid(type)) {
3857 errorf(&env.source_position,
3858 "compound member '%Y' declared 'inline'", env.symbol);
3861 if (specifiers->thread_local ||
3862 specifiers->storage_class != STORAGE_CLASS_NONE) {
3863 errorf(&env.source_position,
3864 "compound member '%Y' must have no storage class",
3868 } else if (flags & DECL_IS_PARAMETER) {
3869 entity = allocate_entity_zero(ENTITY_PARAMETER, NAMESPACE_NORMAL, env.symbol);
3870 orig_type = semantic_parameter(&env.source_position, orig_type, specifiers, entity);
3871 } else if (is_type_function(type)) {
3872 entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, env.symbol);
3873 entity->function.is_inline = specifiers->is_inline;
3874 entity->function.elf_visibility = default_visibility;
3875 entity->function.parameters = env.parameters;
3877 if (env.symbol != NULL) {
3878 /* this needs fixes for C++ */
3879 bool in_function_scope = current_function != NULL;
3881 if (specifiers->thread_local || (
3882 specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3883 specifiers->storage_class != STORAGE_CLASS_NONE &&
3884 (in_function_scope || specifiers->storage_class != STORAGE_CLASS_STATIC)
3886 errorf(&env.source_position, "invalid storage class for '%N'", entity);
3890 entity = allocate_entity_zero(ENTITY_VARIABLE, NAMESPACE_NORMAL, env.symbol);
3891 entity->variable.elf_visibility = default_visibility;
3892 entity->variable.thread_local = specifiers->thread_local;
3894 if (env.symbol != NULL) {
3895 if (specifiers->is_inline && is_type_valid(type)) {
3896 errorf(&env.source_position, "'%N' declared 'inline'", entity);
3899 bool invalid_storage_class = false;
3900 if (current_scope == file_scope) {
3901 if (specifiers->storage_class != STORAGE_CLASS_EXTERN &&
3902 specifiers->storage_class != STORAGE_CLASS_NONE &&
3903 specifiers->storage_class != STORAGE_CLASS_STATIC) {
3904 invalid_storage_class = true;
3907 if (specifiers->thread_local &&
3908 specifiers->storage_class == STORAGE_CLASS_NONE) {
3909 invalid_storage_class = true;
3912 if (invalid_storage_class) {
3913 errorf(&env.source_position, "invalid storage class for variable '%N'", entity);
3918 entity->base.source_position = env.symbol != NULL ? env.source_position : specifiers->source_position;
3919 entity->declaration.type = orig_type;
3920 entity->declaration.alignment = get_type_alignment(orig_type);
3921 entity->declaration.modifiers = env.modifiers;
3922 entity->declaration.attributes = attributes;
3924 storage_class_t storage_class = specifiers->storage_class;
3925 entity->declaration.declared_storage_class = storage_class;
3927 if (storage_class == STORAGE_CLASS_NONE && current_function != NULL)
3928 storage_class = STORAGE_CLASS_AUTO;
3929 entity->declaration.storage_class = storage_class;
3932 if (attributes != NULL) {
3933 handle_entity_attributes(attributes, entity);
3939 static type_t *parse_abstract_declarator(type_t *base_type)
3941 parse_declarator_env_t env;
3942 memset(&env, 0, sizeof(env));
3943 env.may_be_abstract = true;
3944 env.must_be_abstract = true;
3946 construct_type_t *construct_type = parse_inner_declarator(&env);
3948 type_t *result = construct_declarator_type(construct_type, base_type);
3949 if (construct_type != NULL) {
3950 obstack_free(&temp_obst, construct_type);
3952 result = handle_type_attributes(env.attributes, result);
3958 * Check if the declaration of main is suspicious. main should be a
3959 * function with external linkage, returning int, taking either zero
3960 * arguments, two, or three arguments of appropriate types, ie.
3962 * int main([ int argc, char **argv [, char **env ] ]).
3964 * @param decl the declaration to check
3965 * @param type the function type of the declaration
3967 static void check_main(const entity_t *entity)
3969 const source_position_t *pos = &entity->base.source_position;
3970 if (entity->kind != ENTITY_FUNCTION) {
3971 warningf(WARN_MAIN, pos, "'main' is not a function");
3975 if (entity->declaration.storage_class == STORAGE_CLASS_STATIC) {
3976 warningf(WARN_MAIN, pos, "'main' is normally a non-static function");
3979 type_t *type = skip_typeref(entity->declaration.type);
3980 assert(is_type_function(type));
3982 function_type_t const *const func_type = &type->function;
3983 type_t *const ret_type = func_type->return_type;
3984 if (!types_compatible(skip_typeref(ret_type), type_int)) {
3985 warningf(WARN_MAIN, pos, "return type of 'main' should be 'int', but is '%T'", ret_type);
3987 const function_parameter_t *parm = func_type->parameters;
3989 type_t *const first_type = skip_typeref(parm->type);
3990 type_t *const first_type_unqual = get_unqualified_type(first_type);
3991 if (!types_compatible(first_type_unqual, type_int)) {
3992 warningf(WARN_MAIN, pos, "first argument of 'main' should be 'int', but is '%T'", parm->type);
3996 type_t *const second_type = skip_typeref(parm->type);
3997 type_t *const second_type_unqual
3998 = get_unqualified_type(second_type);
3999 if (!types_compatible(second_type_unqual, type_char_ptr_ptr)) {
4000 warningf(WARN_MAIN, pos, "second argument of 'main' should be 'char**', but is '%T'", parm->type);
4004 type_t *const third_type = skip_typeref(parm->type);
4005 type_t *const third_type_unqual
4006 = get_unqualified_type(third_type);
4007 if (!types_compatible(third_type_unqual, type_char_ptr_ptr)) {
4008 warningf(WARN_MAIN, pos, "third argument of 'main' should be 'char**', but is '%T'", parm->type);
4012 goto warn_arg_count;
4016 warningf(WARN_MAIN, pos, "'main' takes only zero, two or three arguments");
4022 * Check if a symbol is the equal to "main".
4024 static bool is_sym_main(const symbol_t *const sym)
4026 return strcmp(sym->string, "main") == 0;
4029 static void error_redefined_as_different_kind(const source_position_t *pos,
4030 const entity_t *old, entity_kind_t new_kind)
4032 char const *const what = get_entity_kind_name(new_kind);
4033 source_position_t const *const ppos = &old->base.source_position;
4034 errorf(pos, "redeclaration of '%N' as %s (declared %P)", old, what, ppos);
4037 static bool is_entity_valid(entity_t *const ent)
4039 if (is_declaration(ent)) {
4040 return is_type_valid(skip_typeref(ent->declaration.type));
4041 } else if (ent->kind == ENTITY_TYPEDEF) {
4042 return is_type_valid(skip_typeref(ent->typedefe.type));
4047 static bool contains_attribute(const attribute_t *list, const attribute_t *attr)
4049 for (const attribute_t *tattr = list; tattr != NULL; tattr = tattr->next) {
4050 if (attributes_equal(tattr, attr))
4057 * test wether new_list contains any attributes not included in old_list
4059 static bool has_new_attributes(const attribute_t *old_list,
4060 const attribute_t *new_list)
4062 for (const attribute_t *attr = new_list; attr != NULL; attr = attr->next) {
4063 if (!contains_attribute(old_list, attr))
4070 * Merge in attributes from an attribute list (probably from a previous
4071 * declaration with the same name). Warning: destroys the old structure
4072 * of the attribute list - don't reuse attributes after this call.
4074 static void merge_in_attributes(declaration_t *decl, attribute_t *attributes)
4077 for (attribute_t *attr = attributes; attr != NULL; attr = next) {
4079 if (contains_attribute(decl->attributes, attr))
4082 /* move attribute to new declarations attributes list */
4083 attr->next = decl->attributes;
4084 decl->attributes = attr;
4089 * record entities for the NAMESPACE_NORMAL, and produce error messages/warnings
4090 * for various problems that occur for multiple definitions
4092 entity_t *record_entity(entity_t *entity, const bool is_definition)
4094 const symbol_t *const symbol = entity->base.symbol;
4095 const namespace_tag_t namespc = (namespace_tag_t)entity->base.namespc;
4096 const source_position_t *pos = &entity->base.source_position;
4098 /* can happen in error cases */
4102 entity_t *const previous_entity = get_entity(symbol, namespc);
4103 /* pushing the same entity twice will break the stack structure */
4104 assert(previous_entity != entity);
4106 if (entity->kind == ENTITY_FUNCTION) {
4107 type_t *const orig_type = entity->declaration.type;
4108 type_t *const type = skip_typeref(orig_type);
4110 assert(is_type_function(type));
4111 if (type->function.unspecified_parameters &&
4112 previous_entity == NULL &&
4113 !entity->declaration.implicit) {
4114 warningf(WARN_STRICT_PROTOTYPES, pos, "function declaration '%#N' is not a prototype", entity);
4117 if (current_scope == file_scope && is_sym_main(symbol)) {
4122 if (is_declaration(entity) &&
4123 entity->declaration.storage_class == STORAGE_CLASS_EXTERN &&
4124 current_scope != file_scope &&
4125 !entity->declaration.implicit) {
4126 warningf(WARN_NESTED_EXTERNS, pos, "nested extern declaration of '%#N'", entity);
4129 if (previous_entity != NULL) {
4130 source_position_t const *const ppos = &previous_entity->base.source_position;
4132 if (previous_entity->base.parent_scope == ¤t_function->parameters &&
4133 previous_entity->base.parent_scope->depth + 1 == current_scope->depth) {
4134 assert(previous_entity->kind == ENTITY_PARAMETER);
4135 errorf(pos, "declaration of '%N' redeclares the '%N' (declared %P)", entity, previous_entity, ppos);
4139 if (previous_entity->base.parent_scope == current_scope) {
4140 if (previous_entity->kind != entity->kind) {
4141 if (is_entity_valid(previous_entity) && is_entity_valid(entity)) {
4142 error_redefined_as_different_kind(pos, previous_entity,
4147 if (previous_entity->kind == ENTITY_ENUM_VALUE) {
4148 errorf(pos, "redeclaration of '%N' (declared %P)", entity, ppos);
4151 if (previous_entity->kind == ENTITY_TYPEDEF) {
4152 /* TODO: C++ allows this for exactly the same type */
4153 errorf(pos, "redefinition of '%N' (declared %P)", entity, ppos);
4157 /* at this point we should have only VARIABLES or FUNCTIONS */
4158 assert(is_declaration(previous_entity) && is_declaration(entity));
4160 declaration_t *const prev_decl = &previous_entity->declaration;
4161 declaration_t *const decl = &entity->declaration;
4163 /* can happen for K&R style declarations */
4164 if (prev_decl->type == NULL &&
4165 previous_entity->kind == ENTITY_PARAMETER &&
4166 entity->kind == ENTITY_PARAMETER) {
4167 prev_decl->type = decl->type;
4168 prev_decl->storage_class = decl->storage_class;
4169 prev_decl->declared_storage_class = decl->declared_storage_class;
4170 prev_decl->modifiers = decl->modifiers;
4171 return previous_entity;
4174 type_t *const type = skip_typeref(decl->type);
4175 type_t *const prev_type = skip_typeref(prev_decl->type);
4177 if (!types_compatible(type, prev_type)) {
4178 errorf(pos, "declaration '%#N' is incompatible with '%#N' (declared %P)", entity, previous_entity, ppos);
4180 unsigned old_storage_class = prev_decl->storage_class;
4182 if (is_definition &&
4184 !(prev_decl->modifiers & DM_USED) &&
4185 prev_decl->storage_class == STORAGE_CLASS_STATIC) {
4186 warningf(WARN_REDUNDANT_DECLS, ppos, "unnecessary static forward declaration for '%#N'", previous_entity);
4189 storage_class_t new_storage_class = decl->storage_class;
4191 /* pretend no storage class means extern for function
4192 * declarations (except if the previous declaration is neither
4193 * none nor extern) */
4194 if (entity->kind == ENTITY_FUNCTION) {
4195 /* the previous declaration could have unspecified parameters or
4196 * be a typedef, so use the new type */
4197 if (prev_type->function.unspecified_parameters || is_definition)
4198 prev_decl->type = type;
4200 switch (old_storage_class) {
4201 case STORAGE_CLASS_NONE:
4202 old_storage_class = STORAGE_CLASS_EXTERN;
4205 case STORAGE_CLASS_EXTERN:
4206 if (is_definition) {
4207 if (prev_type->function.unspecified_parameters && !is_sym_main(symbol)) {
4208 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4210 } else if (new_storage_class == STORAGE_CLASS_NONE) {
4211 new_storage_class = STORAGE_CLASS_EXTERN;
4218 } else if (is_type_incomplete(prev_type)) {
4219 prev_decl->type = type;
4222 if (old_storage_class == STORAGE_CLASS_EXTERN &&
4223 new_storage_class == STORAGE_CLASS_EXTERN) {
4225 warn_redundant_declaration: ;
4227 = has_new_attributes(prev_decl->attributes,
4229 if (has_new_attrs) {
4230 merge_in_attributes(decl, prev_decl->attributes);
4231 } else if (!is_definition &&
4232 is_type_valid(prev_type) &&
4233 strcmp(ppos->input_name, "<builtin>") != 0) {
4234 warningf(WARN_REDUNDANT_DECLS, pos, "redundant declaration for '%Y' (declared %P)", symbol, ppos);
4236 } else if (current_function == NULL) {
4237 if (old_storage_class != STORAGE_CLASS_STATIC &&
4238 new_storage_class == STORAGE_CLASS_STATIC) {
4239 errorf(pos, "static declaration of '%Y' follows non-static declaration (declared %P)", symbol, ppos);
4240 } else if (old_storage_class == STORAGE_CLASS_EXTERN) {
4241 prev_decl->storage_class = STORAGE_CLASS_NONE;
4242 prev_decl->declared_storage_class = STORAGE_CLASS_NONE;
4244 /* ISO/IEC 14882:1998(E) §C.1.2:1 */
4246 goto error_redeclaration;
4247 goto warn_redundant_declaration;
4249 } else if (is_type_valid(prev_type)) {
4250 if (old_storage_class == new_storage_class) {
4251 error_redeclaration:
4252 errorf(pos, "redeclaration of '%Y' (declared %P)", symbol, ppos);
4254 errorf(pos, "redeclaration of '%Y' with different linkage (declared %P)", symbol, ppos);
4259 prev_decl->modifiers |= decl->modifiers;
4260 if (entity->kind == ENTITY_FUNCTION) {
4261 previous_entity->function.is_inline |= entity->function.is_inline;
4263 return previous_entity;
4267 if (is_warn_on(why = WARN_SHADOW) ||
4268 (is_warn_on(why = WARN_SHADOW_LOCAL) && previous_entity->base.parent_scope != file_scope)) {
4269 char const *const what = get_entity_kind_name(previous_entity->kind);
4270 warningf(why, pos, "'%N' shadows %s (declared %P)", entity, what, ppos);
4274 if (entity->kind == ENTITY_FUNCTION) {
4275 if (is_definition &&
4276 entity->declaration.storage_class != STORAGE_CLASS_STATIC &&
4277 !is_sym_main(symbol)) {
4278 if (is_warn_on(WARN_MISSING_PROTOTYPES)) {
4279 warningf(WARN_MISSING_PROTOTYPES, pos, "no previous prototype for '%#N'", entity);
4281 goto warn_missing_declaration;
4284 } else if (entity->kind == ENTITY_VARIABLE) {
4285 if (current_scope == file_scope &&
4286 entity->declaration.storage_class == STORAGE_CLASS_NONE &&
4287 !entity->declaration.implicit) {
4288 warn_missing_declaration:
4289 warningf(WARN_MISSING_DECLARATIONS, pos, "no previous declaration for '%#N'", entity);
4294 assert(entity->base.parent_scope == NULL);
4295 assert(current_scope != NULL);
4297 entity->base.parent_scope = current_scope;
4298 environment_push(entity);
4299 append_entity(current_scope, entity);
4304 static void parser_error_multiple_definition(entity_t *entity,
4305 const source_position_t *source_position)
4307 errorf(source_position, "multiple definition of '%Y' (declared %P)",
4308 entity->base.symbol, &entity->base.source_position);
4311 static bool is_declaration_specifier(const token_t *token)
4313 switch (token->type) {
4317 return is_typedef_symbol(token->symbol);
4324 static void parse_init_declarator_rest(entity_t *entity)
4326 type_t *orig_type = type_error_type;
4328 if (entity->base.kind == ENTITY_TYPEDEF) {
4329 source_position_t const *const pos = &entity->base.source_position;
4330 errorf(pos, "'%N' is initialized (use __typeof__ instead)", entity);
4332 assert(is_declaration(entity));
4333 orig_type = entity->declaration.type;
4336 type_t *type = skip_typeref(orig_type);
4338 if (entity->kind == ENTITY_VARIABLE
4339 && entity->variable.initializer != NULL) {
4340 parser_error_multiple_definition(entity, HERE);
4344 declaration_t *const declaration = &entity->declaration;
4345 bool must_be_constant = false;
4346 if (declaration->storage_class == STORAGE_CLASS_STATIC ||
4347 entity->base.parent_scope == file_scope) {
4348 must_be_constant = true;
4351 if (is_type_function(type)) {
4352 source_position_t const *const pos = &entity->base.source_position;
4353 errorf(pos, "'%N' is initialized like a variable", entity);
4354 orig_type = type_error_type;
4357 parse_initializer_env_t env;
4358 env.type = orig_type;
4359 env.must_be_constant = must_be_constant;
4360 env.entity = entity;
4361 current_init_decl = entity;
4363 initializer_t *initializer = parse_initializer(&env);
4364 current_init_decl = NULL;
4366 if (entity->kind == ENTITY_VARIABLE) {
4367 /* §6.7.5:22 array initializers for arrays with unknown size
4368 * determine the array type size */
4369 declaration->type = env.type;
4370 entity->variable.initializer = initializer;
4374 /* parse rest of a declaration without any declarator */
4375 static void parse_anonymous_declaration_rest(
4376 const declaration_specifiers_t *specifiers)
4379 anonymous_entity = NULL;
4381 source_position_t const *const pos = &specifiers->source_position;
4382 if (specifiers->storage_class != STORAGE_CLASS_NONE ||
4383 specifiers->thread_local) {
4384 warningf(WARN_OTHER, pos, "useless storage class in empty declaration");
4387 type_t *type = specifiers->type;
4388 switch (type->kind) {
4389 case TYPE_COMPOUND_STRUCT:
4390 case TYPE_COMPOUND_UNION: {
4391 if (type->compound.compound->base.symbol == NULL) {
4392 warningf(WARN_OTHER, pos, "unnamed struct/union that defines no instances");
4401 warningf(WARN_OTHER, pos, "empty declaration");
4406 static void check_variable_type_complete(entity_t *ent)
4408 if (ent->kind != ENTITY_VARIABLE)
4411 /* §6.7:7 If an identifier for an object is declared with no linkage, the
4412 * type for the object shall be complete [...] */
4413 declaration_t *decl = &ent->declaration;
4414 if (decl->storage_class == STORAGE_CLASS_EXTERN ||
4415 decl->storage_class == STORAGE_CLASS_STATIC)
4418 type_t *const type = skip_typeref(decl->type);
4419 if (!is_type_incomplete(type))
4422 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
4423 * are given length one. */
4424 if (is_type_array(type) && ent->base.parent_scope == file_scope) {
4425 ARR_APP1(declaration_t*, incomplete_arrays, decl);
4429 errorf(&ent->base.source_position, "variable '%#N' has incomplete type", ent);
4433 static void parse_declaration_rest(entity_t *ndeclaration,
4434 const declaration_specifiers_t *specifiers,
4435 parsed_declaration_func finished_declaration,
4436 declarator_flags_t flags)
4438 add_anchor_token(';');
4439 add_anchor_token(',');
4441 entity_t *entity = finished_declaration(ndeclaration, token.type == '=');
4443 if (token.type == '=') {
4444 parse_init_declarator_rest(entity);
4445 } else if (entity->kind == ENTITY_VARIABLE) {
4446 /* ISO/IEC 14882:1998(E) §8.5.3:3 The initializer can be omitted
4447 * [...] where the extern specifier is explicitly used. */
4448 declaration_t *decl = &entity->declaration;
4449 if (decl->storage_class != STORAGE_CLASS_EXTERN) {
4450 type_t *type = decl->type;
4451 if (is_type_reference(skip_typeref(type))) {
4452 source_position_t const *const pos = &entity->base.source_position;
4453 errorf(pos, "reference '%#N' must be initialized", entity);
4458 check_variable_type_complete(entity);
4463 add_anchor_token('=');
4464 ndeclaration = parse_declarator(specifiers, flags);
4465 rem_anchor_token('=');
4467 expect(';', end_error);
4470 anonymous_entity = NULL;
4471 rem_anchor_token(';');
4472 rem_anchor_token(',');
4475 static entity_t *finished_kr_declaration(entity_t *entity, bool is_definition)
4477 symbol_t *symbol = entity->base.symbol;
4481 assert(entity->base.namespc == NAMESPACE_NORMAL);
4482 entity_t *previous_entity = get_entity(symbol, NAMESPACE_NORMAL);
4483 if (previous_entity == NULL
4484 || previous_entity->base.parent_scope != current_scope) {
4485 errorf(&entity->base.source_position, "expected declaration of a function parameter, found '%Y'",
4490 if (is_definition) {
4491 errorf(HERE, "'%N' is initialised", entity);
4494 return record_entity(entity, false);
4497 static void parse_declaration(parsed_declaration_func finished_declaration,
4498 declarator_flags_t flags)
4500 add_anchor_token(';');
4501 declaration_specifiers_t specifiers;
4502 parse_declaration_specifiers(&specifiers);
4503 rem_anchor_token(';');
4505 if (token.type == ';') {
4506 parse_anonymous_declaration_rest(&specifiers);
4508 entity_t *entity = parse_declarator(&specifiers, flags);
4509 parse_declaration_rest(entity, &specifiers, finished_declaration, flags);
4514 static type_t *get_default_promoted_type(type_t *orig_type)
4516 type_t *result = orig_type;
4518 type_t *type = skip_typeref(orig_type);
4519 if (is_type_integer(type)) {
4520 result = promote_integer(type);
4521 } else if (is_type_atomic(type, ATOMIC_TYPE_FLOAT)) {
4522 result = type_double;
4528 static void parse_kr_declaration_list(entity_t *entity)
4530 if (entity->kind != ENTITY_FUNCTION)
4533 type_t *type = skip_typeref(entity->declaration.type);
4534 assert(is_type_function(type));
4535 if (!type->function.kr_style_parameters)
4538 add_anchor_token('{');
4540 PUSH_SCOPE(&entity->function.parameters);
4542 entity_t *parameter = entity->function.parameters.entities;
4543 for ( ; parameter != NULL; parameter = parameter->base.next) {
4544 assert(parameter->base.parent_scope == NULL);
4545 parameter->base.parent_scope = current_scope;
4546 environment_push(parameter);
4549 /* parse declaration list */
4551 switch (token.type) {
4553 /* This covers symbols, which are no type, too, and results in
4554 * better error messages. The typical cases are misspelled type
4555 * names and missing includes. */
4557 parse_declaration(finished_kr_declaration, DECL_IS_PARAMETER);
4567 /* update function type */
4568 type_t *new_type = duplicate_type(type);
4570 function_parameter_t *parameters = NULL;
4571 function_parameter_t **anchor = ¶meters;
4573 /* did we have an earlier prototype? */
4574 entity_t *proto_type = get_entity(entity->base.symbol, NAMESPACE_NORMAL);
4575 if (proto_type != NULL && proto_type->kind != ENTITY_FUNCTION)
4578 function_parameter_t *proto_parameter = NULL;
4579 if (proto_type != NULL) {
4580 type_t *proto_type_type = proto_type->declaration.type;
4581 proto_parameter = proto_type_type->function.parameters;
4582 /* If a K&R function definition has a variadic prototype earlier, then
4583 * make the function definition variadic, too. This should conform to
4584 * §6.7.5.3:15 and §6.9.1:8. */
4585 new_type->function.variadic = proto_type_type->function.variadic;
4587 /* §6.9.1.7: A K&R style parameter list does NOT act as a function
4589 new_type->function.unspecified_parameters = true;
4592 bool need_incompatible_warning = false;
4593 parameter = entity->function.parameters.entities;
4594 for (; parameter != NULL; parameter = parameter->base.next,
4596 proto_parameter == NULL ? NULL : proto_parameter->next) {
4597 if (parameter->kind != ENTITY_PARAMETER)
4600 type_t *parameter_type = parameter->declaration.type;
4601 if (parameter_type == NULL) {
4602 source_position_t const* const pos = ¶meter->base.source_position;
4604 errorf(pos, "no type specified for function '%N'", parameter);
4605 parameter_type = type_error_type;
4607 warningf(WARN_IMPLICIT_INT, pos, "no type specified for function parameter '%N', using 'int'", parameter);
4608 parameter_type = type_int;
4610 parameter->declaration.type = parameter_type;
4613 semantic_parameter_incomplete(parameter);
4615 /* we need the default promoted types for the function type */
4616 type_t *not_promoted = parameter_type;
4617 parameter_type = get_default_promoted_type(parameter_type);
4619 /* gcc special: if the type of the prototype matches the unpromoted
4620 * type don't promote */
4621 if (!strict_mode && proto_parameter != NULL) {
4622 type_t *proto_p_type = skip_typeref(proto_parameter->type);
4623 type_t *promo_skip = skip_typeref(parameter_type);
4624 type_t *param_skip = skip_typeref(not_promoted);
4625 if (!types_compatible(proto_p_type, promo_skip)
4626 && types_compatible(proto_p_type, param_skip)) {
4628 need_incompatible_warning = true;
4629 parameter_type = not_promoted;
4632 function_parameter_t *const function_parameter
4633 = allocate_parameter(parameter_type);
4635 *anchor = function_parameter;
4636 anchor = &function_parameter->next;
4639 new_type->function.parameters = parameters;
4640 new_type = identify_new_type(new_type);
4642 if (need_incompatible_warning) {
4643 symbol_t const *const sym = entity->base.symbol;
4644 source_position_t const *const pos = &entity->base.source_position;
4645 source_position_t const *const ppos = &proto_type->base.source_position;
4646 warningf(WARN_OTHER, pos, "declaration '%#N' is incompatible with '%#T' (declared %P)", proto_type, new_type, sym, ppos);
4648 entity->declaration.type = new_type;
4650 rem_anchor_token('{');
4653 static bool first_err = true;
4656 * When called with first_err set, prints the name of the current function,
4659 static void print_in_function(void)
4663 char const *const file = current_function->base.base.source_position.input_name;
4664 diagnosticf("%s: In '%N':\n", file, (entity_t const*)current_function);
4669 * Check if all labels are defined in the current function.
4670 * Check if all labels are used in the current function.
4672 static void check_labels(void)
4674 for (const goto_statement_t *goto_statement = goto_first;
4675 goto_statement != NULL;
4676 goto_statement = goto_statement->next) {
4677 /* skip computed gotos */
4678 if (goto_statement->expression != NULL)
4681 label_t *label = goto_statement->label;
4682 if (label->base.source_position.input_name == NULL) {
4683 print_in_function();
4684 source_position_t const *const pos = &goto_statement->base.source_position;
4685 errorf(pos, "'%N' used but not defined", (entity_t const*)label);
4689 if (is_warn_on(WARN_UNUSED_LABEL)) {
4690 for (const label_statement_t *label_statement = label_first;
4691 label_statement != NULL;
4692 label_statement = label_statement->next) {
4693 label_t *label = label_statement->label;
4695 if (! label->used) {
4696 print_in_function();
4697 source_position_t const *const pos = &label_statement->base.source_position;
4698 warningf(WARN_UNUSED_LABEL, pos, "'%N' defined but not used", (entity_t const*)label);
4704 static void warn_unused_entity(warning_t const why, entity_t *entity, entity_t *const last)
4706 entity_t const *const end = last != NULL ? last->base.next : NULL;
4707 for (; entity != end; entity = entity->base.next) {
4708 if (!is_declaration(entity))
4711 declaration_t *declaration = &entity->declaration;
4712 if (declaration->implicit)
4715 if (!declaration->used) {
4716 print_in_function();
4717 warningf(why, &entity->base.source_position, "'%N' is unused", entity);
4718 } else if (entity->kind == ENTITY_VARIABLE && !entity->variable.read) {
4719 print_in_function();
4720 warningf(why, &entity->base.source_position, "'%N' is never read", entity);
4725 static void check_unused_variables(statement_t *const stmt, void *const env)
4729 switch (stmt->kind) {
4730 case STATEMENT_DECLARATION: {
4731 declaration_statement_t const *const decls = &stmt->declaration;
4732 warn_unused_entity(WARN_UNUSED_VARIABLE, decls->declarations_begin, decls->declarations_end);
4737 warn_unused_entity(WARN_UNUSED_VARIABLE, stmt->fors.scope.entities, NULL);
4746 * Check declarations of current_function for unused entities.
4748 static void check_declarations(void)
4750 if (is_warn_on(WARN_UNUSED_PARAMETER)) {
4751 const scope_t *scope = ¤t_function->parameters;
4753 /* do not issue unused warnings for main */
4754 if (!is_sym_main(current_function->base.base.symbol)) {
4755 warn_unused_entity(WARN_UNUSED_PARAMETER, scope->entities, NULL);
4758 if (is_warn_on(WARN_UNUSED_VARIABLE)) {
4759 walk_statements(current_function->statement, check_unused_variables,
4764 static int determine_truth(expression_t const* const cond)
4767 is_constant_expression(cond) != EXPR_CLASS_CONSTANT ? 0 :
4768 fold_constant_to_bool(cond) ? 1 :
4772 static void check_reachable(statement_t *);
4773 static bool reaches_end;
4775 static bool expression_returns(expression_t const *const expr)
4777 switch (expr->kind) {
4779 expression_t const *const func = expr->call.function;
4780 if (func->kind == EXPR_REFERENCE) {
4781 entity_t *entity = func->reference.entity;
4782 if (entity->kind == ENTITY_FUNCTION
4783 && entity->declaration.modifiers & DM_NORETURN)
4787 if (!expression_returns(func))
4790 for (call_argument_t const* arg = expr->call.arguments; arg != NULL; arg = arg->next) {
4791 if (!expression_returns(arg->expression))
4798 case EXPR_REFERENCE:
4799 case EXPR_REFERENCE_ENUM_VALUE:
4801 case EXPR_STRING_LITERAL:
4802 case EXPR_WIDE_STRING_LITERAL:
4803 case EXPR_COMPOUND_LITERAL: // TODO descend into initialisers
4804 case EXPR_LABEL_ADDRESS:
4805 case EXPR_CLASSIFY_TYPE:
4806 case EXPR_SIZEOF: // TODO handle obscure VLA case
4809 case EXPR_BUILTIN_CONSTANT_P:
4810 case EXPR_BUILTIN_TYPES_COMPATIBLE_P:
4815 case EXPR_STATEMENT: {
4816 bool old_reaches_end = reaches_end;
4817 reaches_end = false;
4818 check_reachable(expr->statement.statement);
4819 bool returns = reaches_end;
4820 reaches_end = old_reaches_end;
4824 case EXPR_CONDITIONAL:
4825 // TODO handle constant expression
4827 if (!expression_returns(expr->conditional.condition))
4830 if (expr->conditional.true_expression != NULL
4831 && expression_returns(expr->conditional.true_expression))
4834 return expression_returns(expr->conditional.false_expression);
4837 return expression_returns(expr->select.compound);
4839 case EXPR_ARRAY_ACCESS:
4841 expression_returns(expr->array_access.array_ref) &&
4842 expression_returns(expr->array_access.index);
4845 return expression_returns(expr->va_starte.ap);
4848 return expression_returns(expr->va_arge.ap);
4851 return expression_returns(expr->va_copye.src);
4853 EXPR_UNARY_CASES_MANDATORY
4854 return expression_returns(expr->unary.value);
4856 case EXPR_UNARY_THROW:
4860 // TODO handle constant lhs of && and ||
4862 expression_returns(expr->binary.left) &&
4863 expression_returns(expr->binary.right);
4869 panic("unhandled expression");
4872 static bool initializer_returns(initializer_t const *const init)
4874 switch (init->kind) {
4875 case INITIALIZER_VALUE:
4876 return expression_returns(init->value.value);
4878 case INITIALIZER_LIST: {
4879 initializer_t * const* i = init->list.initializers;
4880 initializer_t * const* const end = i + init->list.len;
4881 bool returns = true;
4882 for (; i != end; ++i) {
4883 if (!initializer_returns(*i))
4889 case INITIALIZER_STRING:
4890 case INITIALIZER_WIDE_STRING:
4891 case INITIALIZER_DESIGNATOR: // designators have no payload
4894 panic("unhandled initializer");
4897 static bool noreturn_candidate;
4899 static void check_reachable(statement_t *const stmt)
4901 if (stmt->base.reachable)
4903 if (stmt->kind != STATEMENT_DO_WHILE)
4904 stmt->base.reachable = true;
4906 statement_t *last = stmt;
4908 switch (stmt->kind) {
4909 case STATEMENT_INVALID:
4910 case STATEMENT_EMPTY:
4912 next = stmt->base.next;
4915 case STATEMENT_DECLARATION: {
4916 declaration_statement_t const *const decl = &stmt->declaration;
4917 entity_t const * ent = decl->declarations_begin;
4918 entity_t const *const last_decl = decl->declarations_end;
4920 for (;; ent = ent->base.next) {
4921 if (ent->kind == ENTITY_VARIABLE &&
4922 ent->variable.initializer != NULL &&
4923 !initializer_returns(ent->variable.initializer)) {
4926 if (ent == last_decl)
4930 next = stmt->base.next;
4934 case STATEMENT_COMPOUND:
4935 next = stmt->compound.statements;
4937 next = stmt->base.next;
4940 case STATEMENT_RETURN: {
4941 expression_t const *const val = stmt->returns.value;
4942 if (val == NULL || expression_returns(val))
4943 noreturn_candidate = false;
4947 case STATEMENT_IF: {
4948 if_statement_t const *const ifs = &stmt->ifs;
4949 expression_t const *const cond = ifs->condition;
4951 if (!expression_returns(cond))
4954 int const val = determine_truth(cond);
4957 check_reachable(ifs->true_statement);
4962 if (ifs->false_statement != NULL) {
4963 check_reachable(ifs->false_statement);
4967 next = stmt->base.next;
4971 case STATEMENT_SWITCH: {
4972 switch_statement_t const *const switchs = &stmt->switchs;
4973 expression_t const *const expr = switchs->expression;
4975 if (!expression_returns(expr))
4978 if (is_constant_expression(expr) == EXPR_CLASS_CONSTANT) {
4979 long const val = fold_constant_to_int(expr);
4980 case_label_statement_t * defaults = NULL;
4981 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
4982 if (i->expression == NULL) {
4987 if (i->first_case <= val && val <= i->last_case) {
4988 check_reachable((statement_t*)i);
4993 if (defaults != NULL) {
4994 check_reachable((statement_t*)defaults);
4998 bool has_default = false;
4999 for (case_label_statement_t *i = switchs->first_case; i != NULL; i = i->next) {
5000 if (i->expression == NULL)
5003 check_reachable((statement_t*)i);
5010 next = stmt->base.next;
5014 case STATEMENT_EXPRESSION: {
5015 /* Check for noreturn function call */
5016 expression_t const *const expr = stmt->expression.expression;
5017 if (!expression_returns(expr))
5020 next = stmt->base.next;
5024 case STATEMENT_CONTINUE:
5025 for (statement_t *parent = stmt;;) {
5026 parent = parent->base.parent;
5027 if (parent == NULL) /* continue not within loop */
5031 switch (parent->kind) {
5032 case STATEMENT_WHILE: goto continue_while;
5033 case STATEMENT_DO_WHILE: goto continue_do_while;
5034 case STATEMENT_FOR: goto continue_for;
5040 case STATEMENT_BREAK:
5041 for (statement_t *parent = stmt;;) {
5042 parent = parent->base.parent;
5043 if (parent == NULL) /* break not within loop/switch */
5046 switch (parent->kind) {
5047 case STATEMENT_SWITCH:
5048 case STATEMENT_WHILE:
5049 case STATEMENT_DO_WHILE:
5052 next = parent->base.next;
5053 goto found_break_parent;
5061 case STATEMENT_GOTO:
5062 if (stmt->gotos.expression) {
5063 if (!expression_returns(stmt->gotos.expression))
5066 statement_t *parent = stmt->base.parent;
5067 if (parent == NULL) /* top level goto */
5071 next = stmt->gotos.label->statement;
5072 if (next == NULL) /* missing label */
5077 case STATEMENT_LABEL:
5078 next = stmt->label.statement;
5081 case STATEMENT_CASE_LABEL:
5082 next = stmt->case_label.statement;
5085 case STATEMENT_WHILE: {
5086 while_statement_t const *const whiles = &stmt->whiles;
5087 expression_t const *const cond = whiles->condition;
5089 if (!expression_returns(cond))
5092 int const val = determine_truth(cond);
5095 check_reachable(whiles->body);
5100 next = stmt->base.next;
5104 case STATEMENT_DO_WHILE:
5105 next = stmt->do_while.body;
5108 case STATEMENT_FOR: {
5109 for_statement_t *const fors = &stmt->fors;
5111 if (fors->condition_reachable)
5113 fors->condition_reachable = true;
5115 expression_t const *const cond = fors->condition;
5120 } else if (expression_returns(cond)) {
5121 val = determine_truth(cond);
5127 check_reachable(fors->body);
5132 next = stmt->base.next;
5136 case STATEMENT_MS_TRY: {
5137 ms_try_statement_t const *const ms_try = &stmt->ms_try;
5138 check_reachable(ms_try->try_statement);
5139 next = ms_try->final_statement;
5143 case STATEMENT_LEAVE: {
5144 statement_t *parent = stmt;
5146 parent = parent->base.parent;
5147 if (parent == NULL) /* __leave not within __try */
5150 if (parent->kind == STATEMENT_MS_TRY) {
5152 next = parent->ms_try.final_statement;
5160 panic("invalid statement kind");
5163 while (next == NULL) {
5164 next = last->base.parent;
5166 noreturn_candidate = false;
5168 type_t *const type = skip_typeref(current_function->base.type);
5169 assert(is_type_function(type));
5170 type_t *const ret = skip_typeref(type->function.return_type);
5171 if (!is_type_atomic(ret, ATOMIC_TYPE_VOID) &&
5172 is_type_valid(ret) &&
5173 !is_sym_main(current_function->base.base.symbol)) {
5174 source_position_t const *const pos = &stmt->base.source_position;
5175 warningf(WARN_RETURN_TYPE, pos, "control reaches end of non-void function");
5180 switch (next->kind) {
5181 case STATEMENT_INVALID:
5182 case STATEMENT_EMPTY:
5183 case STATEMENT_DECLARATION:
5184 case STATEMENT_EXPRESSION:
5186 case STATEMENT_RETURN:
5187 case STATEMENT_CONTINUE:
5188 case STATEMENT_BREAK:
5189 case STATEMENT_GOTO:
5190 case STATEMENT_LEAVE:
5191 panic("invalid control flow in function");
5193 case STATEMENT_COMPOUND:
5194 if (next->compound.stmt_expr) {
5200 case STATEMENT_SWITCH:
5201 case STATEMENT_LABEL:
5202 case STATEMENT_CASE_LABEL:
5204 next = next->base.next;
5207 case STATEMENT_WHILE: {
5209 if (next->base.reachable)
5211 next->base.reachable = true;
5213 while_statement_t const *const whiles = &next->whiles;
5214 expression_t const *const cond = whiles->condition;
5216 if (!expression_returns(cond))
5219 int const val = determine_truth(cond);
5222 check_reachable(whiles->body);
5228 next = next->base.next;
5232 case STATEMENT_DO_WHILE: {
5234 if (next->base.reachable)
5236 next->base.reachable = true;
5238 do_while_statement_t const *const dw = &next->do_while;
5239 expression_t const *const cond = dw->condition;
5241 if (!expression_returns(cond))
5244 int const val = determine_truth(cond);
5247 check_reachable(dw->body);
5253 next = next->base.next;
5257 case STATEMENT_FOR: {
5259 for_statement_t *const fors = &next->fors;
5261 fors->step_reachable = true;
5263 if (fors->condition_reachable)
5265 fors->condition_reachable = true;
5267 expression_t const *const cond = fors->condition;
5272 } else if (expression_returns(cond)) {
5273 val = determine_truth(cond);
5279 check_reachable(fors->body);
5285 next = next->base.next;
5289 case STATEMENT_MS_TRY:
5291 next = next->ms_try.final_statement;
5296 check_reachable(next);
5299 static void check_unreachable(statement_t* const stmt, void *const env)
5303 switch (stmt->kind) {
5304 case STATEMENT_DO_WHILE:
5305 if (!stmt->base.reachable) {
5306 expression_t const *const cond = stmt->do_while.condition;
5307 if (determine_truth(cond) >= 0) {
5308 source_position_t const *const pos = &cond->base.source_position;
5309 warningf(WARN_UNREACHABLE_CODE, pos, "condition of do-while-loop is unreachable");
5314 case STATEMENT_FOR: {
5315 for_statement_t const* const fors = &stmt->fors;
5317 // if init and step are unreachable, cond is unreachable, too
5318 if (!stmt->base.reachable && !fors->step_reachable) {
5319 goto warn_unreachable;
5321 if (!stmt->base.reachable && fors->initialisation != NULL) {
5322 source_position_t const *const pos = &fors->initialisation->base.source_position;
5323 warningf(WARN_UNREACHABLE_CODE, pos, "initialisation of for-statement is unreachable");
5326 if (!fors->condition_reachable && fors->condition != NULL) {
5327 source_position_t const *const pos = &fors->condition->base.source_position;
5328 warningf(WARN_UNREACHABLE_CODE, pos, "condition of for-statement is unreachable");
5331 if (!fors->step_reachable && fors->step != NULL) {
5332 source_position_t const *const pos = &fors->step->base.source_position;
5333 warningf(WARN_UNREACHABLE_CODE, pos, "step of for-statement is unreachable");
5339 case STATEMENT_COMPOUND:
5340 if (stmt->compound.statements != NULL)
5342 goto warn_unreachable;
5344 case STATEMENT_DECLARATION: {
5345 /* Only warn if there is at least one declarator with an initializer.
5346 * This typically occurs in switch statements. */
5347 declaration_statement_t const *const decl = &stmt->declaration;
5348 entity_t const * ent = decl->declarations_begin;
5349 entity_t const *const last = decl->declarations_end;
5351 for (;; ent = ent->base.next) {
5352 if (ent->kind == ENTITY_VARIABLE &&
5353 ent->variable.initializer != NULL) {
5354 goto warn_unreachable;
5364 if (!stmt->base.reachable) {
5365 source_position_t const *const pos = &stmt->base.source_position;
5366 warningf(WARN_UNREACHABLE_CODE, pos, "statement is unreachable");
5372 static void parse_external_declaration(void)
5374 /* function-definitions and declarations both start with declaration
5376 add_anchor_token(';');
5377 declaration_specifiers_t specifiers;
5378 parse_declaration_specifiers(&specifiers);
5379 rem_anchor_token(';');
5381 /* must be a declaration */
5382 if (token.type == ';') {
5383 parse_anonymous_declaration_rest(&specifiers);
5387 add_anchor_token(',');
5388 add_anchor_token('=');
5389 add_anchor_token(';');
5390 add_anchor_token('{');
5392 /* declarator is common to both function-definitions and declarations */
5393 entity_t *ndeclaration = parse_declarator(&specifiers, DECL_FLAGS_NONE);
5395 rem_anchor_token('{');
5396 rem_anchor_token(';');
5397 rem_anchor_token('=');
5398 rem_anchor_token(',');
5400 /* must be a declaration */
5401 switch (token.type) {
5405 parse_declaration_rest(ndeclaration, &specifiers, record_entity,
5410 /* must be a function definition */
5411 parse_kr_declaration_list(ndeclaration);
5413 if (token.type != '{') {
5414 parse_error_expected("while parsing function definition", '{', NULL);
5415 eat_until_matching_token(';');
5419 assert(is_declaration(ndeclaration));
5420 type_t *const orig_type = ndeclaration->declaration.type;
5421 type_t * type = skip_typeref(orig_type);
5423 if (!is_type_function(type)) {
5424 if (is_type_valid(type)) {
5425 errorf(HERE, "declarator '%#N' has a body but is not a function type", ndeclaration);
5431 source_position_t const *const pos = &ndeclaration->base.source_position;
5432 if (is_typeref(orig_type)) {
5434 errorf(pos, "type of function definition '%#N' is a typedef", ndeclaration);
5437 if (is_type_compound(skip_typeref(type->function.return_type))) {
5438 warningf(WARN_AGGREGATE_RETURN, pos, "'%N' returns an aggregate", ndeclaration);
5440 if (type->function.unspecified_parameters) {
5441 warningf(WARN_OLD_STYLE_DEFINITION, pos, "old-style definition of '%N'", ndeclaration);
5443 warningf(WARN_TRADITIONAL, pos, "traditional C rejects ISO C style definition of '%N'", ndeclaration);
5446 /* §6.7.5.3:14 a function definition with () means no
5447 * parameters (and not unspecified parameters) */
5448 if (type->function.unspecified_parameters &&
5449 type->function.parameters == NULL) {
5450 type_t *copy = duplicate_type(type);
5451 copy->function.unspecified_parameters = false;
5452 type = identify_new_type(copy);
5454 ndeclaration->declaration.type = type;
5457 entity_t *const entity = record_entity(ndeclaration, true);
5458 assert(entity->kind == ENTITY_FUNCTION);
5459 assert(ndeclaration->kind == ENTITY_FUNCTION);
5461 function_t *const function = &entity->function;
5462 if (ndeclaration != entity) {
5463 function->parameters = ndeclaration->function.parameters;
5465 assert(is_declaration(entity));
5466 type = skip_typeref(entity->declaration.type);
5468 PUSH_SCOPE(&function->parameters);
5470 entity_t *parameter = function->parameters.entities;
5471 for (; parameter != NULL; parameter = parameter->base.next) {
5472 if (parameter->base.parent_scope == &ndeclaration->function.parameters) {
5473 parameter->base.parent_scope = current_scope;
5475 assert(parameter->base.parent_scope == NULL
5476 || parameter->base.parent_scope == current_scope);
5477 parameter->base.parent_scope = current_scope;
5478 if (parameter->base.symbol == NULL) {
5479 errorf(¶meter->base.source_position, "parameter name omitted");
5482 environment_push(parameter);
5485 if (function->statement != NULL) {
5486 parser_error_multiple_definition(entity, HERE);
5489 /* parse function body */
5490 int label_stack_top = label_top();
5491 function_t *old_current_function = current_function;
5492 entity_t *old_current_entity = current_entity;
5493 current_function = function;
5494 current_entity = entity;
5498 goto_anchor = &goto_first;
5500 label_anchor = &label_first;
5502 statement_t *const body = parse_compound_statement(false);
5503 function->statement = body;
5506 check_declarations();
5507 if (is_warn_on(WARN_RETURN_TYPE) ||
5508 is_warn_on(WARN_UNREACHABLE_CODE) ||
5509 (is_warn_on(WARN_MISSING_NORETURN) && !(function->base.modifiers & DM_NORETURN))) {
5510 noreturn_candidate = true;
5511 check_reachable(body);
5512 if (is_warn_on(WARN_UNREACHABLE_CODE))
5513 walk_statements(body, check_unreachable, NULL);
5514 if (noreturn_candidate &&
5515 !(function->base.modifiers & DM_NORETURN)) {
5516 source_position_t const *const pos = &body->base.source_position;
5517 warningf(WARN_MISSING_NORETURN, pos, "function '%#N' is candidate for attribute 'noreturn'", entity);
5522 assert(current_function == function);
5523 assert(current_entity == entity);
5524 current_entity = old_current_entity;
5525 current_function = old_current_function;
5526 label_pop_to(label_stack_top);
5532 static type_t *make_bitfield_type(type_t *base_type, expression_t *size,
5533 source_position_t *source_position,
5534 const symbol_t *symbol)
5536 type_t *type = allocate_type_zero(TYPE_BITFIELD);
5538 type->bitfield.base_type = base_type;
5539 type->bitfield.size_expression = size;
5542 type_t *skipped_type = skip_typeref(base_type);
5543 if (!is_type_integer(skipped_type)) {
5544 errorf(source_position, "bitfield base type '%T' is not an integer type", base_type);
5547 bit_size = get_type_size(base_type) * 8;
5550 if (is_constant_expression(size) == EXPR_CLASS_CONSTANT) {
5551 long v = fold_constant_to_int(size);
5552 const symbol_t *user_symbol = symbol == NULL ? sym_anonymous : symbol;
5555 errorf(source_position, "negative width in bit-field '%Y'",
5557 } else if (v == 0 && symbol != NULL) {
5558 errorf(source_position, "zero width for bit-field '%Y'",
5560 } else if (bit_size > 0 && (il_size_t)v > bit_size) {
5561 errorf(source_position, "width of '%Y' exceeds its type",
5564 type->bitfield.bit_size = v;
5571 static entity_t *find_compound_entry(compound_t *compound, symbol_t *symbol)
5573 entity_t *iter = compound->members.entities;
5574 for (; iter != NULL; iter = iter->base.next) {
5575 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5578 if (iter->base.symbol == symbol) {
5580 } else if (iter->base.symbol == NULL) {
5581 /* search in anonymous structs and unions */
5582 type_t *type = skip_typeref(iter->declaration.type);
5583 if (is_type_compound(type)) {
5584 if (find_compound_entry(type->compound.compound, symbol)
5595 static void check_deprecated(const source_position_t *source_position,
5596 const entity_t *entity)
5598 if (!is_declaration(entity))
5600 if ((entity->declaration.modifiers & DM_DEPRECATED) == 0)
5603 source_position_t const *const epos = &entity->base.source_position;
5604 char const *const msg = get_deprecated_string(entity->declaration.attributes);
5606 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P): \"%s\"", entity, epos, msg);
5608 warningf(WARN_DEPRECATED_DECLARATIONS, source_position, "'%N' is deprecated (declared %P)", entity, epos);
5613 static expression_t *create_select(const source_position_t *pos,
5615 type_qualifiers_t qualifiers,
5618 assert(entry->kind == ENTITY_COMPOUND_MEMBER);
5620 check_deprecated(pos, entry);
5622 expression_t *select = allocate_expression_zero(EXPR_SELECT);
5623 select->select.compound = addr;
5624 select->select.compound_entry = entry;
5626 type_t *entry_type = entry->declaration.type;
5627 type_t *res_type = get_qualified_type(entry_type, qualifiers);
5629 /* we always do the auto-type conversions; the & and sizeof parser contains
5630 * code to revert this! */
5631 select->base.type = automatic_type_conversion(res_type);
5632 if (res_type->kind == TYPE_BITFIELD) {
5633 select->base.type = res_type->bitfield.base_type;
5640 * Find entry with symbol in compound. Search anonymous structs and unions and
5641 * creates implicit select expressions for them.
5642 * Returns the adress for the innermost compound.
5644 static expression_t *find_create_select(const source_position_t *pos,
5646 type_qualifiers_t qualifiers,
5647 compound_t *compound, symbol_t *symbol)
5649 entity_t *iter = compound->members.entities;
5650 for (; iter != NULL; iter = iter->base.next) {
5651 if (iter->kind != ENTITY_COMPOUND_MEMBER)
5654 symbol_t *iter_symbol = iter->base.symbol;
5655 if (iter_symbol == NULL) {
5656 type_t *type = iter->declaration.type;
5657 if (type->kind != TYPE_COMPOUND_STRUCT
5658 && type->kind != TYPE_COMPOUND_UNION)
5661 compound_t *sub_compound = type->compound.compound;
5663 if (find_compound_entry(sub_compound, symbol) == NULL)
5666 expression_t *sub_addr = create_select(pos, addr, qualifiers, iter);
5667 sub_addr->base.source_position = *pos;
5668 sub_addr->select.implicit = true;
5669 return find_create_select(pos, sub_addr, qualifiers, sub_compound,
5673 if (iter_symbol == symbol) {
5674 return create_select(pos, addr, qualifiers, iter);
5681 static void parse_compound_declarators(compound_t *compound,
5682 const declaration_specifiers_t *specifiers)
5687 if (token.type == ':') {
5688 source_position_t source_position = *HERE;
5691 type_t *base_type = specifiers->type;
5692 expression_t *size = parse_constant_expression();
5694 type_t *type = make_bitfield_type(base_type, size,
5695 &source_position, NULL);
5697 attribute_t *attributes = parse_attributes(NULL);
5698 attribute_t **anchor = &attributes;
5699 while (*anchor != NULL)
5700 anchor = &(*anchor)->next;
5701 *anchor = specifiers->attributes;
5703 entity = allocate_entity_zero(ENTITY_COMPOUND_MEMBER, NAMESPACE_NORMAL, NULL);
5704 entity->base.source_position = source_position;
5705 entity->declaration.declared_storage_class = STORAGE_CLASS_NONE;
5706 entity->declaration.storage_class = STORAGE_CLASS_NONE;
5707 entity->declaration.type = type;
5708 entity->declaration.attributes = attributes;
5710 if (attributes != NULL) {
5711 handle_entity_attributes(attributes, entity);
5713 append_entity(&compound->members, entity);
5715 entity = parse_declarator(specifiers,
5716 DECL_MAY_BE_ABSTRACT | DECL_CREATE_COMPOUND_MEMBER);
5717 source_position_t const *const pos = &entity->base.source_position;
5718 if (entity->kind == ENTITY_TYPEDEF) {
5719 errorf(pos, "typedef not allowed as compound member");
5721 assert(entity->kind == ENTITY_COMPOUND_MEMBER);
5723 /* make sure we don't define a symbol multiple times */
5724 symbol_t *symbol = entity->base.symbol;
5725 if (symbol != NULL) {
5726 entity_t *prev = find_compound_entry(compound, symbol);
5728 source_position_t const *const ppos = &prev->base.source_position;
5729 errorf(pos, "multiple declarations of symbol '%Y' (declared %P)", symbol, ppos);
5733 if (token.type == ':') {
5734 source_position_t source_position = *HERE;
5736 expression_t *size = parse_constant_expression();
5738 type_t *type = entity->declaration.type;
5739 type_t *bitfield_type = make_bitfield_type(type, size,
5740 &source_position, entity->base.symbol);
5742 attribute_t *attributes = parse_attributes(NULL);
5743 entity->declaration.type = bitfield_type;
5744 handle_entity_attributes(attributes, entity);
5746 type_t *orig_type = entity->declaration.type;
5747 type_t *type = skip_typeref(orig_type);
5748 if (is_type_function(type)) {
5749 errorf(pos, "'%N' must not have function type '%T'", entity, orig_type);
5750 } else if (is_type_incomplete(type)) {
5751 /* §6.7.2.1:16 flexible array member */
5752 if (!is_type_array(type) ||
5753 token.type != ';' ||
5754 look_ahead(1)->type != '}') {
5755 errorf(pos, "'%N' has incomplete type '%T'", entity, orig_type);
5760 append_entity(&compound->members, entity);
5763 } while (next_if(','));
5764 expect(';', end_error);
5767 anonymous_entity = NULL;
5770 static void parse_compound_type_entries(compound_t *compound)
5773 add_anchor_token('}');
5776 switch (token.type) {
5778 case T___extension__:
5779 case T_IDENTIFIER: {
5781 declaration_specifiers_t specifiers;
5782 parse_declaration_specifiers(&specifiers);
5783 parse_compound_declarators(compound, &specifiers);
5789 rem_anchor_token('}');
5790 expect('}', end_error);
5793 compound->complete = true;
5799 static type_t *parse_typename(void)
5801 declaration_specifiers_t specifiers;
5802 parse_declaration_specifiers(&specifiers);
5803 if (specifiers.storage_class != STORAGE_CLASS_NONE
5804 || specifiers.thread_local) {
5805 /* TODO: improve error message, user does probably not know what a
5806 * storage class is...
5808 errorf(&specifiers.source_position, "typename must not have a storage class");
5811 type_t *result = parse_abstract_declarator(specifiers.type);
5819 typedef expression_t* (*parse_expression_function)(void);
5820 typedef expression_t* (*parse_expression_infix_function)(expression_t *left);
5822 typedef struct expression_parser_function_t expression_parser_function_t;
5823 struct expression_parser_function_t {
5824 parse_expression_function parser;
5825 precedence_t infix_precedence;
5826 parse_expression_infix_function infix_parser;
5829 static expression_parser_function_t expression_parsers[T_LAST_TOKEN];
5832 * Prints an error message if an expression was expected but not read
5834 static expression_t *expected_expression_error(void)
5836 /* skip the error message if the error token was read */
5837 if (token.type != T_ERROR) {
5838 errorf(HERE, "expected expression, got token %K", &token);
5842 return create_invalid_expression();
5845 static type_t *get_string_type(void)
5847 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_char_ptr : type_char_ptr;
5850 static type_t *get_wide_string_type(void)
5852 return is_warn_on(WARN_WRITE_STRINGS) ? type_const_wchar_t_ptr : type_wchar_t_ptr;
5856 * Parse a string constant.
5858 static expression_t *parse_string_literal(void)
5860 source_position_t begin = token.source_position;
5861 string_t res = token.literal;
5862 bool is_wide = (token.type == T_WIDE_STRING_LITERAL);
5865 while (token.type == T_STRING_LITERAL
5866 || token.type == T_WIDE_STRING_LITERAL) {
5867 warn_string_concat(&token.source_position);
5868 res = concat_strings(&res, &token.literal);
5870 is_wide |= token.type == T_WIDE_STRING_LITERAL;
5873 expression_t *literal;
5875 literal = allocate_expression_zero(EXPR_WIDE_STRING_LITERAL);
5876 literal->base.type = get_wide_string_type();
5878 literal = allocate_expression_zero(EXPR_STRING_LITERAL);
5879 literal->base.type = get_string_type();
5881 literal->base.source_position = begin;
5882 literal->literal.value = res;
5888 * Parse a boolean constant.
5890 static expression_t *parse_boolean_literal(bool value)
5892 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_BOOLEAN);
5893 literal->base.type = type_bool;
5894 literal->literal.value.begin = value ? "true" : "false";
5895 literal->literal.value.size = value ? 4 : 5;
5901 static void warn_traditional_suffix(void)
5903 warningf(WARN_TRADITIONAL, HERE, "traditional C rejects the '%Y' suffix", token.symbol);
5906 static void check_integer_suffix(void)
5908 symbol_t *suffix = token.symbol;
5912 bool not_traditional = false;
5913 const char *c = suffix->string;
5914 if (*c == 'l' || *c == 'L') {
5917 not_traditional = true;
5919 if (*c == 'u' || *c == 'U') {
5922 } else if (*c == 'u' || *c == 'U') {
5923 not_traditional = true;
5926 } else if (*c == 'u' || *c == 'U') {
5927 not_traditional = true;
5929 if (*c == 'l' || *c == 'L') {
5937 errorf(&token.source_position,
5938 "invalid suffix '%s' on integer constant", suffix->string);
5939 } else if (not_traditional) {
5940 warn_traditional_suffix();
5944 static type_t *check_floatingpoint_suffix(void)
5946 symbol_t *suffix = token.symbol;
5947 type_t *type = type_double;
5951 bool not_traditional = false;
5952 const char *c = suffix->string;
5953 if (*c == 'f' || *c == 'F') {
5956 } else if (*c == 'l' || *c == 'L') {
5958 type = type_long_double;
5961 errorf(&token.source_position,
5962 "invalid suffix '%s' on floatingpoint constant", suffix->string);
5963 } else if (not_traditional) {
5964 warn_traditional_suffix();
5971 * Parse an integer constant.
5973 static expression_t *parse_number_literal(void)
5975 expression_kind_t kind;
5978 switch (token.type) {
5980 kind = EXPR_LITERAL_INTEGER;
5981 check_integer_suffix();
5984 case T_INTEGER_OCTAL:
5985 kind = EXPR_LITERAL_INTEGER_OCTAL;
5986 check_integer_suffix();
5989 case T_INTEGER_HEXADECIMAL:
5990 kind = EXPR_LITERAL_INTEGER_HEXADECIMAL;
5991 check_integer_suffix();
5994 case T_FLOATINGPOINT:
5995 kind = EXPR_LITERAL_FLOATINGPOINT;
5996 type = check_floatingpoint_suffix();
5998 case T_FLOATINGPOINT_HEXADECIMAL:
5999 kind = EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL;
6000 type = check_floatingpoint_suffix();
6003 panic("unexpected token type in parse_number_literal");
6006 expression_t *literal = allocate_expression_zero(kind);
6007 literal->base.type = type;
6008 literal->literal.value = token.literal;
6009 literal->literal.suffix = token.symbol;
6012 /* integer type depends on the size of the number and the size
6013 * representable by the types. The backend/codegeneration has to determine
6016 determine_literal_type(&literal->literal);
6021 * Parse a character constant.
6023 static expression_t *parse_character_constant(void)
6025 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_CHARACTER);
6026 literal->base.type = c_mode & _CXX ? type_char : type_int;
6027 literal->literal.value = token.literal;
6029 size_t len = literal->literal.value.size;
6031 if (!GNU_MODE && !(c_mode & _C99)) {
6032 errorf(HERE, "more than 1 character in character constant");
6034 literal->base.type = type_int;
6035 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6044 * Parse a wide character constant.
6046 static expression_t *parse_wide_character_constant(void)
6048 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_WIDE_CHARACTER);
6049 literal->base.type = type_int;
6050 literal->literal.value = token.literal;
6052 size_t len = wstrlen(&literal->literal.value);
6054 warningf(WARN_MULTICHAR, HERE, "multi-character character constant");
6061 static entity_t *create_implicit_function(symbol_t *symbol,
6062 const source_position_t *source_position)
6064 type_t *ntype = allocate_type_zero(TYPE_FUNCTION);
6065 ntype->function.return_type = type_int;
6066 ntype->function.unspecified_parameters = true;
6067 ntype->function.linkage = LINKAGE_C;
6068 type_t *type = identify_new_type(ntype);
6070 entity_t *const entity = allocate_entity_zero(ENTITY_FUNCTION, NAMESPACE_NORMAL, symbol);
6071 entity->declaration.storage_class = STORAGE_CLASS_EXTERN;
6072 entity->declaration.declared_storage_class = STORAGE_CLASS_EXTERN;
6073 entity->declaration.type = type;
6074 entity->declaration.implicit = true;
6075 entity->base.source_position = *source_position;
6077 if (current_scope != NULL)
6078 record_entity(entity, false);
6084 * Performs automatic type cast as described in §6.3.2.1.
6086 * @param orig_type the original type
6088 static type_t *automatic_type_conversion(type_t *orig_type)
6090 type_t *type = skip_typeref(orig_type);
6091 if (is_type_array(type)) {
6092 array_type_t *array_type = &type->array;
6093 type_t *element_type = array_type->element_type;
6094 unsigned qualifiers = array_type->base.qualifiers;
6096 return make_pointer_type(element_type, qualifiers);
6099 if (is_type_function(type)) {
6100 return make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
6107 * reverts the automatic casts of array to pointer types and function
6108 * to function-pointer types as defined §6.3.2.1
6110 type_t *revert_automatic_type_conversion(const expression_t *expression)
6112 switch (expression->kind) {
6113 case EXPR_REFERENCE: {
6114 entity_t *entity = expression->reference.entity;
6115 if (is_declaration(entity)) {
6116 return entity->declaration.type;
6117 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6118 return entity->enum_value.enum_type;
6120 panic("no declaration or enum in reference");
6125 entity_t *entity = expression->select.compound_entry;
6126 assert(is_declaration(entity));
6127 type_t *type = entity->declaration.type;
6128 return get_qualified_type(type,
6129 expression->base.type->base.qualifiers);
6132 case EXPR_UNARY_DEREFERENCE: {
6133 const expression_t *const value = expression->unary.value;
6134 type_t *const type = skip_typeref(value->base.type);
6135 if (!is_type_pointer(type))
6136 return type_error_type;
6137 return type->pointer.points_to;
6140 case EXPR_ARRAY_ACCESS: {
6141 const expression_t *array_ref = expression->array_access.array_ref;
6142 type_t *type_left = skip_typeref(array_ref->base.type);
6143 if (!is_type_pointer(type_left))
6144 return type_error_type;
6145 return type_left->pointer.points_to;
6148 case EXPR_STRING_LITERAL: {
6149 size_t size = expression->string_literal.value.size;
6150 return make_array_type(type_char, size, TYPE_QUALIFIER_NONE);
6153 case EXPR_WIDE_STRING_LITERAL: {
6154 size_t size = wstrlen(&expression->string_literal.value);
6155 return make_array_type(type_wchar_t, size, TYPE_QUALIFIER_NONE);
6158 case EXPR_COMPOUND_LITERAL:
6159 return expression->compound_literal.type;
6164 return expression->base.type;
6168 * Find an entity matching a symbol in a scope.
6169 * Uses current scope if scope is NULL
6171 static entity_t *lookup_entity(const scope_t *scope, symbol_t *symbol,
6172 namespace_tag_t namespc)
6174 if (scope == NULL) {
6175 return get_entity(symbol, namespc);
6178 /* we should optimize here, if scope grows above a certain size we should
6179 construct a hashmap here... */
6180 entity_t *entity = scope->entities;
6181 for ( ; entity != NULL; entity = entity->base.next) {
6182 if (entity->base.symbol == symbol
6183 && (namespace_tag_t)entity->base.namespc == namespc)
6190 static entity_t *parse_qualified_identifier(void)
6192 /* namespace containing the symbol */
6194 source_position_t pos;
6195 const scope_t *lookup_scope = NULL;
6197 if (next_if(T_COLONCOLON))
6198 lookup_scope = &unit->scope;
6202 if (token.type != T_IDENTIFIER) {
6203 parse_error_expected("while parsing identifier", T_IDENTIFIER, NULL);
6204 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6206 symbol = token.symbol;
6211 entity = lookup_entity(lookup_scope, symbol, NAMESPACE_NORMAL);
6213 if (!next_if(T_COLONCOLON))
6216 switch (entity->kind) {
6217 case ENTITY_NAMESPACE:
6218 lookup_scope = &entity->namespacee.members;
6223 lookup_scope = &entity->compound.members;
6226 errorf(&pos, "'%Y' must be a namespace, class, struct or union (but is a %s)",
6227 symbol, get_entity_kind_name(entity->kind));
6229 /* skip further qualifications */
6230 while (next_if(T_IDENTIFIER) && next_if(T_COLONCOLON)) {}
6232 return create_error_entity(sym_anonymous, ENTITY_VARIABLE);
6236 if (entity == NULL) {
6237 if (!strict_mode && token.type == '(') {
6238 /* an implicitly declared function */
6239 warningf(WARN_IMPLICIT_FUNCTION_DECLARATION, &pos, "implicit declaration of function '%Y'", symbol);
6240 entity = create_implicit_function(symbol, &pos);
6242 errorf(&pos, "unknown identifier '%Y' found.", symbol);
6243 entity = create_error_entity(symbol, ENTITY_VARIABLE);
6250 static expression_t *parse_reference(void)
6252 source_position_t const pos = token.source_position;
6253 entity_t *const entity = parse_qualified_identifier();
6256 if (is_declaration(entity)) {
6257 orig_type = entity->declaration.type;
6258 } else if (entity->kind == ENTITY_ENUM_VALUE) {
6259 orig_type = entity->enum_value.enum_type;
6261 panic("expected declaration or enum value in reference");
6264 /* we always do the auto-type conversions; the & and sizeof parser contains
6265 * code to revert this! */
6266 type_t *type = automatic_type_conversion(orig_type);
6268 expression_kind_t kind = EXPR_REFERENCE;
6269 if (entity->kind == ENTITY_ENUM_VALUE)
6270 kind = EXPR_REFERENCE_ENUM_VALUE;
6272 expression_t *expression = allocate_expression_zero(kind);
6273 expression->base.source_position = pos;
6274 expression->base.type = type;
6275 expression->reference.entity = entity;
6277 /* this declaration is used */
6278 if (is_declaration(entity)) {
6279 entity->declaration.used = true;
6282 if (entity->base.parent_scope != file_scope
6283 && (current_function != NULL
6284 && entity->base.parent_scope->depth < current_function->parameters.depth)
6285 && (entity->kind == ENTITY_VARIABLE || entity->kind == ENTITY_PARAMETER)) {
6286 if (entity->kind == ENTITY_VARIABLE) {
6287 /* access of a variable from an outer function */
6288 entity->variable.address_taken = true;
6289 } else if (entity->kind == ENTITY_PARAMETER) {
6290 entity->parameter.address_taken = true;
6292 current_function->need_closure = true;
6295 check_deprecated(&pos, entity);
6297 if (entity == current_init_decl && !in_type_prop && entity->kind == ENTITY_VARIABLE) {
6298 current_init_decl = NULL;
6299 warningf(WARN_INIT_SELF, &pos, "variable '%#N' is initialized by itself", entity);
6305 static bool semantic_cast(expression_t *cast)
6307 expression_t *expression = cast->unary.value;
6308 type_t *orig_dest_type = cast->base.type;
6309 type_t *orig_type_right = expression->base.type;
6310 type_t const *dst_type = skip_typeref(orig_dest_type);
6311 type_t const *src_type = skip_typeref(orig_type_right);
6312 source_position_t const *pos = &cast->base.source_position;
6314 /* §6.5.4 A (void) cast is explicitly permitted, more for documentation than for utility. */
6315 if (dst_type == type_void)
6318 /* only integer and pointer can be casted to pointer */
6319 if (is_type_pointer(dst_type) &&
6320 !is_type_pointer(src_type) &&
6321 !is_type_integer(src_type) &&
6322 is_type_valid(src_type)) {
6323 errorf(pos, "cannot convert type '%T' to a pointer type", orig_type_right);
6327 if (!is_type_scalar(dst_type) && is_type_valid(dst_type)) {
6328 errorf(pos, "conversion to non-scalar type '%T' requested", orig_dest_type);
6332 if (!is_type_scalar(src_type) && is_type_valid(src_type)) {
6333 errorf(pos, "conversion from non-scalar type '%T' requested", orig_type_right);
6337 if (is_type_pointer(src_type) && is_type_pointer(dst_type)) {
6338 type_t *src = skip_typeref(src_type->pointer.points_to);
6339 type_t *dst = skip_typeref(dst_type->pointer.points_to);
6340 unsigned missing_qualifiers =
6341 src->base.qualifiers & ~dst->base.qualifiers;
6342 if (missing_qualifiers != 0) {
6343 warningf(WARN_CAST_QUAL, pos, "cast discards qualifiers '%Q' in pointer target type of '%T'", missing_qualifiers, orig_type_right);
6349 static expression_t *parse_compound_literal(source_position_t const *const pos, type_t *type)
6351 expression_t *expression = allocate_expression_zero(EXPR_COMPOUND_LITERAL);
6352 expression->base.source_position = *pos;
6354 parse_initializer_env_t env;
6357 env.must_be_constant = false;
6358 initializer_t *initializer = parse_initializer(&env);
6361 expression->compound_literal.initializer = initializer;
6362 expression->compound_literal.type = type;
6363 expression->base.type = automatic_type_conversion(type);
6369 * Parse a cast expression.
6371 static expression_t *parse_cast(void)
6373 source_position_t const pos = *HERE;
6376 add_anchor_token(')');
6378 type_t *type = parse_typename();
6380 rem_anchor_token(')');
6381 expect(')', end_error);
6383 if (token.type == '{') {
6384 return parse_compound_literal(&pos, type);
6387 expression_t *cast = allocate_expression_zero(EXPR_UNARY_CAST);
6388 cast->base.source_position = pos;
6390 expression_t *value = parse_subexpression(PREC_CAST);
6391 cast->base.type = type;
6392 cast->unary.value = value;
6394 if (! semantic_cast(cast)) {
6395 /* TODO: record the error in the AST. else it is impossible to detect it */
6400 return create_invalid_expression();
6404 * Parse a statement expression.
6406 static expression_t *parse_statement_expression(void)
6408 expression_t *expression = allocate_expression_zero(EXPR_STATEMENT);
6411 add_anchor_token(')');
6413 statement_t *statement = parse_compound_statement(true);
6414 statement->compound.stmt_expr = true;
6415 expression->statement.statement = statement;
6417 /* find last statement and use its type */
6418 type_t *type = type_void;
6419 const statement_t *stmt = statement->compound.statements;
6421 while (stmt->base.next != NULL)
6422 stmt = stmt->base.next;
6424 if (stmt->kind == STATEMENT_EXPRESSION) {
6425 type = stmt->expression.expression->base.type;
6428 source_position_t const *const pos = &expression->base.source_position;
6429 warningf(WARN_OTHER, pos, "empty statement expression ({})");
6431 expression->base.type = type;
6433 rem_anchor_token(')');
6434 expect(')', end_error);
6441 * Parse a parenthesized expression.
6443 static expression_t *parse_parenthesized_expression(void)
6445 token_t const* const la1 = look_ahead(1);
6446 switch (la1->type) {
6448 /* gcc extension: a statement expression */
6449 return parse_statement_expression();
6452 if (is_typedef_symbol(la1->symbol)) {
6454 return parse_cast();
6459 add_anchor_token(')');
6460 expression_t *result = parse_expression();
6461 result->base.parenthesized = true;
6462 rem_anchor_token(')');
6463 expect(')', end_error);
6469 static expression_t *parse_function_keyword(void)
6473 if (current_function == NULL) {
6474 errorf(HERE, "'__func__' used outside of a function");
6477 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6478 expression->base.type = type_char_ptr;
6479 expression->funcname.kind = FUNCNAME_FUNCTION;
6486 static expression_t *parse_pretty_function_keyword(void)
6488 if (current_function == NULL) {
6489 errorf(HERE, "'__PRETTY_FUNCTION__' used outside of a function");
6492 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6493 expression->base.type = type_char_ptr;
6494 expression->funcname.kind = FUNCNAME_PRETTY_FUNCTION;
6496 eat(T___PRETTY_FUNCTION__);
6501 static expression_t *parse_funcsig_keyword(void)
6503 if (current_function == NULL) {
6504 errorf(HERE, "'__FUNCSIG__' used outside of a function");
6507 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6508 expression->base.type = type_char_ptr;
6509 expression->funcname.kind = FUNCNAME_FUNCSIG;
6516 static expression_t *parse_funcdname_keyword(void)
6518 if (current_function == NULL) {
6519 errorf(HERE, "'__FUNCDNAME__' used outside of a function");
6522 expression_t *expression = allocate_expression_zero(EXPR_FUNCNAME);
6523 expression->base.type = type_char_ptr;
6524 expression->funcname.kind = FUNCNAME_FUNCDNAME;
6526 eat(T___FUNCDNAME__);
6531 static designator_t *parse_designator(void)
6533 designator_t *result = allocate_ast_zero(sizeof(result[0]));
6534 result->source_position = *HERE;
6536 if (token.type != T_IDENTIFIER) {
6537 parse_error_expected("while parsing member designator",
6538 T_IDENTIFIER, NULL);
6541 result->symbol = token.symbol;
6544 designator_t *last_designator = result;
6547 if (token.type != T_IDENTIFIER) {
6548 parse_error_expected("while parsing member designator",
6549 T_IDENTIFIER, NULL);
6552 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6553 designator->source_position = *HERE;
6554 designator->symbol = token.symbol;
6557 last_designator->next = designator;
6558 last_designator = designator;
6562 add_anchor_token(']');
6563 designator_t *designator = allocate_ast_zero(sizeof(result[0]));
6564 designator->source_position = *HERE;
6565 designator->array_index = parse_expression();
6566 rem_anchor_token(']');
6567 expect(']', end_error);
6568 if (designator->array_index == NULL) {
6572 last_designator->next = designator;
6573 last_designator = designator;
6585 * Parse the __builtin_offsetof() expression.
6587 static expression_t *parse_offsetof(void)
6589 expression_t *expression = allocate_expression_zero(EXPR_OFFSETOF);
6590 expression->base.type = type_size_t;
6592 eat(T___builtin_offsetof);
6594 expect('(', end_error);
6595 add_anchor_token(',');
6596 type_t *type = parse_typename();
6597 rem_anchor_token(',');
6598 expect(',', end_error);
6599 add_anchor_token(')');
6600 designator_t *designator = parse_designator();
6601 rem_anchor_token(')');
6602 expect(')', end_error);
6604 expression->offsetofe.type = type;
6605 expression->offsetofe.designator = designator;
6608 memset(&path, 0, sizeof(path));
6609 path.top_type = type;
6610 path.path = NEW_ARR_F(type_path_entry_t, 0);
6612 descend_into_subtype(&path);
6614 if (!walk_designator(&path, designator, true)) {
6615 return create_invalid_expression();
6618 DEL_ARR_F(path.path);
6622 return create_invalid_expression();
6626 * Parses a _builtin_va_start() expression.
6628 static expression_t *parse_va_start(void)
6630 expression_t *expression = allocate_expression_zero(EXPR_VA_START);
6632 eat(T___builtin_va_start);
6634 expect('(', end_error);
6635 add_anchor_token(',');
6636 expression->va_starte.ap = parse_assignment_expression();
6637 rem_anchor_token(',');
6638 expect(',', end_error);
6639 expression_t *const expr = parse_assignment_expression();
6640 if (expr->kind == EXPR_REFERENCE) {
6641 entity_t *const entity = expr->reference.entity;
6642 if (!current_function->base.type->function.variadic) {
6643 errorf(&expr->base.source_position,
6644 "'va_start' used in non-variadic function");
6645 } else if (entity->base.parent_scope != ¤t_function->parameters ||
6646 entity->base.next != NULL ||
6647 entity->kind != ENTITY_PARAMETER) {
6648 errorf(&expr->base.source_position,
6649 "second argument of 'va_start' must be last parameter of the current function");
6651 expression->va_starte.parameter = &entity->variable;
6653 expect(')', end_error);
6656 expect(')', end_error);
6658 return create_invalid_expression();
6662 * Parses a __builtin_va_arg() expression.
6664 static expression_t *parse_va_arg(void)
6666 expression_t *expression = allocate_expression_zero(EXPR_VA_ARG);
6668 eat(T___builtin_va_arg);
6670 expect('(', end_error);
6672 ap.expression = parse_assignment_expression();
6673 expression->va_arge.ap = ap.expression;
6674 check_call_argument(type_valist, &ap, 1);
6676 expect(',', end_error);
6677 expression->base.type = parse_typename();
6678 expect(')', end_error);
6682 return create_invalid_expression();
6686 * Parses a __builtin_va_copy() expression.
6688 static expression_t *parse_va_copy(void)
6690 expression_t *expression = allocate_expression_zero(EXPR_VA_COPY);
6692 eat(T___builtin_va_copy);
6694 expect('(', end_error);
6695 expression_t *dst = parse_assignment_expression();
6696 assign_error_t error = semantic_assign(type_valist, dst);
6697 report_assign_error(error, type_valist, dst, "call argument 1",
6698 &dst->base.source_position);
6699 expression->va_copye.dst = dst;
6701 expect(',', end_error);
6703 call_argument_t src;
6704 src.expression = parse_assignment_expression();
6705 check_call_argument(type_valist, &src, 2);
6706 expression->va_copye.src = src.expression;
6707 expect(')', end_error);
6711 return create_invalid_expression();
6715 * Parses a __builtin_constant_p() expression.
6717 static expression_t *parse_builtin_constant(void)
6719 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_CONSTANT_P);
6721 eat(T___builtin_constant_p);
6723 expect('(', end_error);
6724 add_anchor_token(')');
6725 expression->builtin_constant.value = parse_assignment_expression();
6726 rem_anchor_token(')');
6727 expect(')', end_error);
6728 expression->base.type = type_int;
6732 return create_invalid_expression();
6736 * Parses a __builtin_types_compatible_p() expression.
6738 static expression_t *parse_builtin_types_compatible(void)
6740 expression_t *expression = allocate_expression_zero(EXPR_BUILTIN_TYPES_COMPATIBLE_P);
6742 eat(T___builtin_types_compatible_p);
6744 expect('(', end_error);
6745 add_anchor_token(')');
6746 add_anchor_token(',');
6747 expression->builtin_types_compatible.left = parse_typename();
6748 rem_anchor_token(',');
6749 expect(',', end_error);
6750 expression->builtin_types_compatible.right = parse_typename();
6751 rem_anchor_token(')');
6752 expect(')', end_error);
6753 expression->base.type = type_int;
6757 return create_invalid_expression();
6761 * Parses a __builtin_is_*() compare expression.
6763 static expression_t *parse_compare_builtin(void)
6765 expression_t *expression;
6767 switch (token.type) {
6768 case T___builtin_isgreater:
6769 expression = allocate_expression_zero(EXPR_BINARY_ISGREATER);
6771 case T___builtin_isgreaterequal:
6772 expression = allocate_expression_zero(EXPR_BINARY_ISGREATEREQUAL);
6774 case T___builtin_isless:
6775 expression = allocate_expression_zero(EXPR_BINARY_ISLESS);
6777 case T___builtin_islessequal:
6778 expression = allocate_expression_zero(EXPR_BINARY_ISLESSEQUAL);
6780 case T___builtin_islessgreater:
6781 expression = allocate_expression_zero(EXPR_BINARY_ISLESSGREATER);
6783 case T___builtin_isunordered:
6784 expression = allocate_expression_zero(EXPR_BINARY_ISUNORDERED);
6787 internal_errorf(HERE, "invalid compare builtin found");
6789 expression->base.source_position = *HERE;
6792 expect('(', end_error);
6793 expression->binary.left = parse_assignment_expression();
6794 expect(',', end_error);
6795 expression->binary.right = parse_assignment_expression();
6796 expect(')', end_error);
6798 type_t *const orig_type_left = expression->binary.left->base.type;
6799 type_t *const orig_type_right = expression->binary.right->base.type;
6801 type_t *const type_left = skip_typeref(orig_type_left);
6802 type_t *const type_right = skip_typeref(orig_type_right);
6803 if (!is_type_float(type_left) && !is_type_float(type_right)) {
6804 if (is_type_valid(type_left) && is_type_valid(type_right)) {
6805 type_error_incompatible("invalid operands in comparison",
6806 &expression->base.source_position, orig_type_left, orig_type_right);
6809 semantic_comparison(&expression->binary);
6814 return create_invalid_expression();
6818 * Parses a MS assume() expression.
6820 static expression_t *parse_assume(void)
6822 expression_t *expression = allocate_expression_zero(EXPR_UNARY_ASSUME);
6826 expect('(', end_error);
6827 add_anchor_token(')');
6828 expression->unary.value = parse_assignment_expression();
6829 rem_anchor_token(')');
6830 expect(')', end_error);
6832 expression->base.type = type_void;
6835 return create_invalid_expression();
6839 * Return the label for the current symbol or create a new one.
6841 static label_t *get_label(void)
6843 assert(token.type == T_IDENTIFIER);
6844 assert(current_function != NULL);
6846 entity_t *label = get_entity(token.symbol, NAMESPACE_LABEL);
6847 /* If we find a local label, we already created the declaration. */
6848 if (label != NULL && label->kind == ENTITY_LOCAL_LABEL) {
6849 if (label->base.parent_scope != current_scope) {
6850 assert(label->base.parent_scope->depth < current_scope->depth);
6851 current_function->goto_to_outer = true;
6853 } else if (label == NULL || label->base.parent_scope != ¤t_function->parameters) {
6854 /* There is no matching label in the same function, so create a new one. */
6855 label = allocate_entity_zero(ENTITY_LABEL, NAMESPACE_LABEL, token.symbol);
6860 return &label->label;
6864 * Parses a GNU && label address expression.
6866 static expression_t *parse_label_address(void)
6868 source_position_t source_position = token.source_position;
6870 if (token.type != T_IDENTIFIER) {
6871 parse_error_expected("while parsing label address", T_IDENTIFIER, NULL);
6872 return create_invalid_expression();
6875 label_t *const label = get_label();
6877 label->address_taken = true;
6879 expression_t *expression = allocate_expression_zero(EXPR_LABEL_ADDRESS);
6880 expression->base.source_position = source_position;
6882 /* label address is treated as a void pointer */
6883 expression->base.type = type_void_ptr;
6884 expression->label_address.label = label;
6889 * Parse a microsoft __noop expression.
6891 static expression_t *parse_noop_expression(void)
6893 /* the result is a (int)0 */
6894 expression_t *literal = allocate_expression_zero(EXPR_LITERAL_MS_NOOP);
6895 literal->base.type = type_int;
6896 literal->literal.value.begin = "__noop";
6897 literal->literal.value.size = 6;
6901 if (token.type == '(') {
6902 /* parse arguments */
6904 add_anchor_token(')');
6905 add_anchor_token(',');
6907 if (token.type != ')') do {
6908 (void)parse_assignment_expression();
6909 } while (next_if(','));
6911 rem_anchor_token(',');
6912 rem_anchor_token(')');
6913 expect(')', end_error);
6920 * Parses a primary expression.
6922 static expression_t *parse_primary_expression(void)
6924 switch (token.type) {
6925 case T_false: return parse_boolean_literal(false);
6926 case T_true: return parse_boolean_literal(true);
6928 case T_INTEGER_OCTAL:
6929 case T_INTEGER_HEXADECIMAL:
6930 case T_FLOATINGPOINT:
6931 case T_FLOATINGPOINT_HEXADECIMAL: return parse_number_literal();
6932 case T_CHARACTER_CONSTANT: return parse_character_constant();
6933 case T_WIDE_CHARACTER_CONSTANT: return parse_wide_character_constant();
6934 case T_STRING_LITERAL:
6935 case T_WIDE_STRING_LITERAL: return parse_string_literal();
6936 case T___FUNCTION__:
6937 case T___func__: return parse_function_keyword();
6938 case T___PRETTY_FUNCTION__: return parse_pretty_function_keyword();
6939 case T___FUNCSIG__: return parse_funcsig_keyword();
6940 case T___FUNCDNAME__: return parse_funcdname_keyword();
6941 case T___builtin_offsetof: return parse_offsetof();
6942 case T___builtin_va_start: return parse_va_start();
6943 case T___builtin_va_arg: return parse_va_arg();
6944 case T___builtin_va_copy: return parse_va_copy();
6945 case T___builtin_isgreater:
6946 case T___builtin_isgreaterequal:
6947 case T___builtin_isless:
6948 case T___builtin_islessequal:
6949 case T___builtin_islessgreater:
6950 case T___builtin_isunordered: return parse_compare_builtin();
6951 case T___builtin_constant_p: return parse_builtin_constant();
6952 case T___builtin_types_compatible_p: return parse_builtin_types_compatible();
6953 case T__assume: return parse_assume();
6956 return parse_label_address();
6959 case '(': return parse_parenthesized_expression();
6960 case T___noop: return parse_noop_expression();
6962 /* Gracefully handle type names while parsing expressions. */
6964 return parse_reference();
6966 if (!is_typedef_symbol(token.symbol)) {
6967 return parse_reference();
6971 source_position_t const pos = *HERE;
6972 declaration_specifiers_t specifiers;
6973 parse_declaration_specifiers(&specifiers);
6974 type_t const *const type = parse_abstract_declarator(specifiers.type);
6975 errorf(&pos, "encountered type '%T' while parsing expression", type);
6976 return create_invalid_expression();
6980 errorf(HERE, "unexpected token %K, expected an expression", &token);
6982 return create_invalid_expression();
6985 static expression_t *parse_array_expression(expression_t *left)
6987 expression_t *const expr = allocate_expression_zero(EXPR_ARRAY_ACCESS);
6988 array_access_expression_t *const arr = &expr->array_access;
6991 add_anchor_token(']');
6993 expression_t *const inside = parse_expression();
6995 type_t *const orig_type_left = left->base.type;
6996 type_t *const orig_type_inside = inside->base.type;
6998 type_t *const type_left = skip_typeref(orig_type_left);
6999 type_t *const type_inside = skip_typeref(orig_type_inside);
7005 if (is_type_pointer(type_left)) {
7008 idx_type = type_inside;
7009 res_type = type_left->pointer.points_to;
7011 } else if (is_type_pointer(type_inside)) {
7012 arr->flipped = true;
7015 idx_type = type_left;
7016 res_type = type_inside->pointer.points_to;
7018 res_type = automatic_type_conversion(res_type);
7019 if (!is_type_integer(idx_type)) {
7020 errorf(&idx->base.source_position, "array subscript must have integer type");
7021 } else if (is_type_atomic(idx_type, ATOMIC_TYPE_CHAR)) {
7022 source_position_t const *const pos = &idx->base.source_position;
7023 warningf(WARN_CHAR_SUBSCRIPTS, pos, "array subscript has char type");
7026 if (is_type_valid(type_left) && is_type_valid(type_inside)) {
7027 errorf(&expr->base.source_position, "invalid types '%T[%T]' for array access", orig_type_left, orig_type_inside);
7029 res_type = type_error_type;
7034 arr->array_ref = ref;
7036 arr->base.type = res_type;
7038 rem_anchor_token(']');
7039 expect(']', end_error);
7044 static expression_t *parse_typeprop(expression_kind_t const kind)
7046 expression_t *tp_expression = allocate_expression_zero(kind);
7047 tp_expression->base.type = type_size_t;
7049 eat(kind == EXPR_SIZEOF ? T_sizeof : T___alignof__);
7051 /* we only refer to a type property, mark this case */
7052 bool old = in_type_prop;
7053 in_type_prop = true;
7056 expression_t *expression;
7057 if (token.type == '(' && is_declaration_specifier(look_ahead(1))) {
7058 source_position_t const pos = *HERE;
7060 add_anchor_token(')');
7061 orig_type = parse_typename();
7062 rem_anchor_token(')');
7063 expect(')', end_error);
7065 if (token.type == '{') {
7066 /* It was not sizeof(type) after all. It is sizeof of an expression
7067 * starting with a compound literal */
7068 expression = parse_compound_literal(&pos, orig_type);
7069 goto typeprop_expression;
7072 expression = parse_subexpression(PREC_UNARY);
7074 typeprop_expression:
7075 tp_expression->typeprop.tp_expression = expression;
7077 orig_type = revert_automatic_type_conversion(expression);
7078 expression->base.type = orig_type;
7081 tp_expression->typeprop.type = orig_type;
7082 type_t const* const type = skip_typeref(orig_type);
7083 char const* wrong_type = NULL;
7084 if (is_type_incomplete(type)) {
7085 if (!is_type_atomic(type, ATOMIC_TYPE_VOID) || !GNU_MODE)
7086 wrong_type = "incomplete";
7087 } else if (type->kind == TYPE_FUNCTION) {
7089 /* function types are allowed (and return 1) */
7090 source_position_t const *const pos = &tp_expression->base.source_position;
7091 char const *const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7092 warningf(WARN_OTHER, pos, "%s expression with function argument returns invalid result", what);
7094 wrong_type = "function";
7097 if (is_type_incomplete(type))
7098 wrong_type = "incomplete";
7100 if (type->kind == TYPE_BITFIELD)
7101 wrong_type = "bitfield";
7103 if (wrong_type != NULL) {
7104 char const* const what = kind == EXPR_SIZEOF ? "sizeof" : "alignof";
7105 errorf(&tp_expression->base.source_position,
7106 "operand of %s expression must not be of %s type '%T'",
7107 what, wrong_type, orig_type);
7112 return tp_expression;
7115 static expression_t *parse_sizeof(void)
7117 return parse_typeprop(EXPR_SIZEOF);
7120 static expression_t *parse_alignof(void)
7122 return parse_typeprop(EXPR_ALIGNOF);
7125 static expression_t *parse_select_expression(expression_t *addr)
7127 assert(token.type == '.' || token.type == T_MINUSGREATER);
7128 bool select_left_arrow = (token.type == T_MINUSGREATER);
7129 source_position_t const pos = *HERE;
7132 if (token.type != T_IDENTIFIER) {
7133 parse_error_expected("while parsing select", T_IDENTIFIER, NULL);
7134 return create_invalid_expression();
7136 symbol_t *symbol = token.symbol;
7139 type_t *const orig_type = addr->base.type;
7140 type_t *const type = skip_typeref(orig_type);
7143 bool saw_error = false;
7144 if (is_type_pointer(type)) {
7145 if (!select_left_arrow) {
7147 "request for member '%Y' in something not a struct or union, but '%T'",
7151 type_left = skip_typeref(type->pointer.points_to);
7153 if (select_left_arrow && is_type_valid(type)) {
7154 errorf(&pos, "left hand side of '->' is not a pointer, but '%T'", orig_type);
7160 if (type_left->kind != TYPE_COMPOUND_STRUCT &&
7161 type_left->kind != TYPE_COMPOUND_UNION) {
7163 if (is_type_valid(type_left) && !saw_error) {
7165 "request for member '%Y' in something not a struct or union, but '%T'",
7168 return create_invalid_expression();
7171 compound_t *compound = type_left->compound.compound;
7172 if (!compound->complete) {
7173 errorf(&pos, "request for member '%Y' in incomplete type '%T'",
7175 return create_invalid_expression();
7178 type_qualifiers_t qualifiers = type_left->base.qualifiers;
7179 expression_t *result =
7180 find_create_select(&pos, addr, qualifiers, compound, symbol);
7182 if (result == NULL) {
7183 errorf(&pos, "'%T' has no member named '%Y'", orig_type, symbol);
7184 return create_invalid_expression();
7190 static void check_call_argument(type_t *expected_type,
7191 call_argument_t *argument, unsigned pos)
7193 type_t *expected_type_skip = skip_typeref(expected_type);
7194 assign_error_t error = ASSIGN_ERROR_INCOMPATIBLE;
7195 expression_t *arg_expr = argument->expression;
7196 type_t *arg_type = skip_typeref(arg_expr->base.type);
7198 /* handle transparent union gnu extension */
7199 if (is_type_union(expected_type_skip)
7200 && (get_type_modifiers(expected_type) & DM_TRANSPARENT_UNION)) {
7201 compound_t *union_decl = expected_type_skip->compound.compound;
7202 type_t *best_type = NULL;
7203 entity_t *entry = union_decl->members.entities;
7204 for ( ; entry != NULL; entry = entry->base.next) {
7205 assert(is_declaration(entry));
7206 type_t *decl_type = entry->declaration.type;
7207 error = semantic_assign(decl_type, arg_expr);
7208 if (error == ASSIGN_ERROR_INCOMPATIBLE
7209 || error == ASSIGN_ERROR_POINTER_QUALIFIER_MISSING)
7212 if (error == ASSIGN_SUCCESS) {
7213 best_type = decl_type;
7214 } else if (best_type == NULL) {
7215 best_type = decl_type;
7219 if (best_type != NULL) {
7220 expected_type = best_type;
7224 error = semantic_assign(expected_type, arg_expr);
7225 argument->expression = create_implicit_cast(arg_expr, expected_type);
7227 if (error != ASSIGN_SUCCESS) {
7228 /* report exact scope in error messages (like "in argument 3") */
7230 snprintf(buf, sizeof(buf), "call argument %u", pos);
7231 report_assign_error(error, expected_type, arg_expr, buf,
7232 &arg_expr->base.source_position);
7234 type_t *const promoted_type = get_default_promoted_type(arg_type);
7235 if (!types_compatible(expected_type_skip, promoted_type) &&
7236 !types_compatible(expected_type_skip, type_void_ptr) &&
7237 !types_compatible(type_void_ptr, promoted_type)) {
7238 /* Deliberately show the skipped types in this warning */
7239 source_position_t const *const apos = &arg_expr->base.source_position;
7240 warningf(WARN_TRADITIONAL, apos, "passing call argument %u as '%T' rather than '%T' due to prototype", pos, expected_type_skip, promoted_type);
7246 * Handle the semantic restrictions of builtin calls
7248 static void handle_builtin_argument_restrictions(call_expression_t *call) {
7249 switch (call->function->reference.entity->function.btk) {
7250 case bk_gnu_builtin_return_address:
7251 case bk_gnu_builtin_frame_address: {
7252 /* argument must be constant */
7253 call_argument_t *argument = call->arguments;
7255 if (is_constant_expression(argument->expression) == EXPR_CLASS_VARIABLE) {
7256 errorf(&call->base.source_position,
7257 "argument of '%Y' must be a constant expression",
7258 call->function->reference.entity->base.symbol);
7262 case bk_gnu_builtin_object_size:
7263 if (call->arguments == NULL)
7266 call_argument_t *arg = call->arguments->next;
7267 if (arg != NULL && is_constant_expression(arg->expression) == EXPR_CLASS_VARIABLE) {
7268 errorf(&call->base.source_position,
7269 "second argument of '%Y' must be a constant expression",
7270 call->function->reference.entity->base.symbol);
7273 case bk_gnu_builtin_prefetch:
7274 /* second and third argument must be constant if existent */
7275 if (call->arguments == NULL)
7277 call_argument_t *rw = call->arguments->next;
7278 call_argument_t *locality = NULL;
7281 if (is_constant_expression(rw->expression) == EXPR_CLASS_VARIABLE) {
7282 errorf(&call->base.source_position,
7283 "second argument of '%Y' must be a constant expression",
7284 call->function->reference.entity->base.symbol);
7286 locality = rw->next;
7288 if (locality != NULL) {
7289 if (is_constant_expression(locality->expression) == EXPR_CLASS_VARIABLE) {
7290 errorf(&call->base.source_position,
7291 "third argument of '%Y' must be a constant expression",
7292 call->function->reference.entity->base.symbol);
7294 locality = rw->next;
7303 * Parse a call expression, ie. expression '( ... )'.
7305 * @param expression the function address
7307 static expression_t *parse_call_expression(expression_t *expression)
7309 expression_t *result = allocate_expression_zero(EXPR_CALL);
7310 call_expression_t *call = &result->call;
7311 call->function = expression;
7313 type_t *const orig_type = expression->base.type;
7314 type_t *const type = skip_typeref(orig_type);
7316 function_type_t *function_type = NULL;
7317 if (is_type_pointer(type)) {
7318 type_t *const to_type = skip_typeref(type->pointer.points_to);
7320 if (is_type_function(to_type)) {
7321 function_type = &to_type->function;
7322 call->base.type = function_type->return_type;
7326 if (function_type == NULL && is_type_valid(type)) {
7328 "called object '%E' (type '%T') is not a pointer to a function",
7329 expression, orig_type);
7332 /* parse arguments */
7334 add_anchor_token(')');
7335 add_anchor_token(',');
7337 if (token.type != ')') {
7338 call_argument_t **anchor = &call->arguments;
7340 call_argument_t *argument = allocate_ast_zero(sizeof(*argument));
7341 argument->expression = parse_assignment_expression();
7344 anchor = &argument->next;
7345 } while (next_if(','));
7347 rem_anchor_token(',');
7348 rem_anchor_token(')');
7349 expect(')', end_error);
7351 if (function_type == NULL)
7354 /* check type and count of call arguments */
7355 function_parameter_t *parameter = function_type->parameters;
7356 call_argument_t *argument = call->arguments;
7357 if (!function_type->unspecified_parameters) {
7358 for (unsigned pos = 0; parameter != NULL && argument != NULL;
7359 parameter = parameter->next, argument = argument->next) {
7360 check_call_argument(parameter->type, argument, ++pos);
7363 if (parameter != NULL) {
7364 errorf(&expression->base.source_position, "too few arguments to function '%E'", expression);
7365 } else if (argument != NULL && !function_type->variadic) {
7366 errorf(&argument->expression->base.source_position, "too many arguments to function '%E'", expression);
7370 /* do default promotion for other arguments */
7371 for (; argument != NULL; argument = argument->next) {
7372 type_t *argument_type = argument->expression->base.type;
7373 if (!is_type_object(skip_typeref(argument_type))) {
7374 errorf(&argument->expression->base.source_position,
7375 "call argument '%E' must not be void", argument->expression);
7378 argument_type = get_default_promoted_type(argument_type);
7380 argument->expression
7381 = create_implicit_cast(argument->expression, argument_type);
7386 if (is_type_compound(skip_typeref(function_type->return_type))) {
7387 source_position_t const *const pos = &expression->base.source_position;
7388 warningf(WARN_AGGREGATE_RETURN, pos, "function call has aggregate value");
7391 if (expression->kind == EXPR_REFERENCE) {
7392 reference_expression_t *reference = &expression->reference;
7393 if (reference->entity->kind == ENTITY_FUNCTION &&
7394 reference->entity->function.btk != bk_none)
7395 handle_builtin_argument_restrictions(call);
7402 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right);
7404 static bool same_compound_type(const type_t *type1, const type_t *type2)
7407 is_type_compound(type1) &&
7408 type1->kind == type2->kind &&
7409 type1->compound.compound == type2->compound.compound;
7412 static expression_t const *get_reference_address(expression_t const *expr)
7414 bool regular_take_address = true;
7416 if (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
7417 expr = expr->unary.value;
7419 regular_take_address = false;
7422 if (expr->kind != EXPR_UNARY_DEREFERENCE)
7425 expr = expr->unary.value;
7428 if (expr->kind != EXPR_REFERENCE)
7431 /* special case for functions which are automatically converted to a
7432 * pointer to function without an extra TAKE_ADDRESS operation */
7433 if (!regular_take_address &&
7434 expr->reference.entity->kind != ENTITY_FUNCTION) {
7441 static void warn_reference_address_as_bool(expression_t const* expr)
7443 expr = get_reference_address(expr);
7445 source_position_t const *const pos = &expr->base.source_position;
7446 entity_t const *const ent = expr->reference.entity;
7447 warningf(WARN_ADDRESS, pos, "the address of '%N' will always evaluate as 'true'", ent);
7451 static void warn_assignment_in_condition(const expression_t *const expr)
7453 if (expr->base.kind != EXPR_BINARY_ASSIGN)
7455 if (expr->base.parenthesized)
7457 source_position_t const *const pos = &expr->base.source_position;
7458 warningf(WARN_PARENTHESES, pos, "suggest parentheses around assignment used as truth value");
7461 static void semantic_condition(expression_t const *const expr,
7462 char const *const context)
7464 type_t *const type = skip_typeref(expr->base.type);
7465 if (is_type_scalar(type)) {
7466 warn_reference_address_as_bool(expr);
7467 warn_assignment_in_condition(expr);
7468 } else if (is_type_valid(type)) {
7469 errorf(&expr->base.source_position,
7470 "%s must have scalar type", context);
7475 * Parse a conditional expression, ie. 'expression ? ... : ...'.
7477 * @param expression the conditional expression
7479 static expression_t *parse_conditional_expression(expression_t *expression)
7481 expression_t *result = allocate_expression_zero(EXPR_CONDITIONAL);
7483 conditional_expression_t *conditional = &result->conditional;
7484 conditional->condition = expression;
7487 add_anchor_token(':');
7489 /* §6.5.15:2 The first operand shall have scalar type. */
7490 semantic_condition(expression, "condition of conditional operator");
7492 expression_t *true_expression = expression;
7493 bool gnu_cond = false;
7494 if (GNU_MODE && token.type == ':') {
7497 true_expression = parse_expression();
7499 rem_anchor_token(':');
7500 expect(':', end_error);
7502 expression_t *false_expression =
7503 parse_subexpression(c_mode & _CXX ? PREC_ASSIGNMENT : PREC_CONDITIONAL);
7505 type_t *const orig_true_type = true_expression->base.type;
7506 type_t *const orig_false_type = false_expression->base.type;
7507 type_t *const true_type = skip_typeref(orig_true_type);
7508 type_t *const false_type = skip_typeref(orig_false_type);
7511 source_position_t const *const pos = &conditional->base.source_position;
7512 type_t *result_type;
7513 if (is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7514 is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7515 /* ISO/IEC 14882:1998(E) §5.16:2 */
7516 if (true_expression->kind == EXPR_UNARY_THROW) {
7517 result_type = false_type;
7518 } else if (false_expression->kind == EXPR_UNARY_THROW) {
7519 result_type = true_type;
7521 if (!is_type_atomic(true_type, ATOMIC_TYPE_VOID) ||
7522 !is_type_atomic(false_type, ATOMIC_TYPE_VOID)) {
7523 warningf(WARN_OTHER, pos, "ISO C forbids conditional expression with only one void side");
7525 result_type = type_void;
7527 } else if (is_type_arithmetic(true_type)
7528 && is_type_arithmetic(false_type)) {
7529 result_type = semantic_arithmetic(true_type, false_type);
7530 } else if (same_compound_type(true_type, false_type)) {
7531 /* just take 1 of the 2 types */
7532 result_type = true_type;
7533 } else if (is_type_pointer(true_type) || is_type_pointer(false_type)) {
7534 type_t *pointer_type;
7536 expression_t *other_expression;
7537 if (is_type_pointer(true_type) &&
7538 (!is_type_pointer(false_type) || is_null_pointer_constant(false_expression))) {
7539 pointer_type = true_type;
7540 other_type = false_type;
7541 other_expression = false_expression;
7543 pointer_type = false_type;
7544 other_type = true_type;
7545 other_expression = true_expression;
7548 if (is_null_pointer_constant(other_expression)) {
7549 result_type = pointer_type;
7550 } else if (is_type_pointer(other_type)) {
7551 type_t *to1 = skip_typeref(pointer_type->pointer.points_to);
7552 type_t *to2 = skip_typeref(other_type->pointer.points_to);
7555 if (is_type_atomic(to1, ATOMIC_TYPE_VOID) ||
7556 is_type_atomic(to2, ATOMIC_TYPE_VOID)) {
7558 } else if (types_compatible(get_unqualified_type(to1),
7559 get_unqualified_type(to2))) {
7562 warningf(WARN_OTHER, pos, "pointer types '%T' and '%T' in conditional expression are incompatible", true_type, false_type);
7566 type_t *const type =
7567 get_qualified_type(to, to1->base.qualifiers | to2->base.qualifiers);
7568 result_type = make_pointer_type(type, TYPE_QUALIFIER_NONE);
7569 } else if (is_type_integer(other_type)) {
7570 warningf(WARN_OTHER, pos, "pointer/integer type mismatch in conditional expression ('%T' and '%T')", true_type, false_type);
7571 result_type = pointer_type;
7573 goto types_incompatible;
7577 if (is_type_valid(true_type) && is_type_valid(false_type)) {
7578 type_error_incompatible("while parsing conditional", pos, true_type, false_type);
7580 result_type = type_error_type;
7583 conditional->true_expression
7584 = gnu_cond ? NULL : create_implicit_cast(true_expression, result_type);
7585 conditional->false_expression
7586 = create_implicit_cast(false_expression, result_type);
7587 conditional->base.type = result_type;
7592 * Parse an extension expression.
7594 static expression_t *parse_extension(void)
7597 expression_t *expression = parse_subexpression(PREC_UNARY);
7603 * Parse a __builtin_classify_type() expression.
7605 static expression_t *parse_builtin_classify_type(void)
7607 expression_t *result = allocate_expression_zero(EXPR_CLASSIFY_TYPE);
7608 result->base.type = type_int;
7610 eat(T___builtin_classify_type);
7612 expect('(', end_error);
7613 add_anchor_token(')');
7614 expression_t *expression = parse_expression();
7615 rem_anchor_token(')');
7616 expect(')', end_error);
7617 result->classify_type.type_expression = expression;
7621 return create_invalid_expression();
7625 * Parse a delete expression
7626 * ISO/IEC 14882:1998(E) §5.3.5
7628 static expression_t *parse_delete(void)
7630 expression_t *const result = allocate_expression_zero(EXPR_UNARY_DELETE);
7631 result->base.type = type_void;
7636 result->kind = EXPR_UNARY_DELETE_ARRAY;
7637 expect(']', end_error);
7641 expression_t *const value = parse_subexpression(PREC_CAST);
7642 result->unary.value = value;
7644 type_t *const type = skip_typeref(value->base.type);
7645 if (!is_type_pointer(type)) {
7646 if (is_type_valid(type)) {
7647 errorf(&value->base.source_position,
7648 "operand of delete must have pointer type");
7650 } else if (is_type_atomic(skip_typeref(type->pointer.points_to), ATOMIC_TYPE_VOID)) {
7651 source_position_t const *const pos = &value->base.source_position;
7652 warningf(WARN_OTHER, pos, "deleting 'void*' is undefined");
7659 * Parse a throw expression
7660 * ISO/IEC 14882:1998(E) §15:1
7662 static expression_t *parse_throw(void)
7664 expression_t *const result = allocate_expression_zero(EXPR_UNARY_THROW);
7665 result->base.type = type_void;
7669 expression_t *value = NULL;
7670 switch (token.type) {
7672 value = parse_assignment_expression();
7673 /* ISO/IEC 14882:1998(E) §15.1:3 */
7674 type_t *const orig_type = value->base.type;
7675 type_t *const type = skip_typeref(orig_type);
7676 if (is_type_incomplete(type)) {
7677 errorf(&value->base.source_position,
7678 "cannot throw object of incomplete type '%T'", orig_type);
7679 } else if (is_type_pointer(type)) {
7680 type_t *const points_to = skip_typeref(type->pointer.points_to);
7681 if (is_type_incomplete(points_to) &&
7682 !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7683 errorf(&value->base.source_position,
7684 "cannot throw pointer to incomplete type '%T'", orig_type);
7692 result->unary.value = value;
7697 static bool check_pointer_arithmetic(const source_position_t *source_position,
7698 type_t *pointer_type,
7699 type_t *orig_pointer_type)
7701 type_t *points_to = pointer_type->pointer.points_to;
7702 points_to = skip_typeref(points_to);
7704 if (is_type_incomplete(points_to)) {
7705 if (!GNU_MODE || !is_type_atomic(points_to, ATOMIC_TYPE_VOID)) {
7706 errorf(source_position,
7707 "arithmetic with pointer to incomplete type '%T' not allowed",
7711 warningf(WARN_POINTER_ARITH, source_position, "pointer of type '%T' used in arithmetic", orig_pointer_type);
7713 } else if (is_type_function(points_to)) {
7715 errorf(source_position,
7716 "arithmetic with pointer to function type '%T' not allowed",
7720 warningf(WARN_POINTER_ARITH, source_position, "pointer to a function '%T' used in arithmetic", orig_pointer_type);
7726 static bool is_lvalue(const expression_t *expression)
7728 /* TODO: doesn't seem to be consistent with §6.3.2.1:1 */
7729 switch (expression->kind) {
7730 case EXPR_ARRAY_ACCESS:
7731 case EXPR_COMPOUND_LITERAL:
7732 case EXPR_REFERENCE:
7734 case EXPR_UNARY_DEREFERENCE:
7738 type_t *type = skip_typeref(expression->base.type);
7740 /* ISO/IEC 14882:1998(E) §3.10:3 */
7741 is_type_reference(type) ||
7742 /* Claim it is an lvalue, if the type is invalid. There was a parse
7743 * error before, which maybe prevented properly recognizing it as
7745 !is_type_valid(type);
7750 static void semantic_incdec(unary_expression_t *expression)
7752 type_t *const orig_type = expression->value->base.type;
7753 type_t *const type = skip_typeref(orig_type);
7754 if (is_type_pointer(type)) {
7755 if (!check_pointer_arithmetic(&expression->base.source_position,
7759 } else if (!is_type_real(type) && is_type_valid(type)) {
7760 /* TODO: improve error message */
7761 errorf(&expression->base.source_position,
7762 "operation needs an arithmetic or pointer type");
7765 if (!is_lvalue(expression->value)) {
7766 /* TODO: improve error message */
7767 errorf(&expression->base.source_position, "lvalue required as operand");
7769 expression->base.type = orig_type;
7772 static void semantic_unexpr_arithmetic(unary_expression_t *expression)
7774 type_t *const orig_type = expression->value->base.type;
7775 type_t *const type = skip_typeref(orig_type);
7776 if (!is_type_arithmetic(type)) {
7777 if (is_type_valid(type)) {
7778 /* TODO: improve error message */
7779 errorf(&expression->base.source_position,
7780 "operation needs an arithmetic type");
7785 expression->base.type = orig_type;
7788 static void semantic_unexpr_plus(unary_expression_t *expression)
7790 semantic_unexpr_arithmetic(expression);
7791 source_position_t const *const pos = &expression->base.source_position;
7792 warningf(WARN_TRADITIONAL, pos, "traditional C rejects the unary plus operator");
7795 static void semantic_not(unary_expression_t *expression)
7797 /* §6.5.3.3:1 The operand [...] of the ! operator, scalar type. */
7798 semantic_condition(expression->value, "operand of !");
7799 expression->base.type = c_mode & _CXX ? type_bool : type_int;
7802 static void semantic_unexpr_integer(unary_expression_t *expression)
7804 type_t *const orig_type = expression->value->base.type;
7805 type_t *const type = skip_typeref(orig_type);
7806 if (!is_type_integer(type)) {
7807 if (is_type_valid(type)) {
7808 errorf(&expression->base.source_position,
7809 "operand of ~ must be of integer type");
7814 expression->base.type = orig_type;
7817 static void semantic_dereference(unary_expression_t *expression)
7819 type_t *const orig_type = expression->value->base.type;
7820 type_t *const type = skip_typeref(orig_type);
7821 if (!is_type_pointer(type)) {
7822 if (is_type_valid(type)) {
7823 errorf(&expression->base.source_position,
7824 "Unary '*' needs pointer or array type, but type '%T' given", orig_type);
7829 type_t *result_type = type->pointer.points_to;
7830 result_type = automatic_type_conversion(result_type);
7831 expression->base.type = result_type;
7835 * Record that an address is taken (expression represents an lvalue).
7837 * @param expression the expression
7838 * @param may_be_register if true, the expression might be an register
7840 static void set_address_taken(expression_t *expression, bool may_be_register)
7842 if (expression->kind != EXPR_REFERENCE)
7845 entity_t *const entity = expression->reference.entity;
7847 if (entity->kind != ENTITY_VARIABLE && entity->kind != ENTITY_PARAMETER)
7850 if (entity->declaration.storage_class == STORAGE_CLASS_REGISTER
7851 && !may_be_register) {
7852 source_position_t const *const pos = &expression->base.source_position;
7853 errorf(pos, "address of register '%N' requested", entity);
7856 if (entity->kind == ENTITY_VARIABLE) {
7857 entity->variable.address_taken = true;
7859 assert(entity->kind == ENTITY_PARAMETER);
7860 entity->parameter.address_taken = true;
7865 * Check the semantic of the address taken expression.
7867 static void semantic_take_addr(unary_expression_t *expression)
7869 expression_t *value = expression->value;
7870 value->base.type = revert_automatic_type_conversion(value);
7872 type_t *orig_type = value->base.type;
7873 type_t *type = skip_typeref(orig_type);
7874 if (!is_type_valid(type))
7878 if (!is_lvalue(value)) {
7879 errorf(&expression->base.source_position, "'&' requires an lvalue");
7881 if (type->kind == TYPE_BITFIELD) {
7882 errorf(&expression->base.source_position,
7883 "'&' not allowed on object with bitfield type '%T'",
7887 set_address_taken(value, false);
7889 expression->base.type = make_pointer_type(orig_type, TYPE_QUALIFIER_NONE);
7892 #define CREATE_UNARY_EXPRESSION_PARSER(token_type, unexpression_type, sfunc) \
7893 static expression_t *parse_##unexpression_type(void) \
7895 expression_t *unary_expression \
7896 = allocate_expression_zero(unexpression_type); \
7898 unary_expression->unary.value = parse_subexpression(PREC_UNARY); \
7900 sfunc(&unary_expression->unary); \
7902 return unary_expression; \
7905 CREATE_UNARY_EXPRESSION_PARSER('-', EXPR_UNARY_NEGATE,
7906 semantic_unexpr_arithmetic)
7907 CREATE_UNARY_EXPRESSION_PARSER('+', EXPR_UNARY_PLUS,
7908 semantic_unexpr_plus)
7909 CREATE_UNARY_EXPRESSION_PARSER('!', EXPR_UNARY_NOT,
7911 CREATE_UNARY_EXPRESSION_PARSER('*', EXPR_UNARY_DEREFERENCE,
7912 semantic_dereference)
7913 CREATE_UNARY_EXPRESSION_PARSER('&', EXPR_UNARY_TAKE_ADDRESS,
7915 CREATE_UNARY_EXPRESSION_PARSER('~', EXPR_UNARY_BITWISE_NEGATE,
7916 semantic_unexpr_integer)
7917 CREATE_UNARY_EXPRESSION_PARSER(T_PLUSPLUS, EXPR_UNARY_PREFIX_INCREMENT,
7919 CREATE_UNARY_EXPRESSION_PARSER(T_MINUSMINUS, EXPR_UNARY_PREFIX_DECREMENT,
7922 #define CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(token_type, unexpression_type, \
7924 static expression_t *parse_##unexpression_type(expression_t *left) \
7926 expression_t *unary_expression \
7927 = allocate_expression_zero(unexpression_type); \
7929 unary_expression->unary.value = left; \
7931 sfunc(&unary_expression->unary); \
7933 return unary_expression; \
7936 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_PLUSPLUS,
7937 EXPR_UNARY_POSTFIX_INCREMENT,
7939 CREATE_UNARY_POSTFIX_EXPRESSION_PARSER(T_MINUSMINUS,
7940 EXPR_UNARY_POSTFIX_DECREMENT,
7943 static type_t *semantic_arithmetic(type_t *type_left, type_t *type_right)
7945 /* TODO: handle complex + imaginary types */
7947 type_left = get_unqualified_type(type_left);
7948 type_right = get_unqualified_type(type_right);
7950 /* §6.3.1.8 Usual arithmetic conversions */
7951 if (type_left == type_long_double || type_right == type_long_double) {
7952 return type_long_double;
7953 } else if (type_left == type_double || type_right == type_double) {
7955 } else if (type_left == type_float || type_right == type_float) {
7959 type_left = promote_integer(type_left);
7960 type_right = promote_integer(type_right);
7962 if (type_left == type_right)
7965 bool const signed_left = is_type_signed(type_left);
7966 bool const signed_right = is_type_signed(type_right);
7967 int const rank_left = get_rank(type_left);
7968 int const rank_right = get_rank(type_right);
7970 if (signed_left == signed_right)
7971 return rank_left >= rank_right ? type_left : type_right;
7980 u_rank = rank_right;
7981 u_type = type_right;
7983 s_rank = rank_right;
7984 s_type = type_right;
7989 if (u_rank >= s_rank)
7992 /* casting rank to atomic_type_kind is a bit hacky, but makes things
7994 if (get_atomic_type_size((atomic_type_kind_t) s_rank)
7995 > get_atomic_type_size((atomic_type_kind_t) u_rank))
7999 case ATOMIC_TYPE_INT: return type_unsigned_int;
8000 case ATOMIC_TYPE_LONG: return type_unsigned_long;
8001 case ATOMIC_TYPE_LONGLONG: return type_unsigned_long_long;
8003 default: panic("invalid atomic type");
8008 * Check the semantic restrictions for a binary expression.
8010 static void semantic_binexpr_arithmetic(binary_expression_t *expression)
8012 expression_t *const left = expression->left;
8013 expression_t *const right = expression->right;
8014 type_t *const orig_type_left = left->base.type;
8015 type_t *const orig_type_right = right->base.type;
8016 type_t *const type_left = skip_typeref(orig_type_left);
8017 type_t *const type_right = skip_typeref(orig_type_right);
8019 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8020 /* TODO: improve error message */
8021 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8022 errorf(&expression->base.source_position,
8023 "operation needs arithmetic types");
8028 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8029 expression->left = create_implicit_cast(left, arithmetic_type);
8030 expression->right = create_implicit_cast(right, arithmetic_type);
8031 expression->base.type = arithmetic_type;
8034 static void semantic_binexpr_integer(binary_expression_t *const expression)
8036 expression_t *const left = expression->left;
8037 expression_t *const right = expression->right;
8038 type_t *const orig_type_left = left->base.type;
8039 type_t *const orig_type_right = right->base.type;
8040 type_t *const type_left = skip_typeref(orig_type_left);
8041 type_t *const type_right = skip_typeref(orig_type_right);
8043 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8044 /* TODO: improve error message */
8045 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8046 errorf(&expression->base.source_position,
8047 "operation needs integer types");
8052 type_t *const result_type = semantic_arithmetic(type_left, type_right);
8053 expression->left = create_implicit_cast(left, result_type);
8054 expression->right = create_implicit_cast(right, result_type);
8055 expression->base.type = result_type;
8058 static void warn_div_by_zero(binary_expression_t const *const expression)
8060 if (!is_type_integer(expression->base.type))
8063 expression_t const *const right = expression->right;
8064 /* The type of the right operand can be different for /= */
8065 if (is_type_integer(right->base.type) &&
8066 is_constant_expression(right) == EXPR_CLASS_CONSTANT &&
8067 !fold_constant_to_bool(right)) {
8068 source_position_t const *const pos = &expression->base.source_position;
8069 warningf(WARN_DIV_BY_ZERO, pos, "division by zero");
8074 * Check the semantic restrictions for a div/mod expression.
8076 static void semantic_divmod_arithmetic(binary_expression_t *expression)
8078 semantic_binexpr_arithmetic(expression);
8079 warn_div_by_zero(expression);
8082 static void warn_addsub_in_shift(const expression_t *const expr)
8084 if (expr->base.parenthesized)
8088 switch (expr->kind) {
8089 case EXPR_BINARY_ADD: op = '+'; break;
8090 case EXPR_BINARY_SUB: op = '-'; break;
8094 source_position_t const *const pos = &expr->base.source_position;
8095 warningf(WARN_PARENTHESES, pos, "suggest parentheses around '%c' inside shift", op);
8098 static bool semantic_shift(binary_expression_t *expression)
8100 expression_t *const left = expression->left;
8101 expression_t *const right = expression->right;
8102 type_t *const orig_type_left = left->base.type;
8103 type_t *const orig_type_right = right->base.type;
8104 type_t * type_left = skip_typeref(orig_type_left);
8105 type_t * type_right = skip_typeref(orig_type_right);
8107 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8108 /* TODO: improve error message */
8109 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8110 errorf(&expression->base.source_position,
8111 "operands of shift operation must have integer types");
8116 type_left = promote_integer(type_left);
8118 if (is_constant_expression(right) == EXPR_CLASS_CONSTANT) {
8119 source_position_t const *const pos = &right->base.source_position;
8120 long const count = fold_constant_to_int(right);
8122 warningf(WARN_OTHER, pos, "shift count must be non-negative");
8123 } else if ((unsigned long)count >=
8124 get_atomic_type_size(type_left->atomic.akind) * 8) {
8125 warningf(WARN_OTHER, pos, "shift count must be less than type width");
8129 type_right = promote_integer(type_right);
8130 expression->right = create_implicit_cast(right, type_right);
8135 static void semantic_shift_op(binary_expression_t *expression)
8137 expression_t *const left = expression->left;
8138 expression_t *const right = expression->right;
8140 if (!semantic_shift(expression))
8143 warn_addsub_in_shift(left);
8144 warn_addsub_in_shift(right);
8146 type_t *const orig_type_left = left->base.type;
8147 type_t * type_left = skip_typeref(orig_type_left);
8149 type_left = promote_integer(type_left);
8150 expression->left = create_implicit_cast(left, type_left);
8151 expression->base.type = type_left;
8154 static void semantic_add(binary_expression_t *expression)
8156 expression_t *const left = expression->left;
8157 expression_t *const right = expression->right;
8158 type_t *const orig_type_left = left->base.type;
8159 type_t *const orig_type_right = right->base.type;
8160 type_t *const type_left = skip_typeref(orig_type_left);
8161 type_t *const type_right = skip_typeref(orig_type_right);
8164 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8165 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8166 expression->left = create_implicit_cast(left, arithmetic_type);
8167 expression->right = create_implicit_cast(right, arithmetic_type);
8168 expression->base.type = arithmetic_type;
8169 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8170 check_pointer_arithmetic(&expression->base.source_position,
8171 type_left, orig_type_left);
8172 expression->base.type = type_left;
8173 } else if (is_type_pointer(type_right) && is_type_integer(type_left)) {
8174 check_pointer_arithmetic(&expression->base.source_position,
8175 type_right, orig_type_right);
8176 expression->base.type = type_right;
8177 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8178 errorf(&expression->base.source_position,
8179 "invalid operands to binary + ('%T', '%T')",
8180 orig_type_left, orig_type_right);
8184 static void semantic_sub(binary_expression_t *expression)
8186 expression_t *const left = expression->left;
8187 expression_t *const right = expression->right;
8188 type_t *const orig_type_left = left->base.type;
8189 type_t *const orig_type_right = right->base.type;
8190 type_t *const type_left = skip_typeref(orig_type_left);
8191 type_t *const type_right = skip_typeref(orig_type_right);
8192 source_position_t const *const pos = &expression->base.source_position;
8195 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8196 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8197 expression->left = create_implicit_cast(left, arithmetic_type);
8198 expression->right = create_implicit_cast(right, arithmetic_type);
8199 expression->base.type = arithmetic_type;
8200 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8201 check_pointer_arithmetic(&expression->base.source_position,
8202 type_left, orig_type_left);
8203 expression->base.type = type_left;
8204 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8205 type_t *const unqual_left = get_unqualified_type(skip_typeref(type_left->pointer.points_to));
8206 type_t *const unqual_right = get_unqualified_type(skip_typeref(type_right->pointer.points_to));
8207 if (!types_compatible(unqual_left, unqual_right)) {
8209 "subtracting pointers to incompatible types '%T' and '%T'",
8210 orig_type_left, orig_type_right);
8211 } else if (!is_type_object(unqual_left)) {
8212 if (!is_type_atomic(unqual_left, ATOMIC_TYPE_VOID)) {
8213 errorf(pos, "subtracting pointers to non-object types '%T'",
8216 warningf(WARN_OTHER, pos, "subtracting pointers to void");
8219 expression->base.type = type_ptrdiff_t;
8220 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8221 errorf(pos, "invalid operands of types '%T' and '%T' to binary '-'",
8222 orig_type_left, orig_type_right);
8226 static void warn_string_literal_address(expression_t const* expr)
8228 while (expr->kind == EXPR_UNARY_TAKE_ADDRESS) {
8229 expr = expr->unary.value;
8230 if (expr->kind != EXPR_UNARY_DEREFERENCE)
8232 expr = expr->unary.value;
8235 if (expr->kind == EXPR_STRING_LITERAL
8236 || expr->kind == EXPR_WIDE_STRING_LITERAL) {
8237 source_position_t const *const pos = &expr->base.source_position;
8238 warningf(WARN_ADDRESS, pos, "comparison with string literal results in unspecified behaviour");
8242 static bool maybe_negative(expression_t const *const expr)
8244 switch (is_constant_expression(expr)) {
8245 case EXPR_CLASS_ERROR: return false;
8246 case EXPR_CLASS_CONSTANT: return fold_constant_to_int(expr) < 0;
8247 default: return true;
8251 static void warn_comparison(source_position_t const *const pos, expression_t const *const expr, expression_t const *const other)
8253 warn_string_literal_address(expr);
8255 expression_t const* const ref = get_reference_address(expr);
8256 if (ref != NULL && is_null_pointer_constant(other)) {
8257 entity_t const *const ent = ref->reference.entity;
8258 warningf(WARN_ADDRESS, pos, "the address of '%N' will never be NULL", ent);
8261 if (!expr->base.parenthesized) {
8262 switch (expr->base.kind) {
8263 case EXPR_BINARY_LESS:
8264 case EXPR_BINARY_GREATER:
8265 case EXPR_BINARY_LESSEQUAL:
8266 case EXPR_BINARY_GREATEREQUAL:
8267 case EXPR_BINARY_NOTEQUAL:
8268 case EXPR_BINARY_EQUAL:
8269 warningf(WARN_PARENTHESES, pos, "comparisons like 'x <= y < z' do not have their mathematical meaning");
8278 * Check the semantics of comparison expressions.
8280 * @param expression The expression to check.
8282 static void semantic_comparison(binary_expression_t *expression)
8284 source_position_t const *const pos = &expression->base.source_position;
8285 expression_t *const left = expression->left;
8286 expression_t *const right = expression->right;
8288 warn_comparison(pos, left, right);
8289 warn_comparison(pos, right, left);
8291 type_t *orig_type_left = left->base.type;
8292 type_t *orig_type_right = right->base.type;
8293 type_t *type_left = skip_typeref(orig_type_left);
8294 type_t *type_right = skip_typeref(orig_type_right);
8296 /* TODO non-arithmetic types */
8297 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8298 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8300 /* test for signed vs unsigned compares */
8301 if (is_type_integer(arithmetic_type)) {
8302 bool const signed_left = is_type_signed(type_left);
8303 bool const signed_right = is_type_signed(type_right);
8304 if (signed_left != signed_right) {
8305 /* FIXME long long needs better const folding magic */
8306 /* TODO check whether constant value can be represented by other type */
8307 if ((signed_left && maybe_negative(left)) ||
8308 (signed_right && maybe_negative(right))) {
8309 warningf(WARN_SIGN_COMPARE, pos, "comparison between signed and unsigned");
8314 expression->left = create_implicit_cast(left, arithmetic_type);
8315 expression->right = create_implicit_cast(right, arithmetic_type);
8316 expression->base.type = arithmetic_type;
8317 if ((expression->base.kind == EXPR_BINARY_EQUAL ||
8318 expression->base.kind == EXPR_BINARY_NOTEQUAL) &&
8319 is_type_float(arithmetic_type)) {
8320 warningf(WARN_FLOAT_EQUAL, pos, "comparing floating point with == or != is unsafe");
8322 } else if (is_type_pointer(type_left) && is_type_pointer(type_right)) {
8323 /* TODO check compatibility */
8324 } else if (is_type_pointer(type_left)) {
8325 expression->right = create_implicit_cast(right, type_left);
8326 } else if (is_type_pointer(type_right)) {
8327 expression->left = create_implicit_cast(left, type_right);
8328 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8329 type_error_incompatible("invalid operands in comparison", pos, type_left, type_right);
8331 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8335 * Checks if a compound type has constant fields.
8337 static bool has_const_fields(const compound_type_t *type)
8339 compound_t *compound = type->compound;
8340 entity_t *entry = compound->members.entities;
8342 for (; entry != NULL; entry = entry->base.next) {
8343 if (!is_declaration(entry))
8346 const type_t *decl_type = skip_typeref(entry->declaration.type);
8347 if (decl_type->base.qualifiers & TYPE_QUALIFIER_CONST)
8354 static bool is_valid_assignment_lhs(expression_t const* const left)
8356 type_t *const orig_type_left = revert_automatic_type_conversion(left);
8357 type_t *const type_left = skip_typeref(orig_type_left);
8359 if (!is_lvalue(left)) {
8360 errorf(&left->base.source_position, "left hand side '%E' of assignment is not an lvalue",
8365 if (left->kind == EXPR_REFERENCE
8366 && left->reference.entity->kind == ENTITY_FUNCTION) {
8367 errorf(&left->base.source_position, "cannot assign to function '%E'", left);
8371 if (is_type_array(type_left)) {
8372 errorf(&left->base.source_position, "cannot assign to array '%E'", left);
8375 if (type_left->base.qualifiers & TYPE_QUALIFIER_CONST) {
8376 errorf(&left->base.source_position, "assignment to read-only location '%E' (type '%T')", left,
8380 if (is_type_incomplete(type_left)) {
8381 errorf(&left->base.source_position, "left-hand side '%E' of assignment has incomplete type '%T'",
8382 left, orig_type_left);
8385 if (is_type_compound(type_left) && has_const_fields(&type_left->compound)) {
8386 errorf(&left->base.source_position, "cannot assign to '%E' because compound type '%T' has read-only fields",
8387 left, orig_type_left);
8394 static void semantic_arithmetic_assign(binary_expression_t *expression)
8396 expression_t *left = expression->left;
8397 expression_t *right = expression->right;
8398 type_t *orig_type_left = left->base.type;
8399 type_t *orig_type_right = right->base.type;
8401 if (!is_valid_assignment_lhs(left))
8404 type_t *type_left = skip_typeref(orig_type_left);
8405 type_t *type_right = skip_typeref(orig_type_right);
8407 if (!is_type_arithmetic(type_left) || !is_type_arithmetic(type_right)) {
8408 /* TODO: improve error message */
8409 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8410 errorf(&expression->base.source_position,
8411 "operation needs arithmetic types");
8416 /* combined instructions are tricky. We can't create an implicit cast on
8417 * the left side, because we need the uncasted form for the store.
8418 * The ast2firm pass has to know that left_type must be right_type
8419 * for the arithmetic operation and create a cast by itself */
8420 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8421 expression->right = create_implicit_cast(right, arithmetic_type);
8422 expression->base.type = type_left;
8425 static void semantic_divmod_assign(binary_expression_t *expression)
8427 semantic_arithmetic_assign(expression);
8428 warn_div_by_zero(expression);
8431 static void semantic_arithmetic_addsubb_assign(binary_expression_t *expression)
8433 expression_t *const left = expression->left;
8434 expression_t *const right = expression->right;
8435 type_t *const orig_type_left = left->base.type;
8436 type_t *const orig_type_right = right->base.type;
8437 type_t *const type_left = skip_typeref(orig_type_left);
8438 type_t *const type_right = skip_typeref(orig_type_right);
8440 if (!is_valid_assignment_lhs(left))
8443 if (is_type_arithmetic(type_left) && is_type_arithmetic(type_right)) {
8444 /* combined instructions are tricky. We can't create an implicit cast on
8445 * the left side, because we need the uncasted form for the store.
8446 * The ast2firm pass has to know that left_type must be right_type
8447 * for the arithmetic operation and create a cast by itself */
8448 type_t *const arithmetic_type = semantic_arithmetic(type_left, type_right);
8449 expression->right = create_implicit_cast(right, arithmetic_type);
8450 expression->base.type = type_left;
8451 } else if (is_type_pointer(type_left) && is_type_integer(type_right)) {
8452 check_pointer_arithmetic(&expression->base.source_position,
8453 type_left, orig_type_left);
8454 expression->base.type = type_left;
8455 } else if (is_type_valid(type_left) && is_type_valid(type_right)) {
8456 errorf(&expression->base.source_position,
8457 "incompatible types '%T' and '%T' in assignment",
8458 orig_type_left, orig_type_right);
8462 static void semantic_integer_assign(binary_expression_t *expression)
8464 expression_t *left = expression->left;
8465 expression_t *right = expression->right;
8466 type_t *orig_type_left = left->base.type;
8467 type_t *orig_type_right = right->base.type;
8469 if (!is_valid_assignment_lhs(left))
8472 type_t *type_left = skip_typeref(orig_type_left);
8473 type_t *type_right = skip_typeref(orig_type_right);
8475 if (!is_type_integer(type_left) || !is_type_integer(type_right)) {
8476 /* TODO: improve error message */
8477 if (is_type_valid(type_left) && is_type_valid(type_right)) {
8478 errorf(&expression->base.source_position,
8479 "operation needs integer types");
8484 /* combined instructions are tricky. We can't create an implicit cast on
8485 * the left side, because we need the uncasted form for the store.
8486 * The ast2firm pass has to know that left_type must be right_type
8487 * for the arithmetic operation and create a cast by itself */
8488 type_t *arithmetic_type = semantic_arithmetic(type_left, type_right);
8489 expression->right = create_implicit_cast(right, arithmetic_type);
8490 expression->base.type = type_left;
8493 static void semantic_shift_assign(binary_expression_t *expression)
8495 expression_t *left = expression->left;
8497 if (!is_valid_assignment_lhs(left))
8500 if (!semantic_shift(expression))
8503 expression->base.type = skip_typeref(left->base.type);
8506 static void warn_logical_and_within_or(const expression_t *const expr)
8508 if (expr->base.kind != EXPR_BINARY_LOGICAL_AND)
8510 if (expr->base.parenthesized)
8512 source_position_t const *const pos = &expr->base.source_position;
8513 warningf(WARN_PARENTHESES, pos, "suggest parentheses around && within ||");
8517 * Check the semantic restrictions of a logical expression.
8519 static void semantic_logical_op(binary_expression_t *expression)
8521 /* §6.5.13:2 Each of the operands shall have scalar type.
8522 * §6.5.14:2 Each of the operands shall have scalar type. */
8523 semantic_condition(expression->left, "left operand of logical operator");
8524 semantic_condition(expression->right, "right operand of logical operator");
8525 if (expression->base.kind == EXPR_BINARY_LOGICAL_OR) {
8526 warn_logical_and_within_or(expression->left);
8527 warn_logical_and_within_or(expression->right);
8529 expression->base.type = c_mode & _CXX ? type_bool : type_int;
8533 * Check the semantic restrictions of a binary assign expression.
8535 static void semantic_binexpr_assign(binary_expression_t *expression)
8537 expression_t *left = expression->left;
8538 type_t *orig_type_left = left->base.type;
8540 if (!is_valid_assignment_lhs(left))
8543 assign_error_t error = semantic_assign(orig_type_left, expression->right);
8544 report_assign_error(error, orig_type_left, expression->right,
8545 "assignment", &left->base.source_position);
8546 expression->right = create_implicit_cast(expression->right, orig_type_left);
8547 expression->base.type = orig_type_left;
8551 * Determine if the outermost operation (or parts thereof) of the given
8552 * expression has no effect in order to generate a warning about this fact.
8553 * Therefore in some cases this only examines some of the operands of the
8554 * expression (see comments in the function and examples below).
8556 * f() + 23; // warning, because + has no effect
8557 * x || f(); // no warning, because x controls execution of f()
8558 * x ? y : f(); // warning, because y has no effect
8559 * (void)x; // no warning to be able to suppress the warning
8560 * This function can NOT be used for an "expression has definitely no effect"-
8562 static bool expression_has_effect(const expression_t *const expr)
8564 switch (expr->kind) {
8565 case EXPR_UNKNOWN: break;
8566 case EXPR_INVALID: return true; /* do NOT warn */
8567 case EXPR_REFERENCE: return false;
8568 case EXPR_REFERENCE_ENUM_VALUE: return false;
8569 case EXPR_LABEL_ADDRESS: return false;
8571 /* suppress the warning for microsoft __noop operations */
8572 case EXPR_LITERAL_MS_NOOP: return true;
8573 case EXPR_LITERAL_BOOLEAN:
8574 case EXPR_LITERAL_CHARACTER:
8575 case EXPR_LITERAL_WIDE_CHARACTER:
8576 case EXPR_LITERAL_INTEGER:
8577 case EXPR_LITERAL_INTEGER_OCTAL:
8578 case EXPR_LITERAL_INTEGER_HEXADECIMAL:
8579 case EXPR_LITERAL_FLOATINGPOINT:
8580 case EXPR_LITERAL_FLOATINGPOINT_HEXADECIMAL: return false;
8581 case EXPR_STRING_LITERAL: return false;
8582 case EXPR_WIDE_STRING_LITERAL: return false;
8585 const call_expression_t *const call = &expr->call;
8586 if (call->function->kind != EXPR_REFERENCE)
8589 switch (call->function->reference.entity->function.btk) {
8590 /* FIXME: which builtins have no effect? */
8591 default: return true;
8595 /* Generate the warning if either the left or right hand side of a
8596 * conditional expression has no effect */
8597 case EXPR_CONDITIONAL: {
8598 conditional_expression_t const *const cond = &expr->conditional;
8599 expression_t const *const t = cond->true_expression;
8601 (t == NULL || expression_has_effect(t)) &&
8602 expression_has_effect(cond->false_expression);
8605 case EXPR_SELECT: return false;
8606 case EXPR_ARRAY_ACCESS: return false;
8607 case EXPR_SIZEOF: return false;
8608 case EXPR_CLASSIFY_TYPE: return false;
8609 case EXPR_ALIGNOF: return false;
8611 case EXPR_FUNCNAME: return false;
8612 case EXPR_BUILTIN_CONSTANT_P: return false;
8613 case EXPR_BUILTIN_TYPES_COMPATIBLE_P: return false;
8614 case EXPR_OFFSETOF: return false;
8615 case EXPR_VA_START: return true;
8616 case EXPR_VA_ARG: return true;
8617 case EXPR_VA_COPY: return true;
8618 case EXPR_STATEMENT: return true; // TODO
8619 case EXPR_COMPOUND_LITERAL: return false;
8621 case EXPR_UNARY_NEGATE: return false;
8622 case EXPR_UNARY_PLUS: return false;
8623 case EXPR_UNARY_BITWISE_NEGATE: return false;
8624 case EXPR_UNARY_NOT: return false;
8625 case EXPR_UNARY_DEREFERENCE: return false;
8626 case EXPR_UNARY_TAKE_ADDRESS: return false;
8627 case EXPR_UNARY_POSTFIX_INCREMENT: return true;
8628 case EXPR_UNARY_POSTFIX_DECREMENT: return true;
8629 case EXPR_UNARY_PREFIX_INCREMENT: return true;
8630 case EXPR_UNARY_PREFIX_DECREMENT: return true;
8632 /* Treat void casts as if they have an effect in order to being able to
8633 * suppress the warning */
8634 case EXPR_UNARY_CAST: {
8635 type_t *const type = skip_typeref(expr->base.type);
8636 return is_type_atomic(type, ATOMIC_TYPE_VOID);
8639 case EXPR_UNARY_CAST_IMPLICIT: return true;
8640 case EXPR_UNARY_ASSUME: return true;
8641 case EXPR_UNARY_DELETE: return true;
8642 case EXPR_UNARY_DELETE_ARRAY: return true;
8643 case EXPR_UNARY_THROW: return true;
8645 case EXPR_BINARY_ADD: return false;
8646 case EXPR_BINARY_SUB: return false;
8647 case EXPR_BINARY_MUL: return false;
8648 case EXPR_BINARY_DIV: return false;
8649 case EXPR_BINARY_MOD: return false;
8650 case EXPR_BINARY_EQUAL: return false;
8651 case EXPR_BINARY_NOTEQUAL: return false;
8652 case EXPR_BINARY_LESS: return false;
8653 case EXPR_BINARY_LESSEQUAL: return false;
8654 case EXPR_BINARY_GREATER: return false;
8655 case EXPR_BINARY_GREATEREQUAL: return false;
8656 case EXPR_BINARY_BITWISE_AND: return false;
8657 case EXPR_BINARY_BITWISE_OR: return false;
8658 case EXPR_BINARY_BITWISE_XOR: return false;
8659 case EXPR_BINARY_SHIFTLEFT: return false;
8660 case EXPR_BINARY_SHIFTRIGHT: return false;
8661 case EXPR_BINARY_ASSIGN: return true;
8662 case EXPR_BINARY_MUL_ASSIGN: return true;
8663 case EXPR_BINARY_DIV_ASSIGN: return true;
8664 case EXPR_BINARY_MOD_ASSIGN: return true;
8665 case EXPR_BINARY_ADD_ASSIGN: return true;
8666 case EXPR_BINARY_SUB_ASSIGN: return true;
8667 case EXPR_BINARY_SHIFTLEFT_ASSIGN: return true;
8668 case EXPR_BINARY_SHIFTRIGHT_ASSIGN: return true;
8669 case EXPR_BINARY_BITWISE_AND_ASSIGN: return true;
8670 case EXPR_BINARY_BITWISE_XOR_ASSIGN: return true;
8671 case EXPR_BINARY_BITWISE_OR_ASSIGN: return true;
8673 /* Only examine the right hand side of && and ||, because the left hand
8674 * side already has the effect of controlling the execution of the right
8676 case EXPR_BINARY_LOGICAL_AND:
8677 case EXPR_BINARY_LOGICAL_OR:
8678 /* Only examine the right hand side of a comma expression, because the left
8679 * hand side has a separate warning */
8680 case EXPR_BINARY_COMMA:
8681 return expression_has_effect(expr->binary.right);
8683 case EXPR_BINARY_ISGREATER: return false;
8684 case EXPR_BINARY_ISGREATEREQUAL: return false;
8685 case EXPR_BINARY_ISLESS: return false;
8686 case EXPR_BINARY_ISLESSEQUAL: return false;
8687 case EXPR_BINARY_ISLESSGREATER: return false;
8688 case EXPR_BINARY_ISUNORDERED: return false;
8691 internal_errorf(HERE, "unexpected expression");
8694 static void semantic_comma(binary_expression_t *expression)
8696 const expression_t *const left = expression->left;
8697 if (!expression_has_effect(left)) {
8698 source_position_t const *const pos = &left->base.source_position;
8699 warningf(WARN_UNUSED_VALUE, pos, "left-hand operand of comma expression has no effect");
8701 expression->base.type = expression->right->base.type;
8705 * @param prec_r precedence of the right operand
8707 #define CREATE_BINEXPR_PARSER(token_type, binexpression_type, prec_r, sfunc) \
8708 static expression_t *parse_##binexpression_type(expression_t *left) \
8710 expression_t *binexpr = allocate_expression_zero(binexpression_type); \
8711 binexpr->binary.left = left; \
8714 expression_t *right = parse_subexpression(prec_r); \
8716 binexpr->binary.right = right; \
8717 sfunc(&binexpr->binary); \
8722 CREATE_BINEXPR_PARSER('*', EXPR_BINARY_MUL, PREC_CAST, semantic_binexpr_arithmetic)
8723 CREATE_BINEXPR_PARSER('/', EXPR_BINARY_DIV, PREC_CAST, semantic_divmod_arithmetic)
8724 CREATE_BINEXPR_PARSER('%', EXPR_BINARY_MOD, PREC_CAST, semantic_divmod_arithmetic)
8725 CREATE_BINEXPR_PARSER('+', EXPR_BINARY_ADD, PREC_MULTIPLICATIVE, semantic_add)
8726 CREATE_BINEXPR_PARSER('-', EXPR_BINARY_SUB, PREC_MULTIPLICATIVE, semantic_sub)
8727 CREATE_BINEXPR_PARSER(T_LESSLESS, EXPR_BINARY_SHIFTLEFT, PREC_ADDITIVE, semantic_shift_op)
8728 CREATE_BINEXPR_PARSER(T_GREATERGREATER, EXPR_BINARY_SHIFTRIGHT, PREC_ADDITIVE, semantic_shift_op)
8729 CREATE_BINEXPR_PARSER('<', EXPR_BINARY_LESS, PREC_SHIFT, semantic_comparison)
8730 CREATE_BINEXPR_PARSER('>', EXPR_BINARY_GREATER, PREC_SHIFT, semantic_comparison)
8731 CREATE_BINEXPR_PARSER(T_LESSEQUAL, EXPR_BINARY_LESSEQUAL, PREC_SHIFT, semantic_comparison)
8732 CREATE_BINEXPR_PARSER(T_GREATEREQUAL, EXPR_BINARY_GREATEREQUAL, PREC_SHIFT, semantic_comparison)
8733 CREATE_BINEXPR_PARSER(T_EXCLAMATIONMARKEQUAL, EXPR_BINARY_NOTEQUAL, PREC_RELATIONAL, semantic_comparison)
8734 CREATE_BINEXPR_PARSER(T_EQUALEQUAL, EXPR_BINARY_EQUAL, PREC_RELATIONAL, semantic_comparison)
8735 CREATE_BINEXPR_PARSER('&', EXPR_BINARY_BITWISE_AND, PREC_EQUALITY, semantic_binexpr_integer)
8736 CREATE_BINEXPR_PARSER('^', EXPR_BINARY_BITWISE_XOR, PREC_AND, semantic_binexpr_integer)
8737 CREATE_BINEXPR_PARSER('|', EXPR_BINARY_BITWISE_OR, PREC_XOR, semantic_binexpr_integer)
8738 CREATE_BINEXPR_PARSER(T_ANDAND, EXPR_BINARY_LOGICAL_AND, PREC_OR, semantic_logical_op)
8739 CREATE_BINEXPR_PARSER(T_PIPEPIPE, EXPR_BINARY_LOGICAL_OR, PREC_LOGICAL_AND, semantic_logical_op)
8740 CREATE_BINEXPR_PARSER('=', EXPR_BINARY_ASSIGN, PREC_ASSIGNMENT, semantic_binexpr_assign)
8741 CREATE_BINEXPR_PARSER(T_PLUSEQUAL, EXPR_BINARY_ADD_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8742 CREATE_BINEXPR_PARSER(T_MINUSEQUAL, EXPR_BINARY_SUB_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_addsubb_assign)
8743 CREATE_BINEXPR_PARSER(T_ASTERISKEQUAL, EXPR_BINARY_MUL_ASSIGN, PREC_ASSIGNMENT, semantic_arithmetic_assign)
8744 CREATE_BINEXPR_PARSER(T_SLASHEQUAL, EXPR_BINARY_DIV_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8745 CREATE_BINEXPR_PARSER(T_PERCENTEQUAL, EXPR_BINARY_MOD_ASSIGN, PREC_ASSIGNMENT, semantic_divmod_assign)
8746 CREATE_BINEXPR_PARSER(T_LESSLESSEQUAL, EXPR_BINARY_SHIFTLEFT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8747 CREATE_BINEXPR_PARSER(T_GREATERGREATEREQUAL, EXPR_BINARY_SHIFTRIGHT_ASSIGN, PREC_ASSIGNMENT, semantic_shift_assign)
8748 CREATE_BINEXPR_PARSER(T_ANDEQUAL, EXPR_BINARY_BITWISE_AND_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8749 CREATE_BINEXPR_PARSER(T_PIPEEQUAL, EXPR_BINARY_BITWISE_OR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8750 CREATE_BINEXPR_PARSER(T_CARETEQUAL, EXPR_BINARY_BITWISE_XOR_ASSIGN, PREC_ASSIGNMENT, semantic_integer_assign)
8751 CREATE_BINEXPR_PARSER(',', EXPR_BINARY_COMMA, PREC_ASSIGNMENT, semantic_comma)
8754 static expression_t *parse_subexpression(precedence_t precedence)
8756 if (token.type < 0) {
8757 return expected_expression_error();
8760 expression_parser_function_t *parser
8761 = &expression_parsers[token.type];
8764 if (parser->parser != NULL) {
8765 left = parser->parser();
8767 left = parse_primary_expression();
8769 assert(left != NULL);
8772 if (token.type < 0) {
8773 return expected_expression_error();
8776 parser = &expression_parsers[token.type];
8777 if (parser->infix_parser == NULL)
8779 if (parser->infix_precedence < precedence)
8782 left = parser->infix_parser(left);
8784 assert(left != NULL);
8785 assert(left->kind != EXPR_UNKNOWN);
8792 * Parse an expression.
8794 static expression_t *parse_expression(void)
8796 return parse_subexpression(PREC_EXPRESSION);
8800 * Register a parser for a prefix-like operator.
8802 * @param parser the parser function
8803 * @param token_type the token type of the prefix token
8805 static void register_expression_parser(parse_expression_function parser,
8808 expression_parser_function_t *entry = &expression_parsers[token_type];
8810 if (entry->parser != NULL) {
8811 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8812 panic("trying to register multiple expression parsers for a token");
8814 entry->parser = parser;
8818 * Register a parser for an infix operator with given precedence.
8820 * @param parser the parser function
8821 * @param token_type the token type of the infix operator
8822 * @param precedence the precedence of the operator
8824 static void register_infix_parser(parse_expression_infix_function parser,
8825 int token_type, precedence_t precedence)
8827 expression_parser_function_t *entry = &expression_parsers[token_type];
8829 if (entry->infix_parser != NULL) {
8830 diagnosticf("for token '%k'\n", (token_type_t)token_type);
8831 panic("trying to register multiple infix expression parsers for a "
8834 entry->infix_parser = parser;
8835 entry->infix_precedence = precedence;
8839 * Initialize the expression parsers.
8841 static void init_expression_parsers(void)
8843 memset(&expression_parsers, 0, sizeof(expression_parsers));
8845 register_infix_parser(parse_array_expression, '[', PREC_POSTFIX);
8846 register_infix_parser(parse_call_expression, '(', PREC_POSTFIX);
8847 register_infix_parser(parse_select_expression, '.', PREC_POSTFIX);
8848 register_infix_parser(parse_select_expression, T_MINUSGREATER, PREC_POSTFIX);
8849 register_infix_parser(parse_EXPR_UNARY_POSTFIX_INCREMENT, T_PLUSPLUS, PREC_POSTFIX);
8850 register_infix_parser(parse_EXPR_UNARY_POSTFIX_DECREMENT, T_MINUSMINUS, PREC_POSTFIX);
8851 register_infix_parser(parse_EXPR_BINARY_MUL, '*', PREC_MULTIPLICATIVE);
8852 register_infix_parser(parse_EXPR_BINARY_DIV, '/', PREC_MULTIPLICATIVE);
8853 register_infix_parser(parse_EXPR_BINARY_MOD, '%', PREC_MULTIPLICATIVE);
8854 register_infix_parser(parse_EXPR_BINARY_ADD, '+', PREC_ADDITIVE);
8855 register_infix_parser(parse_EXPR_BINARY_SUB, '-', PREC_ADDITIVE);
8856 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT, T_LESSLESS, PREC_SHIFT);
8857 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT, T_GREATERGREATER, PREC_SHIFT);
8858 register_infix_parser(parse_EXPR_BINARY_LESS, '<', PREC_RELATIONAL);
8859 register_infix_parser(parse_EXPR_BINARY_GREATER, '>', PREC_RELATIONAL);
8860 register_infix_parser(parse_EXPR_BINARY_LESSEQUAL, T_LESSEQUAL, PREC_RELATIONAL);
8861 register_infix_parser(parse_EXPR_BINARY_GREATEREQUAL, T_GREATEREQUAL, PREC_RELATIONAL);
8862 register_infix_parser(parse_EXPR_BINARY_EQUAL, T_EQUALEQUAL, PREC_EQUALITY);
8863 register_infix_parser(parse_EXPR_BINARY_NOTEQUAL, T_EXCLAMATIONMARKEQUAL, PREC_EQUALITY);
8864 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND, '&', PREC_AND);
8865 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR, '^', PREC_XOR);
8866 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR, '|', PREC_OR);
8867 register_infix_parser(parse_EXPR_BINARY_LOGICAL_AND, T_ANDAND, PREC_LOGICAL_AND);
8868 register_infix_parser(parse_EXPR_BINARY_LOGICAL_OR, T_PIPEPIPE, PREC_LOGICAL_OR);
8869 register_infix_parser(parse_conditional_expression, '?', PREC_CONDITIONAL);
8870 register_infix_parser(parse_EXPR_BINARY_ASSIGN, '=', PREC_ASSIGNMENT);
8871 register_infix_parser(parse_EXPR_BINARY_ADD_ASSIGN, T_PLUSEQUAL, PREC_ASSIGNMENT);
8872 register_infix_parser(parse_EXPR_BINARY_SUB_ASSIGN, T_MINUSEQUAL, PREC_ASSIGNMENT);
8873 register_infix_parser(parse_EXPR_BINARY_MUL_ASSIGN, T_ASTERISKEQUAL, PREC_ASSIGNMENT);
8874 register_infix_parser(parse_EXPR_BINARY_DIV_ASSIGN, T_SLASHEQUAL, PREC_ASSIGNMENT);
8875 register_infix_parser(parse_EXPR_BINARY_MOD_ASSIGN, T_PERCENTEQUAL, PREC_ASSIGNMENT);
8876 register_infix_parser(parse_EXPR_BINARY_SHIFTLEFT_ASSIGN, T_LESSLESSEQUAL, PREC_ASSIGNMENT);
8877 register_infix_parser(parse_EXPR_BINARY_SHIFTRIGHT_ASSIGN, T_GREATERGREATEREQUAL, PREC_ASSIGNMENT);
8878 register_infix_parser(parse_EXPR_BINARY_BITWISE_AND_ASSIGN, T_ANDEQUAL, PREC_ASSIGNMENT);
8879 register_infix_parser(parse_EXPR_BINARY_BITWISE_OR_ASSIGN, T_PIPEEQUAL, PREC_ASSIGNMENT);
8880 register_infix_parser(parse_EXPR_BINARY_BITWISE_XOR_ASSIGN, T_CARETEQUAL, PREC_ASSIGNMENT);
8881 register_infix_parser(parse_EXPR_BINARY_COMMA, ',', PREC_EXPRESSION);
8883 register_expression_parser(parse_EXPR_UNARY_NEGATE, '-');
8884 register_expression_parser(parse_EXPR_UNARY_PLUS, '+');
8885 register_expression_parser(parse_EXPR_UNARY_NOT, '!');
8886 register_expression_parser(parse_EXPR_UNARY_BITWISE_NEGATE, '~');
8887 register_expression_parser(parse_EXPR_UNARY_DEREFERENCE, '*');
8888 register_expression_parser(parse_EXPR_UNARY_TAKE_ADDRESS, '&');
8889 register_expression_parser(parse_EXPR_UNARY_PREFIX_INCREMENT, T_PLUSPLUS);
8890 register_expression_parser(parse_EXPR_UNARY_PREFIX_DECREMENT, T_MINUSMINUS);
8891 register_expression_parser(parse_sizeof, T_sizeof);
8892 register_expression_parser(parse_alignof, T___alignof__);
8893 register_expression_parser(parse_extension, T___extension__);
8894 register_expression_parser(parse_builtin_classify_type, T___builtin_classify_type);
8895 register_expression_parser(parse_delete, T_delete);
8896 register_expression_parser(parse_throw, T_throw);
8900 * Parse a asm statement arguments specification.
8902 static asm_argument_t *parse_asm_arguments(bool is_out)
8904 asm_argument_t *result = NULL;
8905 asm_argument_t **anchor = &result;
8907 while (token.type == T_STRING_LITERAL || token.type == '[') {
8908 asm_argument_t *argument = allocate_ast_zero(sizeof(argument[0]));
8909 memset(argument, 0, sizeof(argument[0]));
8912 if (token.type != T_IDENTIFIER) {
8913 parse_error_expected("while parsing asm argument",
8914 T_IDENTIFIER, NULL);
8917 argument->symbol = token.symbol;
8919 expect(']', end_error);
8922 argument->constraints = parse_string_literals();
8923 expect('(', end_error);
8924 add_anchor_token(')');
8925 expression_t *expression = parse_expression();
8926 rem_anchor_token(')');
8928 /* Ugly GCC stuff: Allow lvalue casts. Skip casts, when they do not
8929 * change size or type representation (e.g. int -> long is ok, but
8930 * int -> float is not) */
8931 if (expression->kind == EXPR_UNARY_CAST) {
8932 type_t *const type = expression->base.type;
8933 type_kind_t const kind = type->kind;
8934 if (kind == TYPE_ATOMIC || kind == TYPE_POINTER) {
8937 if (kind == TYPE_ATOMIC) {
8938 atomic_type_kind_t const akind = type->atomic.akind;
8939 flags = get_atomic_type_flags(akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8940 size = get_atomic_type_size(akind);
8942 flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8943 size = get_atomic_type_size(get_intptr_kind());
8947 expression_t *const value = expression->unary.value;
8948 type_t *const value_type = value->base.type;
8949 type_kind_t const value_kind = value_type->kind;
8951 unsigned value_flags;
8952 unsigned value_size;
8953 if (value_kind == TYPE_ATOMIC) {
8954 atomic_type_kind_t const value_akind = value_type->atomic.akind;
8955 value_flags = get_atomic_type_flags(value_akind) & ~ATOMIC_TYPE_FLAG_SIGNED;
8956 value_size = get_atomic_type_size(value_akind);
8957 } else if (value_kind == TYPE_POINTER) {
8958 value_flags = ATOMIC_TYPE_FLAG_INTEGER | ATOMIC_TYPE_FLAG_ARITHMETIC;
8959 value_size = get_atomic_type_size(get_intptr_kind());
8964 if (value_flags != flags || value_size != size)
8968 } while (expression->kind == EXPR_UNARY_CAST);
8972 if (!is_lvalue(expression)) {
8973 errorf(&expression->base.source_position,
8974 "asm output argument is not an lvalue");
8977 if (argument->constraints.begin[0] == '=')
8978 determine_lhs_ent(expression, NULL);
8980 mark_vars_read(expression, NULL);
8982 mark_vars_read(expression, NULL);
8984 argument->expression = expression;
8985 expect(')', end_error);
8987 set_address_taken(expression, true);
8990 anchor = &argument->next;
9002 * Parse a asm statement clobber specification.
9004 static asm_clobber_t *parse_asm_clobbers(void)
9006 asm_clobber_t *result = NULL;
9007 asm_clobber_t **anchor = &result;
9009 while (token.type == T_STRING_LITERAL) {
9010 asm_clobber_t *clobber = allocate_ast_zero(sizeof(clobber[0]));
9011 clobber->clobber = parse_string_literals();
9014 anchor = &clobber->next;
9024 * Parse an asm statement.
9026 static statement_t *parse_asm_statement(void)
9028 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
9029 asm_statement_t *asm_statement = &statement->asms;
9033 if (next_if(T_volatile))
9034 asm_statement->is_volatile = true;
9036 expect('(', end_error);
9037 add_anchor_token(')');
9038 if (token.type != T_STRING_LITERAL) {
9039 parse_error_expected("after asm(", T_STRING_LITERAL, NULL);
9042 asm_statement->asm_text = parse_string_literals();
9044 add_anchor_token(':');
9045 if (!next_if(':')) {
9046 rem_anchor_token(':');
9050 asm_statement->outputs = parse_asm_arguments(true);
9051 if (!next_if(':')) {
9052 rem_anchor_token(':');
9056 asm_statement->inputs = parse_asm_arguments(false);
9057 if (!next_if(':')) {
9058 rem_anchor_token(':');
9061 rem_anchor_token(':');
9063 asm_statement->clobbers = parse_asm_clobbers();
9066 rem_anchor_token(')');
9067 expect(')', end_error);
9068 expect(';', end_error);
9070 if (asm_statement->outputs == NULL) {
9071 /* GCC: An 'asm' instruction without any output operands will be treated
9072 * identically to a volatile 'asm' instruction. */
9073 asm_statement->is_volatile = true;
9078 return create_invalid_statement();
9081 static statement_t *parse_label_inner_statement(statement_t const *const label, char const *const label_kind)
9083 statement_t *inner_stmt;
9084 switch (token.type) {
9086 errorf(&label->base.source_position, "%s at end of compound statement", label_kind);
9087 inner_stmt = create_invalid_statement();
9091 if (label->kind == STATEMENT_LABEL) {
9092 /* Eat an empty statement here, to avoid the warning about an empty
9093 * statement after a label. label:; is commonly used to have a label
9094 * before a closing brace. */
9095 inner_stmt = create_empty_statement();
9102 inner_stmt = parse_statement();
9103 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9104 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9105 if (inner_stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9106 errorf(&inner_stmt->base.source_position, "declaration after %s", label_kind);
9114 * Parse a case statement.
9116 static statement_t *parse_case_statement(void)
9118 statement_t *const statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9119 source_position_t *const pos = &statement->base.source_position;
9123 expression_t *const expression = parse_expression();
9124 statement->case_label.expression = expression;
9125 expression_classification_t const expr_class = is_constant_expression(expression);
9126 if (expr_class != EXPR_CLASS_CONSTANT) {
9127 if (expr_class != EXPR_CLASS_ERROR) {
9128 errorf(pos, "case label does not reduce to an integer constant");
9130 statement->case_label.is_bad = true;
9132 long const val = fold_constant_to_int(expression);
9133 statement->case_label.first_case = val;
9134 statement->case_label.last_case = val;
9138 if (next_if(T_DOTDOTDOT)) {
9139 expression_t *const end_range = parse_expression();
9140 statement->case_label.end_range = end_range;
9141 expression_classification_t const end_class = is_constant_expression(end_range);
9142 if (end_class != EXPR_CLASS_CONSTANT) {
9143 if (end_class != EXPR_CLASS_ERROR) {
9144 errorf(pos, "case range does not reduce to an integer constant");
9146 statement->case_label.is_bad = true;
9148 long const val = fold_constant_to_int(end_range);
9149 statement->case_label.last_case = val;
9151 if (val < statement->case_label.first_case) {
9152 statement->case_label.is_empty_range = true;
9153 warningf(WARN_OTHER, pos, "empty range specified");
9159 PUSH_PARENT(statement);
9161 expect(':', end_error);
9164 if (current_switch != NULL) {
9165 if (! statement->case_label.is_bad) {
9166 /* Check for duplicate case values */
9167 case_label_statement_t *c = &statement->case_label;
9168 for (case_label_statement_t *l = current_switch->first_case; l != NULL; l = l->next) {
9169 if (l->is_bad || l->is_empty_range || l->expression == NULL)
9172 if (c->last_case < l->first_case || c->first_case > l->last_case)
9175 errorf(pos, "duplicate case value (previously used %P)",
9176 &l->base.source_position);
9180 /* link all cases into the switch statement */
9181 if (current_switch->last_case == NULL) {
9182 current_switch->first_case = &statement->case_label;
9184 current_switch->last_case->next = &statement->case_label;
9186 current_switch->last_case = &statement->case_label;
9188 errorf(pos, "case label not within a switch statement");
9191 statement->case_label.statement = parse_label_inner_statement(statement, "case label");
9198 * Parse a default statement.
9200 static statement_t *parse_default_statement(void)
9202 statement_t *statement = allocate_statement_zero(STATEMENT_CASE_LABEL);
9206 PUSH_PARENT(statement);
9208 expect(':', end_error);
9211 if (current_switch != NULL) {
9212 const case_label_statement_t *def_label = current_switch->default_label;
9213 if (def_label != NULL) {
9214 errorf(&statement->base.source_position, "multiple default labels in one switch (previous declared %P)", &def_label->base.source_position);
9216 current_switch->default_label = &statement->case_label;
9218 /* link all cases into the switch statement */
9219 if (current_switch->last_case == NULL) {
9220 current_switch->first_case = &statement->case_label;
9222 current_switch->last_case->next = &statement->case_label;
9224 current_switch->last_case = &statement->case_label;
9227 errorf(&statement->base.source_position,
9228 "'default' label not within a switch statement");
9231 statement->case_label.statement = parse_label_inner_statement(statement, "default label");
9238 * Parse a label statement.
9240 static statement_t *parse_label_statement(void)
9242 statement_t *const statement = allocate_statement_zero(STATEMENT_LABEL);
9243 label_t *const label = get_label();
9244 statement->label.label = label;
9246 PUSH_PARENT(statement);
9248 /* if statement is already set then the label is defined twice,
9249 * otherwise it was just mentioned in a goto/local label declaration so far
9251 source_position_t const* const pos = &statement->base.source_position;
9252 if (label->statement != NULL) {
9253 errorf(pos, "duplicate '%N' (declared %P)", (entity_t const*)label, &label->base.source_position);
9255 label->base.source_position = *pos;
9256 label->statement = statement;
9261 statement->label.statement = parse_label_inner_statement(statement, "label");
9263 /* remember the labels in a list for later checking */
9264 *label_anchor = &statement->label;
9265 label_anchor = &statement->label.next;
9271 static statement_t *parse_inner_statement(void)
9273 statement_t *const stmt = parse_statement();
9274 /* ISO/IEC 9899:1999(E) §6.8:1/6.8.2:1 Declarations are no statements */
9275 /* ISO/IEC 14882:1998(E) §6:1/§6.7 Declarations are statements */
9276 if (stmt->kind == STATEMENT_DECLARATION && !(c_mode & _CXX)) {
9277 errorf(&stmt->base.source_position, "declaration as inner statement, use {}");
9283 * Parse an if statement.
9285 static statement_t *parse_if(void)
9287 statement_t *statement = allocate_statement_zero(STATEMENT_IF);
9291 PUSH_PARENT(statement);
9293 add_anchor_token('{');
9295 expect('(', end_error);
9296 add_anchor_token(')');
9297 expression_t *const expr = parse_expression();
9298 statement->ifs.condition = expr;
9299 /* §6.8.4.1:1 The controlling expression of an if statement shall have
9301 semantic_condition(expr, "condition of 'if'-statment");
9302 mark_vars_read(expr, NULL);
9303 rem_anchor_token(')');
9304 expect(')', end_error);
9307 rem_anchor_token('{');
9309 add_anchor_token(T_else);
9310 statement_t *const true_stmt = parse_inner_statement();
9311 statement->ifs.true_statement = true_stmt;
9312 rem_anchor_token(T_else);
9314 if (next_if(T_else)) {
9315 statement->ifs.false_statement = parse_inner_statement();
9316 } else if (true_stmt->kind == STATEMENT_IF &&
9317 true_stmt->ifs.false_statement != NULL) {
9318 source_position_t const *const pos = &true_stmt->base.source_position;
9319 warningf(WARN_PARENTHESES, pos, "suggest explicit braces to avoid ambiguous 'else'");
9327 * Check that all enums are handled in a switch.
9329 * @param statement the switch statement to check
9331 static void check_enum_cases(const switch_statement_t *statement)
9333 if (!is_warn_on(WARN_SWITCH_ENUM))
9335 const type_t *type = skip_typeref(statement->expression->base.type);
9336 if (! is_type_enum(type))
9338 const enum_type_t *enumt = &type->enumt;
9340 /* if we have a default, no warnings */
9341 if (statement->default_label != NULL)
9344 /* FIXME: calculation of value should be done while parsing */
9345 /* TODO: quadratic algorithm here. Change to an n log n one */
9346 long last_value = -1;
9347 const entity_t *entry = enumt->enume->base.next;
9348 for (; entry != NULL && entry->kind == ENTITY_ENUM_VALUE;
9349 entry = entry->base.next) {
9350 const expression_t *expression = entry->enum_value.value;
9351 long value = expression != NULL ? fold_constant_to_int(expression) : last_value + 1;
9353 for (const case_label_statement_t *l = statement->first_case; l != NULL; l = l->next) {
9354 if (l->expression == NULL)
9356 if (l->first_case <= value && value <= l->last_case) {
9362 source_position_t const *const pos = &statement->base.source_position;
9363 warningf(WARN_SWITCH_ENUM, pos, "'%N' not handled in switch", entry);
9370 * Parse a switch statement.
9372 static statement_t *parse_switch(void)
9374 statement_t *statement = allocate_statement_zero(STATEMENT_SWITCH);
9378 PUSH_PARENT(statement);
9380 expect('(', end_error);
9381 add_anchor_token(')');
9382 expression_t *const expr = parse_expression();
9383 mark_vars_read(expr, NULL);
9384 type_t * type = skip_typeref(expr->base.type);
9385 if (is_type_integer(type)) {
9386 type = promote_integer(type);
9387 if (get_rank(type) >= get_akind_rank(ATOMIC_TYPE_LONG)) {
9388 warningf(WARN_TRADITIONAL, &expr->base.source_position, "'%T' switch expression not converted to '%T' in ISO C", type, type_int);
9390 } else if (is_type_valid(type)) {
9391 errorf(&expr->base.source_position,
9392 "switch quantity is not an integer, but '%T'", type);
9393 type = type_error_type;
9395 statement->switchs.expression = create_implicit_cast(expr, type);
9396 expect(')', end_error);
9397 rem_anchor_token(')');
9399 switch_statement_t *rem = current_switch;
9400 current_switch = &statement->switchs;
9401 statement->switchs.body = parse_inner_statement();
9402 current_switch = rem;
9404 if (statement->switchs.default_label == NULL) {
9405 warningf(WARN_SWITCH_DEFAULT, &statement->base.source_position, "switch has no default case");
9407 check_enum_cases(&statement->switchs);
9413 return create_invalid_statement();
9416 static statement_t *parse_loop_body(statement_t *const loop)
9418 statement_t *const rem = current_loop;
9419 current_loop = loop;
9421 statement_t *const body = parse_inner_statement();
9428 * Parse a while statement.
9430 static statement_t *parse_while(void)
9432 statement_t *statement = allocate_statement_zero(STATEMENT_WHILE);
9436 PUSH_PARENT(statement);
9438 expect('(', end_error);
9439 add_anchor_token(')');
9440 expression_t *const cond = parse_expression();
9441 statement->whiles.condition = cond;
9442 /* §6.8.5:2 The controlling expression of an iteration statement shall
9443 * have scalar type. */
9444 semantic_condition(cond, "condition of 'while'-statement");
9445 mark_vars_read(cond, NULL);
9446 rem_anchor_token(')');
9447 expect(')', end_error);
9449 statement->whiles.body = parse_loop_body(statement);
9455 return create_invalid_statement();
9459 * Parse a do statement.
9461 static statement_t *parse_do(void)
9463 statement_t *statement = allocate_statement_zero(STATEMENT_DO_WHILE);
9467 PUSH_PARENT(statement);
9469 add_anchor_token(T_while);
9470 statement->do_while.body = parse_loop_body(statement);
9471 rem_anchor_token(T_while);
9473 expect(T_while, end_error);
9474 expect('(', end_error);
9475 add_anchor_token(')');
9476 expression_t *const cond = parse_expression();
9477 statement->do_while.condition = cond;
9478 /* §6.8.5:2 The controlling expression of an iteration statement shall
9479 * have scalar type. */
9480 semantic_condition(cond, "condition of 'do-while'-statement");
9481 mark_vars_read(cond, NULL);
9482 rem_anchor_token(')');
9483 expect(')', end_error);
9484 expect(';', end_error);
9490 return create_invalid_statement();
9494 * Parse a for statement.
9496 static statement_t *parse_for(void)
9498 statement_t *statement = allocate_statement_zero(STATEMENT_FOR);
9502 expect('(', end_error1);
9503 add_anchor_token(')');
9505 PUSH_PARENT(statement);
9506 PUSH_SCOPE(&statement->fors.scope);
9511 } else if (is_declaration_specifier(&token)) {
9512 parse_declaration(record_entity, DECL_FLAGS_NONE);
9514 add_anchor_token(';');
9515 expression_t *const init = parse_expression();
9516 statement->fors.initialisation = init;
9517 mark_vars_read(init, ENT_ANY);
9518 if (!expression_has_effect(init)) {
9519 warningf(WARN_UNUSED_VALUE, &init->base.source_position, "initialisation of 'for'-statement has no effect");
9521 rem_anchor_token(';');
9522 expect(';', end_error2);
9527 if (token.type != ';') {
9528 add_anchor_token(';');
9529 expression_t *const cond = parse_expression();
9530 statement->fors.condition = cond;
9531 /* §6.8.5:2 The controlling expression of an iteration statement
9532 * shall have scalar type. */
9533 semantic_condition(cond, "condition of 'for'-statement");
9534 mark_vars_read(cond, NULL);
9535 rem_anchor_token(';');
9537 expect(';', end_error2);
9538 if (token.type != ')') {
9539 expression_t *const step = parse_expression();
9540 statement->fors.step = step;
9541 mark_vars_read(step, ENT_ANY);
9542 if (!expression_has_effect(step)) {
9543 warningf(WARN_UNUSED_VALUE, &step->base.source_position, "step of 'for'-statement has no effect");
9546 expect(')', end_error2);
9547 rem_anchor_token(')');
9548 statement->fors.body = parse_loop_body(statement);
9556 rem_anchor_token(')');
9561 return create_invalid_statement();
9565 * Parse a goto statement.
9567 static statement_t *parse_goto(void)
9569 statement_t *statement = allocate_statement_zero(STATEMENT_GOTO);
9572 if (GNU_MODE && next_if('*')) {
9573 expression_t *expression = parse_expression();
9574 mark_vars_read(expression, NULL);
9576 /* Argh: although documentation says the expression must be of type void*,
9577 * gcc accepts anything that can be casted into void* without error */
9578 type_t *type = expression->base.type;
9580 if (type != type_error_type) {
9581 if (!is_type_pointer(type) && !is_type_integer(type)) {
9582 errorf(&expression->base.source_position,
9583 "cannot convert to a pointer type");
9584 } else if (type != type_void_ptr) {
9585 warningf(WARN_OTHER, &expression->base.source_position, "type of computed goto expression should be 'void*' not '%T'", type);
9587 expression = create_implicit_cast(expression, type_void_ptr);
9590 statement->gotos.expression = expression;
9591 } else if (token.type == T_IDENTIFIER) {
9592 label_t *const label = get_label();
9594 statement->gotos.label = label;
9597 parse_error_expected("while parsing goto", T_IDENTIFIER, '*', NULL);
9599 parse_error_expected("while parsing goto", T_IDENTIFIER, NULL);
9601 return create_invalid_statement();
9604 /* remember the goto's in a list for later checking */
9605 *goto_anchor = &statement->gotos;
9606 goto_anchor = &statement->gotos.next;
9608 expect(';', end_error);
9615 * Parse a continue statement.
9617 static statement_t *parse_continue(void)
9619 if (current_loop == NULL) {
9620 errorf(HERE, "continue statement not within loop");
9623 statement_t *statement = allocate_statement_zero(STATEMENT_CONTINUE);
9626 expect(';', end_error);
9633 * Parse a break statement.
9635 static statement_t *parse_break(void)
9637 if (current_switch == NULL && current_loop == NULL) {
9638 errorf(HERE, "break statement not within loop or switch");
9641 statement_t *statement = allocate_statement_zero(STATEMENT_BREAK);
9644 expect(';', end_error);
9651 * Parse a __leave statement.
9653 static statement_t *parse_leave_statement(void)
9655 if (current_try == NULL) {
9656 errorf(HERE, "__leave statement not within __try");
9659 statement_t *statement = allocate_statement_zero(STATEMENT_LEAVE);
9662 expect(';', end_error);
9669 * Check if a given entity represents a local variable.
9671 static bool is_local_variable(const entity_t *entity)
9673 if (entity->kind != ENTITY_VARIABLE)
9676 switch ((storage_class_tag_t) entity->declaration.storage_class) {
9677 case STORAGE_CLASS_AUTO:
9678 case STORAGE_CLASS_REGISTER: {
9679 const type_t *type = skip_typeref(entity->declaration.type);
9680 if (is_type_function(type)) {
9692 * Check if a given expression represents a local variable.
9694 static bool expression_is_local_variable(const expression_t *expression)
9696 if (expression->base.kind != EXPR_REFERENCE) {
9699 const entity_t *entity = expression->reference.entity;
9700 return is_local_variable(entity);
9704 * Check if a given expression represents a local variable and
9705 * return its declaration then, else return NULL.
9707 entity_t *expression_is_variable(const expression_t *expression)
9709 if (expression->base.kind != EXPR_REFERENCE) {
9712 entity_t *entity = expression->reference.entity;
9713 if (entity->kind != ENTITY_VARIABLE)
9720 * Parse a return statement.
9722 static statement_t *parse_return(void)
9724 statement_t *statement = allocate_statement_zero(STATEMENT_RETURN);
9727 expression_t *return_value = NULL;
9728 if (token.type != ';') {
9729 return_value = parse_expression();
9730 mark_vars_read(return_value, NULL);
9733 const type_t *const func_type = skip_typeref(current_function->base.type);
9734 assert(is_type_function(func_type));
9735 type_t *const return_type = skip_typeref(func_type->function.return_type);
9737 source_position_t const *const pos = &statement->base.source_position;
9738 if (return_value != NULL) {
9739 type_t *return_value_type = skip_typeref(return_value->base.type);
9741 if (is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9742 if (is_type_atomic(return_value_type, ATOMIC_TYPE_VOID)) {
9743 /* ISO/IEC 14882:1998(E) §6.6.3:2 */
9744 /* Only warn in C mode, because GCC does the same */
9745 if (c_mode & _CXX || strict_mode) {
9747 "'return' with a value, in function returning 'void'");
9749 warningf(WARN_OTHER, pos, "'return' with a value, in function returning 'void'");
9751 } else if (!(c_mode & _CXX)) { /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9752 /* Only warn in C mode, because GCC does the same */
9755 "'return' with expression in function returning 'void'");
9757 warningf(WARN_OTHER, pos, "'return' with expression in function returning 'void'");
9761 assign_error_t error = semantic_assign(return_type, return_value);
9762 report_assign_error(error, return_type, return_value, "'return'",
9765 return_value = create_implicit_cast(return_value, return_type);
9766 /* check for returning address of a local var */
9767 if (return_value != NULL && return_value->base.kind == EXPR_UNARY_TAKE_ADDRESS) {
9768 const expression_t *expression = return_value->unary.value;
9769 if (expression_is_local_variable(expression)) {
9770 warningf(WARN_OTHER, pos, "function returns address of local variable");
9773 } else if (!is_type_atomic(return_type, ATOMIC_TYPE_VOID)) {
9774 /* ISO/IEC 14882:1998(E) §6.6.3:3 */
9775 if (c_mode & _CXX || strict_mode) {
9777 "'return' without value, in function returning non-void");
9779 warningf(WARN_OTHER, pos, "'return' without value, in function returning non-void");
9782 statement->returns.value = return_value;
9784 expect(';', end_error);
9791 * Parse a declaration statement.
9793 static statement_t *parse_declaration_statement(void)
9795 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9797 entity_t *before = current_scope->last_entity;
9799 parse_external_declaration();
9801 parse_declaration(record_entity, DECL_FLAGS_NONE);
9804 declaration_statement_t *const decl = &statement->declaration;
9805 entity_t *const begin =
9806 before != NULL ? before->base.next : current_scope->entities;
9807 decl->declarations_begin = begin;
9808 decl->declarations_end = begin != NULL ? current_scope->last_entity : NULL;
9814 * Parse an expression statement, ie. expr ';'.
9816 static statement_t *parse_expression_statement(void)
9818 statement_t *statement = allocate_statement_zero(STATEMENT_EXPRESSION);
9820 expression_t *const expr = parse_expression();
9821 statement->expression.expression = expr;
9822 mark_vars_read(expr, ENT_ANY);
9824 expect(';', end_error);
9831 * Parse a microsoft __try { } __finally { } or
9832 * __try{ } __except() { }
9834 static statement_t *parse_ms_try_statment(void)
9836 statement_t *statement = allocate_statement_zero(STATEMENT_MS_TRY);
9839 PUSH_PARENT(statement);
9841 ms_try_statement_t *rem = current_try;
9842 current_try = &statement->ms_try;
9843 statement->ms_try.try_statement = parse_compound_statement(false);
9848 if (next_if(T___except)) {
9849 expect('(', end_error);
9850 add_anchor_token(')');
9851 expression_t *const expr = parse_expression();
9852 mark_vars_read(expr, NULL);
9853 type_t * type = skip_typeref(expr->base.type);
9854 if (is_type_integer(type)) {
9855 type = promote_integer(type);
9856 } else if (is_type_valid(type)) {
9857 errorf(&expr->base.source_position,
9858 "__expect expression is not an integer, but '%T'", type);
9859 type = type_error_type;
9861 statement->ms_try.except_expression = create_implicit_cast(expr, type);
9862 rem_anchor_token(')');
9863 expect(')', end_error);
9864 statement->ms_try.final_statement = parse_compound_statement(false);
9865 } else if (next_if(T__finally)) {
9866 statement->ms_try.final_statement = parse_compound_statement(false);
9868 parse_error_expected("while parsing __try statement", T___except, T___finally, NULL);
9869 return create_invalid_statement();
9873 return create_invalid_statement();
9876 static statement_t *parse_empty_statement(void)
9878 warningf(WARN_EMPTY_STATEMENT, HERE, "statement is empty");
9879 statement_t *const statement = create_empty_statement();
9884 static statement_t *parse_local_label_declaration(void)
9886 statement_t *statement = allocate_statement_zero(STATEMENT_DECLARATION);
9890 entity_t *begin = NULL;
9891 entity_t *end = NULL;
9892 entity_t **anchor = &begin;
9894 if (token.type != T_IDENTIFIER) {
9895 parse_error_expected("while parsing local label declaration",
9896 T_IDENTIFIER, NULL);
9899 symbol_t *symbol = token.symbol;
9900 entity_t *entity = get_entity(symbol, NAMESPACE_LABEL);
9901 if (entity != NULL && entity->base.parent_scope == current_scope) {
9902 source_position_t const *const ppos = &entity->base.source_position;
9903 errorf(HERE, "multiple definitions of '%N' (previous definition %P)", entity, ppos);
9905 entity = allocate_entity_zero(ENTITY_LOCAL_LABEL, NAMESPACE_LABEL, symbol);
9906 entity->base.parent_scope = current_scope;
9907 entity->base.source_position = token.source_position;
9910 anchor = &entity->base.next;
9913 environment_push(entity);
9916 } while (next_if(','));
9917 expect(';', end_error);
9919 statement->declaration.declarations_begin = begin;
9920 statement->declaration.declarations_end = end;
9924 static void parse_namespace_definition(void)
9928 entity_t *entity = NULL;
9929 symbol_t *symbol = NULL;
9931 if (token.type == T_IDENTIFIER) {
9932 symbol = token.symbol;
9935 entity = get_entity(symbol, NAMESPACE_NORMAL);
9937 && entity->kind != ENTITY_NAMESPACE
9938 && entity->base.parent_scope == current_scope) {
9939 if (is_entity_valid(entity)) {
9940 error_redefined_as_different_kind(&token.source_position,
9941 entity, ENTITY_NAMESPACE);
9947 if (entity == NULL) {
9948 entity = allocate_entity_zero(ENTITY_NAMESPACE, NAMESPACE_NORMAL, symbol);
9949 entity->base.source_position = token.source_position;
9950 entity->base.parent_scope = current_scope;
9953 if (token.type == '=') {
9954 /* TODO: parse namespace alias */
9955 panic("namespace alias definition not supported yet");
9958 environment_push(entity);
9959 append_entity(current_scope, entity);
9961 PUSH_SCOPE(&entity->namespacee.members);
9963 entity_t *old_current_entity = current_entity;
9964 current_entity = entity;
9966 expect('{', end_error);
9968 expect('}', end_error);
9971 assert(current_entity == entity);
9972 current_entity = old_current_entity;
9977 * Parse a statement.
9978 * There's also parse_statement() which additionally checks for
9979 * "statement has no effect" warnings
9981 static statement_t *intern_parse_statement(void)
9983 statement_t *statement = NULL;
9985 /* declaration or statement */
9986 add_anchor_token(';');
9987 switch (token.type) {
9988 case T_IDENTIFIER: {
9989 token_type_t la1_type = (token_type_t)look_ahead(1)->type;
9990 if (la1_type == ':') {
9991 statement = parse_label_statement();
9992 } else if (is_typedef_symbol(token.symbol)) {
9993 statement = parse_declaration_statement();
9995 /* it's an identifier, the grammar says this must be an
9996 * expression statement. However it is common that users mistype
9997 * declaration types, so we guess a bit here to improve robustness
9998 * for incorrect programs */
10002 if (get_entity(token.symbol, NAMESPACE_NORMAL) != NULL) {
10004 statement = parse_expression_statement();
10008 statement = parse_declaration_statement();
10016 case T___extension__: {
10017 /* This can be a prefix to a declaration or an expression statement.
10018 * We simply eat it now and parse the rest with tail recursion. */
10020 statement = intern_parse_statement();
10026 statement = parse_declaration_statement();
10030 statement = parse_local_label_declaration();
10033 case ';': statement = parse_empty_statement(); break;
10034 case '{': statement = parse_compound_statement(false); break;
10035 case T___leave: statement = parse_leave_statement(); break;
10036 case T___try: statement = parse_ms_try_statment(); break;
10037 case T_asm: statement = parse_asm_statement(); break;
10038 case T_break: statement = parse_break(); break;
10039 case T_case: statement = parse_case_statement(); break;
10040 case T_continue: statement = parse_continue(); break;
10041 case T_default: statement = parse_default_statement(); break;
10042 case T_do: statement = parse_do(); break;
10043 case T_for: statement = parse_for(); break;
10044 case T_goto: statement = parse_goto(); break;
10045 case T_if: statement = parse_if(); break;
10046 case T_return: statement = parse_return(); break;
10047 case T_switch: statement = parse_switch(); break;
10048 case T_while: statement = parse_while(); break;
10051 statement = parse_expression_statement();
10055 errorf(HERE, "unexpected token %K while parsing statement", &token);
10056 statement = create_invalid_statement();
10061 rem_anchor_token(';');
10063 assert(statement != NULL
10064 && statement->base.source_position.input_name != NULL);
10070 * parse a statement and emits "statement has no effect" warning if needed
10071 * (This is really a wrapper around intern_parse_statement with check for 1
10072 * single warning. It is needed, because for statement expressions we have
10073 * to avoid the warning on the last statement)
10075 static statement_t *parse_statement(void)
10077 statement_t *statement = intern_parse_statement();
10079 if (statement->kind == STATEMENT_EXPRESSION) {
10080 expression_t *expression = statement->expression.expression;
10081 if (!expression_has_effect(expression)) {
10082 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10090 * Parse a compound statement.
10092 static statement_t *parse_compound_statement(bool inside_expression_statement)
10094 statement_t *statement = allocate_statement_zero(STATEMENT_COMPOUND);
10096 PUSH_PARENT(statement);
10097 PUSH_SCOPE(&statement->compound.scope);
10100 add_anchor_token('}');
10101 /* tokens, which can start a statement */
10102 /* TODO MS, __builtin_FOO */
10103 add_anchor_token('!');
10104 add_anchor_token('&');
10105 add_anchor_token('(');
10106 add_anchor_token('*');
10107 add_anchor_token('+');
10108 add_anchor_token('-');
10109 add_anchor_token('{');
10110 add_anchor_token('~');
10111 add_anchor_token(T_CHARACTER_CONSTANT);
10112 add_anchor_token(T_COLONCOLON);
10113 add_anchor_token(T_FLOATINGPOINT);
10114 add_anchor_token(T_IDENTIFIER);
10115 add_anchor_token(T_INTEGER);
10116 add_anchor_token(T_MINUSMINUS);
10117 add_anchor_token(T_PLUSPLUS);
10118 add_anchor_token(T_STRING_LITERAL);
10119 add_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10120 add_anchor_token(T_WIDE_STRING_LITERAL);
10121 add_anchor_token(T__Bool);
10122 add_anchor_token(T__Complex);
10123 add_anchor_token(T__Imaginary);
10124 add_anchor_token(T___FUNCTION__);
10125 add_anchor_token(T___PRETTY_FUNCTION__);
10126 add_anchor_token(T___alignof__);
10127 add_anchor_token(T___attribute__);
10128 add_anchor_token(T___builtin_va_start);
10129 add_anchor_token(T___extension__);
10130 add_anchor_token(T___func__);
10131 add_anchor_token(T___imag__);
10132 add_anchor_token(T___label__);
10133 add_anchor_token(T___real__);
10134 add_anchor_token(T___thread);
10135 add_anchor_token(T_asm);
10136 add_anchor_token(T_auto);
10137 add_anchor_token(T_bool);
10138 add_anchor_token(T_break);
10139 add_anchor_token(T_case);
10140 add_anchor_token(T_char);
10141 add_anchor_token(T_class);
10142 add_anchor_token(T_const);
10143 add_anchor_token(T_const_cast);
10144 add_anchor_token(T_continue);
10145 add_anchor_token(T_default);
10146 add_anchor_token(T_delete);
10147 add_anchor_token(T_double);
10148 add_anchor_token(T_do);
10149 add_anchor_token(T_dynamic_cast);
10150 add_anchor_token(T_enum);
10151 add_anchor_token(T_extern);
10152 add_anchor_token(T_false);
10153 add_anchor_token(T_float);
10154 add_anchor_token(T_for);
10155 add_anchor_token(T_goto);
10156 add_anchor_token(T_if);
10157 add_anchor_token(T_inline);
10158 add_anchor_token(T_int);
10159 add_anchor_token(T_long);
10160 add_anchor_token(T_new);
10161 add_anchor_token(T_operator);
10162 add_anchor_token(T_register);
10163 add_anchor_token(T_reinterpret_cast);
10164 add_anchor_token(T_restrict);
10165 add_anchor_token(T_return);
10166 add_anchor_token(T_short);
10167 add_anchor_token(T_signed);
10168 add_anchor_token(T_sizeof);
10169 add_anchor_token(T_static);
10170 add_anchor_token(T_static_cast);
10171 add_anchor_token(T_struct);
10172 add_anchor_token(T_switch);
10173 add_anchor_token(T_template);
10174 add_anchor_token(T_this);
10175 add_anchor_token(T_throw);
10176 add_anchor_token(T_true);
10177 add_anchor_token(T_try);
10178 add_anchor_token(T_typedef);
10179 add_anchor_token(T_typeid);
10180 add_anchor_token(T_typename);
10181 add_anchor_token(T_typeof);
10182 add_anchor_token(T_union);
10183 add_anchor_token(T_unsigned);
10184 add_anchor_token(T_using);
10185 add_anchor_token(T_void);
10186 add_anchor_token(T_volatile);
10187 add_anchor_token(T_wchar_t);
10188 add_anchor_token(T_while);
10190 statement_t **anchor = &statement->compound.statements;
10191 bool only_decls_so_far = true;
10192 while (token.type != '}') {
10193 if (token.type == T_EOF) {
10194 errorf(&statement->base.source_position,
10195 "EOF while parsing compound statement");
10198 statement_t *sub_statement = intern_parse_statement();
10199 if (is_invalid_statement(sub_statement)) {
10200 /* an error occurred. if we are at an anchor, return */
10206 if (sub_statement->kind != STATEMENT_DECLARATION) {
10207 only_decls_so_far = false;
10208 } else if (!only_decls_so_far) {
10209 source_position_t const *const pos = &sub_statement->base.source_position;
10210 warningf(WARN_DECLARATION_AFTER_STATEMENT, pos, "ISO C90 forbids mixed declarations and code");
10213 *anchor = sub_statement;
10215 while (sub_statement->base.next != NULL)
10216 sub_statement = sub_statement->base.next;
10218 anchor = &sub_statement->base.next;
10222 /* look over all statements again to produce no effect warnings */
10223 if (is_warn_on(WARN_UNUSED_VALUE)) {
10224 statement_t *sub_statement = statement->compound.statements;
10225 for (; sub_statement != NULL; sub_statement = sub_statement->base.next) {
10226 if (sub_statement->kind != STATEMENT_EXPRESSION)
10228 /* don't emit a warning for the last expression in an expression
10229 * statement as it has always an effect */
10230 if (inside_expression_statement && sub_statement->base.next == NULL)
10233 expression_t *expression = sub_statement->expression.expression;
10234 if (!expression_has_effect(expression)) {
10235 warningf(WARN_UNUSED_VALUE, &expression->base.source_position, "statement has no effect");
10241 rem_anchor_token(T_while);
10242 rem_anchor_token(T_wchar_t);
10243 rem_anchor_token(T_volatile);
10244 rem_anchor_token(T_void);
10245 rem_anchor_token(T_using);
10246 rem_anchor_token(T_unsigned);
10247 rem_anchor_token(T_union);
10248 rem_anchor_token(T_typeof);
10249 rem_anchor_token(T_typename);
10250 rem_anchor_token(T_typeid);
10251 rem_anchor_token(T_typedef);
10252 rem_anchor_token(T_try);
10253 rem_anchor_token(T_true);
10254 rem_anchor_token(T_throw);
10255 rem_anchor_token(T_this);
10256 rem_anchor_token(T_template);
10257 rem_anchor_token(T_switch);
10258 rem_anchor_token(T_struct);
10259 rem_anchor_token(T_static_cast);
10260 rem_anchor_token(T_static);
10261 rem_anchor_token(T_sizeof);
10262 rem_anchor_token(T_signed);
10263 rem_anchor_token(T_short);
10264 rem_anchor_token(T_return);
10265 rem_anchor_token(T_restrict);
10266 rem_anchor_token(T_reinterpret_cast);
10267 rem_anchor_token(T_register);
10268 rem_anchor_token(T_operator);
10269 rem_anchor_token(T_new);
10270 rem_anchor_token(T_long);
10271 rem_anchor_token(T_int);
10272 rem_anchor_token(T_inline);
10273 rem_anchor_token(T_if);
10274 rem_anchor_token(T_goto);
10275 rem_anchor_token(T_for);
10276 rem_anchor_token(T_float);
10277 rem_anchor_token(T_false);
10278 rem_anchor_token(T_extern);
10279 rem_anchor_token(T_enum);
10280 rem_anchor_token(T_dynamic_cast);
10281 rem_anchor_token(T_do);
10282 rem_anchor_token(T_double);
10283 rem_anchor_token(T_delete);
10284 rem_anchor_token(T_default);
10285 rem_anchor_token(T_continue);
10286 rem_anchor_token(T_const_cast);
10287 rem_anchor_token(T_const);
10288 rem_anchor_token(T_class);
10289 rem_anchor_token(T_char);
10290 rem_anchor_token(T_case);
10291 rem_anchor_token(T_break);
10292 rem_anchor_token(T_bool);
10293 rem_anchor_token(T_auto);
10294 rem_anchor_token(T_asm);
10295 rem_anchor_token(T___thread);
10296 rem_anchor_token(T___real__);
10297 rem_anchor_token(T___label__);
10298 rem_anchor_token(T___imag__);
10299 rem_anchor_token(T___func__);
10300 rem_anchor_token(T___extension__);
10301 rem_anchor_token(T___builtin_va_start);
10302 rem_anchor_token(T___attribute__);
10303 rem_anchor_token(T___alignof__);
10304 rem_anchor_token(T___PRETTY_FUNCTION__);
10305 rem_anchor_token(T___FUNCTION__);
10306 rem_anchor_token(T__Imaginary);
10307 rem_anchor_token(T__Complex);
10308 rem_anchor_token(T__Bool);
10309 rem_anchor_token(T_WIDE_STRING_LITERAL);
10310 rem_anchor_token(T_WIDE_CHARACTER_CONSTANT);
10311 rem_anchor_token(T_STRING_LITERAL);
10312 rem_anchor_token(T_PLUSPLUS);
10313 rem_anchor_token(T_MINUSMINUS);
10314 rem_anchor_token(T_INTEGER);
10315 rem_anchor_token(T_IDENTIFIER);
10316 rem_anchor_token(T_FLOATINGPOINT);
10317 rem_anchor_token(T_COLONCOLON);
10318 rem_anchor_token(T_CHARACTER_CONSTANT);
10319 rem_anchor_token('~');
10320 rem_anchor_token('{');
10321 rem_anchor_token('-');
10322 rem_anchor_token('+');
10323 rem_anchor_token('*');
10324 rem_anchor_token('(');
10325 rem_anchor_token('&');
10326 rem_anchor_token('!');
10327 rem_anchor_token('}');
10335 * Check for unused global static functions and variables
10337 static void check_unused_globals(void)
10339 if (!is_warn_on(WARN_UNUSED_FUNCTION) && !is_warn_on(WARN_UNUSED_VARIABLE))
10342 for (const entity_t *entity = file_scope->entities; entity != NULL;
10343 entity = entity->base.next) {
10344 if (!is_declaration(entity))
10347 const declaration_t *declaration = &entity->declaration;
10348 if (declaration->used ||
10349 declaration->modifiers & DM_UNUSED ||
10350 declaration->modifiers & DM_USED ||
10351 declaration->storage_class != STORAGE_CLASS_STATIC)
10356 if (entity->kind == ENTITY_FUNCTION) {
10357 /* inhibit warning for static inline functions */
10358 if (entity->function.is_inline)
10361 why = WARN_UNUSED_FUNCTION;
10362 s = entity->function.statement != NULL ? "defined" : "declared";
10364 why = WARN_UNUSED_VARIABLE;
10368 warningf(why, &declaration->base.source_position, "'%#N' %s but not used", entity, s);
10372 static void parse_global_asm(void)
10374 statement_t *statement = allocate_statement_zero(STATEMENT_ASM);
10377 expect('(', end_error);
10379 statement->asms.asm_text = parse_string_literals();
10380 statement->base.next = unit->global_asm;
10381 unit->global_asm = statement;
10383 expect(')', end_error);
10384 expect(';', end_error);
10389 static void parse_linkage_specification(void)
10393 source_position_t const pos = *HERE;
10394 char const *const linkage = parse_string_literals().begin;
10396 linkage_kind_t old_linkage = current_linkage;
10397 linkage_kind_t new_linkage;
10398 if (strcmp(linkage, "C") == 0) {
10399 new_linkage = LINKAGE_C;
10400 } else if (strcmp(linkage, "C++") == 0) {
10401 new_linkage = LINKAGE_CXX;
10403 errorf(&pos, "linkage string \"%s\" not recognized", linkage);
10404 new_linkage = LINKAGE_INVALID;
10406 current_linkage = new_linkage;
10408 if (next_if('{')) {
10410 expect('}', end_error);
10416 assert(current_linkage == new_linkage);
10417 current_linkage = old_linkage;
10420 static void parse_external(void)
10422 switch (token.type) {
10424 if (look_ahead(1)->type == T_STRING_LITERAL) {
10425 parse_linkage_specification();
10427 DECLARATION_START_NO_EXTERN
10429 case T___extension__:
10430 /* tokens below are for implicit int */
10431 case '&': /* & x; -> int& x; (and error later, because C++ has no
10433 case '*': /* * x; -> int* x; */
10434 case '(':; /* (x); -> int (x); */
10436 parse_external_declaration();
10442 parse_global_asm();
10446 parse_namespace_definition();
10450 if (!strict_mode) {
10451 warningf(WARN_OTHER, HERE, "stray ';' outside of function");
10458 errorf(HERE, "stray %K outside of function", &token);
10459 if (token.type == '(' || token.type == '{' || token.type == '[')
10460 eat_until_matching_token(token.type);
10466 static void parse_externals(void)
10468 add_anchor_token('}');
10469 add_anchor_token(T_EOF);
10472 /* make a copy of the anchor set, so we can check if it is restored after parsing */
10473 unsigned char token_anchor_copy[T_LAST_TOKEN];
10474 memcpy(token_anchor_copy, token_anchor_set, sizeof(token_anchor_copy));
10477 while (token.type != T_EOF && token.type != '}') {
10479 for (int i = 0; i < T_LAST_TOKEN; ++i) {
10480 unsigned char count = token_anchor_set[i] - token_anchor_copy[i];
10482 /* the anchor set and its copy differs */
10483 internal_errorf(HERE, "Leaked anchor token %k %d times", i, count);
10486 if (in_gcc_extension) {
10487 /* an gcc extension scope was not closed */
10488 internal_errorf(HERE, "Leaked __extension__");
10495 rem_anchor_token(T_EOF);
10496 rem_anchor_token('}');
10500 * Parse a translation unit.
10502 static void parse_translation_unit(void)
10504 add_anchor_token(T_EOF);
10509 if (token.type == T_EOF)
10512 errorf(HERE, "stray %K outside of function", &token);
10513 if (token.type == '(' || token.type == '{' || token.type == '[')
10514 eat_until_matching_token(token.type);
10519 void set_default_visibility(elf_visibility_tag_t visibility)
10521 default_visibility = visibility;
10527 * @return the translation unit or NULL if errors occurred.
10529 void start_parsing(void)
10531 environment_stack = NEW_ARR_F(stack_entry_t, 0);
10532 label_stack = NEW_ARR_F(stack_entry_t, 0);
10533 diagnostic_count = 0;
10537 print_to_file(stderr);
10539 assert(unit == NULL);
10540 unit = allocate_ast_zero(sizeof(unit[0]));
10542 assert(file_scope == NULL);
10543 file_scope = &unit->scope;
10545 assert(current_scope == NULL);
10546 scope_push(&unit->scope);
10548 create_gnu_builtins();
10550 create_microsoft_intrinsics();
10553 translation_unit_t *finish_parsing(void)
10555 assert(current_scope == &unit->scope);
10558 assert(file_scope == &unit->scope);
10559 check_unused_globals();
10562 DEL_ARR_F(environment_stack);
10563 DEL_ARR_F(label_stack);
10565 translation_unit_t *result = unit;
10570 /* §6.9.2:2 and §6.9.2:5: At the end of the translation incomplete arrays
10571 * are given length one. */
10572 static void complete_incomplete_arrays(void)
10574 size_t n = ARR_LEN(incomplete_arrays);
10575 for (size_t i = 0; i != n; ++i) {
10576 declaration_t *const decl = incomplete_arrays[i];
10577 type_t *const type = skip_typeref(decl->type);
10579 if (!is_type_incomplete(type))
10582 source_position_t const *const pos = &decl->base.source_position;
10583 warningf(WARN_OTHER, pos, "array '%#N' assumed to have one element", (entity_t const*)decl);
10585 type_t *const new_type = duplicate_type(type);
10586 new_type->array.size_constant = true;
10587 new_type->array.has_implicit_size = true;
10588 new_type->array.size = 1;
10590 type_t *const result = identify_new_type(new_type);
10592 decl->type = result;
10596 void prepare_main_collect2(entity_t *entity)
10598 // create call to __main
10599 symbol_t *symbol = symbol_table_insert("__main");
10600 entity_t *subsubmain_ent
10601 = create_implicit_function(symbol, &builtin_source_position);
10603 expression_t *ref = allocate_expression_zero(EXPR_REFERENCE);
10604 type_t *ftype = subsubmain_ent->declaration.type;
10605 ref->base.source_position = builtin_source_position;
10606 ref->base.type = make_pointer_type(ftype, TYPE_QUALIFIER_NONE);
10607 ref->reference.entity = subsubmain_ent;
10609 expression_t *call = allocate_expression_zero(EXPR_CALL);
10610 call->base.source_position = builtin_source_position;
10611 call->base.type = type_void;
10612 call->call.function = ref;
10614 statement_t *expr_statement = allocate_statement_zero(STATEMENT_EXPRESSION);
10615 expr_statement->base.source_position = builtin_source_position;
10616 expr_statement->expression.expression = call;
10618 statement_t *statement = entity->function.statement;
10619 assert(statement->kind == STATEMENT_COMPOUND);
10620 compound_statement_t *compounds = &statement->compound;
10622 expr_statement->base.next = compounds->statements;
10623 compounds->statements = expr_statement;
10628 lookahead_bufpos = 0;
10629 for (int i = 0; i < MAX_LOOKAHEAD + 2; ++i) {
10632 current_linkage = c_mode & _CXX ? LINKAGE_CXX : LINKAGE_C;
10633 incomplete_arrays = NEW_ARR_F(declaration_t*, 0);
10634 parse_translation_unit();
10635 complete_incomplete_arrays();
10636 DEL_ARR_F(incomplete_arrays);
10637 incomplete_arrays = NULL;
10641 * Initialize the parser.
10643 void init_parser(void)
10645 sym_anonymous = symbol_table_insert("<anonymous>");
10647 memset(token_anchor_set, 0, sizeof(token_anchor_set));
10649 init_expression_parsers();
10650 obstack_init(&temp_obst);
10654 * Terminate the parser.
10656 void exit_parser(void)
10658 obstack_free(&temp_obst, NULL);